@agent-native/core 0.90.9 → 0.90.11

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.
Files changed (132) hide show
  1. package/README.md +7 -28
  2. package/corpus/README.md +1 -1
  3. package/corpus/core/CHANGELOG.md +18 -0
  4. package/corpus/core/docs/content/agent-native-toolkit.mdx +1 -1
  5. package/corpus/core/docs/content/locales/ar-SA/agent-native-toolkit.mdx +1 -1
  6. package/corpus/core/docs/content/locales/ar-SA/tracking.mdx +3 -3
  7. package/corpus/core/docs/content/locales/de-DE/agent-native-toolkit.mdx +1 -1
  8. package/corpus/core/docs/content/locales/de-DE/tracking.mdx +3 -3
  9. package/corpus/core/docs/content/locales/es-ES/agent-native-toolkit.mdx +1 -1
  10. package/corpus/core/docs/content/locales/es-ES/tracking.mdx +3 -3
  11. package/corpus/core/docs/content/locales/fr-FR/agent-native-toolkit.mdx +1 -1
  12. package/corpus/core/docs/content/locales/fr-FR/tracking.mdx +3 -3
  13. package/corpus/core/docs/content/locales/hi-IN/agent-native-toolkit.mdx +1 -1
  14. package/corpus/core/docs/content/locales/hi-IN/tracking.mdx +3 -3
  15. package/corpus/core/docs/content/locales/ja-JP/agent-native-toolkit.mdx +1 -1
  16. package/corpus/core/docs/content/locales/ja-JP/tracking.mdx +3 -3
  17. package/corpus/core/docs/content/locales/ko-KR/agent-native-toolkit.mdx +1 -1
  18. package/corpus/core/docs/content/locales/ko-KR/tracking.mdx +3 -3
  19. package/corpus/core/docs/content/locales/pt-BR/agent-native-toolkit.mdx +1 -1
  20. package/corpus/core/docs/content/locales/pt-BR/tracking.mdx +3 -3
  21. package/corpus/core/docs/content/locales/zh-CN/agent-native-toolkit.mdx +1 -1
  22. package/corpus/core/docs/content/locales/zh-CN/tracking.mdx +3 -3
  23. package/corpus/core/docs/content/locales/zh-TW/agent-native-toolkit.mdx +1 -1
  24. package/corpus/core/docs/content/locales/zh-TW/tracking.mdx +3 -3
  25. package/corpus/core/docs/content/tracking.mdx +3 -3
  26. package/corpus/core/package.json +1 -1
  27. package/corpus/core/src/agent/durable-background.ts +5 -5
  28. package/corpus/core/src/agent/engine/ai-sdk-engine.ts +40 -8
  29. package/corpus/core/src/agent/engine/anthropic-engine.ts +25 -7
  30. package/corpus/core/src/agent/engine/output-tokens.ts +94 -0
  31. package/corpus/core/src/agent/production-agent.ts +46 -7
  32. package/corpus/core/src/agent/types.ts +3 -2
  33. package/corpus/core/src/client/analytics.ts +17 -3
  34. package/corpus/core/src/client/blocks/library/wireframe-kit.tsx +3 -1
  35. package/corpus/core/src/client/blocks/library/wireframe.tsx +6 -1
  36. package/corpus/core/src/db/client.ts +12 -9
  37. package/corpus/core/src/file-upload/builder.ts +10 -23
  38. package/corpus/core/src/file-upload/types.ts +3 -3
  39. package/corpus/core/src/shared/reasoning-effort.ts +23 -0
  40. package/corpus/core/src/styles/blocks.css +7 -0
  41. package/corpus/templates/analytics/.agents/skills/session-replay/SKILL.md +9 -4
  42. package/corpus/templates/analytics/app/components/dashboard/SqlChart.tsx +21 -7
  43. package/corpus/templates/analytics/app/entry.client.tsx +6 -1
  44. package/corpus/templates/analytics/app/pages/sessions/SessionsPage.tsx +1 -1
  45. package/corpus/templates/analytics/changelog/2026-07-07-analytics-now-recovers-from-stale-route-chunks-after-deploys.md +6 -0
  46. package/corpus/templates/analytics/changelog/2026-07-07-metric-dashboard-cards-now-show-warehouse-backed-numeric-val.md +6 -0
  47. package/corpus/templates/clips/actions/create-recording.ts +1 -1
  48. package/corpus/templates/clips/actions/finalize-recording.ts +2 -2
  49. package/corpus/templates/clips/actions/import-loom-recording.ts +1 -1
  50. package/corpus/templates/clips/actions/lib/ensure-seekable-video.ts +1 -1
  51. package/corpus/templates/clips/actions/regenerate-chapters.ts +7 -0
  52. package/corpus/templates/clips/app/hooks/use-auto-title.ts +15 -5
  53. package/corpus/templates/clips/app/routes/download.tsx +12 -4
  54. package/corpus/templates/clips/app/routes/r.$recordingId.tsx +1 -0
  55. package/corpus/templates/clips/changelog/2026-07-07-auto-generated-chapter-requests-now-open-the-matching-agent-.md +6 -0
  56. package/corpus/templates/clips/changelog/2026-07-07-clip-video-uploads-now-compress-in-the-background-while-keeping.md +6 -0
  57. package/corpus/templates/clips/changelog/2026-07-07-desktop-settings-and-fn-dictation-are-more-reliable.md +6 -0
  58. package/corpus/templates/clips/changelog/2026-07-07-desktop-settings-now-includes-a-manual-update-check-with-res.md +6 -0
  59. package/corpus/templates/clips/changelog/2026-07-07-the-clips-desktop-download-page-now-uses-the-agent-native-ap.md +6 -0
  60. package/corpus/templates/clips/desktop/src/app.tsx +95 -8
  61. package/corpus/templates/clips/desktop/src/lib/updater.ts +60 -43
  62. package/corpus/templates/clips/desktop/src/styles.css +5 -0
  63. package/corpus/templates/clips/desktop/src-tauri/src/shortcuts.rs +93 -23
  64. package/corpus/templates/dispatch/changelog/2026-07-07-overview-is-now-just-ask-dispatch-and-a-list-of-apps.md +6 -0
  65. package/dist/agent/durable-background.d.ts +1 -1
  66. package/dist/agent/durable-background.d.ts.map +1 -1
  67. package/dist/agent/durable-background.js +5 -3
  68. package/dist/agent/durable-background.js.map +1 -1
  69. package/dist/agent/engine/ai-sdk-engine.d.ts.map +1 -1
  70. package/dist/agent/engine/ai-sdk-engine.js +24 -4
  71. package/dist/agent/engine/ai-sdk-engine.js.map +1 -1
  72. package/dist/agent/engine/anthropic-engine.d.ts.map +1 -1
  73. package/dist/agent/engine/anthropic-engine.js +13 -3
  74. package/dist/agent/engine/anthropic-engine.js.map +1 -1
  75. package/dist/agent/engine/output-tokens.d.ts +27 -0
  76. package/dist/agent/engine/output-tokens.d.ts.map +1 -1
  77. package/dist/agent/engine/output-tokens.js +70 -0
  78. package/dist/agent/engine/output-tokens.js.map +1 -1
  79. package/dist/agent/production-agent.d.ts.map +1 -1
  80. package/dist/agent/production-agent.js +41 -7
  81. package/dist/agent/production-agent.js.map +1 -1
  82. package/dist/agent/types.d.ts +3 -2
  83. package/dist/agent/types.d.ts.map +1 -1
  84. package/dist/agent/types.js.map +1 -1
  85. package/dist/client/analytics.d.ts.map +1 -1
  86. package/dist/client/analytics.js +14 -3
  87. package/dist/client/analytics.js.map +1 -1
  88. package/dist/client/blocks/library/wireframe-kit.d.ts +1 -0
  89. package/dist/client/blocks/library/wireframe-kit.d.ts.map +1 -1
  90. package/dist/client/blocks/library/wireframe-kit.js +2 -1
  91. package/dist/client/blocks/library/wireframe-kit.js.map +1 -1
  92. package/dist/client/blocks/library/wireframe.d.ts.map +1 -1
  93. package/dist/client/blocks/library/wireframe.js +6 -1
  94. package/dist/client/blocks/library/wireframe.js.map +1 -1
  95. package/dist/db/client.d.ts.map +1 -1
  96. package/dist/db/client.js +12 -7
  97. package/dist/db/client.js.map +1 -1
  98. package/dist/file-upload/builder.d.ts.map +1 -1
  99. package/dist/file-upload/builder.js +9 -19
  100. package/dist/file-upload/builder.js.map +1 -1
  101. package/dist/file-upload/types.d.ts +3 -3
  102. package/dist/file-upload/types.d.ts.map +1 -1
  103. package/dist/file-upload/types.js.map +1 -1
  104. package/dist/secrets/routes.d.ts +6 -6
  105. package/dist/shared/reasoning-effort.d.ts +1 -0
  106. package/dist/shared/reasoning-effort.d.ts.map +1 -1
  107. package/dist/shared/reasoning-effort.js +18 -0
  108. package/dist/shared/reasoning-effort.js.map +1 -1
  109. package/dist/styles/blocks.css +7 -0
  110. package/docs/content/agent-native-toolkit.mdx +1 -1
  111. package/docs/content/locales/ar-SA/agent-native-toolkit.mdx +1 -1
  112. package/docs/content/locales/ar-SA/tracking.mdx +3 -3
  113. package/docs/content/locales/de-DE/agent-native-toolkit.mdx +1 -1
  114. package/docs/content/locales/de-DE/tracking.mdx +3 -3
  115. package/docs/content/locales/es-ES/agent-native-toolkit.mdx +1 -1
  116. package/docs/content/locales/es-ES/tracking.mdx +3 -3
  117. package/docs/content/locales/fr-FR/agent-native-toolkit.mdx +1 -1
  118. package/docs/content/locales/fr-FR/tracking.mdx +3 -3
  119. package/docs/content/locales/hi-IN/agent-native-toolkit.mdx +1 -1
  120. package/docs/content/locales/hi-IN/tracking.mdx +3 -3
  121. package/docs/content/locales/ja-JP/agent-native-toolkit.mdx +1 -1
  122. package/docs/content/locales/ja-JP/tracking.mdx +3 -3
  123. package/docs/content/locales/ko-KR/agent-native-toolkit.mdx +1 -1
  124. package/docs/content/locales/ko-KR/tracking.mdx +3 -3
  125. package/docs/content/locales/pt-BR/agent-native-toolkit.mdx +1 -1
  126. package/docs/content/locales/pt-BR/tracking.mdx +3 -3
  127. package/docs/content/locales/zh-CN/agent-native-toolkit.mdx +1 -1
  128. package/docs/content/locales/zh-CN/tracking.mdx +3 -3
  129. package/docs/content/locales/zh-TW/agent-native-toolkit.mdx +1 -1
  130. package/docs/content/locales/zh-TW/tracking.mdx +3 -3
  131. package/docs/content/tracking.mdx +3 -3
  132. package/package.json +1 -1
@@ -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,sBAAsB,GACvB,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;;;;;;;;GAQG;AACH,SAAS,yCAAyC;IAChD,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC;IACtD,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IACzC,2EAA2E;IAC3E,2EAA2E;IAC3E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,MAAM,KAAK,GACT,MAAM,IAAI,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ;QACxC,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ;YACjC,CAAC,CAAE,MAAM,CAAC,MAAiB;YAC3B,CAAC,CAAC,EAAE,CAAC;IACX,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IAC1E,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,sBAAsB,EAAE,EAAE,CAAC;QACpC,OAAO;YACL,EAAE,EAAE,KAAK;YACT,MAAM,EAAE,GAAG;YACX,KAAK,EACH,qFAAqF;YACvF,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 isA2AProductionRuntime,\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 * 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 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 return (\n isInBackgroundFunctionRuntime() ||\n backgroundRunMarkerExpectsBackgroundRuntime(marker)\n );\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 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-ON for hosted\n * deployments with `A2A_SECRET`: unset/empty/unknown means enabled, and an app\n * opts OUT with an explicit falsy value (`false`/`0`/`no`/`off`). Deliberately\n * kept separate from `AGENT_CHAT_DURABLE_BACKGROUND` so this narrower\n * capability can be disabled independently of the full durable-background\n * worker path.\n */\nexport const AGENT_CHAT_FOREGROUND_SELF_CHAIN_ENV =\n \"AGENT_CHAT_FOREGROUND_SELF_CHAIN\";\n\nfunction isForegroundSelfChainExplicitlyDisabled(): 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 === \"0\" ||\n normalized === \"false\" ||\n normalized === \"no\" ||\n normalized === \"off\"\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 when the runtime is hosted AND `A2A_SECRET` is configured (the HMAC\n * handoff authenticates the self-dispatch), unless the env flag is explicitly\n * falsy. False otherwise — and false means the existing client-driven\n * `auto_continue` re-POST path is used unchanged, byte-for-byte.\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 !isForegroundSelfChainExplicitlyDisabled() &&\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 but a production runtime → refuse (503) — never run unsigned in\n * prod.\n * - no secret + non-prod (local dev) → allow unsigned; the SQL atomic claim\n * in the worker still prevents double-processing.\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): 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 (isA2AProductionRuntime()) {\n return {\n ok: false,\n status: 503,\n error:\n \"Agent chat background processor not configured — set A2A_SECRET on this deployment.\",\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,sBAAsB,GACvB,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;;;;;;;;GAQG;AACH,SAAS,yCAAyC;IAChD,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC;IACtD,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IACzC,2EAA2E;IAC3E,2EAA2E;IAC3E,+DAA+D;IAC/D,MAAM,SAAS,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IACrE,IAAI,CAAC,4BAA4B,CAAC,IAAI,CAAC,SAAS,CAAC;QAAE,OAAO,IAAI,CAAC;IAC/D,OAAO,uBAAuB,SAAS,mBAAmB,CAAC;AAC7D,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K,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IAC1E,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,sBAAsB,EAAE,EAAE,CAAC;QACpC,OAAO;YACL,EAAE,EAAE,KAAK;YACT,MAAM,EAAE,GAAG;YACX,KAAK,EACH,qFAAqF;YACvF,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 isA2AProductionRuntime,\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 * 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 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 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-ON for hosted\n * deployments with `A2A_SECRET`: unset/empty/unknown means enabled, and an app\n * opts OUT with an explicit falsy value (`false`/`0`/`no`/`off`). Deliberately\n * kept separate from `AGENT_CHAT_DURABLE_BACKGROUND` so this narrower\n * capability can be disabled independently of the full durable-background\n * worker path.\n */\nexport const AGENT_CHAT_FOREGROUND_SELF_CHAIN_ENV =\n \"AGENT_CHAT_FOREGROUND_SELF_CHAIN\";\n\nfunction isForegroundSelfChainExplicitlyDisabled(): 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 === \"0\" ||\n normalized === \"false\" ||\n normalized === \"no\" ||\n normalized === \"off\"\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 when the runtime is hosted AND `A2A_SECRET` is configured (the HMAC\n * handoff authenticates the self-dispatch), unless the env flag is explicitly\n * falsy. False otherwise — and false means the existing client-driven\n * `auto_continue` re-POST path is used unchanged, byte-for-byte.\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 !isForegroundSelfChainExplicitlyDisabled() &&\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 but a production runtime → refuse (503) — never run unsigned in\n * prod.\n * - no secret + non-prod (local dev) → allow unsigned; the SQL atomic claim\n * in the worker still prevents double-processing.\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): 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 (isA2AProductionRuntime()) {\n return {\n ok: false,\n status: 503,\n error:\n \"Agent chat background processor not configured — set A2A_SECRET on this deployment.\",\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"]}
@@ -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OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,yBAAyB,EACzB,iBAAiB,EACjB,iBAAiB,GAClB,CAAC"}
@@ -14,7 +14,7 @@
14
14
  import { clearProviderCredentialAuthFailure, readDeployCredentialEnv, recordProviderCredentialAuthFailure, } from "../../server/credential-provider.js";
15
15
  import { normalizeReasoningEffortForModel } from "../../shared/reasoning-effort.js";
16
16
  import { AI_SDK_MODEL_CONFIG } from "../model-config.js";
17
- import { resolveMaxOutputTokensForEngine } from "./output-tokens.js";
17
+ import { clampThinkingBudgetTokens, resolveMaxOutputTokensForEngine, } from "./output-tokens.js";
18
18
  import { engineToolsToAISDK, engineMessagesToAISDK, aiSdkPartToEngineEvents, aiSdkStepToAssistantContent, } from "./translate-ai-sdk.js";
19
19
  // ---------------------------------------------------------------------------
20
20
  // Provider definitions
@@ -206,16 +206,25 @@ class AISDKEngine {
206
206
  // tool-result content arrays, so images degrade to their text notes.
207
207
  toolResultImages: this.capabilities.vision,
208
208
  });
209
+ // Resolved once so both `maxOutputTokens` (below, in the streamText call)
210
+ // and the thinking-budget headroom clamp agree on the same ceiling.
211
+ const resolvedMaxOutputTokens = resolveMaxOutputTokensForEngine(this.name, opts.maxOutputTokens, opts.model);
209
212
  // Build providerOptions for Anthropic-native features when using Anthropic provider
210
213
  const providerOpts = {};
211
214
  if (this.provider === "anthropic" && opts.providerOptions?.anthropic) {
212
215
  const anthropicOpts = opts.providerOptions.anthropic;
213
216
  if (anthropicOpts.thinking) {
217
+ // Only the "enabled" config carries a numeric budgetTokens; clamp it
218
+ // so thinking can't consume the entire maxOutputTokens budget and
219
+ // leave zero room for the actual response ("adaptive" thinking has
220
+ // no budgetTokens field at all per @ai-sdk/anthropic's schema).
214
221
  providerOpts.anthropic = {
215
222
  ...(providerOpts.anthropic ?? {}),
216
223
  thinking: {
217
224
  type: "enabled",
218
- budgetTokens: anthropicOpts.thinking.budgetTokens,
225
+ budgetTokens: typeof anthropicOpts.thinking.budgetTokens === "number"
226
+ ? clampThinkingBudgetTokens(anthropicOpts.thinking.budgetTokens, resolvedMaxOutputTokens)
227
+ : anthropicOpts.thinking.budgetTokens,
219
228
  },
220
229
  };
221
230
  }
@@ -251,11 +260,22 @@ class AISDKEngine {
251
260
  // Gemini 3.x models reject thinkingBudget — they require thinkingLevel.
252
261
  // Gemini 2.5.x models use thinkingBudget (integer token count or -1).
253
262
  const isGemini3 = /^gemini-3/.test(opts.model);
263
+ const thinkingBudget = googleThinkingBudget(reasoningEffort);
254
264
  providerOpts.google = {
255
265
  ...(providerOpts.google ?? {}),
256
266
  thinkingConfig: isGemini3
257
267
  ? { thinkingLevel: gemini3ThinkingLevel(reasoningEffort) }
258
- : { thinkingBudget: googleThinkingBudget(reasoningEffort) },
268
+ : {
269
+ // Unlike Anthropic's adaptive thinking, Gemini 2.5's
270
+ // thinkingBudget IS a concrete numeric token count, so the
271
+ // same headroom clamp applies: at "max" effort this maps to
272
+ // 32000 tokens, which can equal (or exceed) a small
273
+ // maxOutputTokens cap and leave zero room for the actual
274
+ // response. Preserve Gemini's -1 "dynamic" sentinel.
275
+ thinkingBudget: thinkingBudget > 0
276
+ ? clampThinkingBudgetTokens(thinkingBudget, resolvedMaxOutputTokens)
277
+ : thinkingBudget,
278
+ },
259
279
  };
260
280
  }
261
281
  }
@@ -266,7 +286,7 @@ class AISDKEngine {
266
286
  system: opts.systemPrompt,
267
287
  messages,
268
288
  tools: aiSdkTools,
269
- maxOutputTokens: resolveMaxOutputTokensForEngine(this.name, opts.maxOutputTokens, opts.model),
289
+ maxOutputTokens: resolvedMaxOutputTokens,
270
290
  ...(opts.temperature !== undefined
271
291
  ? { temperature: opts.temperature }
272
292
  : {}),
@@ -1 +1 @@
1
- {"version":3,"file":"ai-sdk-engine.js","sourceRoot":"","sources":["../../../src/agent/engine/ai-sdk-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,kCAAkC,EAClC,uBAAuB,EACvB,mCAAmC,GACpC,MA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C,CAAS;IAC3B,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAChD,CAAC;AAED,SAAS,iBAAiB,CAAC,QAAuB;IAChD,MAAM,OAAO,GAAG,iBAAiB,CAAC,QAAQ,CAAC,CAAC;IAC5C,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACxB,MAAM,KAAK,GAAG,uBAAuB,CAAC,CAAC,CAAC,CAAC;QACzC,IAAI,KAAK;YAAE,OAAO,KAAK,CAAC;IAC1B,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,8EAA8E;AAC9E,oCAAoC;AACpC,8EAA8E;AAE9E,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,yBAAyB,EACzB,iBAAiB,EACjB,iBAAiB,GAClB,CAAC","sourcesContent":["/**\n * AISDKEngine — wraps the Vercel AI SDK (ai package) for multi-provider support.\n *\n * Supports Anthropic, OpenAI, Google Gemini, Groq, and any provider with an\n * @ai-sdk/* package. Provider is selected via the `provider` config option.\n *\n * When provider is \"anthropic\", Anthropic-native features (thinking, cacheControl)\n * are forwarded through the AI SDK's providerOptions mechanism — no fidelity loss\n * compared to the native AnthropicEngine.\n *\n * The ai package is an OPTIONAL peer dependency. This engine uses dynamic import()\n * so the core package remains installable without the AI SDK.\n */\n\nimport {\n clearProviderCredentialAuthFailure,\n readDeployCredentialEnv,\n recordProviderCredentialAuthFailure,\n} from \"../../server/credential-provider.js\";\nimport { normalizeReasoningEffortForModel } from \"../../shared/reasoning-effort.js\";\nimport { AI_SDK_MODEL_CONFIG, type AISDKProvider } from \"../model-config.js\";\nimport { resolveMaxOutputTokensForEngine } from \"./output-tokens.js\";\nimport {\n engineToolsToAISDK,\n engineMessagesToAISDK,\n aiSdkPartToEngineEvents,\n aiSdkStepToAssistantContent,\n} from \"./translate-ai-sdk.js\";\nimport type {\n AgentEngine,\n EngineCapabilities,\n EngineStreamOptions,\n EngineEvent,\n EngineContentPart,\n} from \"./types.js\";\n\nexport type { AISDKProvider } from \"../model-config.js\";\n\n// ---------------------------------------------------------------------------\n// Provider definitions\n// ---------------------------------------------------------------------------\n\nconst PROVIDER_CAPABILITIES: Record<AISDKProvider, EngineCapabilities> = {\n anthropic: {\n thinking: true,\n promptCaching: true,\n vision: true,\n computerUse: false, // not exposed through AI SDK yet\n parallelToolCalls: true,\n },\n openai: {\n thinking: true,\n promptCaching: false,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n },\n openrouter: {\n thinking: true,\n promptCaching: true,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n },\n google: {\n thinking: true,\n promptCaching: false,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n },\n groq: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: true,\n },\n mistral: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: true,\n },\n cohere: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: true,\n },\n ollama: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: false,\n },\n};\n\nconst providerModelEntries = Object.entries(AI_SDK_MODEL_CONFIG) as Array<\n [AISDKProvider, (typeof AI_SDK_MODEL_CONFIG)[AISDKProvider]]\n>;\n\nconst PROVIDER_DEFAULT_MODELS = Object.fromEntries(\n providerModelEntries.map(([provider, config]) => [\n provider,\n config.defaultModel,\n ]),\n) as Record<AISDKProvider, string>;\n\nconst PROVIDER_SUPPORTED_MODELS = Object.fromEntries(\n providerModelEntries.map(([provider, config]) => [\n provider,\n config.supportedModels,\n ]),\n) as unknown as Record<AISDKProvider, readonly string[]>;\n\nconst PROVIDER_ENV_VARS: Record<AISDKProvider, string[]> = {\n anthropic: [\"ANTHROPIC_API_KEY\"],\n openai: [\"OPENAI_API_KEY\"],\n openrouter: [\"OPENROUTER_API_KEY\"],\n google: [\"GOOGLE_GENERATIVE_AI_API_KEY\"],\n groq: [\"GROQ_API_KEY\"],\n mistral: [\"MISTRAL_API_KEY\"],\n cohere: [\"COHERE_API_KEY\"],\n ollama: [], // runs locally\n};\n\nconst PROVIDER_PACKAGES: Record<AISDKProvider, string> = {\n anthropic: \"@ai-sdk/anthropic\",\n openai: \"@ai-sdk/openai\",\n openrouter: \"@openrouter/ai-sdk-provider\",\n google: \"@ai-sdk/google\",\n groq: \"@ai-sdk/groq\",\n mistral: \"@ai-sdk/mistral\",\n cohere: \"@ai-sdk/cohere\",\n ollama: \"ai-sdk-ollama\",\n};\n\n/** Factory export name per provider (not all follow `create<Provider>`). */\nconst PROVIDER_FACTORIES: Record<AISDKProvider, string> = {\n anthropic: \"createAnthropic\",\n openai: \"createOpenAI\",\n openrouter: \"createOpenRouter\",\n google: \"createGoogleGenerativeAI\",\n groq: \"createGroq\",\n mistral: \"createMistral\",\n cohere: \"createCohere\",\n ollama: \"createOllama\",\n};\n\nfunction googleThinkingBudget(effort: string) {\n if (effort === \"low\") return 1024;\n // \"medium\" is a normalized effort for Gemini models; without this case it\n // fell through to the -1 (\"dynamic/unlimited\") fallback, so selecting\n // medium effort silently uncapped the thinking budget.\n if (effort === \"medium\") return 4096;\n if (effort === \"high\") return 8000;\n if (effort === \"xhigh\") return 16_000;\n if (effort === \"max\") return 32_000;\n return -1;\n}\n\n/**\n * Map a reasoning effort level to Gemini 3.x thinkingLevel string.\n * Gemini 3 models (gemini-3.*) reject thinkingBudget and require thinkingLevel\n * with values 'low' | 'medium' | 'high'. Gemini 3.0 only supports 'low'/'high';\n * Gemini 3.1+ adds 'medium'. We always emit 'medium' for medium effort since it\n * is accepted by 3.1+, and 3.0 is expected to be phased out quickly.\n */\nfunction gemini3ThinkingLevel(effort: string): string {\n if (effort === \"low\") return \"low\";\n // medium/high/xhigh/max all map to the strongest available level for Gemini 3\n return \"high\";\n}\n\n// ---------------------------------------------------------------------------\n// AISDKEngine implementation\n// ---------------------------------------------------------------------------\n\n/** Config accepted by every `ai-sdk:*` engine. */\nexport interface AISDKEngineConfig {\n /** Override the provider's default model (also becomes the engine's defaultModel). */\n model?: string;\n /** API key — falls back to the provider-specific env var if omitted. */\n apiKey?: string;\n /** Set false in request-scoped multi-tenant runs so provider packages cannot fall back to process.env. */\n allowEnvFallback?: boolean;\n /** Override the provider base URL (useful for proxies or OpenAI-compatible gateways). */\n baseUrl?: string;\n /** OpenRouter: `X-OpenRouter-Title` header for dashboard attribution. */\n appName?: string;\n /** OpenRouter: `HTTP-Referer` header for dashboard attribution. */\n appUrl?: string;\n}\n\nclass AISDKEngine implements AgentEngine {\n readonly name: string;\n readonly label: string;\n readonly defaultModel: string;\n readonly supportedModels: readonly string[];\n readonly capabilities: EngineCapabilities;\n\n private readonly provider: AISDKProvider;\n private readonly apiKey?: string;\n private readonly baseUrl?: string;\n private readonly appName?: string;\n private readonly appUrl?: string;\n\n constructor(provider: AISDKProvider, config: AISDKEngineConfig) {\n this.provider = provider;\n this.name = `ai-sdk:${provider}`;\n this.label = `${capitalize(provider)} (AI SDK)`;\n this.defaultModel = config.model ?? PROVIDER_DEFAULT_MODELS[provider];\n this.supportedModels = PROVIDER_SUPPORTED_MODELS[provider];\n this.capabilities = PROVIDER_CAPABILITIES[provider];\n this.apiKey =\n config.apiKey ??\n (config.allowEnvFallback === false ? \"\" : getProviderApiKey(provider));\n this.baseUrl = config.baseUrl;\n this.appName = config.appName;\n this.appUrl = config.appUrl;\n }\n\n async *stream(opts: EngineStreamOptions): AsyncIterable<EngineEvent> {\n let aiModule: any;\n try {\n aiModule = await import(\"ai\");\n } catch {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `The \"ai\" package is not installed. Run: pnpm add ai ${PROVIDER_PACKAGES[this.provider]}`,\n };\n return;\n }\n\n const { streamText, jsonSchema } = aiModule;\n\n let providerModel: any;\n try {\n providerModel = await this.createProviderModel(opts.model);\n } catch (err: any) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: err?.message ?? String(err),\n };\n return;\n }\n\n const aiSdkTools =\n opts.tools.length > 0\n ? engineToolsToAISDK(opts.tools, jsonSchema)\n : undefined;\n const messages = engineMessagesToAISDK(opts.messages, {\n // Vision-capable provider translators (anthropic/openai/google/\n // openrouter) map image parts to native blocks; the rest stringify\n // tool-result content arrays, so images degrade to their text notes.\n toolResultImages: this.capabilities.vision,\n });\n\n // Build providerOptions for Anthropic-native features when using Anthropic provider\n const providerOpts: Record<string, unknown> = {};\n if (this.provider === \"anthropic\" && opts.providerOptions?.anthropic) {\n const anthropicOpts = opts.providerOptions.anthropic;\n if (anthropicOpts.thinking) {\n providerOpts.anthropic = {\n ...((providerOpts.anthropic as object) ?? {}),\n thinking: {\n type: \"enabled\",\n budgetTokens: anthropicOpts.thinking.budgetTokens,\n },\n };\n }\n if (anthropicOpts.cacheControl) {\n providerOpts.anthropic = {\n ...((providerOpts.anthropic as object) ?? {}),\n cacheControl: anthropicOpts.cacheControl,\n };\n }\n }\n const reasoningEffort = normalizeReasoningEffortForModel(\n opts.model,\n opts.reasoningEffort,\n );\n if (reasoningEffort) {\n if (this.provider === \"anthropic\") {\n providerOpts.anthropic = {\n ...((providerOpts.anthropic as object) ?? {}),\n thinking: (\n providerOpts.anthropic as { thinking?: unknown } | undefined\n )?.thinking ?? { type: \"adaptive\" },\n outputConfig: { effort: reasoningEffort },\n };\n } else if (this.provider === \"openai\") {\n providerOpts.openai = {\n ...((providerOpts.openai as object) ?? {}),\n reasoningEffort,\n };\n } else if (this.provider === \"openrouter\") {\n providerOpts.openrouter = {\n ...((providerOpts.openrouter as object) ?? {}),\n reasoning: { effort: reasoningEffort },\n };\n } else if (this.provider === \"google\") {\n // Gemini 3.x models reject thinkingBudget — they require thinkingLevel.\n // Gemini 2.5.x models use thinkingBudget (integer token count or -1).\n const isGemini3 = /^gemini-3/.test(opts.model);\n providerOpts.google = {\n ...((providerOpts.google as object) ?? {}),\n thinkingConfig: isGemini3\n ? { thinkingLevel: gemini3ThinkingLevel(reasoningEffort) }\n : { thinkingBudget: googleThinkingBudget(reasoningEffort) },\n };\n }\n }\n\n let assistantContent: EngineContentPart[] = [];\n\n try {\n const result = streamText({\n model: providerModel,\n system: opts.systemPrompt,\n messages,\n tools: aiSdkTools,\n maxOutputTokens: resolveMaxOutputTokensForEngine(\n this.name,\n opts.maxOutputTokens,\n opts.model,\n ),\n ...(opts.temperature !== undefined\n ? { temperature: opts.temperature }\n : {}),\n abortSignal: opts.abortSignal,\n onStepFinish: (step: any) => {\n assistantContent = aiSdkStepToAssistantContent(step);\n },\n ...(Object.keys(providerOpts).length > 0\n ? { providerOptions: providerOpts }\n : {}),\n });\n\n // Buffer the terminal stop so assistant-content can be emitted just\n // before it, regardless of where `finish` arrives in the stream.\n let bufferedStop: EngineEvent | undefined;\n\n for await (const part of result.fullStream) {\n for (const event of aiSdkPartToEngineEvents(part)) {\n if (event.type === \"stop\") {\n bufferedStop = event;\n } else {\n yield event;\n }\n }\n }\n\n yield { type: \"assistant-content\", parts: assistantContent };\n await clearProviderCredentialAuthFailure({\n key: PROVIDER_ENV_VARS[this.provider][0],\n value: this.apiKey,\n });\n yield bufferedStop ?? { type: \"stop\", reason: \"end_turn\" };\n } catch (err: any) {\n // Surface structured fields from AI SDK's APICallError so\n // isRetryableError can check statusCode/providerRetryable directly\n // rather than keyword-matching the message string.\n const statusCode: number | undefined =\n typeof err?.statusCode === \"number\" ? err.statusCode : undefined;\n const providerRetryable: boolean | undefined =\n typeof err?.isRetryable === \"boolean\" ? err.isRetryable : undefined;\n if (statusCode === 401) {\n await recordProviderCredentialAuthFailure({\n key: PROVIDER_ENV_VARS[this.provider][0],\n value: this.apiKey,\n status: statusCode,\n code: \"http_401\",\n message: err?.message ?? String(err),\n });\n }\n yield {\n type: \"stop\",\n reason: \"error\",\n error: err?.message ?? String(err),\n // Tag every known status with `http_<status>` (not just 401) so a\n // rate limit surfaces as `http_429`. The structured statusCode\n // already drives turn-level retries, but the run-level continuation\n // logic keys off the errorCode, so this lets a rate-limited turn\n // auto-resume too — matching the Builder gateway path.\n ...(statusCode !== undefined\n ? { errorCode: `http_${statusCode}`, statusCode }\n : {}),\n ...(providerRetryable !== undefined ? { providerRetryable } : {}),\n };\n throw err;\n }\n }\n\n private async createProviderModel(model: string): Promise<any> {\n const pkg = PROVIDER_PACKAGES[this.provider];\n let providerModule: any;\n try {\n providerModule = await importProviderPackage(this.provider);\n } catch {\n throw new Error(\n `Provider package \"${pkg}\" is not installed. Run: pnpm add ai ${pkg}`,\n );\n }\n\n const fnName = PROVIDER_FACTORIES[this.provider];\n const createFn = providerModule[fnName] ?? providerModule.default;\n if (typeof createFn !== \"function\") {\n throw new Error(`\"${pkg}\" does not export ${fnName} or default`);\n }\n\n const config: Record<string, unknown> = {};\n if (this.apiKey !== undefined) config.apiKey = this.apiKey;\n if (this.baseUrl) config.baseURL = this.baseUrl;\n // Scoped to openrouter — other providers' factories may reject unknown keys.\n if (this.provider === \"openrouter\") {\n if (this.appName) config.appName = this.appName;\n if (this.appUrl) config.appUrl = this.appUrl;\n }\n\n const provider = createFn(config);\n // Let first-party OpenAI use the AI SDK's default Responses path so newer\n // GPT reasoning models get the API OpenAI recommends. If someone points\n // the OpenAI provider at an OpenAI-compatible gateway, keep using Chat\n // Completions because many gateway base URLs do not implement Responses.\n return this.provider === \"openai\" && this.baseUrl\n ? provider.chat(model)\n : provider(model);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory functions\n// ---------------------------------------------------------------------------\n\nexport function createAISDKEngine(\n provider: AISDKProvider,\n config: Record<string, unknown> = {},\n): AgentEngine {\n return new AISDKEngine(provider, config as AISDKEngineConfig);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n// Static string-literal imports so bundlers (Nitro/Rollup/Vercel) can analyze\n// and include provider packages. A variable-based `import(pkg)` gets skipped.\nasync function importProviderPackage(provider: AISDKProvider): Promise<any> {\n switch (provider) {\n case \"anthropic\":\n return import(\"@ai-sdk/anthropic\");\n case \"openai\":\n return import(\"@ai-sdk/openai\");\n case \"openrouter\":\n return import(\"@openrouter/ai-sdk-provider\");\n case \"google\":\n return import(\"@ai-sdk/google\");\n case \"groq\":\n return import(\"@ai-sdk/groq\");\n case \"mistral\":\n return import(\"@ai-sdk/mistral\");\n case \"cohere\":\n return import(\"@ai-sdk/cohere\");\n case \"ollama\":\n return import(\"ai-sdk-ollama\");\n }\n}\n\nfunction capitalize(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nfunction getProviderApiKey(provider: AISDKProvider): string | undefined {\n const envVars = PROVIDER_ENV_VARS[provider];\n for (const v of envVars) {\n const value = readDeployCredentialEnv(v);\n if (value) return value;\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Exports for registry registration\n// ---------------------------------------------------------------------------\n\nexport {\n PROVIDER_CAPABILITIES,\n PROVIDER_DEFAULT_MODELS,\n PROVIDER_SUPPORTED_MODELS,\n PROVIDER_ENV_VARS,\n PROVIDER_PACKAGES,\n};\n"]}
1
+ {"version":3,"file":"ai-sdk-engine.js","sourceRoot":"","sources":["../../../src/agent/engine/ai-sdk-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,kCAAkC,EAClC,uBAAuB,EACvB,mCAAmC,GACpC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,gCAAgC,EAAE,MAAM,kCAAkC,CAAC;AACpF,OAAO,EAAE,mBAAmB,EAAsB,MAAM,oBAAoB,CAAC;AAC7E,OAAO,EACL,yBAAyB,EACzB,+BAA+B,GAChC,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,uBAAuB,EACvB,2BAA2B,GAC5B,MAAM,uBAAuB,CAAC;AAW/B,8EAA8E;AAC9E,uBAAuB;AACvB,8EAA8E;AAE9E,MAAM,qBAAqB,GAA8C;IACvE,SAAS,EAAE;QACT,QAAQ,EAA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M,CAAC,gBAAgB,CAAC,CAAC;QAClC,KAAK,QAAQ;YACX,OAAO,MAAM,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC;AACH,CAAC;AAED,SAAS,UAAU,CAAC,CAAS;IAC3B,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAChD,CAAC;AAED,SAAS,iBAAiB,CAAC,QAAuB;IAChD,MAAM,OAAO,GAAG,iBAAiB,CAAC,QAAQ,CAAC,CAAC;IAC5C,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACxB,MAAM,KAAK,GAAG,uBAAuB,CAAC,CAAC,CAAC,CAAC;QACzC,IAAI,KAAK;YAAE,OAAO,KAAK,CAAC;IAC1B,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,8EAA8E;AAC9E,oCAAoC;AACpC,8EAA8E;AAE9E,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,yBAAyB,EACzB,iBAAiB,EACjB,iBAAiB,GAClB,CAAC","sourcesContent":["/**\n * AISDKEngine — wraps the Vercel AI SDK (ai package) for multi-provider support.\n *\n * Supports Anthropic, OpenAI, Google Gemini, Groq, and any provider with an\n * @ai-sdk/* package. Provider is selected via the `provider` config option.\n *\n * When provider is \"anthropic\", Anthropic-native features (thinking, cacheControl)\n * are forwarded through the AI SDK's providerOptions mechanism — no fidelity loss\n * compared to the native AnthropicEngine.\n *\n * The ai package is an OPTIONAL peer dependency. This engine uses dynamic import()\n * so the core package remains installable without the AI SDK.\n */\n\nimport {\n clearProviderCredentialAuthFailure,\n readDeployCredentialEnv,\n recordProviderCredentialAuthFailure,\n} from \"../../server/credential-provider.js\";\nimport { normalizeReasoningEffortForModel } from \"../../shared/reasoning-effort.js\";\nimport { AI_SDK_MODEL_CONFIG, type AISDKProvider } from \"../model-config.js\";\nimport {\n clampThinkingBudgetTokens,\n resolveMaxOutputTokensForEngine,\n} from \"./output-tokens.js\";\nimport {\n engineToolsToAISDK,\n engineMessagesToAISDK,\n aiSdkPartToEngineEvents,\n aiSdkStepToAssistantContent,\n} from \"./translate-ai-sdk.js\";\nimport type {\n AgentEngine,\n EngineCapabilities,\n EngineStreamOptions,\n EngineEvent,\n EngineContentPart,\n} from \"./types.js\";\n\nexport type { AISDKProvider } from \"../model-config.js\";\n\n// ---------------------------------------------------------------------------\n// Provider definitions\n// ---------------------------------------------------------------------------\n\nconst PROVIDER_CAPABILITIES: Record<AISDKProvider, EngineCapabilities> = {\n anthropic: {\n thinking: true,\n promptCaching: true,\n vision: true,\n computerUse: false, // not exposed through AI SDK yet\n parallelToolCalls: true,\n },\n openai: {\n thinking: true,\n promptCaching: false,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n },\n openrouter: {\n thinking: true,\n promptCaching: true,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n },\n google: {\n thinking: true,\n promptCaching: false,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n },\n groq: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: true,\n },\n mistral: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: true,\n },\n cohere: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: true,\n },\n ollama: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: false,\n },\n};\n\nconst providerModelEntries = Object.entries(AI_SDK_MODEL_CONFIG) as Array<\n [AISDKProvider, (typeof AI_SDK_MODEL_CONFIG)[AISDKProvider]]\n>;\n\nconst PROVIDER_DEFAULT_MODELS = Object.fromEntries(\n providerModelEntries.map(([provider, config]) => [\n provider,\n config.defaultModel,\n ]),\n) as Record<AISDKProvider, string>;\n\nconst PROVIDER_SUPPORTED_MODELS = Object.fromEntries(\n providerModelEntries.map(([provider, config]) => [\n provider,\n config.supportedModels,\n ]),\n) as unknown as Record<AISDKProvider, readonly string[]>;\n\nconst PROVIDER_ENV_VARS: Record<AISDKProvider, string[]> = {\n anthropic: [\"ANTHROPIC_API_KEY\"],\n openai: [\"OPENAI_API_KEY\"],\n openrouter: [\"OPENROUTER_API_KEY\"],\n google: [\"GOOGLE_GENERATIVE_AI_API_KEY\"],\n groq: [\"GROQ_API_KEY\"],\n mistral: [\"MISTRAL_API_KEY\"],\n cohere: [\"COHERE_API_KEY\"],\n ollama: [], // runs locally\n};\n\nconst PROVIDER_PACKAGES: Record<AISDKProvider, string> = {\n anthropic: \"@ai-sdk/anthropic\",\n openai: \"@ai-sdk/openai\",\n openrouter: \"@openrouter/ai-sdk-provider\",\n google: \"@ai-sdk/google\",\n groq: \"@ai-sdk/groq\",\n mistral: \"@ai-sdk/mistral\",\n cohere: \"@ai-sdk/cohere\",\n ollama: \"ai-sdk-ollama\",\n};\n\n/** Factory export name per provider (not all follow `create<Provider>`). */\nconst PROVIDER_FACTORIES: Record<AISDKProvider, string> = {\n anthropic: \"createAnthropic\",\n openai: \"createOpenAI\",\n openrouter: \"createOpenRouter\",\n google: \"createGoogleGenerativeAI\",\n groq: \"createGroq\",\n mistral: \"createMistral\",\n cohere: \"createCohere\",\n ollama: \"createOllama\",\n};\n\nfunction googleThinkingBudget(effort: string) {\n if (effort === \"low\") return 1024;\n // \"medium\" is a normalized effort for Gemini models; without this case it\n // fell through to the -1 (\"dynamic/unlimited\") fallback, so selecting\n // medium effort silently uncapped the thinking budget.\n if (effort === \"medium\") return 4096;\n if (effort === \"high\") return 8000;\n if (effort === \"xhigh\") return 16_000;\n if (effort === \"max\") return 32_000;\n return -1;\n}\n\n/**\n * Map a reasoning effort level to Gemini 3.x thinkingLevel string.\n * Gemini 3 models (gemini-3.*) reject thinkingBudget and require thinkingLevel\n * with values 'low' | 'medium' | 'high'. Gemini 3.0 only supports 'low'/'high';\n * Gemini 3.1+ adds 'medium'. We always emit 'medium' for medium effort since it\n * is accepted by 3.1+, and 3.0 is expected to be phased out quickly.\n */\nfunction gemini3ThinkingLevel(effort: string): string {\n if (effort === \"low\") return \"low\";\n // medium/high/xhigh/max all map to the strongest available level for Gemini 3\n return \"high\";\n}\n\n// ---------------------------------------------------------------------------\n// AISDKEngine implementation\n// ---------------------------------------------------------------------------\n\n/** Config accepted by every `ai-sdk:*` engine. */\nexport interface AISDKEngineConfig {\n /** Override the provider's default model (also becomes the engine's defaultModel). */\n model?: string;\n /** API key — falls back to the provider-specific env var if omitted. */\n apiKey?: string;\n /** Set false in request-scoped multi-tenant runs so provider packages cannot fall back to process.env. */\n allowEnvFallback?: boolean;\n /** Override the provider base URL (useful for proxies or OpenAI-compatible gateways). */\n baseUrl?: string;\n /** OpenRouter: `X-OpenRouter-Title` header for dashboard attribution. */\n appName?: string;\n /** OpenRouter: `HTTP-Referer` header for dashboard attribution. */\n appUrl?: string;\n}\n\nclass AISDKEngine implements AgentEngine {\n readonly name: string;\n readonly label: string;\n readonly defaultModel: string;\n readonly supportedModels: readonly string[];\n readonly capabilities: EngineCapabilities;\n\n private readonly provider: AISDKProvider;\n private readonly apiKey?: string;\n private readonly baseUrl?: string;\n private readonly appName?: string;\n private readonly appUrl?: string;\n\n constructor(provider: AISDKProvider, config: AISDKEngineConfig) {\n this.provider = provider;\n this.name = `ai-sdk:${provider}`;\n this.label = `${capitalize(provider)} (AI SDK)`;\n this.defaultModel = config.model ?? PROVIDER_DEFAULT_MODELS[provider];\n this.supportedModels = PROVIDER_SUPPORTED_MODELS[provider];\n this.capabilities = PROVIDER_CAPABILITIES[provider];\n this.apiKey =\n config.apiKey ??\n (config.allowEnvFallback === false ? \"\" : getProviderApiKey(provider));\n this.baseUrl = config.baseUrl;\n this.appName = config.appName;\n this.appUrl = config.appUrl;\n }\n\n async *stream(opts: EngineStreamOptions): AsyncIterable<EngineEvent> {\n let aiModule: any;\n try {\n aiModule = await import(\"ai\");\n } catch {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `The \"ai\" package is not installed. Run: pnpm add ai ${PROVIDER_PACKAGES[this.provider]}`,\n };\n return;\n }\n\n const { streamText, jsonSchema } = aiModule;\n\n let providerModel: any;\n try {\n providerModel = await this.createProviderModel(opts.model);\n } catch (err: any) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: err?.message ?? String(err),\n };\n return;\n }\n\n const aiSdkTools =\n opts.tools.length > 0\n ? engineToolsToAISDK(opts.tools, jsonSchema)\n : undefined;\n const messages = engineMessagesToAISDK(opts.messages, {\n // Vision-capable provider translators (anthropic/openai/google/\n // openrouter) map image parts to native blocks; the rest stringify\n // tool-result content arrays, so images degrade to their text notes.\n toolResultImages: this.capabilities.vision,\n });\n\n // Resolved once so both `maxOutputTokens` (below, in the streamText call)\n // and the thinking-budget headroom clamp agree on the same ceiling.\n const resolvedMaxOutputTokens = resolveMaxOutputTokensForEngine(\n this.name,\n opts.maxOutputTokens,\n opts.model,\n );\n\n // Build providerOptions for Anthropic-native features when using Anthropic provider\n const providerOpts: Record<string, unknown> = {};\n if (this.provider === \"anthropic\" && opts.providerOptions?.anthropic) {\n const anthropicOpts = opts.providerOptions.anthropic;\n if (anthropicOpts.thinking) {\n // Only the \"enabled\" config carries a numeric budgetTokens; clamp it\n // so thinking can't consume the entire maxOutputTokens budget and\n // leave zero room for the actual response (\"adaptive\" thinking has\n // no budgetTokens field at all per @ai-sdk/anthropic's schema).\n providerOpts.anthropic = {\n ...((providerOpts.anthropic as object) ?? {}),\n thinking: {\n type: \"enabled\",\n budgetTokens:\n typeof anthropicOpts.thinking.budgetTokens === \"number\"\n ? clampThinkingBudgetTokens(\n anthropicOpts.thinking.budgetTokens,\n resolvedMaxOutputTokens,\n )\n : anthropicOpts.thinking.budgetTokens,\n },\n };\n }\n if (anthropicOpts.cacheControl) {\n providerOpts.anthropic = {\n ...((providerOpts.anthropic as object) ?? {}),\n cacheControl: anthropicOpts.cacheControl,\n };\n }\n }\n const reasoningEffort = normalizeReasoningEffortForModel(\n opts.model,\n opts.reasoningEffort,\n );\n if (reasoningEffort) {\n if (this.provider === \"anthropic\") {\n providerOpts.anthropic = {\n ...((providerOpts.anthropic as object) ?? {}),\n thinking: (\n providerOpts.anthropic as { thinking?: unknown } | undefined\n )?.thinking ?? { type: \"adaptive\" },\n outputConfig: { effort: reasoningEffort },\n };\n } else if (this.provider === \"openai\") {\n providerOpts.openai = {\n ...((providerOpts.openai as object) ?? {}),\n reasoningEffort,\n };\n } else if (this.provider === \"openrouter\") {\n providerOpts.openrouter = {\n ...((providerOpts.openrouter as object) ?? {}),\n reasoning: { effort: reasoningEffort },\n };\n } else if (this.provider === \"google\") {\n // Gemini 3.x models reject thinkingBudget — they require thinkingLevel.\n // Gemini 2.5.x models use thinkingBudget (integer token count or -1).\n const isGemini3 = /^gemini-3/.test(opts.model);\n const thinkingBudget = googleThinkingBudget(reasoningEffort);\n providerOpts.google = {\n ...((providerOpts.google as object) ?? {}),\n thinkingConfig: isGemini3\n ? { thinkingLevel: gemini3ThinkingLevel(reasoningEffort) }\n : {\n // Unlike Anthropic's adaptive thinking, Gemini 2.5's\n // thinkingBudget IS a concrete numeric token count, so the\n // same headroom clamp applies: at \"max\" effort this maps to\n // 32000 tokens, which can equal (or exceed) a small\n // maxOutputTokens cap and leave zero room for the actual\n // response. Preserve Gemini's -1 \"dynamic\" sentinel.\n thinkingBudget:\n thinkingBudget > 0\n ? clampThinkingBudgetTokens(\n thinkingBudget,\n resolvedMaxOutputTokens,\n )\n : thinkingBudget,\n },\n };\n }\n }\n\n let assistantContent: EngineContentPart[] = [];\n\n try {\n const result = streamText({\n model: providerModel,\n system: opts.systemPrompt,\n messages,\n tools: aiSdkTools,\n maxOutputTokens: resolvedMaxOutputTokens,\n ...(opts.temperature !== undefined\n ? { temperature: opts.temperature }\n : {}),\n abortSignal: opts.abortSignal,\n onStepFinish: (step: any) => {\n assistantContent = aiSdkStepToAssistantContent(step);\n },\n ...(Object.keys(providerOpts).length > 0\n ? { providerOptions: providerOpts }\n : {}),\n });\n\n // Buffer the terminal stop so assistant-content can be emitted just\n // before it, regardless of where `finish` arrives in the stream.\n let bufferedStop: EngineEvent | undefined;\n\n for await (const part of result.fullStream) {\n for (const event of aiSdkPartToEngineEvents(part)) {\n if (event.type === \"stop\") {\n bufferedStop = event;\n } else {\n yield event;\n }\n }\n }\n\n yield { type: \"assistant-content\", parts: assistantContent };\n await clearProviderCredentialAuthFailure({\n key: PROVIDER_ENV_VARS[this.provider][0],\n value: this.apiKey,\n });\n yield bufferedStop ?? { type: \"stop\", reason: \"end_turn\" };\n } catch (err: any) {\n // Surface structured fields from AI SDK's APICallError so\n // isRetryableError can check statusCode/providerRetryable directly\n // rather than keyword-matching the message string.\n const statusCode: number | undefined =\n typeof err?.statusCode === \"number\" ? err.statusCode : undefined;\n const providerRetryable: boolean | undefined =\n typeof err?.isRetryable === \"boolean\" ? err.isRetryable : undefined;\n if (statusCode === 401) {\n await recordProviderCredentialAuthFailure({\n key: PROVIDER_ENV_VARS[this.provider][0],\n value: this.apiKey,\n status: statusCode,\n code: \"http_401\",\n message: err?.message ?? String(err),\n });\n }\n yield {\n type: \"stop\",\n reason: \"error\",\n error: err?.message ?? String(err),\n // Tag every known status with `http_<status>` (not just 401) so a\n // rate limit surfaces as `http_429`. The structured statusCode\n // already drives turn-level retries, but the run-level continuation\n // logic keys off the errorCode, so this lets a rate-limited turn\n // auto-resume too — matching the Builder gateway path.\n ...(statusCode !== undefined\n ? { errorCode: `http_${statusCode}`, statusCode }\n : {}),\n ...(providerRetryable !== undefined ? { providerRetryable } : {}),\n };\n throw err;\n }\n }\n\n private async createProviderModel(model: string): Promise<any> {\n const pkg = PROVIDER_PACKAGES[this.provider];\n let providerModule: any;\n try {\n providerModule = await importProviderPackage(this.provider);\n } catch {\n throw new Error(\n `Provider package \"${pkg}\" is not installed. Run: pnpm add ai ${pkg}`,\n );\n }\n\n const fnName = PROVIDER_FACTORIES[this.provider];\n const createFn = providerModule[fnName] ?? providerModule.default;\n if (typeof createFn !== \"function\") {\n throw new Error(`\"${pkg}\" does not export ${fnName} or default`);\n }\n\n const config: Record<string, unknown> = {};\n if (this.apiKey !== undefined) config.apiKey = this.apiKey;\n if (this.baseUrl) config.baseURL = this.baseUrl;\n // Scoped to openrouter — other providers' factories may reject unknown keys.\n if (this.provider === \"openrouter\") {\n if (this.appName) config.appName = this.appName;\n if (this.appUrl) config.appUrl = this.appUrl;\n }\n\n const provider = createFn(config);\n // Let first-party OpenAI use the AI SDK's default Responses path so newer\n // GPT reasoning models get the API OpenAI recommends. If someone points\n // the OpenAI provider at an OpenAI-compatible gateway, keep using Chat\n // Completions because many gateway base URLs do not implement Responses.\n return this.provider === \"openai\" && this.baseUrl\n ? provider.chat(model)\n : provider(model);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory functions\n// ---------------------------------------------------------------------------\n\nexport function createAISDKEngine(\n provider: AISDKProvider,\n config: Record<string, unknown> = {},\n): AgentEngine {\n return new AISDKEngine(provider, config as AISDKEngineConfig);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n// Static string-literal imports so bundlers (Nitro/Rollup/Vercel) can analyze\n// and include provider packages. A variable-based `import(pkg)` gets skipped.\nasync function importProviderPackage(provider: AISDKProvider): Promise<any> {\n switch (provider) {\n case \"anthropic\":\n return import(\"@ai-sdk/anthropic\");\n case \"openai\":\n return import(\"@ai-sdk/openai\");\n case \"openrouter\":\n return import(\"@openrouter/ai-sdk-provider\");\n case \"google\":\n return import(\"@ai-sdk/google\");\n case \"groq\":\n return import(\"@ai-sdk/groq\");\n case \"mistral\":\n return import(\"@ai-sdk/mistral\");\n case \"cohere\":\n return import(\"@ai-sdk/cohere\");\n case \"ollama\":\n return import(\"ai-sdk-ollama\");\n }\n}\n\nfunction capitalize(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nfunction getProviderApiKey(provider: AISDKProvider): string | undefined {\n const envVars = PROVIDER_ENV_VARS[provider];\n for (const v of envVars) {\n const value = readDeployCredentialEnv(v);\n if (value) return value;\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Exports for registry registration\n// ---------------------------------------------------------------------------\n\nexport {\n PROVIDER_CAPABILITIES,\n PROVIDER_DEFAULT_MODELS,\n PROVIDER_SUPPORTED_MODELS,\n PROVIDER_ENV_VARS,\n PROVIDER_PACKAGES,\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic-engine.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/anthropic-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAqBH,OAAO,KAAK,EACV,WAAW,EACX,kBAAkB,EAGnB,MAAM,YAAY,CAAC;AAEpB,eAAO,MAAM,sBAAsB,EAAE,kBAMpC,CAAC;AAEF,eAAO,MAAM,0BAA0B,sHACC,CAAC;AACzC,eAAO,MAAM,uBAAuB,yCAAsC,CAAC;AAwM3E;;;GAGG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GACnC,WAAW,CAyBb"}
1
+ {"version":3,"file":"anthropic-engine.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/anthropic-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAwBH,OAAO,KAAK,EACV,WAAW,EACX,kBAAkB,EAGnB,MAAM,YAAY,CAAC;AAEpB,eAAO,MAAM,sBAAsB,EAAE,kBAMpC,CAAC;AAEF,eAAO,MAAM,0BAA0B,sHACC,CAAC;AACzC,eAAO,MAAM,uBAAuB,yCAAsC,CAAC;AAuN3E;;;GAGG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GACnC,WAAW,CAyBb"}
@@ -11,7 +11,7 @@ import { clearProviderCredentialAuthFailure, readDeployCredentialEnv, recordProv
11
11
  import { normalizeReasoningEffortForModel } from "../../shared/reasoning-effort.js";
12
12
  import { ANTHROPIC_MODEL_CONFIG } from "../model-config.js";
13
13
  import { LLM_MISSING_CREDENTIALS_ERROR_CODE, LLM_MISSING_CREDENTIALS_MESSAGE, } from "./credential-errors.js";
14
- import { resolveMaxOutputTokensForEngine } from "./output-tokens.js";
14
+ import { clampThinkingBudgetTokens, resolveMaxOutputTokensForEngine, } from "./output-tokens.js";
15
15
  import { engineToolsToAnthropic, engineMessagesToAnthropic, anthropicContentToEngine, anthropicChunkToEngineEvents, createAnthropicChunkStreamState, } from "./translate-anthropic.js";
16
16
  export const ANTHROPIC_CAPABILITIES = {
17
17
  thinking: true,
@@ -38,12 +38,22 @@ class AnthropicEngine {
38
38
  const tools = engineToolsToAnthropic(opts.tools);
39
39
  const messages = engineMessagesToAnthropic(opts.messages);
40
40
  const anthropicOpts = opts.providerOptions?.anthropic;
41
+ // Resolved once so both max_tokens and the thinking-budget headroom
42
+ // clamp below agree on the same ceiling.
43
+ const resolvedMaxOutputTokens = resolveMaxOutputTokensForEngine(this.name, opts.maxOutputTokens, opts.model);
41
44
  // Build extra body params for Anthropic-native features
42
45
  const extra = {};
43
46
  if (anthropicOpts?.thinking) {
44
47
  extra.thinking = {
45
48
  type: anthropicOpts.thinking.type,
46
- budget_tokens: anthropicOpts.thinking.budgetTokens,
49
+ // Only the "enabled" config carries a numeric budget_tokens; clamp it
50
+ // so thinking can't consume the entire max_tokens budget and leave
51
+ // zero room for the actual response ("adaptive" thinking has no
52
+ // budget_tokens field at all, so it passes through unclamped).
53
+ budget_tokens: anthropicOpts.thinking.type === "enabled" &&
54
+ typeof anthropicOpts.thinking.budgetTokens === "number"
55
+ ? clampThinkingBudgetTokens(anthropicOpts.thinking.budgetTokens, resolvedMaxOutputTokens)
56
+ : anthropicOpts.thinking.budgetTokens,
47
57
  };
48
58
  }
49
59
  if (anthropicOpts?.topK !== undefined) {
@@ -103,7 +113,7 @@ class AnthropicEngine {
103
113
  }
104
114
  const requestParams = {
105
115
  model: opts.model,
106
- max_tokens: resolveMaxOutputTokensForEngine(this.name, opts.maxOutputTokens, opts.model),
116
+ max_tokens: resolvedMaxOutputTokens,
107
117
  system: systemBlocks,
108
118
  tools: cachedTools.length > 0 ? cachedTools : undefined,
109
119
  messages: cachedMessages,
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic-engine.js","sourceRoot":"","sources":["../../../src/agent/engine/anthropic-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EACL,kCAAkC,EAClC,uBAAuB,EACvB,mCAAmC,GACpC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,gCAAgC,EAAE,MAAM,kCAAkC,CAAC;AACpF,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EACL,kCAAkC,EAClC,+BAA+B,GAChC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,wBAAwB,EACxB,4BAA4B,EAC5B,+BAA+B,GAChC,MAAM,0BAA0B,CAAC;AAQlC,MAAM,CAAC,MAAM,sBAAsB,GAAuB;IACxD,QAAQ,EAAE,IAAI;IACd,aAAa,EAAE,IAAI;IACnB,MAAM,EAAE,IAAI;IACZ,WAAW,EAAE,IAAI;IACjB,iBAAiB,EAAE,IAAI;CACxB,CAAC;AAEF,MAAM,CAAC,MAAM,0BAA0B,GACrC,sBAAsB,CAAC,eAAe,CAAC;AACzC,MAAM,CAAC,MAAM,uBAAuB,GAAG,sBAAsB,CAAC,YAAY,CAAC;AAE3E,MAAM,eAAe;IACV,IAAI,GAAG,WAAW,CAAC;IACnB,KAAK,GAAG,wBAAwB,CAAC;IACjC,YAAY,GAAG,uBAAuB,CAAC;IACvC,eAAe,GAAG,0BAA0B,CAAC;IAC7C,YAAY,GAAG,sBAAsB,CAAC;IAE9B,MAAM,CAAS;IAEhC,YAAY,MAAc;QACxB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED,KAAK,CAA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MAAM,GAA4B,EAAE;IAEpC,MAAM,gBAAgB,GAAG,MAAM,CAAC,gBAAgB,KAAK,KAAK,CAAC;IAC3D,MAAM,MAAM,GACT,MAAM,CAAC,MAA6B;QACrC,CAAC,gBAAgB,CAAC,CAAC,CAAC,uBAAuB,CAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACtE,EAAE,CAAC;IACL,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,wDAAwD;QACxD,OAAO;YACL,IAAI,EAAE,WAAW;YACjB,KAAK,EAAE,wBAAwB;YAC/B,YAAY,EAAE,uBAAuB;YACrC,eAAe,EAAE,0BAA0B;YAC3C,YAAY,EAAE,sBAAsB;YACpC,KAAK,CAAC,CAAC,MAAM;gBACX,MAAM;oBACJ,IAAI,EAAE,MAAe;oBACrB,MAAM,EAAE,OAAgB;oBACxB,KAAK,EAAE,+BAA+B;oBACtC,SAAS,EAAE,kCAAkC;iBAC9C,CAAC;YACJ,CAAC;SACF,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,eAAe,CAAC,MAAM,CAAC,CAAC;AACrC,CAAC","sourcesContent":["/**\n * AnthropicEngine — wraps @anthropic-ai/sdk for use as an AgentEngine.\n *\n * This is the default, best-in-class engine. It supports all Anthropic-native\n * features: extended thinking, prompt caching, vision, computer use, and\n * parallel tool calls.\n *\n * All providerOptions.anthropic fields are forwarded directly to the SDK.\n */\n\nimport {\n clearProviderCredentialAuthFailure,\n readDeployCredentialEnv,\n recordProviderCredentialAuthFailure,\n} from \"../../server/credential-provider.js\";\nimport { normalizeReasoningEffortForModel } from \"../../shared/reasoning-effort.js\";\nimport { ANTHROPIC_MODEL_CONFIG } from \"../model-config.js\";\nimport {\n LLM_MISSING_CREDENTIALS_ERROR_CODE,\n LLM_MISSING_CREDENTIALS_MESSAGE,\n} from \"./credential-errors.js\";\nimport { resolveMaxOutputTokensForEngine } from \"./output-tokens.js\";\nimport {\n engineToolsToAnthropic,\n engineMessagesToAnthropic,\n anthropicContentToEngine,\n anthropicChunkToEngineEvents,\n createAnthropicChunkStreamState,\n} from \"./translate-anthropic.js\";\nimport type {\n AgentEngine,\n EngineCapabilities,\n EngineStreamOptions,\n EngineEvent,\n} from \"./types.js\";\n\nexport const ANTHROPIC_CAPABILITIES: EngineCapabilities = {\n thinking: true,\n promptCaching: true,\n vision: true,\n computerUse: true,\n parallelToolCalls: true,\n};\n\nexport const ANTHROPIC_SUPPORTED_MODELS =\n ANTHROPIC_MODEL_CONFIG.supportedModels;\nexport const ANTHROPIC_DEFAULT_MODEL = ANTHROPIC_MODEL_CONFIG.defaultModel;\n\nclass AnthropicEngine implements AgentEngine {\n readonly name = \"anthropic\";\n readonly label = \"Claude (Anthropic SDK)\";\n readonly defaultModel = ANTHROPIC_DEFAULT_MODEL;\n readonly supportedModels = ANTHROPIC_SUPPORTED_MODELS;\n readonly capabilities = ANTHROPIC_CAPABILITIES;\n\n private readonly apiKey: string;\n\n constructor(apiKey: string) {\n this.apiKey = apiKey;\n }\n\n async *stream(opts: EngineStreamOptions): AsyncIterable<EngineEvent> {\n const Anthropic = (await import(\"@anthropic-ai/sdk\")).default;\n const client = new Anthropic({ apiKey: this.apiKey });\n\n const tools = engineToolsToAnthropic(opts.tools);\n const messages = engineMessagesToAnthropic(opts.messages);\n const anthropicOpts = opts.providerOptions?.anthropic;\n\n // Build extra body params for Anthropic-native features\n const extra: Record<string, unknown> = {};\n if (anthropicOpts?.thinking) {\n extra.thinking = {\n type: anthropicOpts.thinking.type,\n budget_tokens: anthropicOpts.thinking.budgetTokens,\n };\n }\n if (anthropicOpts?.topK !== undefined) {\n extra.top_k = anthropicOpts.topK;\n }\n const reasoningEffort = normalizeReasoningEffortForModel(\n opts.model,\n opts.reasoningEffort,\n );\n if (reasoningEffort) {\n if (!extra.thinking) {\n extra.thinking = { type: \"adaptive\" };\n }\n extra.output_config = { effort: reasoningEffort };\n }\n\n // Apply prompt caching to the system prompt and tools by default.\n // Cache is pure upside: identical prefixes on subsequent turns get ~90%\n // off input cost and much faster time-to-first-token. If the prefix\n // changes turn-to-turn, it's a no-op. Templates can opt out by setting\n // providerOptions.anthropic.cacheControl = false.\n const cacheEnabled = anthropicOpts?.cacheControl !== false;\n const systemBlocks: any[] = [{ type: \"text\", text: opts.systemPrompt }];\n if (cacheEnabled) {\n systemBlocks[0].cache_control = { type: \"ephemeral\" };\n }\n\n // Apply cache_control to the last tool definition when caching is enabled.\n // Anthropic caches the prefix up to and including the last cached block.\n let cachedTools = tools;\n if (cacheEnabled && tools.length > 0) {\n cachedTools = [...tools];\n const last = { ...cachedTools[cachedTools.length - 1] } as any;\n last.cache_control = { type: \"ephemeral\" };\n cachedTools[cachedTools.length - 1] = last;\n }\n\n // Apply a moving cache breakpoint on the last user message's last content\n // block so the entire conversation prefix (system + tools + growing\n // history) is cached turn-over-turn as the thread lengthens. Mirrors the\n // Builder gateway engine's identical handling in builder-engine.ts.\n let cachedMessages = messages;\n if (cacheEnabled && messages.length > 0) {\n let lastUserIdx = -1;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n if ((messages[i] as any).role === \"user\") {\n lastUserIdx = i;\n break;\n }\n }\n if (lastUserIdx >= 0) {\n cachedMessages = [...messages];\n const lastMsg = { ...cachedMessages[lastUserIdx] } as any;\n if (Array.isArray(lastMsg.content) && lastMsg.content.length > 0) {\n const content = [...lastMsg.content];\n const lastBlock = { ...content[content.length - 1] } as any;\n lastBlock.cache_control = { type: \"ephemeral\" };\n content[content.length - 1] = lastBlock;\n lastMsg.content = content;\n cachedMessages[lastUserIdx] = lastMsg;\n }\n }\n }\n\n const requestParams: any = {\n model: opts.model,\n max_tokens: resolveMaxOutputTokensForEngine(\n this.name,\n opts.maxOutputTokens,\n opts.model,\n ),\n system: systemBlocks,\n tools: cachedTools.length > 0 ? cachedTools : undefined,\n messages: cachedMessages,\n ...(opts.temperature !== undefined\n ? { temperature: opts.temperature }\n : {}),\n ...extra,\n };\n\n // Remove undefined tools to avoid Anthropic API validation errors\n if (!requestParams.tools) delete requestParams.tools;\n\n const apiStream = client.messages.stream(requestParams, {\n signal: opts.abortSignal,\n });\n\n // Per-stream state lets the translator carry each tool-call's id/name from\n // its `content_block_start` onto the streamed `input_json_delta` chunks, so\n // long tool-input generation emits countable `tool-input-start` /\n // `tool-input-delta` progress events (mirroring the Builder engine).\n const chunkState = createAnthropicChunkStreamState();\n\n try {\n for await (const chunk of apiStream) {\n const events = anthropicChunkToEngineEvents(chunk, chunkState);\n for (const event of events) {\n yield event;\n }\n }\n\n const finalMessage = await apiStream.finalMessage();\n const assistantContent = anthropicContentToEngine(finalMessage.content);\n\n // Emit usage\n if (finalMessage.usage) {\n yield {\n type: \"usage\",\n inputTokens: finalMessage.usage.input_tokens ?? 0,\n outputTokens: finalMessage.usage.output_tokens ?? 0,\n cacheReadTokens:\n (finalMessage.usage as any).cache_read_input_tokens ?? 0,\n cacheWriteTokens:\n (finalMessage.usage as any).cache_creation_input_tokens ?? 0,\n };\n }\n\n yield { type: \"assistant-content\", parts: assistantContent };\n await clearProviderCredentialAuthFailure({\n key: \"ANTHROPIC_API_KEY\",\n value: this.apiKey,\n });\n\n // Emit stop reason\n const stopReason = finalMessage.stop_reason ?? \"end_turn\";\n yield {\n type: \"stop\",\n reason:\n stopReason === \"tool_use\"\n ? \"tool_use\"\n : stopReason === \"max_tokens\"\n ? \"max_tokens\"\n : \"end_turn\",\n };\n } catch (err: any) {\n const statusCode: number | undefined =\n typeof err?.status === \"number\"\n ? err.status\n : typeof err?.statusCode === \"number\"\n ? err.statusCode\n : undefined;\n if (statusCode === 401) {\n await recordProviderCredentialAuthFailure({\n key: \"ANTHROPIC_API_KEY\",\n value: this.apiKey,\n status: statusCode,\n code: \"http_401\",\n message: err?.message ?? String(err),\n });\n }\n yield {\n type: \"stop\",\n reason: \"error\",\n error: err?.message ?? String(err),\n // Forward the provider HTTP status for EVERY known status, not just\n // 401. The Anthropic SDK reports empty-body failures as a bare\n // \"429 status code (no body)\" message, so without a structured\n // statusCode/errorCode `isRetryableError` couldn't classify a rate\n // limit (it matches \"529\"/\"502\" substrings but not \"429\") and the\n // run failed hard instead of backing off + retrying like the Builder\n // gateway path does. `http_429`/`http_529` also let the run-level\n // continuation logic auto-resume a rate-limited turn.\n ...(statusCode !== undefined\n ? { errorCode: `http_${statusCode}`, statusCode }\n : {}),\n };\n throw err;\n }\n }\n}\n\n/**\n * Create an AnthropicEngine instance.\n * Falls back to the deployment Anthropic key if no key is provided.\n */\nexport function createAnthropicEngine(\n config: Record<string, unknown> = {},\n): AgentEngine {\n const allowEnvFallback = config.allowEnvFallback !== false;\n const apiKey =\n (config.apiKey as string | undefined) ??\n (allowEnvFallback ? readDeployCredentialEnv(\"ANTHROPIC_API_KEY\") : \"\") ??\n \"\";\n if (!apiKey) {\n // Return a \"missing key\" engine that immediately errors\n return {\n name: \"anthropic\",\n label: \"Claude (Anthropic SDK)\",\n defaultModel: ANTHROPIC_DEFAULT_MODEL,\n supportedModels: ANTHROPIC_SUPPORTED_MODELS,\n capabilities: ANTHROPIC_CAPABILITIES,\n async *stream() {\n yield {\n type: \"stop\" as const,\n reason: \"error\" as const,\n error: LLM_MISSING_CREDENTIALS_MESSAGE,\n errorCode: LLM_MISSING_CREDENTIALS_ERROR_CODE,\n };\n },\n };\n }\n return new AnthropicEngine(apiKey);\n}\n"]}
1
+ {"version":3,"file":"anthropic-engine.js","sourceRoot":"","sources":["../../../src/agent/engine/anthropic-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EACL,kCAAkC,EAClC,uBAAuB,EACvB,mCAAmC,GACpC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,gCAAgC,EAAE,MAAM,kCAAkC,CAAC;AACpF,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EACL,kCAAkC,EAClC,+BAA+B,GAChC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,yBAAyB,EACzB,+BAA+B,GAChC,MAAM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uB,CAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACtE,EAAE,CAAC;IACL,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,wDAAwD;QACxD,OAAO;YACL,IAAI,EAAE,WAAW;YACjB,KAAK,EAAE,wBAAwB;YAC/B,YAAY,EAAE,uBAAuB;YACrC,eAAe,EAAE,0BAA0B;YAC3C,YAAY,EAAE,sBAAsB;YACpC,KAAK,CAAC,CAAC,MAAM;gBACX,MAAM;oBACJ,IAAI,EAAE,MAAe;oBACrB,MAAM,EAAE,OAAgB;oBACxB,KAAK,EAAE,+BAA+B;oBACtC,SAAS,EAAE,kCAAkC;iBAC9C,CAAC;YACJ,CAAC;SACF,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,eAAe,CAAC,MAAM,CAAC,CAAC;AACrC,CAAC","sourcesContent":["/**\n * AnthropicEngine — wraps @anthropic-ai/sdk for use as an AgentEngine.\n *\n * This is the default, best-in-class engine. It supports all Anthropic-native\n * features: extended thinking, prompt caching, vision, computer use, and\n * parallel tool calls.\n *\n * All providerOptions.anthropic fields are forwarded directly to the SDK.\n */\n\nimport {\n clearProviderCredentialAuthFailure,\n readDeployCredentialEnv,\n recordProviderCredentialAuthFailure,\n} from \"../../server/credential-provider.js\";\nimport { normalizeReasoningEffortForModel } from \"../../shared/reasoning-effort.js\";\nimport { ANTHROPIC_MODEL_CONFIG } from \"../model-config.js\";\nimport {\n LLM_MISSING_CREDENTIALS_ERROR_CODE,\n LLM_MISSING_CREDENTIALS_MESSAGE,\n} from \"./credential-errors.js\";\nimport {\n clampThinkingBudgetTokens,\n resolveMaxOutputTokensForEngine,\n} from \"./output-tokens.js\";\nimport {\n engineToolsToAnthropic,\n engineMessagesToAnthropic,\n anthropicContentToEngine,\n anthropicChunkToEngineEvents,\n createAnthropicChunkStreamState,\n} from \"./translate-anthropic.js\";\nimport type {\n AgentEngine,\n EngineCapabilities,\n EngineStreamOptions,\n EngineEvent,\n} from \"./types.js\";\n\nexport const ANTHROPIC_CAPABILITIES: EngineCapabilities = {\n thinking: true,\n promptCaching: true,\n vision: true,\n computerUse: true,\n parallelToolCalls: true,\n};\n\nexport const ANTHROPIC_SUPPORTED_MODELS =\n ANTHROPIC_MODEL_CONFIG.supportedModels;\nexport const ANTHROPIC_DEFAULT_MODEL = ANTHROPIC_MODEL_CONFIG.defaultModel;\n\nclass AnthropicEngine implements AgentEngine {\n readonly name = \"anthropic\";\n readonly label = \"Claude (Anthropic SDK)\";\n readonly defaultModel = ANTHROPIC_DEFAULT_MODEL;\n readonly supportedModels = ANTHROPIC_SUPPORTED_MODELS;\n readonly capabilities = ANTHROPIC_CAPABILITIES;\n\n private readonly apiKey: string;\n\n constructor(apiKey: string) {\n this.apiKey = apiKey;\n }\n\n async *stream(opts: EngineStreamOptions): AsyncIterable<EngineEvent> {\n const Anthropic = (await import(\"@anthropic-ai/sdk\")).default;\n const client = new Anthropic({ apiKey: this.apiKey });\n\n const tools = engineToolsToAnthropic(opts.tools);\n const messages = engineMessagesToAnthropic(opts.messages);\n const anthropicOpts = opts.providerOptions?.anthropic;\n\n // Resolved once so both max_tokens and the thinking-budget headroom\n // clamp below agree on the same ceiling.\n const resolvedMaxOutputTokens = resolveMaxOutputTokensForEngine(\n this.name,\n opts.maxOutputTokens,\n opts.model,\n );\n\n // Build extra body params for Anthropic-native features\n const extra: Record<string, unknown> = {};\n if (anthropicOpts?.thinking) {\n extra.thinking = {\n type: anthropicOpts.thinking.type,\n // Only the \"enabled\" config carries a numeric budget_tokens; clamp it\n // so thinking can't consume the entire max_tokens budget and leave\n // zero room for the actual response (\"adaptive\" thinking has no\n // budget_tokens field at all, so it passes through unclamped).\n budget_tokens:\n anthropicOpts.thinking.type === \"enabled\" &&\n typeof anthropicOpts.thinking.budgetTokens === \"number\"\n ? clampThinkingBudgetTokens(\n anthropicOpts.thinking.budgetTokens,\n resolvedMaxOutputTokens,\n )\n : anthropicOpts.thinking.budgetTokens,\n };\n }\n if (anthropicOpts?.topK !== undefined) {\n extra.top_k = anthropicOpts.topK;\n }\n const reasoningEffort = normalizeReasoningEffortForModel(\n opts.model,\n opts.reasoningEffort,\n );\n if (reasoningEffort) {\n if (!extra.thinking) {\n extra.thinking = { type: \"adaptive\" };\n }\n extra.output_config = { effort: reasoningEffort };\n }\n\n // Apply prompt caching to the system prompt and tools by default.\n // Cache is pure upside: identical prefixes on subsequent turns get ~90%\n // off input cost and much faster time-to-first-token. If the prefix\n // changes turn-to-turn, it's a no-op. Templates can opt out by setting\n // providerOptions.anthropic.cacheControl = false.\n const cacheEnabled = anthropicOpts?.cacheControl !== false;\n const systemBlocks: any[] = [{ type: \"text\", text: opts.systemPrompt }];\n if (cacheEnabled) {\n systemBlocks[0].cache_control = { type: \"ephemeral\" };\n }\n\n // Apply cache_control to the last tool definition when caching is enabled.\n // Anthropic caches the prefix up to and including the last cached block.\n let cachedTools = tools;\n if (cacheEnabled && tools.length > 0) {\n cachedTools = [...tools];\n const last = { ...cachedTools[cachedTools.length - 1] } as any;\n last.cache_control = { type: \"ephemeral\" };\n cachedTools[cachedTools.length - 1] = last;\n }\n\n // Apply a moving cache breakpoint on the last user message's last content\n // block so the entire conversation prefix (system + tools + growing\n // history) is cached turn-over-turn as the thread lengthens. Mirrors the\n // Builder gateway engine's identical handling in builder-engine.ts.\n let cachedMessages = messages;\n if (cacheEnabled && messages.length > 0) {\n let lastUserIdx = -1;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n if ((messages[i] as any).role === \"user\") {\n lastUserIdx = i;\n break;\n }\n }\n if (lastUserIdx >= 0) {\n cachedMessages = [...messages];\n const lastMsg = { ...cachedMessages[lastUserIdx] } as any;\n if (Array.isArray(lastMsg.content) && lastMsg.content.length > 0) {\n const content = [...lastMsg.content];\n const lastBlock = { ...content[content.length - 1] } as any;\n lastBlock.cache_control = { type: \"ephemeral\" };\n content[content.length - 1] = lastBlock;\n lastMsg.content = content;\n cachedMessages[lastUserIdx] = lastMsg;\n }\n }\n }\n\n const requestParams: any = {\n model: opts.model,\n max_tokens: resolvedMaxOutputTokens,\n system: systemBlocks,\n tools: cachedTools.length > 0 ? cachedTools : undefined,\n messages: cachedMessages,\n ...(opts.temperature !== undefined\n ? { temperature: opts.temperature }\n : {}),\n ...extra,\n };\n\n // Remove undefined tools to avoid Anthropic API validation errors\n if (!requestParams.tools) delete requestParams.tools;\n\n const apiStream = client.messages.stream(requestParams, {\n signal: opts.abortSignal,\n });\n\n // Per-stream state lets the translator carry each tool-call's id/name from\n // its `content_block_start` onto the streamed `input_json_delta` chunks, so\n // long tool-input generation emits countable `tool-input-start` /\n // `tool-input-delta` progress events (mirroring the Builder engine).\n const chunkState = createAnthropicChunkStreamState();\n\n try {\n for await (const chunk of apiStream) {\n const events = anthropicChunkToEngineEvents(chunk, chunkState);\n for (const event of events) {\n yield event;\n }\n }\n\n const finalMessage = await apiStream.finalMessage();\n const assistantContent = anthropicContentToEngine(finalMessage.content);\n\n // Emit usage\n if (finalMessage.usage) {\n yield {\n type: \"usage\",\n inputTokens: finalMessage.usage.input_tokens ?? 0,\n outputTokens: finalMessage.usage.output_tokens ?? 0,\n cacheReadTokens:\n (finalMessage.usage as any).cache_read_input_tokens ?? 0,\n cacheWriteTokens:\n (finalMessage.usage as any).cache_creation_input_tokens ?? 0,\n };\n }\n\n yield { type: \"assistant-content\", parts: assistantContent };\n await clearProviderCredentialAuthFailure({\n key: \"ANTHROPIC_API_KEY\",\n value: this.apiKey,\n });\n\n // Emit stop reason\n const stopReason = finalMessage.stop_reason ?? \"end_turn\";\n yield {\n type: \"stop\",\n reason:\n stopReason === \"tool_use\"\n ? \"tool_use\"\n : stopReason === \"max_tokens\"\n ? \"max_tokens\"\n : \"end_turn\",\n };\n } catch (err: any) {\n const statusCode: number | undefined =\n typeof err?.status === \"number\"\n ? err.status\n : typeof err?.statusCode === \"number\"\n ? err.statusCode\n : undefined;\n if (statusCode === 401) {\n await recordProviderCredentialAuthFailure({\n key: \"ANTHROPIC_API_KEY\",\n value: this.apiKey,\n status: statusCode,\n code: \"http_401\",\n message: err?.message ?? String(err),\n });\n }\n yield {\n type: \"stop\",\n reason: \"error\",\n error: err?.message ?? String(err),\n // Forward the provider HTTP status for EVERY known status, not just\n // 401. The Anthropic SDK reports empty-body failures as a bare\n // \"429 status code (no body)\" message, so without a structured\n // statusCode/errorCode `isRetryableError` couldn't classify a rate\n // limit (it matches \"529\"/\"502\" substrings but not \"429\") and the\n // run failed hard instead of backing off + retrying like the Builder\n // gateway path does. `http_429`/`http_529` also let the run-level\n // continuation logic auto-resume a rate-limited turn.\n ...(statusCode !== undefined\n ? { errorCode: `http_${statusCode}`, statusCode }\n : {}),\n };\n throw err;\n }\n }\n}\n\n/**\n * Create an AnthropicEngine instance.\n * Falls back to the deployment Anthropic key if no key is provided.\n */\nexport function createAnthropicEngine(\n config: Record<string, unknown> = {},\n): AgentEngine {\n const allowEnvFallback = config.allowEnvFallback !== false;\n const apiKey =\n (config.apiKey as string | undefined) ??\n (allowEnvFallback ? readDeployCredentialEnv(\"ANTHROPIC_API_KEY\") : \"\") ??\n \"\";\n if (!apiKey) {\n // Return a \"missing key\" engine that immediately errors\n return {\n name: \"anthropic\",\n label: \"Claude (Anthropic SDK)\",\n defaultModel: ANTHROPIC_DEFAULT_MODEL,\n supportedModels: ANTHROPIC_SUPPORTED_MODELS,\n capabilities: ANTHROPIC_CAPABILITIES,\n async *stream() {\n yield {\n type: \"stop\" as const,\n reason: \"error\" as const,\n error: LLM_MISSING_CREDENTIALS_MESSAGE,\n errorCode: LLM_MISSING_CREDENTIALS_ERROR_CODE,\n };\n },\n };\n }\n return new AnthropicEngine(apiKey);\n}\n"]}
@@ -2,6 +2,33 @@ export declare const DEFAULT_OPENROUTER_MAX_OUTPUT_TOKENS = 8192;
2
2
  export declare const DEFAULT_AI_SDK_MAX_OUTPUT_TOKENS = 4096;
3
3
  export declare const DEFAULT_ANTHROPIC_MAX_OUTPUT_TOKENS = 8192;
4
4
  export declare const DEFAULT_BUILDER_MAX_OUTPUT_TOKENS = 8192;
5
+ /** Cap for the first attempt of an interactive chat turn. */
6
+ export declare const MAIN_CHAT_MAX_OUTPUT_TOKENS_CAP = 32000;
7
+ /**
8
+ * Cap used only when retrying a turn that came back with an empty final
9
+ * response (see production-agent.ts's empty-final-response retry). Higher
10
+ * than the first-attempt cap so the retry meaningfully raises the ceiling.
11
+ */
12
+ export declare const EMPTY_RESPONSE_RETRY_MAX_OUTPUT_TOKENS_CAP = 64000;
13
+ /**
14
+ * Resolve the max_output_tokens floor for the first attempt of an
15
+ * interactive chat turn: min(model ceiling, 32K). Always at or above the
16
+ * flat per-engine defaults above, regardless of whether the model is known.
17
+ */
18
+ export declare function resolveMainChatMaxOutputTokens(modelId?: string): number;
19
+ /**
20
+ * Resolve the max_output_tokens to use when retrying a turn after an empty
21
+ * final response: min(model ceiling, 64K).
22
+ */
23
+ export declare function resolveEmptyResponseRetryMaxOutputTokens(modelId?: string): number;
24
+ /** Anthropic's documented minimum extended-thinking budget. */
25
+ export declare const ANTHROPIC_MIN_THINKING_BUDGET_TOKENS = 1024;
26
+ /**
27
+ * Clamp a requested Anthropic thinking budget so it leaves guaranteed
28
+ * headroom under `maxOutputTokens` for non-thinking output, and stays within
29
+ * the provider's valid range (>= 1024, < maxOutputTokens).
30
+ */
31
+ export declare function clampThinkingBudgetTokens(requestedBudgetTokens: number, maxOutputTokens: number): number | undefined;
5
32
  export declare function normalizeMaxOutputTokens(value: unknown, modelId?: string): number | null;
6
33
  export declare function defaultMaxOutputTokensForEngine(engineName: string, modelId?: string): number;
7
34
  export declare function resolveMaxOutputTokensForEngine(engineName: string, explicit?: unknown, modelId?: string): number;
@@ -1 +1 @@
1
- {"version":3,"file":"output-tokens.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/output-tokens.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,oCAAoC,OAAO,CAAC;AACzD,eAAO,MAAM,gCAAgC,OAAO,CAAC;AACrD,eAAO,MAAM,mCAAmC,OAAO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