@agent-native/core 0.119.4 → 0.119.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/corpus/README.md +2 -2
- package/corpus/core/CHANGELOG.md +14 -0
- package/corpus/core/package.json +1 -1
- package/corpus/core/src/agent/durable-background.ts +1 -0
- package/corpus/core/src/agent/engine/index.ts +2 -0
- package/corpus/core/src/agent/engine/registry.ts +95 -2
- package/corpus/core/src/deploy/build.ts +144 -2
- package/corpus/core/src/deploy/workspace-deploy.ts +123 -1
- package/corpus/core/src/integrations/integration-durable-dispatch-config.ts +22 -0
- package/corpus/core/src/integrations/integration-durable-dispatch.ts +190 -0
- package/corpus/core/src/integrations/pending-tasks-retry-job.ts +175 -87
- package/corpus/core/src/integrations/pending-tasks-store.ts +114 -11
- package/corpus/core/src/integrations/plugin.ts +113 -60
- package/corpus/core/src/integrations/task-queue-stats.ts +68 -15
- package/corpus/core/src/integrations/webhook-handler.ts +21 -46
- package/corpus/core/src/scripts/agent-engines/list-agent-engines.ts +8 -0
- package/corpus/core/src/scripts/agent-engines/manage-agent-engine.ts +5 -1
- package/corpus/core/src/scripts/agent-engines/set-agent-engine.ts +9 -1
- package/corpus/core/src/server/auth.ts +6 -0
- package/corpus/core/src/templates/default/.agents/skills/integration-webhooks/SKILL.md +63 -22
- package/corpus/core/src/templates/headless/.agents/skills/integration-webhooks/SKILL.md +63 -22
- package/corpus/core/src/templates/workspace-core/.agents/skills/integration-webhooks/SKILL.md +63 -22
- package/corpus/templates/dispatch/changelog/2026-07-21-recover-stalled-slack-agent-work.md +6 -0
- package/corpus/templates/slides/actions/patch-deck.ts +2 -1
- package/corpus/templates/slides/changelog/2026-07-23-opening-or-refining-a-deck-no-longer-crashes-with-a-blank-er.md +6 -0
- package/corpus/templates/slides/shared/aspect-ratios.ts +4 -1
- package/corpus/templates/tasks/.oxfmtrc.json +8 -0
- package/corpus/templates/tasks/AGENTS.md +34 -41
- package/corpus/templates/tasks/README.md +13 -6
- package/corpus/templates/tasks/actions/bulk-delete-inbox-items.ts +10 -8
- package/corpus/templates/tasks/actions/bulk-delete-tasks.ts +10 -8
- package/corpus/templates/tasks/actions/bulk-mark-inbox-items-ready.ts +1 -1
- package/corpus/templates/tasks/actions/bulk-update-tasks.ts +12 -10
- package/corpus/templates/tasks/actions/create-inbox-item.ts +7 -4
- package/corpus/templates/tasks/actions/create-task.ts +2 -1
- package/corpus/templates/tasks/actions/delete-inbox-item.ts +6 -4
- package/corpus/templates/tasks/actions/delete-task.ts +1 -1
- package/corpus/templates/tasks/actions/list-inbox-items.ts +4 -2
- package/corpus/templates/tasks/actions/list-visible-task-fields.ts +3 -1
- package/corpus/templates/tasks/actions/mark-inbox-item-ready.ts +6 -4
- package/corpus/templates/tasks/actions/navigate.ts +16 -14
- package/corpus/templates/tasks/actions/reorder-inbox-items.ts +9 -7
- package/corpus/templates/tasks/actions/update-inbox-item.ts +6 -4
- package/corpus/templates/tasks/actions/update-task.ts +12 -9
- package/corpus/templates/tasks/actions/update-visible-task-fields.ts +10 -8
- package/corpus/templates/tasks/actions/view-screen.ts +1 -1
- package/corpus/templates/tasks/app/components/tasks/fields/TaskFieldsSidebar.tsx +15 -0
- package/corpus/templates/tasks/changelog/2026-07-23-task-detail-extensions.md +6 -0
- package/corpus/templates/tasks/drizzle.config.ts +3 -0
- package/corpus/templates/tasks/package.json +4 -1
- package/corpus/templates/tasks/server/db/schema.ts +0 -10
- package/corpus/templates/tasks/server/db/test-tasks-table.ts +0 -5
- package/corpus/templates/tasks/server/plugins/agent-chat.ts +1 -1
- package/corpus/templates/tasks/server/plugins/db.ts +43 -10
- package/corpus/templates/tasks/server/user-config/store.ts +42 -81
- package/corpus/templates/tasks/tsconfig.json +1 -2
- package/corpus/templates/tasks/vitest.config.ts +10 -1
- package/dist/agent/durable-background.d.ts +1 -0
- package/dist/agent/durable-background.d.ts.map +1 -1
- package/dist/agent/durable-background.js +1 -0
- package/dist/agent/durable-background.js.map +1 -1
- package/dist/agent/engine/index.d.ts +1 -1
- package/dist/agent/engine/index.d.ts.map +1 -1
- package/dist/agent/engine/index.js +1 -1
- package/dist/agent/engine/index.js.map +1 -1
- package/dist/agent/engine/registry.d.ts +32 -1
- package/dist/agent/engine/registry.d.ts.map +1 -1
- package/dist/agent/engine/registry.js +75 -3
- package/dist/agent/engine/registry.js.map +1 -1
- package/dist/deploy/build.d.ts +3 -0
- package/dist/deploy/build.d.ts.map +1 -1
- package/dist/deploy/build.js +106 -3
- package/dist/deploy/build.js.map +1 -1
- package/dist/deploy/workspace-deploy.d.ts.map +1 -1
- package/dist/deploy/workspace-deploy.js +103 -2
- package/dist/deploy/workspace-deploy.js.map +1 -1
- package/dist/file-upload/actions/upload-image.d.ts +1 -1
- package/dist/integrations/integration-durable-dispatch-config.d.ts +7 -0
- package/dist/integrations/integration-durable-dispatch-config.d.ts.map +1 -0
- package/dist/integrations/integration-durable-dispatch-config.js +16 -0
- package/dist/integrations/integration-durable-dispatch-config.js.map +1 -0
- package/dist/integrations/integration-durable-dispatch.d.ts +23 -0
- package/dist/integrations/integration-durable-dispatch.d.ts.map +1 -0
- package/dist/integrations/integration-durable-dispatch.js +115 -0
- package/dist/integrations/integration-durable-dispatch.js.map +1 -0
- package/dist/integrations/pending-tasks-retry-job.d.ts +13 -1
- package/dist/integrations/pending-tasks-retry-job.d.ts.map +1 -1
- package/dist/integrations/pending-tasks-retry-job.js +133 -74
- package/dist/integrations/pending-tasks-retry-job.js.map +1 -1
- package/dist/integrations/pending-tasks-store.d.ts +14 -2
- package/dist/integrations/pending-tasks-store.d.ts.map +1 -1
- package/dist/integrations/pending-tasks-store.js +75 -11
- package/dist/integrations/pending-tasks-store.js.map +1 -1
- package/dist/integrations/plugin.d.ts.map +1 -1
- package/dist/integrations/plugin.js +88 -55
- package/dist/integrations/plugin.js.map +1 -1
- package/dist/integrations/task-queue-stats.d.ts +15 -3
- package/dist/integrations/task-queue-stats.d.ts.map +1 -1
- package/dist/integrations/task-queue-stats.js +45 -15
- package/dist/integrations/task-queue-stats.js.map +1 -1
- package/dist/integrations/webhook-handler.d.ts +1 -1
- package/dist/integrations/webhook-handler.d.ts.map +1 -1
- package/dist/integrations/webhook-handler.js +18 -42
- package/dist/integrations/webhook-handler.js.map +1 -1
- package/dist/notifications/routes.d.ts +2 -2
- package/dist/observability/routes.d.ts +5 -5
- package/dist/progress/routes.d.ts +1 -1
- package/dist/provider-api/actions/custom-provider-registration.d.ts +5 -5
- package/dist/provider-api/actions/provider-api.d.ts +4 -4
- package/dist/resources/handlers.d.ts +1 -1
- package/dist/scripts/agent-engines/list-agent-engines.d.ts.map +1 -1
- package/dist/scripts/agent-engines/list-agent-engines.js +8 -2
- package/dist/scripts/agent-engines/list-agent-engines.js.map +1 -1
- package/dist/scripts/agent-engines/manage-agent-engine.d.ts.map +1 -1
- package/dist/scripts/agent-engines/manage-agent-engine.js +5 -2
- package/dist/scripts/agent-engines/manage-agent-engine.js.map +1 -1
- package/dist/scripts/agent-engines/set-agent-engine.d.ts.map +1 -1
- package/dist/scripts/agent-engines/set-agent-engine.js +9 -2
- package/dist/scripts/agent-engines/set-agent-engine.js.map +1 -1
- package/dist/secrets/routes.d.ts +3 -3
- package/dist/server/agent-engine-api-key-route.d.ts +1 -1
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js +5 -0
- package/dist/server/auth.js.map +1 -1
- package/dist/server/realtime-token.d.ts +1 -1
- package/dist/server/transcribe-voice.d.ts +1 -1
- package/dist/templates/default/.agents/skills/integration-webhooks/SKILL.md +63 -22
- package/dist/templates/headless/.agents/skills/integration-webhooks/SKILL.md +63 -22
- package/dist/templates/workspace-core/.agents/skills/integration-webhooks/SKILL.md +63 -22
- package/package.json +1 -1
- package/src/agent/durable-background.ts +1 -0
- package/src/agent/engine/index.ts +2 -0
- package/src/agent/engine/registry.ts +95 -2
- package/src/deploy/build.ts +144 -2
- package/src/deploy/workspace-deploy.ts +123 -1
- package/src/integrations/integration-durable-dispatch-config.ts +22 -0
- package/src/integrations/integration-durable-dispatch.ts +190 -0
- package/src/integrations/pending-tasks-retry-job.ts +175 -87
- package/src/integrations/pending-tasks-store.ts +114 -11
- package/src/integrations/plugin.ts +113 -60
- package/src/integrations/task-queue-stats.ts +68 -15
- package/src/integrations/webhook-handler.ts +21 -46
- package/src/scripts/agent-engines/list-agent-engines.ts +8 -0
- package/src/scripts/agent-engines/manage-agent-engine.ts +5 -1
- package/src/scripts/agent-engines/set-agent-engine.ts +9 -1
- package/src/server/auth.ts +6 -0
- package/src/templates/default/.agents/skills/integration-webhooks/SKILL.md +63 -22
- package/src/templates/headless/.agents/skills/integration-webhooks/SKILL.md +63 -22
- package/src/templates/workspace-core/.agents/skills/integration-webhooks/SKILL.md +63 -22
- package/corpus/templates/tasks/.prettierrc +0 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"durable-background.js","sourceRoot":"","sources":["../../src/agent/durable-background.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,mCAAmC,CAAC;AAE3C;;;;GAIG;AACH,MAAM,CAAC,MAAM,2BAA2B,GACtC,wCAAwC,CAAC;AAE3C;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,yBAAyB,CAAC;AAExE;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,kCAAkC,GAAG,uBAAuB,8BAA8B,EAAE,CAAC;AAE1G;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,wBAAwB,CAAC;AACzE,MAAM,CAAC,MAAM,8BAA8B,GAAG,KAAK,CAAC;AACpD,MAAM,CAAC,MAAM,gCAAgC,GAAG,OAAO,CAAC;AACxD,MAAM,CAAC,MAAM,sCAAsC,GACjD,6B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3C,KAAK;aACN,CAAC;QACJ,CAAC;IACH,CAAC;SAAM,IAAI,CAAC,qBAAqB,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC;QAChD,wEAAwE;QACxE,yEAAyE;QACzE,0EAA0E;QAC1E,gEAAgE;QAChE,OAAO;YACL,EAAE,EAAE,KAAK;YACT,MAAM,EAAE,GAAG;YACX,KAAK,EACH,8IAA8I;YAChJ,KAAK;SACN,CAAC;IACJ,CAAC;IAED,qEAAqE;IACrE,wEAAwE;IACxE,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ,EAAE,CAAC;QAChD,MAAM,CAAC,+BAA+B,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC;IACtD,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAC3C,CAAC","sourcesContent":["/**\n * Durable background agent-chat runs (Netlify background functions).\n *\n * Off by default. When enabled, a long in-app agent-chat turn is dispatched\n * into a Netlify *background* function (15-min budget) instead of completing\n * synchronously under the ~40s soft-timeout. The foreground POST claims the\n * run slot, inserts the run row, fires an HMAC-signed self-dispatch to\n * `AGENT_CHAT_PROCESS_RUN_PATH`, and returns the existing SSE subscription so\n * the client streams the same events (via the cross-isolate SQL-poll path)\n * with no client change.\n *\n * This module owns ONLY the gating decision + shared constants so both the\n * HTTP handler (`production-agent.ts`) and the processor route\n * (`agent-chat-plugin.ts`) agree on when the path is active without a circular\n * import. The actual run machinery is reused verbatim from run-manager /\n * run-store / self-dispatch / internal-token.\n *\n * GUARDRAIL: when `isAgentChatDurableBackgroundEnabled()` returns false, the\n * agent-chat handler must behave byte-for-byte like the current synchronous\n * path. The gate is true only when ALL of these hold:\n * 1. `AGENT_CHAT_DURABLE_BACKGROUND` env is explicitly enabled, or a\n * workspace app's agent-chat plugin opts in with `durableBackgroundRuns`\n * where the workspace deploy emits a per-app background function by\n * default. Single-template Netlify deploys must set the env flag because\n * that same flag controls whether `server-agent-background` is emitted.\n * 2. The runtime is hosted/serverless (local dev keeps the inline path so SSE\n * stays a single live stream and no second function is needed).\n * 3. `A2A_SECRET` is configured (the HMAC handoff is required to authenticate\n * the background dispatch; without it the dispatch can't be trusted).\n *\n * Opt-in keeps the blast radius small while the worker path is still being\n * proven. And even when enabled, a *dispatch failure degrades to an inline run*:\n * if the self-dispatch self-POST can't be delivered (fast connection error or\n * fast non-2xx), the foreground handler runs the turn synchronously instead of\n * erroring (see `production-agent.ts` — the inline fallback claims the run row\n * atomically so a delayed delivery can never double-execute). So an app where\n * durable dispatch happens to fail still gets a working chat, just without the\n * 15-min budget.\n */\nimport {\n hasConfiguredA2ASecret,\n isTrustedLocalRuntime,\n} from \"../a2a/auth-policy.js\";\nimport {\n extractBearerToken,\n verifyInternalToken,\n} from \"../integrations/internal-token.js\";\n\n/**\n * Framework route the background function actually runs — sibling to\n * `AGENT_TEAM_PROCESS_RUN_PATH`. Reached *through* the Netlify background\n * function, so it inherits the 15-min budget.\n */\nexport const AGENT_CHAT_PROCESS_RUN_PATH =\n \"/_agent-native/agent-chat/_process-run\";\n\n/**\n * Name of the standalone Netlify background function the build emits (see\n * `emitSingleTemplateNetlifyBackgroundFunction` in deploy/build.ts). Shared so\n * the emit and the dispatch-path helper below can never drift on the name.\n *\n * MUST end in `-background` — both because that is the conventional Netlify\n * async-function suffix and because `isInBackgroundFunctionRuntime()` reads the\n * `AWS_LAMBDA_FUNCTION_NAME` `-background` suffix as a secondary runtime signal.\n */\nexport const AGENT_BACKGROUND_FUNCTION_NAME = \"server-agent-background\";\n\n/**\n * Default function URL of the background function on Netlify. Every Netlify\n * function is reachable at `/.netlify/functions/<name>` BY DEFAULT; that default\n * url is removed ONLY if the function declares a custom `config.path`. The\n * emitted background function declares NO custom `config.path` (it sets\n * `background: true` and nothing else routing-related), so it KEEPS this default\n * url — and the Nitro `server` function already excludes `/.netlify/*` from its\n * `/*` catch-all, so this namespace is never shadowed. The foreground therefore\n * dispatches HERE on hosted Netlify (see `resolveAgentChatProcessRunDispatchPath`).\n */\nexport const AGENT_BACKGROUND_FUNCTION_URL_PATH = `/.netlify/functions/${AGENT_BACKGROUND_FUNCTION_NAME}`;\n\n/**\n * Marker carried in a Netlify background-function body when the shared\n * long-running worker should route to a processor other than agent chat.\n * The emitted wrapper defaults to the normal agent-chat `_process-run` route;\n * A2A uses this marker to reuse the same 15-minute function for async tasks.\n */\nexport const AGENT_BACKGROUND_PROCESSOR_FIELD = \"__agentNativeProcessor\";\nexport const AGENT_BACKGROUND_PROCESSOR_A2A = \"a2a\";\nexport const AGENT_BACKGROUND_PROCESSOR_ROUTE = \"route\";\nexport const AGENT_BACKGROUND_PROCESSOR_ROUTE_FIELD =\n \"__agentNativeProcessorRoute\";\n\n/**\n * The per-app workspace background function URL path. Workspace deploy emits one\n * background function per app named `<app>-agent-background`, reachable at its\n * DEFAULT url `/.netlify/functions/<app>-agent-background` (no custom\n * `config.path`). The foreground resolves the current workspace app id from\n * `AGENT_NATIVE_WORKSPACE_APP_ID` (set by the workspace function entry) so it can\n * dispatch to the right per-app function url. Returns `null` when no workspace\n * app id is configured (single-template deploy).\n */\nfunction resolveWorkspaceBackgroundFunctionUrlPath(): string | null {\n const raw = process.env.AGENT_NATIVE_WORKSPACE_APP_ID;\n if (typeof raw !== \"string\") return null;\n // Mirror the workspace app-id normalization (resources/store.ts): take the\n // first path segment and accept only the safe slug shape used for function\n // names. Anything else falls back to the single-template name.\n const candidate = raw.trim().replace(/^\\/+/, \"\").split(\"/\")[0] ?? \"\";\n if (!/^[a-z0-9][a-z0-9-]{0,127}$/.test(candidate)) return null;\n return `/.netlify/functions/${candidate}-agent-background`;\n}\n\nfunction isNetlifyHostedRuntimeForDispatch(): boolean {\n if (process.env.NETLIFY_LOCAL === \"true\") return false;\n if (process.env.NETLIFY === \"false\") return false;\n if (process.env.NETLIFY && process.env.NETLIFY !== \"false\") return true;\n // Netlify sets AWS Lambda runtime env on deployed Functions, but the build-time\n // NETLIFY flag is not always present in the runtime isolate. Treat Lambda as\n // Netlify here unless Netlify was explicitly disabled above; non-Netlify AWS\n // falls back inline if the /.netlify/functions dispatch fast-fails.\n return Boolean(process.env.AWS_LAMBDA_FUNCTION_NAME);\n}\n\n/**\n * Resolve the path the foreground POST should self-dispatch the chat background\n * worker to.\n *\n * GROUNDED IN THE REAL NETLIFY BUILD OUTPUT + THE NETLIFY DOCS DEFAULT-URL RULE:\n * the background function is emitted INTO the scanned dir\n * (`.netlify/functions-internal/server-agent-background`, or per-app\n * `<app>-agent-background` for workspaces) with `export const config = {\n * background: true, ... }` and NO custom `config.path`. Because it has no custom\n * path, Netlify keeps its DEFAULT function url `/.netlify/functions/<name>`, and\n * `background: true` makes any invocation of that url ASYNC (immediate 202,\n * 15-min budget). The Nitro `server` function already excludes `/.netlify/*`\n * from its `/*` catch-all, so the default-url namespace is NEVER shadowed by the\n * synchronous function.\n *\n * Therefore on hosted Netlify the foreground dispatches to the function's DEFAULT\n * url (`/.netlify/functions/<name>`); the function entry then rewrites the\n * incoming pathname to `AGENT_CHAT_PROCESS_RUN_PATH` (base-path-prefixed for\n * workspaces) before delegating to the Nitro router, so the `_process-run`\n * plugin runs with the async 15-min budget. Everywhere else (local dev, `netlify\n * dev`, non-Netlify hosts where no second function exists) there is no second\n * function, so the foreground dispatches to the framework route\n * `AGENT_CHAT_PROCESS_RUN_PATH` and the same in-process catch-all handles it\n * inline. The HMAC token (signed over the runId) is unchanged either way.\n *\n * NOTE: this is the DOC-CORRECT approach. An earlier attempt gave the function a\n * custom `config.path` + a catch-all `excludedPath` patch; the custom path was\n * NOT honored as a route in prod (probe → 404). Using the default function url\n * (no custom path) is what Netlify documents and is simpler — there is nothing\n * to shadow because `/.netlify/*` is already excluded from the `server` catch-all.\n */\nexport function resolveAgentChatProcessRunDispatchPath(): string {\n if (isNetlifyHostedRuntimeForDispatch()) {\n return (\n resolveWorkspaceBackgroundFunctionUrlPath() ??\n AGENT_BACKGROUND_FUNCTION_URL_PATH\n );\n }\n return AGENT_CHAT_PROCESS_RUN_PATH;\n}\n\nexport function resolveDurableBackgroundDispatchPath(\n fallbackPath: string,\n): string {\n if (isNetlifyHostedRuntimeForDispatch()) {\n return (\n resolveWorkspaceBackgroundFunctionUrlPath() ??\n AGENT_BACKGROUND_FUNCTION_URL_PATH\n );\n }\n return fallbackPath;\n}\n\nexport function dispatchPathTargetsNetlifyBackgroundFunction(\n dispatchPath: string,\n): boolean {\n return dispatchPath.startsWith(\"/.netlify/functions/\");\n}\n\n/**\n * Env flag for durable background runs. DEFAULT-OFF (opt-in): unset means\n * disabled; an app opts IN with an explicit truthy value (`true`/`1`/`yes`/`on`).\n */\nexport const AGENT_CHAT_DURABLE_BACKGROUND_ENV =\n \"AGENT_CHAT_DURABLE_BACKGROUND\";\n\n/**\n * Body field the foreground handler injects when self-dispatching to the\n * background processor. Its presence is how the re-entered handler knows it is\n * the background worker (run inline with the background soft-timeout; do NOT\n * re-claim the slot or re-dispatch). Untrusted on its own — the route also\n * verifies the HMAC token before invoking the handler.\n */\nexport const AGENT_CHAT_BACKGROUND_RUN_FIELD = \"__backgroundRun\";\n\n/**\n * Mirror of run-manager's private `isHostedRuntime`. Kept in sync deliberately:\n * the durable-background gate must agree with the soft-timeout regime about\n * what \"hosted\" means.\n */\nexport function isHostedRuntimeForDurableBackground(): boolean {\n if (\n process.env.NETLIFY &&\n process.env.NETLIFY !== \"false\" &&\n process.env.NETLIFY_LOCAL !== \"true\"\n ) {\n return true;\n }\n if (\n process.env.AWS_LAMBDA_FUNCTION_NAME &&\n process.env.NETLIFY_LOCAL !== \"true\"\n ) {\n return true;\n }\n return Boolean(\n process.env.CF_PAGES ||\n process.env.VERCEL ||\n process.env.VERCEL_ENV ||\n process.env.RENDER ||\n process.env.FLY_APP_NAME ||\n process.env.K_SERVICE,\n );\n}\n\n/**\n * True when THIS process is actually executing inside a Netlify *background*\n * function (the long, 15-min-budget async function whose deployed name ends in\n * `-background`). Netlify runs functions on AWS Lambda and sets\n * `AWS_LAMBDA_FUNCTION_NAME` to the function's name, so a `-background` suffix is\n * the runtime proof that the ~60s synchronous wall does NOT apply here.\n *\n * This is the SAFETY GUARD for the soft-timeout regime. The `_process-run`\n * self-dispatch worker (`isBackgroundWorker`) is NOT enough on its own: if the\n * `-background` function was never emitted (deploy gate off, or Netlify routed\n * the path to the synchronous function), the self-POST lands on the regular\n * ~60s `server` function. A worker there MUST use the 40s soft-timeout and\n * checkpoint before the 60s wall — using the ~13min budget would overshoot the\n * hard wall and get killed at 60s, then re-dispatch/resume in a wasteful loop.\n * So the 13-min budget is taken ONLY when this returns true.\n *\n * The PRIMARY signal is a `globalThis` marker the emitted background function's\n * entry sets at cold start — the deployed Lambda name is not guaranteed to end\n * in `-background` on Netlify, so the entry marks its own runtime. A `globalThis`\n * flag (not `process.env`) keeps the no-env-mutation guard satisfied and carries\n * no cross-request state (set once per isolate). The `AWS_LAMBDA_FUNCTION_NAME`\n * suffix and the explicit `AGENT_CHAT_FORCE_BACKGROUND_RUNTIME` env (truthy) are\n * additional signals — the latter an operator escape hatch. Off by default.\n */\nexport function isInBackgroundFunctionRuntime(): boolean {\n // Set by the emitted `-background` function entry at cold start (the primary,\n // most reliable signal — see the emit in deploy/build.ts).\n if (\n (globalThis as Record<string, unknown>)\n .__AGENT_NATIVE_BACKGROUND_RUNTIME__ === true\n ) {\n return true;\n }\n const lambdaName = process.env.AWS_LAMBDA_FUNCTION_NAME;\n if (\n typeof lambdaName === \"string\" &&\n lambdaName.toLowerCase().endsWith(\"-background\")\n ) {\n return true;\n }\n const forced = process.env.AGENT_CHAT_FORCE_BACKGROUND_RUNTIME;\n if (forced != null) {\n const v = forced.trim().toLowerCase();\n return v === \"1\" || v === \"true\" || v === \"yes\" || v === \"on\";\n }\n return false;\n}\n\nexport function backgroundRunMarkerExpectsBackgroundRuntime(\n marker: unknown,\n): boolean {\n return (\n typeof marker === \"object\" &&\n marker !== null &&\n (marker as { backgroundFunctionRuntimeExpected?: unknown })\n .backgroundFunctionRuntimeExpected === true\n );\n}\n\nexport function shouldUseBackgroundFunctionTimeoutForWorker(\n _marker: unknown,\n): boolean {\n // The dispatch marker says which URL the foreground targeted, not where the\n // request actually landed. Only the worker runtime proof can safely lift the\n // hosted 40s clamp to the 15-minute background-function budget.\n return isInBackgroundFunctionRuntime();\n}\n\nexport function backgroundRuntimeDiagnosticDetail(marker: unknown): string {\n return [\n `markerExpected=${backgroundRunMarkerExpectsBackgroundRuntime(marker)}`,\n `runtimeDetected=${isInBackgroundFunctionRuntime()}`,\n `globalMarker=${(globalThis as Record<string, unknown>).__AGENT_NATIVE_BACKGROUND_RUNTIME__ === true}`,\n `lambdaNameEndsBackground=${typeof process.env.AWS_LAMBDA_FUNCTION_NAME === \"string\" && process.env.AWS_LAMBDA_FUNCTION_NAME.toLowerCase().endsWith(\"-background\")}`,\n `forceEnv=${typeof process.env.AGENT_CHAT_FORCE_BACKGROUND_RUNTIME === \"string\" && process.env.AGENT_CHAT_FORCE_BACKGROUND_RUNTIME.trim().length > 0}`,\n ].join(\" \");\n}\n\nfunction isFlagEnabled(): boolean {\n // Read the literal key (not `process.env[CONST]`) so guard:no-env-credentials\n // can statically verify it against the allowlisted `AGENT_*` prefix. Keep this\n // in sync with AGENT_CHAT_DURABLE_BACKGROUND_ENV.\n //\n // DEFAULT-OFF (opt-in): durable background runs are still being hardened. A\n // premature fleet-wide default-on caused real-user incidents (Assets/Analytics\n // hit \"Failed to dispatch\" + stalls, 2026-06-24) because the async background\n // worker path is not yet proven end-to-end and the deploy-time env opt-out is\n // not reliably baked into a given deploy. So an unset/empty/unknown flag means\n // OFF; an app opts IN only with an explicit truthy value\n // (AGENT_CHAT_DURABLE_BACKGROUND=true). This still composes with the hosted +\n // A2A_SECRET gates below. Flip back to default-on only after the 15-min\n // background-function worker is verified live in production (see the\n // project_durable_bg_prod_verified memory).\n const raw = process.env.AGENT_CHAT_DURABLE_BACKGROUND;\n if (raw == null) return false;\n const normalized = raw.trim().toLowerCase();\n return (\n normalized === \"1\" ||\n normalized === \"true\" ||\n normalized === \"yes\" ||\n normalized === \"on\"\n );\n}\n\nfunction isFlagExplicitlyDisabled(): boolean {\n const raw = process.env.AGENT_CHAT_DURABLE_BACKGROUND;\n if (raw == null) return false;\n const normalized = raw.trim().toLowerCase();\n return (\n normalized === \"0\" ||\n normalized === \"false\" ||\n normalized === \"no\" ||\n normalized === \"off\"\n );\n}\n\n/**\n * The single gate. True when the env flag is explicitly enabled, or a workspace\n * app opted in and has a per-app background-function target, AND the runtime is\n * hosted AND A2A_SECRET is configured. False otherwise — and false means the\n * current synchronous behavior is used unchanged. Single-template Netlify app\n * opt-ins deliberately require the env flag too because that flag controls\n * whether the `server-agent-background` function exists in the deploy output.\n */\nexport function isAgentChatDurableBackgroundEnabled(options?: {\n appOptIn?: boolean;\n}): boolean {\n // An app-level opt-out must win over a stale deploy-wide env flag. Netlify\n // environment variables can outlive the source config that originally set\n // them; allowing that flag to re-enable a worker an app explicitly disabled\n // recreates the missing-background-function failure this gate is meant to\n // prevent.\n if (options?.appOptIn === false) return false;\n const envOptIn = isFlagEnabled();\n const workspaceAppOptIn =\n options?.appOptIn === true &&\n !isFlagExplicitlyDisabled() &&\n resolveWorkspaceBackgroundFunctionUrlPath() !== null;\n return (\n (envOptIn || workspaceAppOptIn) &&\n isHostedRuntimeForDurableBackground() &&\n hasConfiguredA2ASecret()\n );\n}\n\n/**\n * Env flag for the FOREGROUND server-driven self-chain. DEFAULT-OFF: a hosted\n * app must explicitly opt in with a truthy value (`true`/`1`/`yes`/`on`). A\n * regular Netlify function has a fixed 60-second wall, and a self-dispatched\n * successor can otherwise be killed before it persists its next continuation.\n * Keep this separate from `AGENT_CHAT_DURABLE_BACKGROUND` so the experimental\n * regular-function chain can be enabled independently after its deployment is\n * proven safe.\n */\nexport const AGENT_CHAT_FOREGROUND_SELF_CHAIN_ENV =\n \"AGENT_CHAT_FOREGROUND_SELF_CHAIN\";\n\nfunction isForegroundSelfChainExplicitlyEnabled(): boolean {\n // Read the literal key (not `process.env[CONST]`) so guard:no-env-credentials\n // can statically verify it against the allowlisted `AGENT_*` prefix. Keep this\n // in sync with AGENT_CHAT_FOREGROUND_SELF_CHAIN_ENV.\n const raw = process.env.AGENT_CHAT_FOREGROUND_SELF_CHAIN;\n if (raw == null) return false;\n const normalized = raw.trim().toLowerCase();\n return (\n normalized === \"1\" ||\n normalized === \"true\" ||\n normalized === \"yes\" ||\n normalized === \"on\"\n );\n}\n\n/**\n * Gate for the foreground self-chain: a normal (non-durable-background)\n * agent-chat turn that hits its soft-timeout chunk boundary continues via a\n * server-side self-dispatch on the REGULAR function (not a Netlify\n * `-background` function) instead of depending on the client to re-POST\n * `auto_continue`. Composes exactly like `isAgentChatDurableBackgroundEnabled`:\n * true only when the env flag is explicitly truthy, the runtime is hosted, and\n * `A2A_SECRET` is configured (the HMAC handoff authenticates the dispatch).\n * False means the existing client-driven `auto_continue` re-POST path is used.\n *\n * Deliberately independent of `isAgentChatDurableBackgroundEnabled`: an app can\n * use this narrower capability without opting into the full 15-min\n * background-function worker path, and the two gates never need to agree.\n * When BOTH would be true for a given run, the durable-background dispatch\n * decision in `production-agent.ts` is evaluated first and takes precedence —\n * a run already dispatched to the durable background worker chains via the\n * existing `isBackgroundWorker` path, not this one.\n */\nexport function isAgentChatForegroundSelfChainEnabled(): boolean {\n return (\n isForegroundSelfChainExplicitlyEnabled() &&\n isHostedRuntimeForDurableBackground() &&\n hasConfiguredA2ASecret()\n );\n}\n\n/** Decision returned by `prepareProcessRunRequest`. */\nexport type ProcessRunPreparation =\n | {\n ok: true;\n /** The pre-claimed run id the background worker must reuse. */\n runId: string;\n /** Body to stash for the re-entered handler (marker guaranteed present). */\n body: Record<string, unknown>;\n }\n | {\n ok: false;\n /** HTTP status the route should return. */\n status: number;\n /** Error payload. */\n error: string;\n /**\n * The run id parsed from the body, when present. Carried even on failure\n * so the route can RECORD the auth/validation failure ONTO the run\n * (diag_stage) before returning the error status — otherwise a 401/503 in\n * the unreadable Netlify background function would leave the run to time\n * out with no clue why. Null when no run id could be parsed.\n */\n runId: string | null;\n };\n\n/**\n * Parse the run id from a `_process-run` request body without authenticating.\n * Mirrors the precedence in `prepareProcessRunRequest` (marker.runId, then\n * top-level taskId). Returns null when neither is a usable string. Used so the\n * route can attach a diagnostic to the run even on an auth/validation failure.\n */\nexport function extractProcessRunId(body: unknown): string | null {\n if (!body || typeof body !== \"object\") return null;\n const record = body as Record<string, unknown>;\n const marker = record[AGENT_CHAT_BACKGROUND_RUN_FIELD] as\n | { runId?: unknown }\n | undefined;\n if (marker && typeof marker.runId === \"string\" && marker.runId) {\n return marker.runId;\n }\n if (typeof record.taskId === \"string\" && record.taskId) {\n return record.taskId;\n }\n return null;\n}\n\n/**\n * Pure, transport-agnostic core of the `_process-run` route: validate the body,\n * authenticate the HMAC self-dispatch, and produce the body the re-entered\n * agent-chat handler should run as the background worker.\n *\n * Auth policy mirrors the agent-teams processor exactly:\n * - `A2A_SECRET` set → require a valid `verifyInternalToken(runId, token)`.\n * - no secret → require `isTrustedLocalRuntime({ loopback })` (see\n * auth-policy.ts): refuse (503) unless `A2A_ALLOW_UNSIGNED_INTERNAL=1` is\n * set. This function has no h3 `event` of its own, so callers that CAN\n * see the inbound socket peer (the route handler, which has the event)\n * should compute `loopback` from it and pass it through; callers that\n * can't determine the peer address should omit it (defaults to `false`\n * — never trust unsigned dispatch without an explicit opt-in).\n *\n * Extracted from the route handler so the auth + marker-prep decision is unit\n * testable without booting the whole Nitro plugin. The route only adds body\n * reading and the final handler invocation around this.\n */\nexport function prepareProcessRunRequest(\n body: unknown,\n authHeader: string | undefined,\n loopback: boolean = false,\n): ProcessRunPreparation {\n if (!body || typeof body !== \"object\") {\n return {\n ok: false,\n status: 400,\n error: \"Invalid request body\",\n runId: null,\n };\n }\n const record = body as Record<string, unknown>;\n const marker = record[AGENT_CHAT_BACKGROUND_RUN_FIELD] as\n | { runId?: unknown }\n | undefined;\n const runId =\n marker && typeof marker.runId === \"string\"\n ? marker.runId\n : typeof record.taskId === \"string\"\n ? (record.taskId as string)\n : \"\";\n if (!runId) {\n return { ok: false, status: 400, error: \"runId required\", runId: null };\n }\n\n if (hasConfiguredA2ASecret()) {\n const token = extractBearerToken(authHeader);\n if (!verifyInternalToken(runId, token ?? \"\")) {\n return {\n ok: false,\n status: 401,\n error: \"Invalid or expired processor token\",\n runId,\n };\n }\n } else if (!isTrustedLocalRuntime({ loopback })) {\n // Callers that can see the h3 `event` (the route handler) pass the real\n // loopback signal; callers without one default to non-loopback. Unsigned\n // dispatch is still allowed via A2A_ALLOW_UNSIGNED_INTERNAL=1 for trusted\n // local/dev setups; see auth-policy.ts `isTrustedLocalRuntime`.\n return {\n ok: false,\n status: 503,\n error:\n \"Agent chat background processor not configured — set A2A_SECRET on this deployment (or A2A_ALLOW_UNSIGNED_INTERNAL=1 for trusted local dev).\",\n runId,\n };\n }\n\n // Ensure the marker is present so the re-entered handler runs as the\n // background worker (reuses runId/turnId, no re-claim, no re-dispatch).\n if (!marker || typeof marker.runId !== \"string\") {\n record[AGENT_CHAT_BACKGROUND_RUN_FIELD] = { runId };\n }\n return { ok: true, runId, body: record };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"durable-background.js","sourceRoot":"","sources":["../../src/agent/durable-background.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,mCAAmC,CAAC;AAE3C;;;;GAIG;AACH,MAAM,CAAC,MAAM,2BAA2B,GACtC,wCAAwC,CAAC;AAE3C;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,yBAAyB,CAAC;AAExE;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,kCAAkC,GAAG,uBAAuB,8BAA8B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CAAC;IAED,IAAI,sBAAsB,EAAE,EAAE,CAAC;QAC7B,MAAM,KAAK,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;QAC7C,IAAI,CAAC,mBAAmB,CAAC,KAAK,EAAE,KAAK,IAAI,EAAE,CAAC,EAAE,CAAC;YAC7C,OAAO;gBACL,EAAE,EAAE,KAAK;gBACT,MAAM,EAAE,GAAG;gBACX,KAAK,EAAE,oCAAoC;gBAC3C,KAAK;aACN,CAAC;QACJ,CAAC;IACH,CAAC;SAAM,IAAI,CAAC,qBAAqB,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC;QAChD,wEAAwE;QACxE,yEAAyE;QACzE,0EAA0E;QAC1E,gEAAgE;QAChE,OAAO;YACL,EAAE,EAAE,KAAK;YACT,MAAM,EAAE,GAAG;YACX,KAAK,EACH,8IAA8I;YAChJ,KAAK;SACN,CAAC;IACJ,CAAC;IAED,qEAAqE;IACrE,wEAAwE;IACxE,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ,EAAE,CAAC;QAChD,MAAM,CAAC,+BAA+B,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC;IACtD,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAC3C,CAAC","sourcesContent":["/**\n * Durable background agent-chat runs (Netlify background functions).\n *\n * Off by default. When enabled, a long in-app agent-chat turn is dispatched\n * into a Netlify *background* function (15-min budget) instead of completing\n * synchronously under the ~40s soft-timeout. The foreground POST claims the\n * run slot, inserts the run row, fires an HMAC-signed self-dispatch to\n * `AGENT_CHAT_PROCESS_RUN_PATH`, and returns the existing SSE subscription so\n * the client streams the same events (via the cross-isolate SQL-poll path)\n * with no client change.\n *\n * This module owns ONLY the gating decision + shared constants so both the\n * HTTP handler (`production-agent.ts`) and the processor route\n * (`agent-chat-plugin.ts`) agree on when the path is active without a circular\n * import. The actual run machinery is reused verbatim from run-manager /\n * run-store / self-dispatch / internal-token.\n *\n * GUARDRAIL: when `isAgentChatDurableBackgroundEnabled()` returns false, the\n * agent-chat handler must behave byte-for-byte like the current synchronous\n * path. The gate is true only when ALL of these hold:\n * 1. `AGENT_CHAT_DURABLE_BACKGROUND` env is explicitly enabled, or a\n * workspace app's agent-chat plugin opts in with `durableBackgroundRuns`\n * where the workspace deploy emits a per-app background function by\n * default. Single-template Netlify deploys must set the env flag because\n * that same flag controls whether `server-agent-background` is emitted.\n * 2. The runtime is hosted/serverless (local dev keeps the inline path so SSE\n * stays a single live stream and no second function is needed).\n * 3. `A2A_SECRET` is configured (the HMAC handoff is required to authenticate\n * the background dispatch; without it the dispatch can't be trusted).\n *\n * Opt-in keeps the blast radius small while the worker path is still being\n * proven. And even when enabled, a *dispatch failure degrades to an inline run*:\n * if the self-dispatch self-POST can't be delivered (fast connection error or\n * fast non-2xx), the foreground handler runs the turn synchronously instead of\n * erroring (see `production-agent.ts` — the inline fallback claims the run row\n * atomically so a delayed delivery can never double-execute). So an app where\n * durable dispatch happens to fail still gets a working chat, just without the\n * 15-min budget.\n */\nimport {\n hasConfiguredA2ASecret,\n isTrustedLocalRuntime,\n} from \"../a2a/auth-policy.js\";\nimport {\n extractBearerToken,\n verifyInternalToken,\n} from \"../integrations/internal-token.js\";\n\n/**\n * Framework route the background function actually runs — sibling to\n * `AGENT_TEAM_PROCESS_RUN_PATH`. Reached *through* the Netlify background\n * function, so it inherits the 15-min budget.\n */\nexport const AGENT_CHAT_PROCESS_RUN_PATH =\n \"/_agent-native/agent-chat/_process-run\";\n\n/**\n * Name of the standalone Netlify background function the build emits (see\n * `emitSingleTemplateNetlifyBackgroundFunction` in deploy/build.ts). Shared so\n * the emit and the dispatch-path helper below can never drift on the name.\n *\n * MUST end in `-background` — both because that is the conventional Netlify\n * async-function suffix and because `isInBackgroundFunctionRuntime()` reads the\n * `AWS_LAMBDA_FUNCTION_NAME` `-background` suffix as a secondary runtime signal.\n */\nexport const AGENT_BACKGROUND_FUNCTION_NAME = \"server-agent-background\";\n\n/**\n * Default function URL of the background function on Netlify. Every Netlify\n * function is reachable at `/.netlify/functions/<name>` BY DEFAULT; that default\n * url is removed ONLY if the function declares a custom `config.path`. The\n * emitted background function declares NO custom `config.path` (it sets\n * `background: true` and nothing else routing-related), so it KEEPS this default\n * url — and the Nitro `server` function already excludes `/.netlify/*` from its\n * `/*` catch-all, so this namespace is never shadowed. The foreground therefore\n * dispatches HERE on hosted Netlify (see `resolveAgentChatProcessRunDispatchPath`).\n */\nexport const AGENT_BACKGROUND_FUNCTION_URL_PATH = `/.netlify/functions/${AGENT_BACKGROUND_FUNCTION_NAME}`;\n\n/**\n * Marker carried in a Netlify background-function body when the shared\n * long-running worker should route to a processor other than agent chat.\n * The emitted wrapper defaults to the normal agent-chat `_process-run` route;\n * A2A uses this marker to reuse the same 15-minute function for async tasks.\n */\nexport const AGENT_BACKGROUND_PROCESSOR_FIELD = \"__agentNativeProcessor\";\nexport const AGENT_BACKGROUND_PROCESSOR_A2A = \"a2a\";\nexport const AGENT_BACKGROUND_PROCESSOR_INTEGRATION = \"integration\";\nexport const AGENT_BACKGROUND_PROCESSOR_ROUTE = \"route\";\nexport const AGENT_BACKGROUND_PROCESSOR_ROUTE_FIELD =\n \"__agentNativeProcessorRoute\";\n\n/**\n * The per-app workspace background function URL path. Workspace deploy emits one\n * background function per app named `<app>-agent-background`, reachable at its\n * DEFAULT url `/.netlify/functions/<app>-agent-background` (no custom\n * `config.path`). The foreground resolves the current workspace app id from\n * `AGENT_NATIVE_WORKSPACE_APP_ID` (set by the workspace function entry) so it can\n * dispatch to the right per-app function url. Returns `null` when no workspace\n * app id is configured (single-template deploy).\n */\nfunction resolveWorkspaceBackgroundFunctionUrlPath(): string | null {\n const raw = process.env.AGENT_NATIVE_WORKSPACE_APP_ID;\n if (typeof raw !== \"string\") return null;\n // Mirror the workspace app-id normalization (resources/store.ts): take the\n // first path segment and accept only the safe slug shape used for function\n // names. Anything else falls back to the single-template name.\n const candidate = raw.trim().replace(/^\\/+/, \"\").split(\"/\")[0] ?? \"\";\n if (!/^[a-z0-9][a-z0-9-]{0,127}$/.test(candidate)) return null;\n return `/.netlify/functions/${candidate}-agent-background`;\n}\n\nfunction isNetlifyHostedRuntimeForDispatch(): boolean {\n if (process.env.NETLIFY_LOCAL === \"true\") return false;\n if (process.env.NETLIFY === \"false\") return false;\n if (process.env.NETLIFY && process.env.NETLIFY !== \"false\") return true;\n // Netlify sets AWS Lambda runtime env on deployed Functions, but the build-time\n // NETLIFY flag is not always present in the runtime isolate. Treat Lambda as\n // Netlify here unless Netlify was explicitly disabled above; non-Netlify AWS\n // falls back inline if the /.netlify/functions dispatch fast-fails.\n return Boolean(process.env.AWS_LAMBDA_FUNCTION_NAME);\n}\n\n/**\n * Resolve the path the foreground POST should self-dispatch the chat background\n * worker to.\n *\n * GROUNDED IN THE REAL NETLIFY BUILD OUTPUT + THE NETLIFY DOCS DEFAULT-URL RULE:\n * the background function is emitted INTO the scanned dir\n * (`.netlify/functions-internal/server-agent-background`, or per-app\n * `<app>-agent-background` for workspaces) with `export const config = {\n * background: true, ... }` and NO custom `config.path`. Because it has no custom\n * path, Netlify keeps its DEFAULT function url `/.netlify/functions/<name>`, and\n * `background: true` makes any invocation of that url ASYNC (immediate 202,\n * 15-min budget). The Nitro `server` function already excludes `/.netlify/*`\n * from its `/*` catch-all, so the default-url namespace is NEVER shadowed by the\n * synchronous function.\n *\n * Therefore on hosted Netlify the foreground dispatches to the function's DEFAULT\n * url (`/.netlify/functions/<name>`); the function entry then rewrites the\n * incoming pathname to `AGENT_CHAT_PROCESS_RUN_PATH` (base-path-prefixed for\n * workspaces) before delegating to the Nitro router, so the `_process-run`\n * plugin runs with the async 15-min budget. Everywhere else (local dev, `netlify\n * dev`, non-Netlify hosts where no second function exists) there is no second\n * function, so the foreground dispatches to the framework route\n * `AGENT_CHAT_PROCESS_RUN_PATH` and the same in-process catch-all handles it\n * inline. The HMAC token (signed over the runId) is unchanged either way.\n *\n * NOTE: this is the DOC-CORRECT approach. An earlier attempt gave the function a\n * custom `config.path` + a catch-all `excludedPath` patch; the custom path was\n * NOT honored as a route in prod (probe → 404). Using the default function url\n * (no custom path) is what Netlify documents and is simpler — there is nothing\n * to shadow because `/.netlify/*` is already excluded from the `server` catch-all.\n */\nexport function resolveAgentChatProcessRunDispatchPath(): string {\n if (isNetlifyHostedRuntimeForDispatch()) {\n return (\n resolveWorkspaceBackgroundFunctionUrlPath() ??\n AGENT_BACKGROUND_FUNCTION_URL_PATH\n );\n }\n return AGENT_CHAT_PROCESS_RUN_PATH;\n}\n\nexport function resolveDurableBackgroundDispatchPath(\n fallbackPath: string,\n): string {\n if (isNetlifyHostedRuntimeForDispatch()) {\n return (\n resolveWorkspaceBackgroundFunctionUrlPath() ??\n AGENT_BACKGROUND_FUNCTION_URL_PATH\n );\n }\n return fallbackPath;\n}\n\nexport function dispatchPathTargetsNetlifyBackgroundFunction(\n dispatchPath: string,\n): boolean {\n return dispatchPath.startsWith(\"/.netlify/functions/\");\n}\n\n/**\n * Env flag for durable background runs. DEFAULT-OFF (opt-in): unset means\n * disabled; an app opts IN with an explicit truthy value (`true`/`1`/`yes`/`on`).\n */\nexport const AGENT_CHAT_DURABLE_BACKGROUND_ENV =\n \"AGENT_CHAT_DURABLE_BACKGROUND\";\n\n/**\n * Body field the foreground handler injects when self-dispatching to the\n * background processor. Its presence is how the re-entered handler knows it is\n * the background worker (run inline with the background soft-timeout; do NOT\n * re-claim the slot or re-dispatch). Untrusted on its own — the route also\n * verifies the HMAC token before invoking the handler.\n */\nexport const AGENT_CHAT_BACKGROUND_RUN_FIELD = \"__backgroundRun\";\n\n/**\n * Mirror of run-manager's private `isHostedRuntime`. Kept in sync deliberately:\n * the durable-background gate must agree with the soft-timeout regime about\n * what \"hosted\" means.\n */\nexport function isHostedRuntimeForDurableBackground(): boolean {\n if (\n process.env.NETLIFY &&\n process.env.NETLIFY !== \"false\" &&\n process.env.NETLIFY_LOCAL !== \"true\"\n ) {\n return true;\n }\n if (\n process.env.AWS_LAMBDA_FUNCTION_NAME &&\n process.env.NETLIFY_LOCAL !== \"true\"\n ) {\n return true;\n }\n return Boolean(\n process.env.CF_PAGES ||\n process.env.VERCEL ||\n process.env.VERCEL_ENV ||\n process.env.RENDER ||\n process.env.FLY_APP_NAME ||\n process.env.K_SERVICE,\n );\n}\n\n/**\n * True when THIS process is actually executing inside a Netlify *background*\n * function (the long, 15-min-budget async function whose deployed name ends in\n * `-background`). Netlify runs functions on AWS Lambda and sets\n * `AWS_LAMBDA_FUNCTION_NAME` to the function's name, so a `-background` suffix is\n * the runtime proof that the ~60s synchronous wall does NOT apply here.\n *\n * This is the SAFETY GUARD for the soft-timeout regime. The `_process-run`\n * self-dispatch worker (`isBackgroundWorker`) is NOT enough on its own: if the\n * `-background` function was never emitted (deploy gate off, or Netlify routed\n * the path to the synchronous function), the self-POST lands on the regular\n * ~60s `server` function. A worker there MUST use the 40s soft-timeout and\n * checkpoint before the 60s wall — using the ~13min budget would overshoot the\n * hard wall and get killed at 60s, then re-dispatch/resume in a wasteful loop.\n * So the 13-min budget is taken ONLY when this returns true.\n *\n * The PRIMARY signal is a `globalThis` marker the emitted background function's\n * entry sets at cold start — the deployed Lambda name is not guaranteed to end\n * in `-background` on Netlify, so the entry marks its own runtime. A `globalThis`\n * flag (not `process.env`) keeps the no-env-mutation guard satisfied and carries\n * no cross-request state (set once per isolate). The `AWS_LAMBDA_FUNCTION_NAME`\n * suffix and the explicit `AGENT_CHAT_FORCE_BACKGROUND_RUNTIME` env (truthy) are\n * additional signals — the latter an operator escape hatch. Off by default.\n */\nexport function isInBackgroundFunctionRuntime(): boolean {\n // Set by the emitted `-background` function entry at cold start (the primary,\n // most reliable signal — see the emit in deploy/build.ts).\n if (\n (globalThis as Record<string, unknown>)\n .__AGENT_NATIVE_BACKGROUND_RUNTIME__ === true\n ) {\n return true;\n }\n const lambdaName = process.env.AWS_LAMBDA_FUNCTION_NAME;\n if (\n typeof lambdaName === \"string\" &&\n lambdaName.toLowerCase().endsWith(\"-background\")\n ) {\n return true;\n }\n const forced = process.env.AGENT_CHAT_FORCE_BACKGROUND_RUNTIME;\n if (forced != null) {\n const v = forced.trim().toLowerCase();\n return v === \"1\" || v === \"true\" || v === \"yes\" || v === \"on\";\n }\n return false;\n}\n\nexport function backgroundRunMarkerExpectsBackgroundRuntime(\n marker: unknown,\n): boolean {\n return (\n typeof marker === \"object\" &&\n marker !== null &&\n (marker as { backgroundFunctionRuntimeExpected?: unknown })\n .backgroundFunctionRuntimeExpected === true\n );\n}\n\nexport function shouldUseBackgroundFunctionTimeoutForWorker(\n _marker: unknown,\n): boolean {\n // The dispatch marker says which URL the foreground targeted, not where the\n // request actually landed. Only the worker runtime proof can safely lift the\n // hosted 40s clamp to the 15-minute background-function budget.\n return isInBackgroundFunctionRuntime();\n}\n\nexport function backgroundRuntimeDiagnosticDetail(marker: unknown): string {\n return [\n `markerExpected=${backgroundRunMarkerExpectsBackgroundRuntime(marker)}`,\n `runtimeDetected=${isInBackgroundFunctionRuntime()}`,\n `globalMarker=${(globalThis as Record<string, unknown>).__AGENT_NATIVE_BACKGROUND_RUNTIME__ === true}`,\n `lambdaNameEndsBackground=${typeof process.env.AWS_LAMBDA_FUNCTION_NAME === \"string\" && process.env.AWS_LAMBDA_FUNCTION_NAME.toLowerCase().endsWith(\"-background\")}`,\n `forceEnv=${typeof process.env.AGENT_CHAT_FORCE_BACKGROUND_RUNTIME === \"string\" && process.env.AGENT_CHAT_FORCE_BACKGROUND_RUNTIME.trim().length > 0}`,\n ].join(\" \");\n}\n\nfunction isFlagEnabled(): boolean {\n // Read the literal key (not `process.env[CONST]`) so guard:no-env-credentials\n // can statically verify it against the allowlisted `AGENT_*` prefix. Keep this\n // in sync with AGENT_CHAT_DURABLE_BACKGROUND_ENV.\n //\n // DEFAULT-OFF (opt-in): durable background runs are still being hardened. A\n // premature fleet-wide default-on caused real-user incidents (Assets/Analytics\n // hit \"Failed to dispatch\" + stalls, 2026-06-24) because the async background\n // worker path is not yet proven end-to-end and the deploy-time env opt-out is\n // not reliably baked into a given deploy. So an unset/empty/unknown flag means\n // OFF; an app opts IN only with an explicit truthy value\n // (AGENT_CHAT_DURABLE_BACKGROUND=true). This still composes with the hosted +\n // A2A_SECRET gates below. Flip back to default-on only after the 15-min\n // background-function worker is verified live in production (see the\n // project_durable_bg_prod_verified memory).\n const raw = process.env.AGENT_CHAT_DURABLE_BACKGROUND;\n if (raw == null) return false;\n const normalized = raw.trim().toLowerCase();\n return (\n normalized === \"1\" ||\n normalized === \"true\" ||\n normalized === \"yes\" ||\n normalized === \"on\"\n );\n}\n\nfunction isFlagExplicitlyDisabled(): boolean {\n const raw = process.env.AGENT_CHAT_DURABLE_BACKGROUND;\n if (raw == null) return false;\n const normalized = raw.trim().toLowerCase();\n return (\n normalized === \"0\" ||\n normalized === \"false\" ||\n normalized === \"no\" ||\n normalized === \"off\"\n );\n}\n\n/**\n * The single gate. True when the env flag is explicitly enabled, or a workspace\n * app opted in and has a per-app background-function target, AND the runtime is\n * hosted AND A2A_SECRET is configured. False otherwise — and false means the\n * current synchronous behavior is used unchanged. Single-template Netlify app\n * opt-ins deliberately require the env flag too because that flag controls\n * whether the `server-agent-background` function exists in the deploy output.\n */\nexport function isAgentChatDurableBackgroundEnabled(options?: {\n appOptIn?: boolean;\n}): boolean {\n // An app-level opt-out must win over a stale deploy-wide env flag. Netlify\n // environment variables can outlive the source config that originally set\n // them; allowing that flag to re-enable a worker an app explicitly disabled\n // recreates the missing-background-function failure this gate is meant to\n // prevent.\n if (options?.appOptIn === false) return false;\n const envOptIn = isFlagEnabled();\n const workspaceAppOptIn =\n options?.appOptIn === true &&\n !isFlagExplicitlyDisabled() &&\n resolveWorkspaceBackgroundFunctionUrlPath() !== null;\n return (\n (envOptIn || workspaceAppOptIn) &&\n isHostedRuntimeForDurableBackground() &&\n hasConfiguredA2ASecret()\n );\n}\n\n/**\n * Env flag for the FOREGROUND server-driven self-chain. DEFAULT-OFF: a hosted\n * app must explicitly opt in with a truthy value (`true`/`1`/`yes`/`on`). A\n * regular Netlify function has a fixed 60-second wall, and a self-dispatched\n * successor can otherwise be killed before it persists its next continuation.\n * Keep this separate from `AGENT_CHAT_DURABLE_BACKGROUND` so the experimental\n * regular-function chain can be enabled independently after its deployment is\n * proven safe.\n */\nexport const AGENT_CHAT_FOREGROUND_SELF_CHAIN_ENV =\n \"AGENT_CHAT_FOREGROUND_SELF_CHAIN\";\n\nfunction isForegroundSelfChainExplicitlyEnabled(): boolean {\n // Read the literal key (not `process.env[CONST]`) so guard:no-env-credentials\n // can statically verify it against the allowlisted `AGENT_*` prefix. Keep this\n // in sync with AGENT_CHAT_FOREGROUND_SELF_CHAIN_ENV.\n const raw = process.env.AGENT_CHAT_FOREGROUND_SELF_CHAIN;\n if (raw == null) return false;\n const normalized = raw.trim().toLowerCase();\n return (\n normalized === \"1\" ||\n normalized === \"true\" ||\n normalized === \"yes\" ||\n normalized === \"on\"\n );\n}\n\n/**\n * Gate for the foreground self-chain: a normal (non-durable-background)\n * agent-chat turn that hits its soft-timeout chunk boundary continues via a\n * server-side self-dispatch on the REGULAR function (not a Netlify\n * `-background` function) instead of depending on the client to re-POST\n * `auto_continue`. Composes exactly like `isAgentChatDurableBackgroundEnabled`:\n * true only when the env flag is explicitly truthy, the runtime is hosted, and\n * `A2A_SECRET` is configured (the HMAC handoff authenticates the dispatch).\n * False means the existing client-driven `auto_continue` re-POST path is used.\n *\n * Deliberately independent of `isAgentChatDurableBackgroundEnabled`: an app can\n * use this narrower capability without opting into the full 15-min\n * background-function worker path, and the two gates never need to agree.\n * When BOTH would be true for a given run, the durable-background dispatch\n * decision in `production-agent.ts` is evaluated first and takes precedence —\n * a run already dispatched to the durable background worker chains via the\n * existing `isBackgroundWorker` path, not this one.\n */\nexport function isAgentChatForegroundSelfChainEnabled(): boolean {\n return (\n isForegroundSelfChainExplicitlyEnabled() &&\n isHostedRuntimeForDurableBackground() &&\n hasConfiguredA2ASecret()\n );\n}\n\n/** Decision returned by `prepareProcessRunRequest`. */\nexport type ProcessRunPreparation =\n | {\n ok: true;\n /** The pre-claimed run id the background worker must reuse. */\n runId: string;\n /** Body to stash for the re-entered handler (marker guaranteed present). */\n body: Record<string, unknown>;\n }\n | {\n ok: false;\n /** HTTP status the route should return. */\n status: number;\n /** Error payload. */\n error: string;\n /**\n * The run id parsed from the body, when present. Carried even on failure\n * so the route can RECORD the auth/validation failure ONTO the run\n * (diag_stage) before returning the error status — otherwise a 401/503 in\n * the unreadable Netlify background function would leave the run to time\n * out with no clue why. Null when no run id could be parsed.\n */\n runId: string | null;\n };\n\n/**\n * Parse the run id from a `_process-run` request body without authenticating.\n * Mirrors the precedence in `prepareProcessRunRequest` (marker.runId, then\n * top-level taskId). Returns null when neither is a usable string. Used so the\n * route can attach a diagnostic to the run even on an auth/validation failure.\n */\nexport function extractProcessRunId(body: unknown): string | null {\n if (!body || typeof body !== \"object\") return null;\n const record = body as Record<string, unknown>;\n const marker = record[AGENT_CHAT_BACKGROUND_RUN_FIELD] as\n | { runId?: unknown }\n | undefined;\n if (marker && typeof marker.runId === \"string\" && marker.runId) {\n return marker.runId;\n }\n if (typeof record.taskId === \"string\" && record.taskId) {\n return record.taskId;\n }\n return null;\n}\n\n/**\n * Pure, transport-agnostic core of the `_process-run` route: validate the body,\n * authenticate the HMAC self-dispatch, and produce the body the re-entered\n * agent-chat handler should run as the background worker.\n *\n * Auth policy mirrors the agent-teams processor exactly:\n * - `A2A_SECRET` set → require a valid `verifyInternalToken(runId, token)`.\n * - no secret → require `isTrustedLocalRuntime({ loopback })` (see\n * auth-policy.ts): refuse (503) unless `A2A_ALLOW_UNSIGNED_INTERNAL=1` is\n * set. This function has no h3 `event` of its own, so callers that CAN\n * see the inbound socket peer (the route handler, which has the event)\n * should compute `loopback` from it and pass it through; callers that\n * can't determine the peer address should omit it (defaults to `false`\n * — never trust unsigned dispatch without an explicit opt-in).\n *\n * Extracted from the route handler so the auth + marker-prep decision is unit\n * testable without booting the whole Nitro plugin. The route only adds body\n * reading and the final handler invocation around this.\n */\nexport function prepareProcessRunRequest(\n body: unknown,\n authHeader: string | undefined,\n loopback: boolean = false,\n): ProcessRunPreparation {\n if (!body || typeof body !== \"object\") {\n return {\n ok: false,\n status: 400,\n error: \"Invalid request body\",\n runId: null,\n };\n }\n const record = body as Record<string, unknown>;\n const marker = record[AGENT_CHAT_BACKGROUND_RUN_FIELD] as\n | { runId?: unknown }\n | undefined;\n const runId =\n marker && typeof marker.runId === \"string\"\n ? marker.runId\n : typeof record.taskId === \"string\"\n ? (record.taskId as string)\n : \"\";\n if (!runId) {\n return { ok: false, status: 400, error: \"runId required\", runId: null };\n }\n\n if (hasConfiguredA2ASecret()) {\n const token = extractBearerToken(authHeader);\n if (!verifyInternalToken(runId, token ?? \"\")) {\n return {\n ok: false,\n status: 401,\n error: \"Invalid or expired processor token\",\n runId,\n };\n }\n } else if (!isTrustedLocalRuntime({ loopback })) {\n // Callers that can see the h3 `event` (the route handler) pass the real\n // loopback signal; callers without one default to non-loopback. Unsigned\n // dispatch is still allowed via A2A_ALLOW_UNSIGNED_INTERNAL=1 for trusted\n // local/dev setups; see auth-policy.ts `isTrustedLocalRuntime`.\n return {\n ok: false,\n status: 503,\n error:\n \"Agent chat background processor not configured — set A2A_SECRET on this deployment (or A2A_ALLOW_UNSIGNED_INTERNAL=1 for trusted local dev).\",\n runId,\n };\n }\n\n // Ensure the marker is present so the re-entered handler runs as the\n // background worker (reuses runId/turnId, no re-claim, no re-dispatch).\n if (!marker || typeof marker.runId !== \"string\") {\n record[AGENT_CHAT_BACKGROUND_RUN_FIELD] = { runId };\n }\n return { ok: true, runId, body: record };\n}\n"]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Public exports for the pluggable agent engine system.
|
|
3
3
|
*/
|
|
4
4
|
export type { AgentEngine, EngineCapabilities, EngineTool, EngineMessage, EngineContentPart, EngineTextPart, EngineImagePart, EngineToolCallPart, EngineToolResultPart, EngineThinkingPart, EngineEvent, EngineStreamOptions, } from "./types.js";
|
|
5
|
-
export { registerAgentEngine, getAgentEngineEntry, listAgentEngines, resolveEngine, getConfiguredEngineNameForRequest, getStoredModelForEngine, normalizeModelForEngine, detectEngineFromEnv, detectEngineFromEnvForRequest, detectEngineFromUserSecrets, isAgentEngineSettingConfigured, isAgentEnginePackageInstalled, isStoredEngineUsable, isStoredEngineUsableForRequest, isResolvedEngineUsableForRequest, type AgentEngineEntry, type ResolveEngineConfig, } from "./registry.js";
|
|
5
|
+
export { registerAgentEngine, getAgentEngineEntry, listAgentEngines, resolveEngine, getConfiguredEngineNameForRequest, getStoredModelForEngine, normalizeModelForEngine, resolveEnginePreservesCustomModels, type NormalizeModelOptions, detectEngineFromEnv, detectEngineFromEnvForRequest, detectEngineFromUserSecrets, isAgentEngineSettingConfigured, isAgentEnginePackageInstalled, isStoredEngineUsable, isStoredEngineUsableForRequest, isResolvedEngineUsableForRequest, type AgentEngineEntry, type ResolveEngineConfig, } from "./registry.js";
|
|
6
6
|
export { createBuilderEngine, BUILDER_DEFAULT_MODEL, BUILDER_SUPPORTED_MODELS, BUILDER_CAPABILITIES, } from "./builder-engine.js";
|
|
7
7
|
export { createAnthropicEngine, ANTHROPIC_DEFAULT_MODEL, ANTHROPIC_SUPPORTED_MODELS, ANTHROPIC_CAPABILITIES, } from "./anthropic-engine.js";
|
|
8
8
|
export { createAISDKEngine, type AISDKProvider } from "./ai-sdk-engine.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,YAAY,EACV,WAAW,EACX,kBAAkB,EAClB,UAAU,EACV,aAAa,EACb,iBAAiB,EACjB,cAAc,EACd,eAAe,EACf,kBAAkB,EAClB,oBAAoB,EACpB,kBAAkB,EAClB,WAAW,EACX,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,iCAAiC,EACjC,uBAAuB,EACvB,uBAAuB,EACvB,mBAAmB,EACnB,6BAA6B,EAC7B,2BAA2B,EAC3B,8BAA8B,EAC9B,6BAA6B,EAC7B,oBAAoB,EACpB,8BAA8B,EAC9B,gCAAgC,EAChC,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,GACzB,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,0BAA0B,EAC1B,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,iBAAiB,EAAE,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,YAAY,EACV,WAAW,EACX,kBAAkB,EAClB,UAAU,EACV,aAAa,EACb,iBAAiB,EACjB,cAAc,EACd,eAAe,EACf,kBAAkB,EAClB,oBAAoB,EACpB,kBAAkB,EAClB,WAAW,EACX,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,iCAAiC,EACjC,uBAAuB,EACvB,uBAAuB,EACvB,kCAAkC,EAClC,KAAK,qBAAqB,EAC1B,mBAAmB,EACnB,6BAA6B,EAC7B,2BAA2B,EAC3B,8BAA8B,EAC9B,6BAA6B,EAC7B,oBAAoB,EACpB,8BAA8B,EAC9B,gCAAgC,EAChC,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,GACzB,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,0BAA0B,EAC1B,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,iBAAiB,EAAE,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Public exports for the pluggable agent engine system.
|
|
3
3
|
*/
|
|
4
|
-
export { registerAgentEngine, getAgentEngineEntry, listAgentEngines, resolveEngine, getConfiguredEngineNameForRequest, getStoredModelForEngine, normalizeModelForEngine, detectEngineFromEnv, detectEngineFromEnvForRequest, detectEngineFromUserSecrets, isAgentEngineSettingConfigured, isAgentEnginePackageInstalled, isStoredEngineUsable, isStoredEngineUsableForRequest, isResolvedEngineUsableForRequest, } from "./registry.js";
|
|
4
|
+
export { registerAgentEngine, getAgentEngineEntry, listAgentEngines, resolveEngine, getConfiguredEngineNameForRequest, getStoredModelForEngine, normalizeModelForEngine, resolveEnginePreservesCustomModels, detectEngineFromEnv, detectEngineFromEnvForRequest, detectEngineFromUserSecrets, isAgentEngineSettingConfigured, isAgentEnginePackageInstalled, isStoredEngineUsable, isStoredEngineUsableForRequest, isResolvedEngineUsableForRequest, } from "./registry.js";
|
|
5
5
|
export { createBuilderEngine, BUILDER_DEFAULT_MODEL, BUILDER_SUPPORTED_MODELS, BUILDER_CAPABILITIES, } from "./builder-engine.js";
|
|
6
6
|
export { createAnthropicEngine, ANTHROPIC_DEFAULT_MODEL, ANTHROPIC_SUPPORTED_MODELS, ANTHROPIC_CAPABILITIES, } from "./anthropic-engine.js";
|
|
7
7
|
export { createAISDKEngine } from "./ai-sdk-engine.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/agent/engine/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAiBH,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,iCAAiC,EACjC,uBAAuB,EACvB,uBAAuB,EACvB,mBAAmB,EACnB,6BAA6B,EAC7B,2BAA2B,EAC3B,8BAA8B,EAC9B,6BAA6B,EAC7B,oBAAoB,EACpB,8BAA8B,EAC9B,gCAAgC,GAGjC,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,0BAA0B,EAC1B,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,iBAAiB,EAAsB,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["/**\n * Public exports for the pluggable agent engine system.\n */\n\nexport type {\n AgentEngine,\n EngineCapabilities,\n EngineTool,\n EngineMessage,\n EngineContentPart,\n EngineTextPart,\n EngineImagePart,\n EngineToolCallPart,\n EngineToolResultPart,\n EngineThinkingPart,\n EngineEvent,\n EngineStreamOptions,\n} from \"./types.js\";\n\nexport {\n registerAgentEngine,\n getAgentEngineEntry,\n listAgentEngines,\n resolveEngine,\n getConfiguredEngineNameForRequest,\n getStoredModelForEngine,\n normalizeModelForEngine,\n detectEngineFromEnv,\n detectEngineFromEnvForRequest,\n detectEngineFromUserSecrets,\n isAgentEngineSettingConfigured,\n isAgentEnginePackageInstalled,\n isStoredEngineUsable,\n isStoredEngineUsableForRequest,\n isResolvedEngineUsableForRequest,\n type AgentEngineEntry,\n type ResolveEngineConfig,\n} from \"./registry.js\";\n\nexport {\n createBuilderEngine,\n BUILDER_DEFAULT_MODEL,\n BUILDER_SUPPORTED_MODELS,\n BUILDER_CAPABILITIES,\n} from \"./builder-engine.js\";\n\nexport {\n createAnthropicEngine,\n ANTHROPIC_DEFAULT_MODEL,\n ANTHROPIC_SUPPORTED_MODELS,\n ANTHROPIC_CAPABILITIES,\n} from \"./anthropic-engine.js\";\nexport { createAISDKEngine, type AISDKProvider } from \"./ai-sdk-engine.js\";\nexport { registerBuiltinEngines } from \"./builtin.js\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/agent/engine/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAiBH,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,iCAAiC,EACjC,uBAAuB,EACvB,uBAAuB,EACvB,kCAAkC,EAElC,mBAAmB,EACnB,6BAA6B,EAC7B,2BAA2B,EAC3B,8BAA8B,EAC9B,6BAA6B,EAC7B,oBAAoB,EACpB,8BAA8B,EAC9B,gCAAgC,GAGjC,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,0BAA0B,EAC1B,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,iBAAiB,EAAsB,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["/**\n * Public exports for the pluggable agent engine system.\n */\n\nexport type {\n AgentEngine,\n EngineCapabilities,\n EngineTool,\n EngineMessage,\n EngineContentPart,\n EngineTextPart,\n EngineImagePart,\n EngineToolCallPart,\n EngineToolResultPart,\n EngineThinkingPart,\n EngineEvent,\n EngineStreamOptions,\n} from \"./types.js\";\n\nexport {\n registerAgentEngine,\n getAgentEngineEntry,\n listAgentEngines,\n resolveEngine,\n getConfiguredEngineNameForRequest,\n getStoredModelForEngine,\n normalizeModelForEngine,\n resolveEnginePreservesCustomModels,\n type NormalizeModelOptions,\n detectEngineFromEnv,\n detectEngineFromEnvForRequest,\n detectEngineFromUserSecrets,\n isAgentEngineSettingConfigured,\n isAgentEnginePackageInstalled,\n isStoredEngineUsable,\n isStoredEngineUsableForRequest,\n isResolvedEngineUsableForRequest,\n type AgentEngineEntry,\n type ResolveEngineConfig,\n} from \"./registry.js\";\n\nexport {\n createBuilderEngine,\n BUILDER_DEFAULT_MODEL,\n BUILDER_SUPPORTED_MODELS,\n BUILDER_CAPABILITIES,\n} from \"./builder-engine.js\";\n\nexport {\n createAnthropicEngine,\n ANTHROPIC_DEFAULT_MODEL,\n ANTHROPIC_SUPPORTED_MODELS,\n ANTHROPIC_CAPABILITIES,\n} from \"./anthropic-engine.js\";\nexport { createAISDKEngine, type AISDKProvider } from \"./ai-sdk-engine.js\";\nexport { registerBuiltinEngines } from \"./builtin.js\";\n"]}
|
|
@@ -38,7 +38,38 @@ export declare function getAgentEngineEntry(name: string): AgentEngineEntry | un
|
|
|
38
38
|
/** List all registered engine entries */
|
|
39
39
|
export declare function listAgentEngines(): AgentEngineEntry[];
|
|
40
40
|
export declare function isAgentEnginePackageInstalled(entry: AgentEngineEntry): boolean;
|
|
41
|
-
export
|
|
41
|
+
export interface NormalizeModelOptions {
|
|
42
|
+
/**
|
|
43
|
+
* Force unrecognized (custom) model IDs to be kept verbatim, as if
|
|
44
|
+
* `engine.preserveCustomModels` were set on a live engine instance.
|
|
45
|
+
*
|
|
46
|
+
* The settings actions call `normalizeModelForEngine` with a static registry
|
|
47
|
+
* ENTRY, which never carries the runtime `preserveCustomModels` flag — that
|
|
48
|
+
* is only set on the engine INSTANCE created with an OpenAI-compatible
|
|
49
|
+
* `baseUrl`. They resolve the capability with
|
|
50
|
+
* {@link resolveEnginePreservesCustomModels} and pass it here so a gateway
|
|
51
|
+
* model (e.g. an Ollama `gemma4`) is not rewritten to the OpenAI default on
|
|
52
|
+
* save/read. First-party OpenAI (no gateway) leaves this unset, so an unknown
|
|
53
|
+
* or invalid model still normalizes to a supported one.
|
|
54
|
+
*/
|
|
55
|
+
preserveCustomModels?: boolean;
|
|
56
|
+
}
|
|
57
|
+
export declare function normalizeModelForEngine(engine: Pick<AgentEngine, "name" | "defaultModel" | "supportedModels" | "preserveCustomModels">, model: string | null | undefined, options?: NormalizeModelOptions): string;
|
|
58
|
+
/**
|
|
59
|
+
* Whether models saved or read for this engine ENTRY should be preserved
|
|
60
|
+
* verbatim instead of normalized against the built-in catalog.
|
|
61
|
+
*
|
|
62
|
+
* `normalizeModelForEngine` honors a live engine's `preserveCustomModels`, but
|
|
63
|
+
* that flag is only set on an AI SDK engine INSTANCE when the OpenAI provider
|
|
64
|
+
* is pointed at an OpenAI-compatible gateway (a custom base URL — e.g. Ollama
|
|
65
|
+
* Cloud or LiteLLM), whose model IDs are not in the built-in OpenAI catalog.
|
|
66
|
+
* The static registry entry the settings actions pass to
|
|
67
|
+
* `normalizeModelForEngine` cannot carry that runtime flag, so this async
|
|
68
|
+
* helper reproduces the same decision — `ai-sdk:openai` AND a resolved base URL
|
|
69
|
+
* — from the request's stored/deploy config. First-party OpenAI (no gateway)
|
|
70
|
+
* returns false so an unknown/invalid model still normalizes to a supported one.
|
|
71
|
+
*/
|
|
72
|
+
export declare function resolveEnginePreservesCustomModels(entry: Pick<AgentEngineEntry, "name">): Promise<boolean>;
|
|
42
73
|
/**
|
|
43
74
|
* First registered engine whose requiredEnvVars are all set. Registration
|
|
44
75
|
* order controls priority — the Builder gateway is registered first so it
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAiBH,OAAO,KAAK,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAIlE,MAAM,WAAW,gBAAgB;IAC/B,yEAAyE;IACzE,IAAI,EAAE,MAAM,CAAC;IACb,kCAAkC;IAClC,KA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55,41 @@ function packageNameFromInstallSpecifier(specifier) {
|
|
|
55
55
|
const versionIndex = trimmed.indexOf("@");
|
|
56
56
|
return versionIndex === -1 ? trimmed : trimmed.slice(0, versionIndex);
|
|
57
57
|
}
|
|
58
|
+
/**
|
|
59
|
+
* True only when there is positive evidence this module is executing from a
|
|
60
|
+
* bundled serverless function where optional dependencies were inlined into the
|
|
61
|
+
* bundle and are therefore NOT resolvable via `require.resolve` — even though
|
|
62
|
+
* the dynamic `import()` the engine uses to load them still works.
|
|
63
|
+
*
|
|
64
|
+
* Deliberately narrow. The Nitro Vercel/Netlify presets (which agent-native's
|
|
65
|
+
* own `deploy` command emits) inline optional peers and always set these env
|
|
66
|
+
* markers, so they are a reliable signal. Other serverless runtimes — a
|
|
67
|
+
* container on Cloud Run / Google Cloud Functions (`K_SERVICE` /
|
|
68
|
+
* `FUNCTION_TARGET`), or a plain AWS Lambda — commonly ship a real
|
|
69
|
+
* `node_modules` where `require.resolve` is authoritative; there a resolve miss
|
|
70
|
+
* means the package is genuinely absent and must NOT be masked. Those runtimes
|
|
71
|
+
* are still covered *when the code is actually bundled*, via the module-path
|
|
72
|
+
* check below, which stays false for a normal `node_modules` layout.
|
|
73
|
+
*/
|
|
74
|
+
function isBundledServerlessRuntime() {
|
|
75
|
+
const env = process.env;
|
|
76
|
+
// Nitro's Vercel/Netlify presets inline optional peers into the function
|
|
77
|
+
// bundle; these platforms always set these markers.
|
|
78
|
+
if (env.VERCEL || env.NETLIFY)
|
|
79
|
+
return true;
|
|
80
|
+
// Otherwise require direct evidence that this module is running from inside a
|
|
81
|
+
// bundle output directory (Vercel's `/var/task`, Nitro's `.output/server`,
|
|
82
|
+
// inlined `_libs`). This is the real signal that `require.resolve` cannot be
|
|
83
|
+
// trusted; it stays false for normal `node_modules` layouts (dev, tests, and
|
|
84
|
+
// container/Lambda/Cloud Run deploys that ship their dependencies), so a
|
|
85
|
+
// genuine "package not installed" miss still surfaces there.
|
|
86
|
+
try {
|
|
87
|
+
return /[\\/](?:_libs|\.vercel|\.netlify|\.output)[\\/]|\/var\/task\//.test(import.meta.url ?? "");
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
58
93
|
function canResolvePackage(packageName) {
|
|
59
94
|
const cached = _packageAvailabilityCache.get(packageName);
|
|
60
95
|
if (cached !== undefined)
|
|
@@ -65,7 +100,15 @@ function canResolvePackage(packageName) {
|
|
|
65
100
|
available = true;
|
|
66
101
|
}
|
|
67
102
|
catch {
|
|
68
|
-
|
|
103
|
+
// Bundled serverless runtimes (e.g. Nitro on Vercel/Netlify) inline optional
|
|
104
|
+
// provider packages into the function bundle, so require.resolve cannot find
|
|
105
|
+
// them even though the dynamic `import()` the engine actually uses to load
|
|
106
|
+
// them works. Treat them as available there and let the engine's own import
|
|
107
|
+
// be the real gate — it already fails with a clear "pnpm add …" message when
|
|
108
|
+
// the package is genuinely missing. Without this, every engine-usability
|
|
109
|
+
// gate rejects the AI-SDK engines at runtime and the agent silently falls
|
|
110
|
+
// back to the native Anthropic engine.
|
|
111
|
+
available = isBundledServerlessRuntime();
|
|
69
112
|
}
|
|
70
113
|
_packageAvailabilityCache.set(packageName, available);
|
|
71
114
|
return available;
|
|
@@ -121,12 +164,17 @@ function findLatestSupportedVersionMatch(candidate, supportedModels) {
|
|
|
121
164
|
}
|
|
122
165
|
return best?.model;
|
|
123
166
|
}
|
|
124
|
-
export function normalizeModelForEngine(engine, model) {
|
|
167
|
+
export function normalizeModelForEngine(engine, model, options = {}) {
|
|
125
168
|
const candidate = typeof model === "string" ? model.trim() : "";
|
|
126
169
|
if (!candidate)
|
|
127
170
|
return engine.defaultModel;
|
|
128
|
-
|
|
171
|
+
// Preserve custom IDs verbatim BEFORE any catalog/version matching, so a
|
|
172
|
+
// version-shaped gateway model that happens to share a family with a
|
|
173
|
+
// built-in model (e.g. `gpt-5.4` on an OpenAI-compatible endpoint) is not
|
|
174
|
+
// rewritten to a catalog entry.
|
|
175
|
+
if (engine.preserveCustomModels || options.preserveCustomModels) {
|
|
129
176
|
return candidate;
|
|
177
|
+
}
|
|
130
178
|
if (engine.supportedModels.length === 0)
|
|
131
179
|
return candidate;
|
|
132
180
|
if (candidate === "auto" || engine.supportedModels.includes(candidate)) {
|
|
@@ -135,6 +183,30 @@ export function normalizeModelForEngine(engine, model) {
|
|
|
135
183
|
return (findLatestSupportedVersionMatch(candidate, engine.supportedModels) ??
|
|
136
184
|
engine.defaultModel);
|
|
137
185
|
}
|
|
186
|
+
/**
|
|
187
|
+
* Whether models saved or read for this engine ENTRY should be preserved
|
|
188
|
+
* verbatim instead of normalized against the built-in catalog.
|
|
189
|
+
*
|
|
190
|
+
* `normalizeModelForEngine` honors a live engine's `preserveCustomModels`, but
|
|
191
|
+
* that flag is only set on an AI SDK engine INSTANCE when the OpenAI provider
|
|
192
|
+
* is pointed at an OpenAI-compatible gateway (a custom base URL — e.g. Ollama
|
|
193
|
+
* Cloud or LiteLLM), whose model IDs are not in the built-in OpenAI catalog.
|
|
194
|
+
* The static registry entry the settings actions pass to
|
|
195
|
+
* `normalizeModelForEngine` cannot carry that runtime flag, so this async
|
|
196
|
+
* helper reproduces the same decision — `ai-sdk:openai` AND a resolved base URL
|
|
197
|
+
* — from the request's stored/deploy config. First-party OpenAI (no gateway)
|
|
198
|
+
* returns false so an unknown/invalid model still normalizes to a supported one.
|
|
199
|
+
*/
|
|
200
|
+
export async function resolveEnginePreservesCustomModels(entry) {
|
|
201
|
+
if (entry.name !== "ai-sdk:openai")
|
|
202
|
+
return false;
|
|
203
|
+
try {
|
|
204
|
+
return Boolean(await resolveOpenAiBaseUrl());
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
138
210
|
function assertAgentEnginePackageInstalled(entry) {
|
|
139
211
|
if (isAgentEnginePackageInstalled(entry))
|
|
140
212
|
return;
|