integration-outbound
What it does
integration-outbound (.framework/functions/integration-outbound.ts) is the single egress path for outbound calls. Every attempt is recorded as a webhook_deliveries row (direction: 'outbound'), so there is no fire-and-forget — the delivery row exists before, during, and after the wire call.
execute runs this sequence:
- Resolve the integration row by
integration_slug: the caller-account row first, then a system row (account_id IS NULL); both must beis_active. - Open (or reuse, on
delivery_id) thewebhook_deliveriesrow —status: 'pending',attempt_count: 0,max_attemptsfromaction_config.max_attempts→integration.config.retry_policy.max_attempts→3. - Resolve the credential field (
action_config.credential_field, defaultapi_token) viaresolveCredential(.framework/functions/_shared/ resolve-credentials.ts) — server-side only:source: 'env_var'readsprocess.env[value],source: 'value'returns the literal. An absent or explicitly-empty (source: 'value',value: '') entry means "call without auth":executeskips resolution, passes no credential to the adapter, and auditsintegration.credential_missing/integration.credential_emptywithskipped: true— the adapter decides whether a key is required. A named-but-unsetenv_varstill throws. Every resolution or failure emits anintegration.credential_*audit event. - Pick the adapter:
action_config.adapter || integration.config.outbound_adapter. Built-ins live inbuiltInOutboundAdapters(adapters/openai-outbound,adapters/generic-webhook-outbound,adapters/resend-outbound); any other name is dynamically imported as./<name>and must exportbuildRequest. fetchthe request the adapter built, then update the delivery todelivered(withresponse_status,response_body,duration_ms) or back topending/failedwithnext_attempt_at.
Known callers: _shared/llm.ts (callOpenAI, callOpenAIEmbeddings, callOpenAIChat — all integration_slug: 'openai'), the pipeline stage handlers http_request, agent_inference, send_email, and handler_module: 'webhook' (all integration_slug: 'generic-http'), the retryPendingDeliveries sweep (.framework/functions/_shared/ retry-deliveries.ts), and manual retry in deliveries.ts.
Route and methods
POST /api/integration-outbound—public/_redirectsmaps/api/*to/.netlify/functions/:splat; the default export iscreateHandler(execute).- There is no
actiondispatch — the request body is the contract.
Authentication
createHandler resolves a principal and rejects anonymous requests with 401, so any authenticated caller works (human JWT or x-api-key machine principal). Internal callers import execute directly and pass their own CoreContext.
The delivery_id path first checks account ownership: a non-system caller (not system_admin, not an unbound internal machine) gets Delivery belongs to a different account (403) when the row's account_id differs from theirs. For the stored-payload retry branch the caller must additionally be ctx.principal.isInternal — true for the internal-invoke secret, is_internal API keys, and SYSTEM_PRINCIPAL. A non-internal same-account caller keeps the row id for bookkeeping but skips the stored-payload replay. See Agent notes.
Request contract
Top-level body fields:
| Field | Type | Required | Notes |
|---|---|---|---|
integration_slug | string | yes | integrations.slug; account-scoped row wins over the system row. |
record_id | uuid | no | Fetched via admin-data get and passed to the adapter as record. |
action_config | object | no | See below. |
delivery_id | uuid | no | Reuse an existing delivery row (retry path). |
action_config keys consumed by execute itself:
| Key | Notes |
|---|---|
adapter | Adapter name; falls back to integration.config.outbound_adapter. |
credential_field | integrations.credentials field to resolve; default api_token. Honored only for system principals — non-system callers are pinned to api_token so a scoped key can't name another credential field. |
max_attempts | Overrides config.retry_policy.max_attempts and the default 3. |
action_slug | Stored on the delivery row for traceability. |
update_record / update_fields | On success, stamps last_outbound_status, last_outbound_at, plus update_fields onto record_id via admin-data update. |
Adapter-specific action_config keys:
adapters/generic-webhook-outbound—url(required),method(defaultPOST),headers,body. AddsAuthorization: Bearer <credential>when a credential resolved.adapters/openai-outbound—endpoint(required, e.g./chat/completions,/embeddings),body. Base URL fromintegration.config.base_url(defaulthttps://api.openai.com/v1).adapters/resend-outbound—toandsubjectrequired;htmlortext;fromresolvesactionConfig.from→config.from→EMAIL_FROMenv →onboarding@resend.dev; optionalreply_to;config.api_urloverrides the Resend endpoint.- Custom adapters — dynamically imported
./<name>module exportingbuildRequest(record, ctx)→{ url, method, headers?, body?, external_id? }.
Response contract
Success returns, inside the standard { data, error, meta } envelope:
{ "success": true, "delivery_id": "<uuid>", "response_status": 200,
"response_body": { }, "is_retry": false }response_body is the parsed JSON response, or the raw text when it isn't JSON. A non-2xx target response throws — the delivery row is still updated first (see Side effects), so the attempt is durable even though the HTTP response is an error envelope.
Side effects
webhook_deliveriesinsert (pending) or update (processing→delivered/pending/failedwithattempt_count,next_attempt_at,response_status,response_body,duration_ms,last_error).- Audit events:
integration.outbound.started,.succeeded,.failed_http,.error, plusintegration.credential_*events fromresolveCredential. - One external
fetchper attempt. The tracking INSERT is intentionally overlapped with the wire call (insertPromise), so logging does not serialize ahead of latency. - Optional admin-data
updateonrecord_idwhenaction_config.update_recordis set — runs the full permission/audit pipeline, not a raw write.
Errors
| Condition | Error |
|---|---|
| No slug | integration_slug is required |
| Slug matches no active account or system integration | Integration not found: <slug> |
| Retry of unknown delivery | Delivery not found: <id> |
env_var credential names an unset variable | Environment variable <var> … is not set (audits integration.credential_env_missing). Absent/empty credential entries do not throw — the call proceeds unauthenticated and the adapter enforces its own requirement (e.g. OpenAI adapter requires api_token credential) |
| No adapter name resolved | No outbound adapter configured for integration <slug> |
Adapter import failed or lacks buildRequest | Outbound adapter not found: <name> |
| Adapter returned no url/method | Outbound adapter must return url and method |
| Delivery insert failed | Failed to create outbound delivery record |
| Non-2xx target | Outbound HTTP <method> to <url> failed with status <status> |
| Delivery-row insert races and fails | Failed to create outbound delivery record (surfaced where insertPromise is awaited) |
Thrown errors map to HTTP 500 unless they carry statusCode; the delivery row keeps the attempt either way.
Agent notes
- Retry semantics.
computeNextAttemptis30s * 2^attemptcapped at 1 hour plus up to 20% jitter. A failed attempt stayspendingwithnext_attempt_atuntilattempt_count >= max_attempts, thenfailed.retryPendingDeliveries(run bysystem-croneach tick) sweepspendingrows withattempt_count < 10whosenext_attempt_atis due or null — up to 100 per pass — and re-invokesexecute({ delivery_id })underSYSTEM_PRINCIPAL. Manual retry:POST /api/deliveries?action=retry { id }— outbound only. Inbound retry is unimplemented. - Non-internal
delivery_id. TheisInternalcheck gates only the payload-replay branch; the row id itself is still honored. An ordinary caller can passdelivery_idand have their request's outcome stamped onto that row (status: 'processing'→ result). There is no per-account check on the row — treatdelivery_idas an internal field. generic-httpis unauthenticated by default — and that works. Migration004seeds it withapi_token: { source: 'value', value: '' };executetreats an absent or empty-literal credential as "no auth", sohttp_request/webhook/agent_inferencestages send the request with noAuthorizationheader on a stock install (the generic adapter only adds Bearer when a credential resolved). To authenticate, set a real token or point the field at anenv_var; to authenticate differently, passaction_config.headers. The skip is still audited asintegration.credential_empty/credential_missingwithskipped: true.openaiseed usesenv_var: OPENAI_API_KEY;callOpenAIChatdefaults togpt-4o-mini/0.7/4000, overridable viaconfig.models.chat/.embeddingon the integration row.- Mock responses live in callers, not here.
callInferencein.framework/functions/_shared/agent-runner.tscatches "not found"/ "credential" errors and returns a marked mock; this function always throws. - Do not call outbound adapters or
fetchexternal URLs directly — delivery tracking, credential audit, and retry all depend on going throughexecute. See integrations and webhooks.