@agent-native/core 0.90.3 → 0.90.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/agent-native.js +25 -3
- package/corpus/README.md +1 -1
- package/corpus/core/CHANGELOG.md +17 -0
- package/corpus/core/bin/agent-native.js +25 -3
- package/corpus/core/package.json +1 -1
- package/corpus/core/src/agent/durable-background.ts +18 -18
- package/corpus/core/src/agent/engine/ai-sdk-engine.ts +8 -2
- package/corpus/core/src/agent/engine/anthropic-engine.ts +11 -1
- package/corpus/core/src/agent/engine/index.ts +1 -0
- package/corpus/core/src/agent/engine/registry.ts +63 -2
- package/corpus/core/src/agent/production-agent.ts +22 -11
- package/corpus/core/src/agent/run-manager.ts +17 -6
- package/corpus/core/src/agent/run-store.ts +16 -11
- package/corpus/core/src/cli/create.ts +35 -0
- package/corpus/core/src/cli/design-connect.ts +263 -1
- package/corpus/core/src/cli/index.ts +84 -7
- package/corpus/core/src/cli/workspacify.ts +34 -0
- package/corpus/core/src/client/KeepTabOpenNotice.tsx +20 -15
- package/corpus/core/src/client/RunStuckBanner.tsx +14 -13
- package/corpus/core/src/client/agent-chat-adapter.ts +28 -17
- package/corpus/core/src/client/history/VersionHistoryPanel.tsx +77 -47
- package/corpus/core/src/client/history/index.ts +3 -0
- package/corpus/core/src/client/history/use-history.ts +28 -0
- package/corpus/core/src/client/index.ts +8 -0
- package/corpus/core/src/client/review/index.ts +5 -0
- package/corpus/core/src/client/review/use-review.ts +40 -2
- package/corpus/core/src/client/use-run-stuck-detection.ts +8 -5
- package/corpus/core/src/history/actions/create-resource-version.ts +11 -8
- package/corpus/core/src/history/index.ts +0 -1
- package/corpus/core/src/history/registry.ts +24 -12
- package/corpus/core/src/history/store.ts +84 -53
- package/corpus/core/src/review/actions/consume-review-feedback.ts +15 -5
- package/corpus/core/src/review/actions/delete-review-comment.ts +15 -3
- package/corpus/core/src/review/actions/resolve-review-thread.ts +12 -5
- package/corpus/core/src/review/index.ts +0 -5
- package/corpus/core/src/review/registry.ts +24 -12
- package/corpus/core/src/review/store.ts +10 -7
- package/corpus/core/src/server/agent-chat-plugin.ts +6 -0
- package/corpus/core/src/server/credential-provider.ts +13 -3
- package/corpus/templates/assets/actions/_preset-skeleton-validation.ts +11 -11
- package/corpus/templates/assets/actions/generate-image.ts +64 -28
- package/corpus/templates/assets/app/components/generation/GenerationResults.tsx +1 -1
- package/corpus/templates/assets/app/routes/brand-kits.$id_.presets.$presetId.tsx +91 -74
- package/corpus/templates/assets/server/lib/generation.ts +29 -4
- package/corpus/templates/assets/server/lib/image-processing.ts +131 -0
- package/corpus/templates/calendar/.agents/skills/event-management/SKILL.md +24 -2
- package/corpus/templates/calendar/AGENTS.md +3 -0
- package/corpus/templates/calendar/actions/create-event.ts +8 -34
- package/corpus/templates/calendar/actions/event-action-helpers.ts +52 -0
- package/corpus/templates/calendar/actions/manage-event-draft.ts +7 -34
- package/corpus/templates/calendar/actions/update-event.ts +10 -23
- package/corpus/templates/calendar/app/components/calendar/AttendeeAutocomplete.tsx +47 -0
- package/corpus/templates/calendar/app/components/calendar/CreateEventDialog.tsx +23 -0
- package/corpus/templates/calendar/app/components/calendar/EventAttendeesSection.tsx +59 -2
- package/corpus/templates/calendar/app/components/calendar/EventDetailPanel.tsx +40 -1
- package/corpus/templates/calendar/app/components/calendar/EventDetailPopover.tsx +34 -1
- package/corpus/templates/calendar/app/hooks/use-events.ts +6 -0
- package/corpus/templates/calendar/app/i18n/zh-TW.ts +4 -0
- package/corpus/templates/calendar/app/i18n-data.ts +40 -0
- package/corpus/templates/calendar/changelog/2026-07-07-you-can-mark-event-guests-as-optional-while-inviting-them-or.md +6 -0
- package/corpus/templates/calendar/server/handlers/events.ts +1 -0
- package/corpus/templates/calendar/server/lib/google-calendar.ts +4 -0
- package/corpus/templates/calendar/server/plugins/agent-chat.ts +1 -1
- package/corpus/templates/calendar/shared/api.ts +2 -0
- package/corpus/templates/clips/.agents/skills/ai-video-tools/SKILL.md +29 -3
- package/corpus/templates/clips/actions/generate-workflow.ts +19 -8
- package/corpus/templates/clips/actions/get-clips-ai-prefs.ts +36 -0
- package/corpus/templates/clips/actions/lib/clips-ai-prefs.ts +28 -0
- package/corpus/templates/clips/actions/regenerate-chapters.ts +21 -7
- package/corpus/templates/clips/actions/regenerate-summary.ts +26 -8
- package/corpus/templates/clips/actions/regenerate-title.ts +44 -7
- package/corpus/templates/clips/actions/update-clips-ai-prefs.ts +50 -0
- package/corpus/templates/clips/app/components/meetings/meeting-card.tsx +7 -2
- package/corpus/templates/clips/app/hooks/use-auto-title.ts +25 -10
- package/corpus/templates/clips/app/i18n/ar-SA.ts +28 -6
- package/corpus/templates/clips/app/i18n/de-DE.ts +28 -6
- package/corpus/templates/clips/app/i18n/en-US.ts +29 -6
- package/corpus/templates/clips/app/i18n/es-ES.ts +29 -6
- package/corpus/templates/clips/app/i18n/fr-FR.ts +30 -6
- package/corpus/templates/clips/app/i18n/hi-IN.ts +26 -6
- package/corpus/templates/clips/app/i18n/ja-JP.ts +27 -6
- package/corpus/templates/clips/app/i18n/ko-KR.ts +28 -6
- package/corpus/templates/clips/app/i18n/pt-BR.ts +28 -6
- package/corpus/templates/clips/app/i18n/zh-CN.ts +26 -6
- package/corpus/templates/clips/app/i18n/zh-TW.ts +25 -6
- package/corpus/templates/clips/app/routes/_app.meetings._index.tsx +73 -0
- package/corpus/templates/clips/app/routes/_app.settings._index.tsx +1 -0
- package/corpus/templates/clips/app/routes/r.$recordingId.tsx +70 -2
- package/corpus/templates/clips/changelog/2026-07-07-ai-tools-can-include-the-full-video-not-just-the-transcript-.md +6 -0
- package/corpus/templates/clips/changelog/2026-07-07-clips-desktop-now-surfaces-meetings-and-dictate-directly-in-.md +6 -0
- package/corpus/templates/clips/changelog/2026-07-07-meeting-notes-now-explain-exactly-how-to-start-granola-style.md +6 -0
- package/corpus/templates/clips/changelog/2026-07-07-meeting-start-alerts-now-include-separate-start-notes-and-jo.md +6 -0
- package/corpus/templates/clips/changelog/2026-07-07-recordings-start-more-predictably-and-newly-saved-clips-refr.md +6 -0
- package/corpus/templates/clips/chrome-extension/public/manifest.json +1 -1
- package/corpus/templates/clips/desktop/src/app.tsx +435 -105
- package/corpus/templates/clips/desktop/src/lib/recorder.ts +27 -21
- package/corpus/templates/clips/desktop/src/overlays/meeting-notification.tsx +23 -22
- package/corpus/templates/clips/desktop/src/styles.css +167 -2
- package/corpus/templates/clips/desktop/src-tauri/src/native_screen.rs +1 -1
- package/corpus/templates/clips/desktop/src-tauri/src/notifications.rs +3 -7
- package/corpus/templates/clips/desktop/src-tauri/src/tray_meetings.rs +5 -4
- package/corpus/templates/clips/server/routes/_agent-native/clips/user-prefs.put.ts +16 -8
- package/corpus/templates/clips/shared/clips-ai-prefs.ts +81 -0
- package/corpus/templates/content/AGENTS.md +1 -0
- package/corpus/templates/content/actions/_database-source-utils.ts +73 -8
- package/corpus/templates/content/actions/_database-utils.ts +2 -1
- package/corpus/templates/content/actions/prepare-builder-source-review.ts +20 -1
- package/corpus/templates/content/actions/stage-builder-source-bulk-update.ts +663 -0
- package/corpus/templates/content/app/components/editor/DocumentProperties.tsx +33 -7
- package/corpus/templates/content/app/components/editor/database/DatabaseView.tsx +53 -4
- package/corpus/templates/content/app/components/editor/database/settings.tsx +24 -0
- package/corpus/templates/content/app/hooks/use-content-database.ts +70 -1
- package/corpus/templates/content/app/hooks/use-document-properties.ts +63 -5
- package/corpus/templates/content/app/i18n/zh-TW.ts +3 -0
- package/corpus/templates/content/app/i18n-data.ts +31 -0
- package/corpus/templates/content/changelog/2026-07-01-builder-source-rows-can-be-staged-in-bulk-with-a-reviewable.md +6 -0
- package/corpus/templates/content/changelog/2026-07-07-builder-backed-database-fields-now-edit-like-normal-content-fields.md +6 -0
- package/corpus/templates/content/parity/matrix.md +24 -24
- package/corpus/templates/content/parity/matrix.ts +2 -0
- package/corpus/templates/content/shared/api.ts +59 -4
- package/corpus/templates/design/.agents/skills/visual-edit/SKILL.md +16 -1
- package/corpus/templates/design/actions/add-localhost-screens.ts +1 -0
- package/corpus/templates/design/actions/connect-localhost.ts +26 -3
- package/corpus/templates/design/actions/open-visual-edit.ts +4 -37
- package/corpus/templates/design/app/components/design/DesignCanvas.tsx +362 -12
- package/corpus/templates/design/app/components/design/bridge/editor-chrome.bridge.ts +89 -14
- package/corpus/templates/design/app/components/design/bridge-security.ts +7 -1
- package/corpus/templates/design/app/components/design/multi-screen/types.ts +1 -1
- package/corpus/templates/design/app/i18n/zh-TW.ts +3 -0
- package/corpus/templates/design/app/i18n-data.ts +41 -0
- package/corpus/templates/design/changelog/2026-07-07-local-visual-edit-keeps-bridge-access-when-opening-previousl.md +6 -0
- package/corpus/templates/design/changelog/2026-07-07-local-visual-edit-now-keeps-the-live-app-connection-authenti.md +6 -0
- package/corpus/templates/design/changelog/2026-07-07-local-visual-edit-uses-live-app-iframes-for-click-to-edit-pr.md +6 -0
- package/dist/agent/durable-background.d.ts +12 -12
- package/dist/agent/durable-background.js +18 -18
- package/dist/agent/durable-background.js.map +1 -1
- package/dist/agent/engine/ai-sdk-engine.d.ts.map +1 -1
- package/dist/agent/engine/ai-sdk-engine.js +8 -2
- package/dist/agent/engine/ai-sdk-engine.js.map +1 -1
- package/dist/agent/engine/anthropic-engine.d.ts.map +1 -1
- package/dist/agent/engine/anthropic-engine.js +11 -1
- package/dist/agent/engine/anthropic-engine.js.map +1 -1
- package/dist/agent/engine/index.d.ts +1 -1
- package/dist/agent/engine/index.d.ts.map +1 -1
- package/dist/agent/engine/index.js +1 -1
- package/dist/agent/engine/index.js.map +1 -1
- package/dist/agent/engine/registry.d.ts +14 -0
- package/dist/agent/engine/registry.d.ts.map +1 -1
- package/dist/agent/engine/registry.js +56 -2
- package/dist/agent/engine/registry.js.map +1 -1
- package/dist/agent/production-agent.d.ts +2 -2
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +18 -11
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/agent/run-manager.d.ts +7 -1
- package/dist/agent/run-manager.d.ts.map +1 -1
- package/dist/agent/run-manager.js +6 -1
- package/dist/agent/run-manager.js.map +1 -1
- package/dist/agent/run-store.d.ts +1 -1
- package/dist/agent/run-store.d.ts.map +1 -1
- package/dist/agent/run-store.js +15 -10
- package/dist/agent/run-store.js.map +1 -1
- package/dist/cli/create.d.ts.map +1 -1
- package/dist/cli/create.js +31 -0
- package/dist/cli/create.js.map +1 -1
- package/dist/cli/design-connect.d.ts.map +1 -1
- package/dist/cli/design-connect.js +197 -1
- package/dist/cli/design-connect.js.map +1 -1
- package/dist/cli/index.js +76 -9
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/workspacify.d.ts.map +1 -1
- package/dist/cli/workspacify.js +30 -0
- package/dist/cli/workspacify.js.map +1 -1
- package/dist/client/KeepTabOpenNotice.d.ts +9 -10
- package/dist/client/KeepTabOpenNotice.d.ts.map +1 -1
- package/dist/client/KeepTabOpenNotice.js +8 -4
- package/dist/client/KeepTabOpenNotice.js.map +1 -1
- package/dist/client/RunStuckBanner.d.ts.map +1 -1
- package/dist/client/RunStuckBanner.js +14 -13
- package/dist/client/RunStuckBanner.js.map +1 -1
- package/dist/client/agent-chat-adapter.d.ts.map +1 -1
- package/dist/client/agent-chat-adapter.js +25 -17
- package/dist/client/agent-chat-adapter.js.map +1 -1
- package/dist/client/history/VersionHistoryPanel.d.ts +1 -1
- package/dist/client/history/VersionHistoryPanel.d.ts.map +1 -1
- package/dist/client/history/VersionHistoryPanel.js +12 -5
- package/dist/client/history/VersionHistoryPanel.js.map +1 -1
- package/dist/client/history/index.d.ts +1 -1
- package/dist/client/history/index.d.ts.map +1 -1
- package/dist/client/history/index.js +1 -1
- package/dist/client/history/index.js.map +1 -1
- package/dist/client/history/use-history.d.ts +12 -0
- package/dist/client/history/use-history.d.ts.map +1 -1
- package/dist/client/history/use-history.js +6 -0
- package/dist/client/history/use-history.js.map +1 -1
- package/dist/client/index.d.ts +2 -2
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +2 -2
- package/dist/client/index.js.map +1 -1
- package/dist/client/review/index.d.ts +1 -1
- package/dist/client/review/index.d.ts.map +1 -1
- package/dist/client/review/index.js +1 -1
- package/dist/client/review/index.js.map +1 -1
- package/dist/client/review/use-review.d.ts +23 -0
- package/dist/client/review/use-review.d.ts.map +1 -1
- package/dist/client/review/use-review.js +8 -0
- package/dist/client/review/use-review.js.map +1 -1
- package/dist/client/use-run-stuck-detection.d.ts +1 -1
- package/dist/client/use-run-stuck-detection.d.ts.map +1 -1
- package/dist/client/use-run-stuck-detection.js +6 -4
- package/dist/client/use-run-stuck-detection.js.map +1 -1
- package/dist/collab/struct-routes.d.ts +1 -1
- package/dist/file-upload/actions/upload-image.d.ts +1 -1
- package/dist/history/actions/create-resource-version.js +7 -4
- package/dist/history/actions/create-resource-version.js.map +1 -1
- package/dist/history/index.d.ts +1 -1
- package/dist/history/index.d.ts.map +1 -1
- package/dist/history/index.js +1 -1
- package/dist/history/index.js.map +1 -1
- package/dist/history/registry.d.ts.map +1 -1
- package/dist/history/registry.js +14 -12
- package/dist/history/registry.js.map +1 -1
- package/dist/history/store.d.ts.map +1 -1
- package/dist/history/store.js +74 -49
- package/dist/history/store.js.map +1 -1
- package/dist/notifications/routes.d.ts +1 -1
- package/dist/resources/handlers.d.ts +3 -3
- package/dist/review/actions/consume-review-feedback.d.ts +1 -0
- package/dist/review/actions/consume-review-feedback.js +8 -2
- package/dist/review/actions/consume-review-feedback.js.map +1 -1
- package/dist/review/actions/delete-review-comment.d.ts +2 -1
- package/dist/review/actions/delete-review-comment.js +11 -3
- package/dist/review/actions/delete-review-comment.js.map +1 -1
- package/dist/review/actions/resolve-review-thread.d.ts +2 -1
- package/dist/review/actions/resolve-review-thread.js +5 -2
- package/dist/review/actions/resolve-review-thread.js.map +1 -1
- package/dist/review/index.d.ts +1 -1
- package/dist/review/index.d.ts.map +1 -1
- package/dist/review/index.js +1 -1
- package/dist/review/index.js.map +1 -1
- package/dist/review/registry.d.ts.map +1 -1
- package/dist/review/registry.js +14 -12
- package/dist/review/registry.js.map +1 -1
- package/dist/review/store.d.ts +3 -3
- package/dist/review/store.d.ts.map +1 -1
- package/dist/review/store.js +7 -4
- package/dist/review/store.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +5 -0
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/agent-engine-api-key-route.d.ts +1 -1
- package/dist/server/credential-provider.d.ts +2 -0
- package/dist/server/credential-provider.d.ts.map +1 -1
- package/dist/server/credential-provider.js +13 -3
- package/dist/server/credential-provider.js.map +1 -1
- 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,+DAA+D;IAC/D,MAAM,SAAS,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE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;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-OFF (opt-in):\n * unset means disabled; an app opts IN with an explicit truthy value\n * (`true`/`1`/`yes`/`on`) — same parsing convention as\n * `AGENT_CHAT_DURABLE_BACKGROUND`, deliberately kept as a separate flag so\n * this narrower capability can be enabled/disabled independently of the full\n * durable-background worker path.\n */\nexport const AGENT_CHAT_FOREGROUND_SELF_CHAIN_ENV =\n \"AGENT_CHAT_FOREGROUND_SELF_CHAIN\";\n\nfunction isForegroundSelfChainFlagEnabled(): boolean {\n // Read the literal key (not `process.env[CONST]`) so guard:no-env-credentials\n // can statically verify it against the allowlisted `AGENT_*` prefix. Keep this\n // in sync with AGENT_CHAT_FOREGROUND_SELF_CHAIN_ENV.\n const raw = process.env.AGENT_CHAT_FOREGROUND_SELF_CHAIN;\n if (raw == null) return false;\n const normalized = raw.trim().toLowerCase();\n return (\n normalized === \"1\" ||\n normalized === \"true\" ||\n normalized === \"yes\" ||\n normalized === \"on\"\n );\n}\n\n/**\n * Gate for the OPT-IN foreground self-chain: a normal (non-durable-background)\n * agent-chat turn that hits its soft-timeout chunk boundary continues via a\n * server-side self-dispatch on the REGULAR function (not a Netlify\n * `-background` function) instead of depending on the client to re-POST\n * `auto_continue`. Composes exactly like `isAgentChatDurableBackgroundEnabled`:\n * true only when the env flag is explicitly truthy AND the runtime is hosted\n * AND `A2A_SECRET` is configured (the HMAC handoff authenticates the\n * self-dispatch). False otherwise — and false means the existing\n * client-driven `auto_continue` re-POST path is used unchanged, byte-for-byte.\n *\n * Deliberately independent of `isAgentChatDurableBackgroundEnabled`: an app can\n * enable 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 isForegroundSelfChainFlagEnabled() &&\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,CAAC;AAED,SAAS,iCAAiC;IACxC,IAAI,OAAO,CAAC,GAAG,CAAC,aAAa,KAAK,MAAM;QAAE,OAAO,KAAK,CA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AED,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai-sdk-engine.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/ai-sdk-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAQH,O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AAMxD,QAAA,MAAM,qBAAqB,EAAE,MAAM,CAAC,aAAa,EAAE,kBAAkB,CAyDpE,CAAC;AAMF,QAAA,MAAM,uBAAuB,EAKxB,MAAM,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;AAEnC,QAAA,MAAM,yBAAyB,EAKf,MAAM,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC;AAEzD,QAAA,MAAM,iBAAiB,EAAE,MAAM,CAAC,aAAa,EAAE,MAAM,EAAE,CAStD,CAAC;AAEF,QAAA,MAAM,iBAAiB,EAAE,MAAM,CAAC,aAAa,EAAE,MAAM,CASpD,CAAC;AA2CF,kDAAkD;AAClD,MAAM,WAAW,iBAAiB;IAChC,sFAAsF;IACtF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wEAAwE;IACxE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,0GAA0G;IAC1G,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,yFAAyF;IACzF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yEAAyE;IACzE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mEAAmE;IACnE,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAqPD,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,aAAa,EACvB,MAAM,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GACnC,WAAW,CAEb;AA8CD,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,yBAAyB,EACzB,iBAAiB,EACjB,iBAAiB,GAClB,CAAC"}
|
|
@@ -317,8 +317,14 @@ class AISDKEngine {
|
|
|
317
317
|
type: "stop",
|
|
318
318
|
reason: "error",
|
|
319
319
|
error: err?.message ?? String(err),
|
|
320
|
-
|
|
321
|
-
|
|
320
|
+
// Tag every known status with `http_<status>` (not just 401) so a
|
|
321
|
+
// rate limit surfaces as `http_429`. The structured statusCode
|
|
322
|
+
// already drives turn-level retries, but the run-level continuation
|
|
323
|
+
// logic keys off the errorCode, so this lets a rate-limited turn
|
|
324
|
+
// auto-resume too — matching the Builder gateway path.
|
|
325
|
+
...(statusCode !== undefined
|
|
326
|
+
? { errorCode: `http_${statusCode}`, statusCode }
|
|
327
|
+
: {}),
|
|
322
328
|
...(providerRetryable !== undefined ? { providerRetryable } : {}),
|
|
323
329
|
};
|
|
324
330
|
throw err;
|
|
@@ -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,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,gCAAgC,EAAE,MAAM,kCAAkC,CAAC;AACpF,OAAO,EAAE,mBAAmB,EAAsB,MAAM,oBAAoB,CAAC;AAC7E,OAAO,EAAE,+BAA+B,EAAE,MAAM,oBAAoB,CAAC;AACrE,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,EAAE,IAAI;QACd,aAAa,EAAE,IAAI;QACnB,MAAM,EAAE,IAAI;QACZ,WAAW,EAAE,KAAK,EAAE,iCAAiC;QACrD,iBAAiB,EAAE,IAAI;KACxB;IACD,MAAM,EAAE;QACN,QAAQ,EAAE,IAAI;QACd,aAAa,EAAE,KAAK;QACpB,MAAM,EAAE,IAAI;QACZ,WAAW,EAAE,KAAK;QAClB,iBAAiB,EAAE,IAAI;KACxB;IACD,UAAU,EAAE;QACV,QAAQ,EAAE,IAAI;QACd,aAAa,EAAE,IAAI;QACnB,MAAM,EAAE,IAAI;QACZ,WAAW,EAAE,KAAK;QAClB,iBAAiB,EAAE,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,CAAC,gBAAgB,CAAC,CAAC;QAClC,KAAK,YAAY;YACf,OAAO,MAAM,CAAC,6BAA6B,CAAC,CAAC;QAC/C,KAAK,QAAQ;YACX,OAAO,MAAM,CAAC,gBAAgB,CAAC,CAAC;QAClC,KAAK,MAAM;YACT,OAAO,MAAM,CAAC,cAAc,CAAC,CAAC;QAChC,KAAK,SAAS;YACZ,OAAO,MAAM,CAAC,iBAAiB,CAAC,CAAC;QACnC,KAAK,QAAQ;YACX,OAAO,MAAM,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 { 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 ...(statusCode === 401 ? { errorCode: \"http_401\" } : {}),\n ...(statusCode !== undefined ? { statusCode } : {}),\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,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AG,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 +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;
|
|
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"}
|
|
@@ -177,7 +177,17 @@ class AnthropicEngine {
|
|
|
177
177
|
type: "stop",
|
|
178
178
|
reason: "error",
|
|
179
179
|
error: err?.message ?? String(err),
|
|
180
|
-
|
|
180
|
+
// Forward the provider HTTP status for EVERY known status, not just
|
|
181
|
+
// 401. The Anthropic SDK reports empty-body failures as a bare
|
|
182
|
+
// "429 status code (no body)" message, so without a structured
|
|
183
|
+
// statusCode/errorCode `isRetryableError` couldn't classify a rate
|
|
184
|
+
// limit (it matches "529"/"502" substrings but not "429") and the
|
|
185
|
+
// run failed hard instead of backing off + retrying like the Builder
|
|
186
|
+
// gateway path does. `http_429`/`http_529` also let the run-level
|
|
187
|
+
// continuation logic auto-resume a rate-limited turn.
|
|
188
|
+
...(statusCode !== undefined
|
|
189
|
+
? { errorCode: `http_${statusCode}`, statusCode }
|
|
190
|
+
: {}),
|
|
181
191
|
};
|
|
182
192
|
throw err;
|
|
183
193
|
}
|
|
@@ -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,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B,OAAO,EAAE,GAAG,EAAE,OAAO,IAAI,MAAM,CAAC,GAAG,CAAC;iBACrC,CAAC,CAAC;YACL,CAAC;YACD,MAAM;gBACJ,IAAI,EAAE,MAAM;gBACZ,MAAM,EAAE,OAAO;gBACf,KAAK,EAAE,GAAG,EAAE,OAAO,IAAI,MAAM,CAAC,GAAG,CAAC;gBAClC,GAAG,CAAC,UAAU,KAAK,GAAG,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,UAAU,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACrE,CAAC;YACF,MAAM,GAAG,CAAC;QACZ,CAAC;IACH,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CACnC,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 ...(statusCode === 401 ? { errorCode: \"http_401\", statusCode } : {}),\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,g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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"]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Public exports for the pluggable agent engine system.
|
|
3
3
|
*/
|
|
4
4
|
export type { AgentEngine, EngineCapabilities, EngineTool, EngineMessage, EngineContentPart, EngineTextPart, EngineImagePart, EngineToolCallPart, EngineToolResultPart, EngineThinkingPart, EngineEvent, EngineStreamOptions, } from "./types.js";
|
|
5
|
-
export { registerAgentEngine, getAgentEngineEntry, listAgentEngines, resolveEngine, getStoredModelForEngine, normalizeModelForEngine, detectEngineFromEnv, detectEngineFromUserSecrets, isAgentEngineSettingConfigured, isAgentEnginePackageInstalled, isStoredEngineUsable, isStoredEngineUsableForRequest, isResolvedEngineUsableForRequest, type AgentEngineEntry, type ResolveEngineConfig, } from "./registry.js";
|
|
5
|
+
export { registerAgentEngine, getAgentEngineEntry, listAgentEngines, resolveEngine, getStoredModelForEngine, normalizeModelForEngine, detectEngineFromEnv, detectEngineFromEnvForRequest, detectEngineFromUserSecrets, isAgentEngineSettingConfigured, isAgentEnginePackageInstalled, isStoredEngineUsable, isStoredEngineUsableForRequest, isResolvedEngineUsableForRequest, type AgentEngineEntry, type ResolveEngineConfig, } from "./registry.js";
|
|
6
6
|
export { createBuilderEngine, BUILDER_DEFAULT_MODEL, BUILDER_SUPPORTED_MODELS, BUILDER_CAPABILITIES, } from "./builder-engine.js";
|
|
7
7
|
export { createAnthropicEngine, ANTHROPIC_DEFAULT_MODEL, ANTHROPIC_SUPPORTED_MODELS, ANTHROPIC_CAPABILITIES, } from "./anthropic-engine.js";
|
|
8
8
|
export { createAISDKEngine, type AISDKProvider } from "./ai-sdk-engine.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,YAAY,EACV,WAAW,EACX,kBAAkB,EAClB,UAAU,EACV,aAAa,EACb,iBAAiB,EACjB,cAAc,EACd,eAAe,EACf,kBAAkB,EAClB,oBAAoB,EACpB,kBAAkB,EAClB,WAAW,EACX,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,uBAAuB,EACvB,uBAAuB,EACvB,mBAAmB,EACnB,2BAA2B,EAC3B,8BAA8B,EAC9B,6BAA6B,EAC7B,oBAAoB,EACpB,8BAA8B,EAC9B,gCAAgC,EAChC,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,GACzB,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,0BAA0B,EAC1B,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,iBAAiB,EAAE,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,YAAY,EACV,WAAW,EACX,kBAAkB,EAClB,UAAU,EACV,aAAa,EACb,iBAAiB,EACjB,cAAc,EACd,eAAe,EACf,kBAAkB,EAClB,oBAAoB,EACpB,kBAAkB,EAClB,WAAW,EACX,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,uBAAuB,EACvB,uBAAuB,EACvB,mBAAmB,EACnB,6BAA6B,EAC7B,2BAA2B,EAC3B,8BAA8B,EAC9B,6BAA6B,EAC7B,oBAAoB,EACpB,8BAA8B,EAC9B,gCAAgC,EAChC,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,GACzB,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,0BAA0B,EAC1B,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,iBAAiB,EAAE,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Public exports for the pluggable agent engine system.
|
|
3
3
|
*/
|
|
4
|
-
export { registerAgentEngine, getAgentEngineEntry, listAgentEngines, resolveEngine, getStoredModelForEngine, normalizeModelForEngine, detectEngineFromEnv, detectEngineFromUserSecrets, isAgentEngineSettingConfigured, isAgentEnginePackageInstalled, isStoredEngineUsable, isStoredEngineUsableForRequest, isResolvedEngineUsableForRequest, } from "./registry.js";
|
|
4
|
+
export { registerAgentEngine, getAgentEngineEntry, listAgentEngines, resolveEngine, getStoredModelForEngine, normalizeModelForEngine, detectEngineFromEnv, detectEngineFromEnvForRequest, detectEngineFromUserSecrets, isAgentEngineSettingConfigured, isAgentEnginePackageInstalled, isStoredEngineUsable, isStoredEngineUsableForRequest, isResolvedEngineUsableForRequest, } from "./registry.js";
|
|
5
5
|
export { createBuilderEngine, BUILDER_DEFAULT_MODEL, BUILDER_SUPPORTED_MODELS, BUILDER_CAPABILITIES, } from "./builder-engine.js";
|
|
6
6
|
export { createAnthropicEngine, ANTHROPIC_DEFAULT_MODEL, ANTHROPIC_SUPPORTED_MODELS, ANTHROPIC_CAPABILITIES, } from "./anthropic-engine.js";
|
|
7
7
|
export { createAISDKEngine } from "./ai-sdk-engine.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/agent/engine/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAiBH,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,uBAAuB,EACvB,uBAAuB,EACvB,mBAAmB,EACnB,2BAA2B,EAC3B,8BAA8B,EAC9B,6BAA6B,EAC7B,oBAAoB,EACpB,8BAA8B,EAC9B,gCAAgC,GAGjC,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,0BAA0B,EAC1B,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,iBAAiB,EAAsB,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["/**\n * Public exports for the pluggable agent engine system.\n */\n\nexport type {\n AgentEngine,\n EngineCapabilities,\n EngineTool,\n EngineMessage,\n EngineContentPart,\n EngineTextPart,\n EngineImagePart,\n EngineToolCallPart,\n EngineToolResultPart,\n EngineThinkingPart,\n EngineEvent,\n EngineStreamOptions,\n} from \"./types.js\";\n\nexport {\n registerAgentEngine,\n getAgentEngineEntry,\n listAgentEngines,\n resolveEngine,\n getStoredModelForEngine,\n normalizeModelForEngine,\n detectEngineFromEnv,\n detectEngineFromUserSecrets,\n isAgentEngineSettingConfigured,\n isAgentEnginePackageInstalled,\n isStoredEngineUsable,\n isStoredEngineUsableForRequest,\n isResolvedEngineUsableForRequest,\n type AgentEngineEntry,\n type ResolveEngineConfig,\n} from \"./registry.js\";\n\nexport {\n createBuilderEngine,\n BUILDER_DEFAULT_MODEL,\n BUILDER_SUPPORTED_MODELS,\n BUILDER_CAPABILITIES,\n} from \"./builder-engine.js\";\n\nexport {\n createAnthropicEngine,\n ANTHROPIC_DEFAULT_MODEL,\n ANTHROPIC_SUPPORTED_MODELS,\n ANTHROPIC_CAPABILITIES,\n} from \"./anthropic-engine.js\";\nexport { createAISDKEngine, type AISDKProvider } from \"./ai-sdk-engine.js\";\nexport { registerBuiltinEngines } from \"./builtin.js\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/agent/engine/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAiBH,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,uBAAuB,EACvB,uBAAuB,EACvB,mBAAmB,EACnB,6BAA6B,EAC7B,2BAA2B,EAC3B,8BAA8B,EAC9B,6BAA6B,EAC7B,oBAAoB,EACpB,8BAA8B,EAC9B,gCAAgC,GAGjC,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,0BAA0B,EAC1B,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,iBAAiB,EAAsB,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["/**\n * Public exports for the pluggable agent engine system.\n */\n\nexport type {\n AgentEngine,\n EngineCapabilities,\n EngineTool,\n EngineMessage,\n EngineContentPart,\n EngineTextPart,\n EngineImagePart,\n EngineToolCallPart,\n EngineToolResultPart,\n EngineThinkingPart,\n EngineEvent,\n EngineStreamOptions,\n} from \"./types.js\";\n\nexport {\n registerAgentEngine,\n getAgentEngineEntry,\n listAgentEngines,\n resolveEngine,\n getStoredModelForEngine,\n normalizeModelForEngine,\n detectEngineFromEnv,\n detectEngineFromEnvForRequest,\n detectEngineFromUserSecrets,\n isAgentEngineSettingConfigured,\n isAgentEnginePackageInstalled,\n isStoredEngineUsable,\n isStoredEngineUsableForRequest,\n isResolvedEngineUsableForRequest,\n type AgentEngineEntry,\n type ResolveEngineConfig,\n} from \"./registry.js\";\n\nexport {\n createBuilderEngine,\n BUILDER_DEFAULT_MODEL,\n BUILDER_SUPPORTED_MODELS,\n BUILDER_CAPABILITIES,\n} from \"./builder-engine.js\";\n\nexport {\n createAnthropicEngine,\n ANTHROPIC_DEFAULT_MODEL,\n ANTHROPIC_SUPPORTED_MODELS,\n ANTHROPIC_CAPABILITIES,\n} from \"./anthropic-engine.js\";\nexport { createAISDKEngine, type AISDKProvider } from \"./ai-sdk-engine.js\";\nexport { registerBuiltinEngines } from \"./builtin.js\";\n"]}
|
|
@@ -48,8 +48,19 @@ export declare function normalizeModelForEngine(engine: Pick<AgentEngine, "name"
|
|
|
48
48
|
* on the first pass, so an explicit provider key (ANTHROPIC_API_KEY etc.)
|
|
49
49
|
* is picked instead. Builder is still used as the fallback when no other
|
|
50
50
|
* provider key is set.
|
|
51
|
+
*
|
|
52
|
+
* This sync helper is for CLI/status callers that cannot await settings. Prefer
|
|
53
|
+
* {@link detectEngineFromEnvForRequest} at request time so sticky auth-failure
|
|
54
|
+
* markers can skip rejected deploy keys.
|
|
51
55
|
*/
|
|
52
56
|
export declare function detectEngineFromEnv(): AgentEngineEntry | null;
|
|
57
|
+
/**
|
|
58
|
+
* Request-aware env auto-detect. Same priority as {@link detectEngineFromEnv},
|
|
59
|
+
* but skips provider keys that currently have an auth-failure marker so a
|
|
60
|
+
* rejected deploy key does not permanently win selection and leave chat stuck
|
|
61
|
+
* on `missing_credentials`.
|
|
62
|
+
*/
|
|
63
|
+
export declare function detectEngineFromEnvForRequest(): Promise<AgentEngineEntry | null>;
|
|
53
64
|
/**
|
|
54
65
|
* Detect a usable engine from the current request user's accessible
|
|
55
66
|
* `app_secrets` rows. Mirrors `detectEngineFromEnv` but consults the
|
|
@@ -86,6 +97,9 @@ export declare function isAgentEngineSettingConfigured(stored: unknown): boolean
|
|
|
86
97
|
* AND an API key for it is reachable via the engine's required env vars.
|
|
87
98
|
* Inline keys on the global settings row are ignored; see
|
|
88
99
|
* `isAgentEngineSettingConfigured`.
|
|
100
|
+
*
|
|
101
|
+
* Sync helper for CLI/status. Prefer {@link isStoredEngineUsableForRequest}
|
|
102
|
+
* so sticky auth-failure markers are respected.
|
|
89
103
|
*/
|
|
90
104
|
export declare function isStoredEngineUsable(stored: unknown, entry: AgentEngineEntry): boolean;
|
|
91
105
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAiBH,OAAO,KAAK,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAIlE,MAAM,WAAW,gBAAgB;IAC/B,yEAAyE;IACzE,IAAI,EAAE,MAAM,CAAC;IACb,kCAAkC;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,0CAA0C;IAC1C,WAAW,EAAE,MAAM,CAAC;IACpB,+DAA+D;IAC/D,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,0BAA0B;IAC1B,YAAY,EAAE,kBAAkB,CAAC;IACjC,2BAA2B;IAC3B,YAAY,EAAE,MAAM,CAAC;IACrB,mDAAmD;IACnD,eAAe,EAAE,SAAS,MAA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AAgC,CACpD,MAAM,EAAE,WAAW,EACnB,OAAO,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAO,GAChC,OAAO,CAAC,OAAO,CAAC,CA+BlB;AAED,MAAM,WAAW,mBAAmB;IAClC,0EAA0E;IAC1E,YAAY,CAAC,EACT,MAAM,GACN,WAAW,GACX;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAC;IACtD,uDAAuD;IACvD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,qDAAqD;IACrD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,kEAAkE;IAClE,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,aAAa,CACjC,MAAM,EAAE,mBAAmB,GAC1B,OAAO,CAAC,WAAW,CAAC,CAwHtB;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,uBAAuB,CAC3C,MAAM,EAAE,WAAW,GAAG,MAAM,EAC5B,OAAO,GAAE;IAAE,KAAK,CAAC,EAAE,MAAM,CAAA;CAAO,GAC/B,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAgC7B"}
|
|
@@ -105,6 +105,10 @@ function assertAgentEnginePackageInstalled(entry) {
|
|
|
105
105
|
* on the first pass, so an explicit provider key (ANTHROPIC_API_KEY etc.)
|
|
106
106
|
* is picked instead. Builder is still used as the fallback when no other
|
|
107
107
|
* provider key is set.
|
|
108
|
+
*
|
|
109
|
+
* This sync helper is for CLI/status callers that cannot await settings. Prefer
|
|
110
|
+
* {@link detectEngineFromEnvForRequest} at request time so sticky auth-failure
|
|
111
|
+
* markers can skip rejected deploy keys.
|
|
108
112
|
*/
|
|
109
113
|
export function detectEngineFromEnv() {
|
|
110
114
|
const preferByo = /^(1|true)$/i.test(process.env.AGENT_ENGINE_PREFER_BYO_KEY ?? "");
|
|
@@ -135,6 +139,52 @@ export function detectEngineFromEnv() {
|
|
|
135
139
|
}
|
|
136
140
|
return null;
|
|
137
141
|
}
|
|
142
|
+
async function envKeyUsableForEntry(entry, key) {
|
|
143
|
+
if (!(canUseDeployCredentialFallbackForRequest(key) &&
|
|
144
|
+
!!readDeployCredentialEnv(key))) {
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
if (entry.name === "builder") {
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
const value = readDeployCredentialEnv(key);
|
|
151
|
+
if (!value)
|
|
152
|
+
return false;
|
|
153
|
+
return !(await getProviderCredentialAuthFailure({ key, value }));
|
|
154
|
+
}
|
|
155
|
+
async function hasUsableEnvKeys(entry) {
|
|
156
|
+
if (!isAgentEnginePackageInstalled(entry))
|
|
157
|
+
return false;
|
|
158
|
+
if (entry.requiredEnvVars.length === 0)
|
|
159
|
+
return false;
|
|
160
|
+
for (const key of entry.requiredEnvVars) {
|
|
161
|
+
if (!(await envKeyUsableForEntry(entry, key)))
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Request-aware env auto-detect. Same priority as {@link detectEngineFromEnv},
|
|
168
|
+
* but skips provider keys that currently have an auth-failure marker so a
|
|
169
|
+
* rejected deploy key does not permanently win selection and leave chat stuck
|
|
170
|
+
* on `missing_credentials`.
|
|
171
|
+
*/
|
|
172
|
+
export async function detectEngineFromEnvForRequest() {
|
|
173
|
+
const preferByo = /^(1|true)$/i.test(process.env.AGENT_ENGINE_PREFER_BYO_KEY ?? "");
|
|
174
|
+
if (preferByo) {
|
|
175
|
+
for (const entry of _registry.values()) {
|
|
176
|
+
if (entry.name === "builder")
|
|
177
|
+
continue;
|
|
178
|
+
if (await hasUsableEnvKeys(entry))
|
|
179
|
+
return entry;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
for (const entry of _registry.values()) {
|
|
183
|
+
if (await hasUsableEnvKeys(entry))
|
|
184
|
+
return entry;
|
|
185
|
+
}
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
138
188
|
function shouldTraceEngineDetection() {
|
|
139
189
|
return /^(1|true)$/i.test(process.env.AGENT_NATIVE_DEBUG_AGENT_ENGINE_DETECT ??
|
|
140
190
|
process.env.AGENT_NATIVE_DEBUG_CREDENTIAL_RESOLVE ??
|
|
@@ -303,6 +353,9 @@ async function engineCreateConfigForEntry(entry, apiKey, extra) {
|
|
|
303
353
|
* AND an API key for it is reachable via the engine's required env vars.
|
|
304
354
|
* Inline keys on the global settings row are ignored; see
|
|
305
355
|
* `isAgentEngineSettingConfigured`.
|
|
356
|
+
*
|
|
357
|
+
* Sync helper for CLI/status. Prefer {@link isStoredEngineUsableForRequest}
|
|
358
|
+
* so sticky auth-failure markers are respected.
|
|
306
359
|
*/
|
|
307
360
|
export function isStoredEngineUsable(stored, entry) {
|
|
308
361
|
if (!isAgentEnginePackageInstalled(entry))
|
|
@@ -470,8 +523,9 @@ export async function resolveEngine(config) {
|
|
|
470
523
|
return detectedFromUser.create(await engineCreateConfigForEntry(detectedFromUser, apiKey));
|
|
471
524
|
}
|
|
472
525
|
// 8. Auto-detect from any provider env var — so just dropping a key in
|
|
473
|
-
// .env works without also setting AGENT_ENGINE.
|
|
474
|
-
|
|
526
|
+
// .env works without also setting AGENT_ENGINE. Skip keys with active
|
|
527
|
+
// auth-failure markers so a rejected deploy key cannot permanently win.
|
|
528
|
+
const detected = await detectEngineFromEnvForRequest();
|
|
475
529
|
if (detected) {
|
|
476
530
|
return detected.create(await engineCreateConfigForEntry(detected, apiKey));
|
|
477
531
|
}
|