@agent-native/core 0.98.4 → 0.98.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/corpus/README.md +2 -2
- package/corpus/core/CHANGELOG.md +28 -0
- package/corpus/core/docs/content/durable-background-runs.mdx +37 -0
- package/corpus/core/docs/content/external-agents.mdx +62 -7
- package/corpus/core/docs/content/locales/ar-SA/external-agents.mdx +38 -7
- package/corpus/core/docs/content/locales/ar-SA/tracking.mdx +2 -0
- package/corpus/core/docs/content/locales/de-DE/external-agents.mdx +39 -7
- package/corpus/core/docs/content/locales/de-DE/tracking.mdx +2 -0
- package/corpus/core/docs/content/locales/es-ES/external-agents.mdx +39 -7
- package/corpus/core/docs/content/locales/es-ES/tracking.mdx +2 -0
- package/corpus/core/docs/content/locales/fr-FR/external-agents.mdx +39 -7
- package/corpus/core/docs/content/locales/fr-FR/tracking.mdx +4 -2
- package/corpus/core/docs/content/locales/hi-IN/external-agents.mdx +38 -7
- package/corpus/core/docs/content/locales/hi-IN/tracking.mdx +2 -0
- package/corpus/core/docs/content/locales/ja-JP/external-agents.mdx +38 -7
- package/corpus/core/docs/content/locales/ja-JP/tracking.mdx +2 -0
- package/corpus/core/docs/content/locales/ko-KR/external-agents.mdx +38 -7
- package/corpus/core/docs/content/locales/ko-KR/tracking.mdx +2 -0
- package/corpus/core/docs/content/locales/pt-BR/external-agents.mdx +39 -7
- package/corpus/core/docs/content/locales/pt-BR/tracking.mdx +2 -0
- package/corpus/core/docs/content/locales/zh-CN/external-agents.mdx +37 -7
- package/corpus/core/docs/content/locales/zh-CN/tracking.mdx +2 -0
- package/corpus/core/docs/content/locales/zh-TW/durable-background-runs.mdx +14 -0
- package/corpus/core/docs/content/locales/zh-TW/external-agents.mdx +37 -7
- package/corpus/core/docs/content/locales/zh-TW/tracking.mdx +2 -0
- package/corpus/core/docs/content/tracking.mdx +2 -0
- package/corpus/core/package.json +1 -1
- package/corpus/core/src/a2a/handlers.ts +95 -21
- package/corpus/core/src/a2a/task-store.ts +65 -3
- package/corpus/core/src/agent/durable-background.ts +16 -16
- package/corpus/core/src/agent/engine/ai-sdk-engine.ts +25 -8
- package/corpus/core/src/agent/engine/anthropic-engine.ts +17 -3
- package/corpus/core/src/agent/engine/output-tokens.ts +6 -6
- package/corpus/core/src/agent/production-agent.ts +200 -27
- package/corpus/core/src/agent/run-manager.ts +81 -1
- package/corpus/core/src/agent/run-store.ts +301 -41
- package/corpus/core/src/client/AgentPanel.tsx +6 -2
- package/corpus/core/src/client/AssistantChat.tsx +364 -69
- package/corpus/core/src/client/agent-chat-adapter.ts +169 -1
- package/corpus/core/src/client/chat/message-components.tsx +3 -0
- package/corpus/core/src/client/chat/tool-call-display.tsx +20 -36
- package/corpus/core/src/client/conversation/use-near-bottom-autoscroll.ts +7 -0
- package/corpus/core/src/client/extensions/AgentNativeExtensionFrame.tsx +2 -0
- package/corpus/core/src/client/extensions/EmbeddedExtension.tsx +2 -0
- package/corpus/core/src/client/extensions/ExtensionEditor.tsx +9 -2
- package/corpus/core/src/client/extensions/ExtensionViewer.tsx +2 -0
- package/corpus/core/src/client/extensions/InlineExtensionFrame.tsx +2 -0
- package/corpus/core/src/client/extensions/portable-extension.ts +2 -0
- package/corpus/core/src/client/session-replay.ts +361 -29
- package/corpus/core/src/client/sse-event-processor.ts +43 -1
- package/corpus/core/src/demo/actions/toggle-demo-mode.ts +1 -1
- package/corpus/core/src/demo/config.ts +6 -6
- package/corpus/core/src/demo/fetch-interceptor.ts +13 -4
- package/corpus/core/src/demo/redact.ts +13 -149
- package/corpus/core/src/extensions/html-shell.ts +3 -0
- package/corpus/core/src/extensions/session-replay-iframe.ts +131 -0
- package/corpus/core/src/integrations/adapters/slack.ts +123 -13
- package/corpus/core/src/integrations/identity-links-store.ts +210 -0
- package/corpus/core/src/integrations/identity.ts +132 -0
- package/corpus/core/src/integrations/index.ts +6 -0
- package/corpus/core/src/integrations/plugin.ts +58 -1
- package/corpus/core/src/integrations/types.ts +7 -0
- package/corpus/core/src/mcp/build-server.ts +127 -22
- package/corpus/core/src/mcp/external-agent-policy.ts +18 -0
- package/corpus/core/src/mcp/index.ts +1 -0
- package/corpus/core/src/scripts/agent-engines/list-agent-engines.ts +1 -20
- package/corpus/core/src/server/agent-chat/plugin-options.ts +12 -1
- package/corpus/core/src/server/agent-chat/script-entries.ts +20 -3
- package/corpus/core/src/server/agent-chat-plugin.ts +3 -0
- package/corpus/core/src/session-replay-iframe-protocol.ts +58 -0
- package/corpus/core/src/shared/reasoning-effort.ts +35 -0
- package/corpus/core/src/styles/agent-conversation.css +26 -0
- package/corpus/core/src/templates/workspace-core/.agents/skills/external-agents/SKILL.md +34 -5
- package/corpus/core/src/templates/workspace-core/.agents/skills/observability/SKILL.md +0 -15
- package/corpus/templates/analytics/.agents/skills/session-replay/SKILL.md +30 -21
- package/corpus/templates/analytics/AGENTS.md +27 -0
- package/corpus/templates/analytics/actions/create-session-replay-agent-link.ts +0 -1
- package/corpus/templates/analytics/actions/get-error-issue.ts +1 -0
- package/corpus/templates/analytics/actions/get-session-replay-summary.ts +1 -0
- package/corpus/templates/analytics/actions/get-session-replay-timeline.ts +40 -0
- package/corpus/templates/analytics/actions/list-error-issues.ts +13 -0
- package/corpus/templates/analytics/actions/list-session-recordings.ts +1 -0
- package/corpus/templates/analytics/actions/query-agent-native-analytics.ts +4 -0
- package/corpus/templates/analytics/app/global.css +2 -2
- package/corpus/templates/analytics/app/hooks/use-dashboard-chat-context.ts +41 -4
- package/corpus/templates/analytics/app/pages/sessions/SessionDetailPage.tsx +52 -203
- package/corpus/templates/analytics/app/pages/sessions/SessionsPage.tsx +69 -16
- package/corpus/templates/analytics/changelog/2026-07-12-analytics-chat-retries-before-showing-a-generic-no-data-mess.md +6 -0
- package/corpus/templates/analytics/changelog/2026-07-12-analytics-sessions-search-no-longer-loses-fast-keystrokes-an.md +6 -0
- package/corpus/templates/analytics/changelog/2026-07-12-chart-selection-respects-chat-state.md +6 -0
- package/corpus/templates/analytics/changelog/2026-07-12-connected-external-agents-can-now-look-up-sessions-error-iss.md +6 -0
- package/corpus/templates/analytics/changelog/2026-07-12-demo-mode-anonymizes-error-reporting-emails.md +6 -0
- package/corpus/templates/analytics/changelog/2026-07-12-session-identities-stay-visible-when-demo-mode-is-off.md +6 -0
- package/corpus/templates/analytics/changelog/2026-07-12-session-replays-show-iframe-content.md +6 -0
- package/corpus/templates/analytics/netlify.toml +0 -3
- package/corpus/templates/analytics/server/lib/analytics-connector-catalog.ts +14 -0
- package/corpus/templates/analytics/server/lib/error-capture.ts +101 -2
- package/corpus/templates/analytics/server/lib/real-data-actions.ts +24 -0
- package/corpus/templates/analytics/server/lib/session-replay-agent-context.ts +49 -17
- package/corpus/templates/analytics/server/lib/session-replay.ts +18 -16
- package/corpus/templates/analytics/server/plugins/agent-chat.ts +43 -6
- package/corpus/templates/analytics/server/plugins/db.ts +15 -0
- package/corpus/templates/assets/app/global.css +1 -1
- package/corpus/templates/brain/app/global.css +2 -2
- package/corpus/templates/brain/changelog/2026-07-12-fix-long-response-progress.md +6 -0
- package/corpus/templates/forms/app/components/CloudUpgrade.tsx +1 -1
- package/corpus/templates/forms/app/components/ThemeToggle.tsx +22 -6
- package/corpus/templates/forms/app/components/builder/FieldPropertiesPanel.tsx +5 -5
- package/corpus/templates/forms/app/components/builder/FieldRenderer.tsx +3 -3
- package/corpus/templates/forms/app/components/layout/Sidebar.tsx +16 -16
- package/corpus/templates/forms/app/global.css +164 -13
- package/corpus/templates/forms/app/pages/AskPage.tsx +35 -13
- package/corpus/templates/forms/app/pages/FormBuilderPage.tsx +143 -67
- package/corpus/templates/forms/app/pages/FormFillPage.tsx +44 -11
- package/corpus/templates/forms/app/pages/FormsListPage.tsx +42 -24
- package/corpus/templates/forms/app/pages/ResponseInsightsPage.tsx +28 -15
- package/corpus/templates/forms/app/pages/ResponsesPage.tsx +46 -20
- package/corpus/templates/forms/app/routes/_app.settings.tsx +1 -1
- package/corpus/templates/forms/changelog/2026-07-12-ask-forms-suggestions-now-sit-beneath-the-composer-for-a-tig.md +6 -0
- package/corpus/templates/forms/changelog/2026-07-12-builder-response-tables-now-fill-the-view-without-a-redundan.md +6 -0
- package/corpus/templates/forms/changelog/2026-07-12-form-builder-surfaces-are-calmer-fields-stay-stable-on-hover.md +6 -0
- package/corpus/templates/forms/changelog/2026-07-12-response-tables-now-fill-the-available-pane-with-a-flexible-.md +6 -0
- package/corpus/templates/forms/changelog/2026-07-12-smoother-more-tactile-controls-throughout-animated-icon-and-.md +6 -0
- package/corpus/templates/mail/AGENTS.md +3 -1
- package/corpus/templates/mail/app/components/email/EmailThread.tsx +21 -13
- package/corpus/templates/mail/app/components/email/email-iframe-document.ts +18 -0
- package/corpus/templates/mail/server/lib/mail-integrations.ts +3 -0
- package/dist/a2a/handlers.d.ts.map +1 -1
- package/dist/a2a/handlers.js +84 -15
- package/dist/a2a/handlers.js.map +1 -1
- package/dist/a2a/task-store.d.ts +20 -1
- package/dist/a2a/task-store.d.ts.map +1 -1
- package/dist/a2a/task-store.js +57 -4
- package/dist/a2a/task-store.js.map +1 -1
- package/dist/agent/durable-background.d.ts +10 -10
- package/dist/agent/durable-background.d.ts.map +1 -1
- package/dist/agent/durable-background.js +16 -16
- 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 +19 -8
- 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 -3
- package/dist/agent/engine/anthropic-engine.js.map +1 -1
- package/dist/agent/engine/output-tokens.js +6 -6
- package/dist/agent/engine/output-tokens.js.map +1 -1
- package/dist/agent/production-agent.d.ts +52 -0
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +154 -26
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/agent/run-manager.d.ts +9 -0
- package/dist/agent/run-manager.d.ts.map +1 -1
- package/dist/agent/run-manager.js +71 -1
- package/dist/agent/run-manager.js.map +1 -1
- package/dist/agent/run-store.d.ts +9 -0
- package/dist/agent/run-store.d.ts.map +1 -1
- package/dist/agent/run-store.js +243 -48
- package/dist/agent/run-store.js.map +1 -1
- package/dist/client/AgentPanel.d.ts.map +1 -1
- package/dist/client/AgentPanel.js +6 -2
- package/dist/client/AgentPanel.js.map +1 -1
- package/dist/client/AssistantChat.d.ts +21 -0
- package/dist/client/AssistantChat.d.ts.map +1 -1
- package/dist/client/AssistantChat.js +298 -67
- package/dist/client/AssistantChat.js.map +1 -1
- package/dist/client/agent-chat-adapter.d.ts.map +1 -1
- package/dist/client/agent-chat-adapter.js +146 -1
- package/dist/client/agent-chat-adapter.js.map +1 -1
- package/dist/client/chat/message-components.d.ts.map +1 -1
- package/dist/client/chat/message-components.js +2 -1
- package/dist/client/chat/message-components.js.map +1 -1
- package/dist/client/chat/tool-call-display.d.ts +3 -1
- package/dist/client/chat/tool-call-display.d.ts.map +1 -1
- package/dist/client/chat/tool-call-display.js +13 -37
- package/dist/client/chat/tool-call-display.js.map +1 -1
- package/dist/client/conversation/use-near-bottom-autoscroll.d.ts +1 -0
- package/dist/client/conversation/use-near-bottom-autoscroll.d.ts.map +1 -1
- package/dist/client/conversation/use-near-bottom-autoscroll.js +6 -0
- package/dist/client/conversation/use-near-bottom-autoscroll.js.map +1 -1
- package/dist/client/extensions/AgentNativeExtensionFrame.d.ts.map +1 -1
- package/dist/client/extensions/AgentNativeExtensionFrame.js +2 -1
- package/dist/client/extensions/AgentNativeExtensionFrame.js.map +1 -1
- package/dist/client/extensions/EmbeddedExtension.d.ts.map +1 -1
- package/dist/client/extensions/EmbeddedExtension.js +2 -1
- package/dist/client/extensions/EmbeddedExtension.js.map +1 -1
- package/dist/client/extensions/ExtensionEditor.d.ts.map +1 -1
- package/dist/client/extensions/ExtensionEditor.js +5 -2
- package/dist/client/extensions/ExtensionEditor.js.map +1 -1
- package/dist/client/extensions/ExtensionViewer.d.ts.map +1 -1
- package/dist/client/extensions/ExtensionViewer.js +2 -1
- package/dist/client/extensions/ExtensionViewer.js.map +1 -1
- package/dist/client/extensions/InlineExtensionFrame.d.ts.map +1 -1
- package/dist/client/extensions/InlineExtensionFrame.js +2 -1
- package/dist/client/extensions/InlineExtensionFrame.js.map +1 -1
- package/dist/client/extensions/portable-extension.d.ts.map +1 -1
- package/dist/client/extensions/portable-extension.js +2 -0
- package/dist/client/extensions/portable-extension.js.map +1 -1
- package/dist/client/session-replay.d.ts.map +1 -1
- package/dist/client/session-replay.js +308 -29
- package/dist/client/session-replay.js.map +1 -1
- package/dist/client/sse-event-processor.d.ts +5 -0
- package/dist/client/sse-event-processor.d.ts.map +1 -1
- package/dist/client/sse-event-processor.js +37 -1
- package/dist/client/sse-event-processor.js.map +1 -1
- package/dist/collab/routes.d.ts +1 -1
- package/dist/demo/actions/toggle-demo-mode.js +1 -1
- package/dist/demo/actions/toggle-demo-mode.js.map +1 -1
- package/dist/demo/config.js +6 -6
- package/dist/demo/config.js.map +1 -1
- package/dist/demo/fetch-interceptor.d.ts.map +1 -1
- package/dist/demo/fetch-interceptor.js +13 -4
- package/dist/demo/fetch-interceptor.js.map +1 -1
- package/dist/demo/redact.d.ts +7 -7
- package/dist/demo/redact.d.ts.map +1 -1
- package/dist/demo/redact.js +8 -145
- package/dist/demo/redact.js.map +1 -1
- package/dist/extensions/html-shell.d.ts.map +1 -1
- package/dist/extensions/html-shell.js +2 -0
- package/dist/extensions/html-shell.js.map +1 -1
- package/dist/extensions/session-replay-iframe.d.ts +10 -0
- package/dist/extensions/session-replay-iframe.d.ts.map +1 -0
- package/dist/extensions/session-replay-iframe.js +121 -0
- package/dist/extensions/session-replay-iframe.js.map +1 -0
- package/dist/file-upload/actions/upload-image.d.ts +1 -1
- package/dist/integrations/adapters/slack.d.ts.map +1 -1
- package/dist/integrations/adapters/slack.js +98 -13
- package/dist/integrations/adapters/slack.js.map +1 -1
- package/dist/integrations/identity-links-store.d.ts +23 -0
- package/dist/integrations/identity-links-store.d.ts.map +1 -0
- package/dist/integrations/identity-links-store.js +158 -0
- package/dist/integrations/identity-links-store.js.map +1 -0
- package/dist/integrations/identity.d.ts +11 -0
- package/dist/integrations/identity.d.ts.map +1 -0
- package/dist/integrations/identity.js +100 -0
- package/dist/integrations/identity.js.map +1 -0
- package/dist/integrations/index.d.ts +2 -0
- package/dist/integrations/index.d.ts.map +1 -1
- package/dist/integrations/index.js +2 -0
- package/dist/integrations/index.js.map +1 -1
- package/dist/integrations/plugin.d.ts.map +1 -1
- package/dist/integrations/plugin.js +43 -1
- package/dist/integrations/plugin.js.map +1 -1
- package/dist/integrations/types.d.ts +6 -0
- package/dist/integrations/types.d.ts.map +1 -1
- package/dist/integrations/types.js.map +1 -1
- package/dist/mcp/build-server.d.ts +9 -2
- package/dist/mcp/build-server.d.ts.map +1 -1
- package/dist/mcp/build-server.js +97 -20
- package/dist/mcp/build-server.js.map +1 -1
- package/dist/mcp/external-agent-policy.d.ts +19 -0
- package/dist/mcp/external-agent-policy.d.ts.map +1 -0
- package/dist/mcp/external-agent-policy.js +2 -0
- package/dist/mcp/external-agent-policy.js.map +1 -0
- package/dist/mcp/index.d.ts +1 -0
- package/dist/mcp/index.d.ts.map +1 -1
- package/dist/mcp/index.js.map +1 -1
- package/dist/notifications/routes.d.ts +1 -1
- package/dist/scripts/agent-engines/list-agent-engines.d.ts.map +1 -1
- package/dist/scripts/agent-engines/list-agent-engines.js +1 -19
- package/dist/scripts/agent-engines/list-agent-engines.js.map +1 -1
- package/dist/server/agent-chat/plugin-options.d.ts +11 -1
- package/dist/server/agent-chat/plugin-options.d.ts.map +1 -1
- package/dist/server/agent-chat/plugin-options.js.map +1 -1
- package/dist/server/agent-chat/script-entries.d.ts.map +1 -1
- package/dist/server/agent-chat/script-entries.js +16 -2
- package/dist/server/agent-chat/script-entries.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +3 -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/transcribe-voice.d.ts +1 -1
- package/dist/session-replay-iframe-protocol.d.ts +36 -0
- package/dist/session-replay-iframe-protocol.d.ts.map +1 -0
- package/dist/session-replay-iframe-protocol.js +24 -0
- package/dist/session-replay-iframe-protocol.js.map +1 -0
- package/dist/shared/reasoning-effort.d.ts +11 -0
- package/dist/shared/reasoning-effort.d.ts.map +1 -1
- package/dist/shared/reasoning-effort.js +36 -0
- package/dist/shared/reasoning-effort.js.map +1 -1
- package/dist/styles/agent-conversation.css +26 -0
- package/dist/templates/workspace-core/.agents/skills/external-agents/SKILL.md +34 -5
- package/dist/templates/workspace-core/.agents/skills/observability/SKILL.md +0 -15
- package/docs/content/durable-background-runs.mdx +37 -0
- package/docs/content/external-agents.mdx +62 -7
- package/docs/content/locales/ar-SA/external-agents.mdx +38 -7
- package/docs/content/locales/ar-SA/tracking.mdx +2 -0
- package/docs/content/locales/de-DE/external-agents.mdx +39 -7
- package/docs/content/locales/de-DE/tracking.mdx +2 -0
- package/docs/content/locales/es-ES/external-agents.mdx +39 -7
- package/docs/content/locales/es-ES/tracking.mdx +2 -0
- package/docs/content/locales/fr-FR/external-agents.mdx +39 -7
- package/docs/content/locales/fr-FR/tracking.mdx +4 -2
- package/docs/content/locales/hi-IN/external-agents.mdx +38 -7
- package/docs/content/locales/hi-IN/tracking.mdx +2 -0
- package/docs/content/locales/ja-JP/external-agents.mdx +38 -7
- package/docs/content/locales/ja-JP/tracking.mdx +2 -0
- package/docs/content/locales/ko-KR/external-agents.mdx +38 -7
- package/docs/content/locales/ko-KR/tracking.mdx +2 -0
- package/docs/content/locales/pt-BR/external-agents.mdx +39 -7
- package/docs/content/locales/pt-BR/tracking.mdx +2 -0
- package/docs/content/locales/zh-CN/external-agents.mdx +37 -7
- package/docs/content/locales/zh-CN/tracking.mdx +2 -0
- package/docs/content/locales/zh-TW/durable-background-runs.mdx +14 -0
- package/docs/content/locales/zh-TW/external-agents.mdx +37 -7
- package/docs/content/locales/zh-TW/tracking.mdx +2 -0
- package/docs/content/tracking.mdx +2 -0
- package/package.json +2 -2
- package/src/templates/workspace-core/.agents/skills/external-agents/SKILL.md +34 -5
- package/src/templates/workspace-core/.agents/skills/observability/SKILL.md +0 -15
- package/corpus/core/src/observability/hosted-model-experiment.ts +0 -118
- package/dist/observability/hosted-model-experiment.d.ts +0 -39
- package/dist/observability/hosted-model-experiment.d.ts.map +0 -1
- package/dist/observability/hosted-model-experiment.js +0 -90
- package/dist/observability/hosted-model-experiment.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task-store.js","sourceRoot":"","sources":["../../src/a2a/task-store.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAG3E,IAAI,YAAuC,CAAC;AAE5C,KAAK,UAAU,WAAW;IACxB,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,CAAC,KAAK,IAAI,EAAE;YACzB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;YAC3B,MAAM,SAAS,GAAG;;;;;;;;;;uBAUD,OAAO,EAAE;uBACT,OAAO,EAAE;;OAEzB,CAAC;YAEF,IAAI,UAAU,EAAE,EAAE,CAAC;gBACjB,wEAAwE;gBACxE,kEAAkE;gBAClE,MAAM,iBAAiB,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;gBAChD,oEAAoE;gBACpE,sEAAsE;gBACtE,sEAAsE;gBACtE,oEAAoE;gBACpE,uEAAuE;gBACvE,WAAW;gBACX,MAAM,kBAAkB,CACtB,WAAW,EACX,aAAa,EACb,iEAAiE,CAClE,CAAC;gBACF,OAAO;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CAAC,GAAG,EAAE,CAAC;IACvB,MAAM,SAAS,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAC3C,MAAM,MAAM,CAAC,OAAO,CAAC;QACnB,GAAG,EAAE;;;;;uEAK8D;QACnE,IAAI,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE,EAAE,CAAC;KACpD,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,SAAkB;IAChD,MAAM,WAAW,EAAE,CAAC;IACpB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAE3B,IAAI,SAAS,EAAE,CAAC;QACd,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC;YACpC,GAAG,EAAE,uEAAuE;YAC5E,IAAI,EAAE,CAAC,SAAS,CAAC;SAClB,CAAC,CAAC;QACH,OAAO,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAC/B,CAAC;IAED,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,OAAO,CACnC,kDAAkD,CACnD,CAAC;IACF,OAAO,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import crypto from \"crypto\";\n\nimport { getDbExec, intType, isPostgres } from \"../db/client.js\";\nimport { ensureTableExists, ensureColumnExists } from \"../db/ddl-guard.js\";\nimport type { Task, Message, TaskState, Artifact } from \"./types.js\";\n\nlet _initPromise: Promise<void> | undefined;\n\nasync function ensureTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n const createSql = `\n CREATE TABLE IF NOT EXISTS a2a_tasks (\n id TEXT PRIMARY KEY,\n context_id TEXT,\n status_state TEXT NOT NULL DEFAULT 'submitted',\n status_message TEXT,\n status_timestamp TEXT NOT NULL,\n history TEXT NOT NULL DEFAULT '[]',\n artifacts TEXT NOT NULL DEFAULT '[]',\n metadata TEXT,\n created_at ${intType()} NOT NULL,\n updated_at ${intType()} NOT NULL\n )\n `;\n\n if (isPostgres()) {\n // PG-guard: probe information_schema before issuing DDL to avoid ACCESS\n // EXCLUSIVE lock contention in fresh background-worker processes.\n await ensureTableExists(\"a2a_tasks\", createSql);\n // Additive migration: owner_email column. Bound to the JWT-verified\n // caller at task-creation time so handleGet / handleCancel can reject\n // mismatched callers (the IDOR class fixed in PR #369). Existing rows\n // have NULL owner_email and remain accessible to legacy callers via\n // the legacy-token apiKeyEnv path; new rows are scoped from this point\n // forward.\n await ensureColumnExists(\n \"a2a_tasks\",\n \"owner_email\",\n `ALTER TABLE a2a_tasks ADD COLUMN IF NOT EXISTS owner_email TEXT`,\n );\n return;\n }\n\n // SQLite (local dev): no lock problem — keep the original behaviour.\n await client.execute(createSql);\n // Additive migration: owner_email column. Bound to the JWT-verified\n // caller at task-creation time so handleGet / handleCancel can reject\n // mismatched callers (the IDOR class fixed in PR #369). Existing rows\n // have NULL owner_email and remain accessible to legacy callers via\n // the legacy-token apiKeyEnv path; new rows are scoped from this point\n // forward.\n try {\n await client.execute(\n `ALTER TABLE a2a_tasks ADD COLUMN owner_email TEXT`,\n );\n } catch {\n // Column already exists — expected on every restart after first run.\n }\n })().catch((err) => {\n // Retry init on the next call after a failed startup.\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\nfunction taskFromRow(row: any): Task & { ownerEmail?: string | null } {\n return {\n id: row.id as string,\n contextId: (row.context_id as string) || undefined,\n status: {\n state: row.status_state as TaskState,\n message: row.status_message\n ? JSON.parse(row.status_message as string)\n : undefined,\n timestamp: row.status_timestamp as string,\n },\n history: JSON.parse(row.history as string),\n artifacts: JSON.parse(row.artifacts as string),\n metadata: row.metadata ? JSON.parse(row.metadata as string) : undefined,\n ownerEmail: (row.owner_email as string | null) ?? null,\n };\n}\n\nfunction getAffectedRowCount(result: unknown): number | undefined {\n const resultRecord = result as\n | {\n rowsAffected?: number;\n rowCount?: number;\n count?: number;\n }\n | undefined;\n return (\n resultRecord?.rowsAffected ?? resultRecord?.rowCount ?? resultRecord?.count\n );\n}\n\nexport async function createTask(\n message: Message,\n contextId?: string,\n metadata?: Record<string, unknown>,\n ownerEmail?: string | null,\n): Promise<Task> {\n await ensureTable();\n const client = getDbExec();\n const id = crypto.randomUUID();\n const now = Date.now();\n const timestamp = new Date().toISOString();\n\n const task: Task = {\n id,\n contextId,\n status: { state: \"submitted\", timestamp },\n history: [message],\n artifacts: [],\n metadata,\n };\n\n await client.execute({\n sql: `INSERT INTO a2a_tasks (id, context_id, status_state, status_timestamp, history, artifacts, metadata, owner_email, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n args: [\n id,\n contextId ?? null,\n \"submitted\",\n timestamp,\n JSON.stringify([message]),\n \"[]\",\n metadata ? JSON.stringify(metadata) : null,\n ownerEmail ?? null,\n now,\n now,\n ],\n });\n\n return task;\n}\n\n/**\n * Fetch the verified owner email recorded against a task at creation time.\n * Returns null when the task has no owner (legacy rows or unauthenticated\n * deployments) or when the task is missing.\n *\n * Used by `handleGet` / `handleCancel` to reject IDOR access — the JWT-\n * verified caller's email must match `owner_email` to read or cancel.\n */\nexport async function getTaskOwner(id: string): Promise<string | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT owner_email FROM a2a_tasks WHERE id = ?`,\n args: [id],\n });\n if (rows.length === 0) return null;\n const ownerEmail = (rows[0] as any).owner_email;\n return typeof ownerEmail === \"string\" && ownerEmail ? ownerEmail : null;\n}\n\n/**\n * Atomically claim a task for processing. Only succeeds when the task is in\n * state 'submitted' or 'working' — flipping it to 'processing' so concurrent\n * processors can't pick it up twice. Returns the task if claimed, null if it\n * was already claimed/completed/missing.\n *\n * Used by the cross-platform async processor (`_process-task` route) to avoid\n * duplicate handler runs when retries fire.\n */\nexport async function claimA2ATaskForProcessing(\n id: string,\n): Promise<Task | null> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const timestamp = new Date().toISOString();\n\n const result = await client.execute({\n sql: `UPDATE a2a_tasks\n SET status_state = 'processing',\n status_timestamp = ?,\n updated_at = ?\n WHERE id = ?\n AND status_state IN ('submitted', 'working')`,\n args: [timestamp, now, id],\n });\n const affected = getAffectedRowCount(result);\n if (affected === 0) return null;\n\n const { rows } = await client.execute({\n sql: `SELECT * FROM a2a_tasks WHERE id = ?`,\n args: [id],\n });\n if (rows.length === 0) return null;\n return taskFromRow(rows[0]);\n}\n\nexport async function getA2ATaskDispatchState(id: string): Promise<{\n id: string;\n statusState: string;\n metadata: Record<string, unknown> | undefined;\n updatedAt: number;\n} | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT id, status_state, metadata, updated_at FROM a2a_tasks WHERE id = ?`,\n args: [id],\n });\n const row = rows[0] as any;\n if (!row) return null;\n return {\n id: row.id as string,\n statusState: row.status_state as string,\n metadata: row.metadata ? JSON.parse(row.metadata as string) : undefined,\n updatedAt: Number(row.updated_at ?? 0),\n };\n}\n\nexport async function touchQueuedA2ATaskDispatch(id: string): Promise<boolean> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const result = await client.execute({\n sql: `UPDATE a2a_tasks\n SET updated_at = ?\n WHERE id = ?\n AND status_state IN ('submitted', 'working')`,\n args: [now, id],\n });\n const affected = getAffectedRowCount(result);\n return affected !== 0;\n}\n\nexport async function touchProcessingA2ATask(id: string): Promise<boolean> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const result = await client.execute({\n sql: `UPDATE a2a_tasks\n SET updated_at = ?\n WHERE id = ?\n AND status_state = 'processing'`,\n args: [now, id],\n });\n const affected = getAffectedRowCount(result);\n return affected !== 0;\n}\n\nexport async function resetStuckA2ATaskForRetry(\n id: string,\n processingCutoff: number,\n): Promise<boolean> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const timestamp = new Date().toISOString();\n const result = await client.execute({\n sql: `UPDATE a2a_tasks\n SET status_state = 'working',\n status_timestamp = ?,\n updated_at = ?\n WHERE id = ?\n AND status_state = 'processing'\n AND updated_at <= ?`,\n args: [timestamp, now, id, processingCutoff],\n });\n const affected = getAffectedRowCount(result);\n return affected !== 0;\n}\n\nexport async function failStuckA2ATask(\n id: string,\n processingCutoff: number,\n reason: string,\n): Promise<boolean> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const timestamp = new Date().toISOString();\n const message: Message = {\n role: \"agent\",\n parts: [{ type: \"text\", text: reason }],\n };\n const result = await client.execute({\n sql: `UPDATE a2a_tasks\n SET status_state = 'failed',\n status_message = ?,\n status_timestamp = ?,\n updated_at = ?\n WHERE id = ?\n AND status_state = 'processing'\n AND updated_at <= ?`,\n args: [JSON.stringify(message), timestamp, now, id, processingCutoff],\n });\n const affected = getAffectedRowCount(result);\n return affected !== 0;\n}\n\nexport async function getTask(id: string): Promise<Task | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT * FROM a2a_tasks WHERE id = ?`,\n args: [id],\n });\n if (rows.length === 0) return null;\n return taskFromRow(rows[0]);\n}\n\nexport async function updateTask(\n id: string,\n update: {\n state?: TaskState;\n message?: Message;\n artifacts?: Artifact[];\n },\n): Promise<Task | null> {\n await ensureTable();\n const client = getDbExec();\n\n // Read current task\n const { rows } = await client.execute({\n sql: `SELECT * FROM a2a_tasks WHERE id = ?`,\n args: [id],\n });\n if (rows.length === 0) return null;\n\n const task = taskFromRow(rows[0]);\n const now = Date.now();\n\n if (update.state) {\n task.status = {\n state: update.state,\n message: update.message ?? task.status.message,\n timestamp: new Date().toISOString(),\n };\n }\n\n if (update.message && task.history) {\n task.history.push(update.message);\n }\n\n if (update.artifacts) {\n task.artifacts = [...(task.artifacts ?? []), ...update.artifacts];\n }\n\n await client.execute({\n sql: `UPDATE a2a_tasks SET status_state = ?, status_message = ?, status_timestamp = ?, history = ?, artifacts = ?, updated_at = ? WHERE id = ?`,\n args: [\n task.status.state,\n task.status.message ? JSON.stringify(task.status.message) : null,\n task.status.timestamp,\n JSON.stringify(task.history),\n JSON.stringify(task.artifacts),\n now,\n id,\n ],\n });\n\n return task;\n}\n\nexport async function updateTaskStatusMessage(\n id: string,\n message: Message,\n): Promise<void> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const timestamp = new Date().toISOString();\n await client.execute({\n sql: `UPDATE a2a_tasks\n SET status_message = ?,\n status_timestamp = ?,\n updated_at = ?\n WHERE id = ?\n AND status_state IN ('submitted', 'working', 'processing')`,\n args: [JSON.stringify(message), timestamp, now, id],\n });\n}\n\nexport async function listTasks(contextId?: string): Promise<Task[]> {\n await ensureTable();\n const client = getDbExec();\n\n if (contextId) {\n const { rows } = await client.execute({\n sql: `SELECT * FROM a2a_tasks WHERE context_id = ? ORDER BY created_at DESC`,\n args: [contextId],\n });\n return rows.map(taskFromRow);\n }\n\n const { rows } = await client.execute(\n `SELECT * FROM a2a_tasks ORDER BY created_at DESC`,\n );\n return rows.map(taskFromRow);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"task-store.js","sourceRoot":"","sources":["../../src/a2a/task-store.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAG3E,IAAI,YAAuC,CAAC;AAE5C,KAAK,UAAU,WAAW;IACxB,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,CAAC,KAAK,IAAI,EAAE;YACzB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;YAC3B,MAAM,SAAS,GAAG;;;;;;;;;;uBAUD,OAAO,EAAE;uBACT,OAAO,EAAE;;OAEzB,CAAC;YAEF,IAAI,UAAU,EAAE,EAAE,CAAC;gBACjB,wEAAwE;gBACxE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AU,uBAAuB,CAC3C,EAAU,EACV,OAAgB;IAEhB,MAAM,WAAW,EAAE,CAAC;IACpB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACvB,MAAM,SAAS,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAC3C,MAAM,MAAM,CAAC,OAAO,CAAC;QACnB,GAAG,EAAE;;;;;uEAK8D;QACnE,IAAI,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE,EAAE,CAAC;KACpD,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,SAAkB;IAChD,MAAM,WAAW,EAAE,CAAC;IACpB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAE3B,IAAI,SAAS,EAAE,CAAC;QACd,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC;YACpC,GAAG,EAAE,uEAAuE;YAC5E,IAAI,EAAE,CAAC,SAAS,CAAC;SAClB,CAAC,CAAC;QACH,OAAO,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAC/B,CAAC;IAED,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,OAAO,CACnC,kDAAkD,CACnD,CAAC;IACF,OAAO,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import crypto from \"crypto\";\n\nimport { getDbExec, intType, isPostgres } from \"../db/client.js\";\nimport { ensureTableExists, ensureColumnExists } from \"../db/ddl-guard.js\";\nimport type { Task, Message, TaskState, Artifact } from \"./types.js\";\n\nlet _initPromise: Promise<void> | undefined;\n\nasync function ensureTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n const createSql = `\n CREATE TABLE IF NOT EXISTS a2a_tasks (\n id TEXT PRIMARY KEY,\n context_id TEXT,\n status_state TEXT NOT NULL DEFAULT 'submitted',\n status_message TEXT,\n status_timestamp TEXT NOT NULL,\n history TEXT NOT NULL DEFAULT '[]',\n artifacts TEXT NOT NULL DEFAULT '[]',\n metadata TEXT,\n created_at ${intType()} NOT NULL,\n updated_at ${intType()} NOT NULL\n )\n `;\n\n if (isPostgres()) {\n // PG-guard: probe information_schema before issuing DDL to avoid ACCESS\n // EXCLUSIVE lock contention in fresh background-worker processes.\n await ensureTableExists(\"a2a_tasks\", createSql);\n // Additive migration: owner_email column. Bound to the JWT-verified\n // caller at task-creation time so handleGet / handleCancel can reject\n // mismatched callers (the IDOR class fixed in PR #369). Existing rows\n // have NULL owner_email and remain accessible to legacy callers via\n // the legacy-token apiKeyEnv path; new rows are scoped from this point\n // forward.\n await ensureColumnExists(\n \"a2a_tasks\",\n \"owner_email\",\n `ALTER TABLE a2a_tasks ADD COLUMN IF NOT EXISTS owner_email TEXT`,\n );\n return;\n }\n\n // SQLite (local dev): no lock problem — keep the original behaviour.\n await client.execute(createSql);\n // Additive migration: owner_email column. Bound to the JWT-verified\n // caller at task-creation time so handleGet / handleCancel can reject\n // mismatched callers (the IDOR class fixed in PR #369). Existing rows\n // have NULL owner_email and remain accessible to legacy callers via\n // the legacy-token apiKeyEnv path; new rows are scoped from this point\n // forward.\n try {\n await client.execute(\n `ALTER TABLE a2a_tasks ADD COLUMN owner_email TEXT`,\n );\n } catch {\n // Column already exists — expected on every restart after first run.\n }\n })().catch((err) => {\n // Retry init on the next call after a failed startup.\n _initPromise = undefined;\n throw err;\n });\n }\n return _initPromise;\n}\n\nfunction taskFromRow(row: any): Task & { ownerEmail?: string | null } {\n return {\n id: row.id as string,\n contextId: (row.context_id as string) || undefined,\n status: {\n state: row.status_state as TaskState,\n message: row.status_message\n ? JSON.parse(row.status_message as string)\n : undefined,\n timestamp: row.status_timestamp as string,\n },\n history: JSON.parse(row.history as string),\n artifacts: JSON.parse(row.artifacts as string),\n metadata: row.metadata ? JSON.parse(row.metadata as string) : undefined,\n ownerEmail: (row.owner_email as string | null) ?? null,\n };\n}\n\nfunction getAffectedRowCount(result: unknown): number | undefined {\n const resultRecord = result as\n | {\n rowsAffected?: number;\n rowCount?: number;\n count?: number;\n }\n | undefined;\n return (\n resultRecord?.rowsAffected ?? resultRecord?.rowCount ?? resultRecord?.count\n );\n}\n\nexport async function createTask(\n message: Message,\n contextId?: string,\n metadata?: Record<string, unknown>,\n ownerEmail?: string | null,\n): Promise<Task> {\n await ensureTable();\n const client = getDbExec();\n const id = crypto.randomUUID();\n const now = Date.now();\n const timestamp = new Date().toISOString();\n\n const task: Task = {\n id,\n contextId,\n status: { state: \"submitted\", timestamp },\n history: [message],\n artifacts: [],\n metadata,\n };\n\n await client.execute({\n sql: `INSERT INTO a2a_tasks (id, context_id, status_state, status_timestamp, history, artifacts, metadata, owner_email, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n args: [\n id,\n contextId ?? null,\n \"submitted\",\n timestamp,\n JSON.stringify([message]),\n \"[]\",\n metadata ? JSON.stringify(metadata) : null,\n ownerEmail ?? null,\n now,\n now,\n ],\n });\n\n return task;\n}\n\n/**\n * Fetch the verified owner email recorded against a task at creation time.\n * Returns null when the task has no owner (legacy rows or unauthenticated\n * deployments) or when the task is missing.\n *\n * Used by `handleGet` / `handleCancel` to reject IDOR access — the JWT-\n * verified caller's email must match `owner_email` to read or cancel.\n */\nexport async function getTaskOwner(id: string): Promise<string | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT owner_email FROM a2a_tasks WHERE id = ?`,\n args: [id],\n });\n if (rows.length === 0) return null;\n const ownerEmail = (rows[0] as any).owner_email;\n return typeof ownerEmail === \"string\" && ownerEmail ? ownerEmail : null;\n}\n\n/**\n * Atomically claim a task for processing. Only succeeds when the task is in\n * state 'submitted' or 'working' — flipping it to 'processing' so concurrent\n * processors can't pick it up twice. Returns the task if claimed, null if it\n * was already claimed/completed/missing.\n *\n * Used by the cross-platform async processor (`_process-task` route) to avoid\n * duplicate handler runs when retries fire.\n */\nexport async function claimA2ATaskForProcessing(\n id: string,\n): Promise<Task | null> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const timestamp = new Date().toISOString();\n\n const result = await client.execute({\n sql: `UPDATE a2a_tasks\n SET status_state = 'processing',\n status_timestamp = ?,\n updated_at = ?\n WHERE id = ?\n AND status_state IN ('submitted', 'working')`,\n args: [timestamp, now, id],\n });\n const affected = getAffectedRowCount(result);\n if (affected === 0) return null;\n\n const { rows } = await client.execute({\n sql: `SELECT * FROM a2a_tasks WHERE id = ?`,\n args: [id],\n });\n if (rows.length === 0) return null;\n return taskFromRow(rows[0]);\n}\n\nexport async function getA2ATaskDispatchState(id: string): Promise<{\n id: string;\n statusState: string;\n metadata: Record<string, unknown> | undefined;\n updatedAt: number;\n createdAt: number;\n} | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT id, status_state, metadata, created_at, updated_at FROM a2a_tasks WHERE id = ?`,\n args: [id],\n });\n const row = rows[0] as any;\n if (!row) return null;\n return {\n id: row.id as string,\n statusState: row.status_state as string,\n metadata: row.metadata ? JSON.parse(row.metadata as string) : undefined,\n updatedAt: Number(row.updated_at ?? 0),\n createdAt: Number(row.created_at ?? 0),\n };\n}\n\nexport async function touchQueuedA2ATaskDispatch(id: string): Promise<boolean> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const result = await client.execute({\n sql: `UPDATE a2a_tasks\n SET updated_at = ?\n WHERE id = ?\n AND status_state IN ('submitted', 'working')`,\n args: [now, id],\n });\n const affected = getAffectedRowCount(result);\n return affected !== 0;\n}\n\nexport async function touchProcessingA2ATask(id: string): Promise<boolean> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const result = await client.execute({\n sql: `UPDATE a2a_tasks\n SET updated_at = ?\n WHERE id = ?\n AND status_state = 'processing'`,\n args: [now, id],\n });\n const affected = getAffectedRowCount(result);\n return affected !== 0;\n}\n\nexport async function resetStuckA2ATaskForRetry(\n id: string,\n processingCutoff: number,\n): Promise<boolean> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const timestamp = new Date().toISOString();\n const result = await client.execute({\n sql: `UPDATE a2a_tasks\n SET status_state = 'working',\n status_timestamp = ?,\n updated_at = ?\n WHERE id = ?\n AND status_state = 'processing'\n AND updated_at <= ?`,\n args: [timestamp, now, id, processingCutoff],\n });\n const affected = getAffectedRowCount(result);\n return affected !== 0;\n}\n\n/**\n * Fail a processing task once it is stuck. Two independent conditions can\n * trigger this, either of which alone is sufficient:\n * - `updated_at <= processingCutoff`: no heartbeat/progress touch in a\n * while — the processor likely died.\n * - `created_at <= createdAtCutoff` — a hard wall on total run time. A\n * hung await inside a still-alive process keeps `updated_at` fresh via\n * the liveness heartbeat forever, so staleness alone never trips; age\n * since creation is the only bound that catches it.\n */\nexport async function failStuckA2ATask(\n id: string,\n processingCutoff: number,\n reason: string,\n createdAtCutoff?: number,\n): Promise<boolean> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const timestamp = new Date().toISOString();\n const message: Message = {\n role: \"agent\",\n parts: [{ type: \"text\", text: reason }],\n };\n const ageCondition =\n createdAtCutoff !== undefined\n ? `AND (updated_at <= ? OR created_at <= ?)`\n : `AND updated_at <= ?`;\n const result = await client.execute({\n sql: `UPDATE a2a_tasks\n SET status_state = 'failed',\n status_message = ?,\n status_timestamp = ?,\n updated_at = ?\n WHERE id = ?\n AND status_state = 'processing'\n ${ageCondition}`,\n args:\n createdAtCutoff !== undefined\n ? [\n JSON.stringify(message),\n timestamp,\n now,\n id,\n processingCutoff,\n createdAtCutoff,\n ]\n : [JSON.stringify(message), timestamp, now, id, processingCutoff],\n });\n const affected = getAffectedRowCount(result);\n return affected !== 0;\n}\n\n/**\n * Fail a queued (submitted/working) task whose age since creation exceeds\n * `createdAtCutoff` — the dispatch-retry loop kept throttling/refiring\n * without ever reaching `processing`. Mirrors `failStuckA2ATask` but is\n * gated on the queued state set and on `created_at` (queued tasks have no\n * heartbeat, so staleness of `updated_at` isn't a meaningful signal here).\n */\nexport async function failStuckQueuedA2ATask(\n id: string,\n createdAtCutoff: number,\n reason: string,\n): Promise<boolean> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const timestamp = new Date().toISOString();\n const message: Message = {\n role: \"agent\",\n parts: [{ type: \"text\", text: reason }],\n };\n const result = await client.execute({\n sql: `UPDATE a2a_tasks\n SET status_state = 'failed',\n status_message = ?,\n status_timestamp = ?,\n updated_at = ?\n WHERE id = ?\n AND status_state IN ('submitted', 'working')\n AND created_at <= ?`,\n args: [JSON.stringify(message), timestamp, now, id, createdAtCutoff],\n });\n const affected = getAffectedRowCount(result);\n return affected !== 0;\n}\n\nexport async function getTask(id: string): Promise<Task | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT * FROM a2a_tasks WHERE id = ?`,\n args: [id],\n });\n if (rows.length === 0) return null;\n return taskFromRow(rows[0]);\n}\n\nexport async function updateTask(\n id: string,\n update: {\n state?: TaskState;\n message?: Message;\n artifacts?: Artifact[];\n },\n): Promise<Task | null> {\n await ensureTable();\n const client = getDbExec();\n\n // Read current task\n const { rows } = await client.execute({\n sql: `SELECT * FROM a2a_tasks WHERE id = ?`,\n args: [id],\n });\n if (rows.length === 0) return null;\n\n const task = taskFromRow(rows[0]);\n const now = Date.now();\n\n if (update.state) {\n task.status = {\n state: update.state,\n message: update.message ?? task.status.message,\n timestamp: new Date().toISOString(),\n };\n }\n\n if (update.message && task.history) {\n task.history.push(update.message);\n }\n\n if (update.artifacts) {\n task.artifacts = [...(task.artifacts ?? []), ...update.artifacts];\n }\n\n await client.execute({\n sql: `UPDATE a2a_tasks SET status_state = ?, status_message = ?, status_timestamp = ?, history = ?, artifacts = ?, updated_at = ? WHERE id = ?`,\n args: [\n task.status.state,\n task.status.message ? JSON.stringify(task.status.message) : null,\n task.status.timestamp,\n JSON.stringify(task.history),\n JSON.stringify(task.artifacts),\n now,\n id,\n ],\n });\n\n return task;\n}\n\nexport async function updateTaskStatusMessage(\n id: string,\n message: Message,\n): Promise<void> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const timestamp = new Date().toISOString();\n await client.execute({\n sql: `UPDATE a2a_tasks\n SET status_message = ?,\n status_timestamp = ?,\n updated_at = ?\n WHERE id = ?\n AND status_state IN ('submitted', 'working', 'processing')`,\n args: [JSON.stringify(message), timestamp, now, id],\n });\n}\n\nexport async function listTasks(contextId?: string): Promise<Task[]> {\n await ensureTable();\n const client = getDbExec();\n\n if (contextId) {\n const { rows } = await client.execute({\n sql: `SELECT * FROM a2a_tasks WHERE context_id = ? ORDER BY created_at DESC`,\n args: [contextId],\n });\n return rows.map(taskFromRow);\n }\n\n const { rows } = await client.execute(\n `SELECT * FROM a2a_tasks ORDER BY created_at DESC`,\n );\n return rows.map(taskFromRow);\n}\n"]}
|
|
@@ -128,12 +128,13 @@ export declare function isAgentChatDurableBackgroundEnabled(options?: {
|
|
|
128
128
|
appOptIn?: boolean;
|
|
129
129
|
}): boolean;
|
|
130
130
|
/**
|
|
131
|
-
* Env flag for the FOREGROUND server-driven self-chain. DEFAULT-
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
*
|
|
136
|
-
*
|
|
131
|
+
* Env flag for the FOREGROUND server-driven self-chain. DEFAULT-OFF: a hosted
|
|
132
|
+
* app must explicitly opt in with a truthy value (`true`/`1`/`yes`/`on`). A
|
|
133
|
+
* regular Netlify function has a fixed 60-second wall, and a self-dispatched
|
|
134
|
+
* successor can otherwise be killed before it persists its next continuation.
|
|
135
|
+
* Keep this separate from `AGENT_CHAT_DURABLE_BACKGROUND` so the experimental
|
|
136
|
+
* regular-function chain can be enabled independently after its deployment is
|
|
137
|
+
* proven safe.
|
|
137
138
|
*/
|
|
138
139
|
export declare const AGENT_CHAT_FOREGROUND_SELF_CHAIN_ENV = "AGENT_CHAT_FOREGROUND_SELF_CHAIN";
|
|
139
140
|
/**
|
|
@@ -142,10 +143,9 @@ export declare const AGENT_CHAT_FOREGROUND_SELF_CHAIN_ENV = "AGENT_CHAT_FOREGROU
|
|
|
142
143
|
* server-side self-dispatch on the REGULAR function (not a Netlify
|
|
143
144
|
* `-background` function) instead of depending on the client to re-POST
|
|
144
145
|
* `auto_continue`. Composes exactly like `isAgentChatDurableBackgroundEnabled`:
|
|
145
|
-
* true when the
|
|
146
|
-
* handoff authenticates the
|
|
147
|
-
*
|
|
148
|
-
* `auto_continue` re-POST path is used unchanged, byte-for-byte.
|
|
146
|
+
* true only when the env flag is explicitly truthy, the runtime is hosted, and
|
|
147
|
+
* `A2A_SECRET` is configured (the HMAC handoff authenticates the dispatch).
|
|
148
|
+
* False means the existing client-driven `auto_continue` re-POST path is used.
|
|
149
149
|
*
|
|
150
150
|
* Deliberately independent of `isAgentChatDurableBackgroundEnabled`: an app can
|
|
151
151
|
* use this narrower capability without opting into the full 15-min
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"durable-background.d.ts","sourceRoot":"","sources":["../../src/agent/durable-background.ts"],"names":[],"mappings":"AAgDA;;;;GAIG;AACH,eAAO,MAAM,2BAA2B,2CACE,CAAC;AAE3C;;;;;;;;GAQG;AACH,eAAO,MAAM,8BAA8B,4BAA4B,CAAC;AAExE;;;;;;;;;GASG;AACH,eAAO,MAAM,kCAAkC,gDAA0D,CAAC;AAE1G;;;;;GAKG;AACH,eAAO,MAAM,gCAAgC,2BAA2B,CAAC;AACzE,eAAO,MAAM,8BAA8B,QAAQ,CAAC;AACpD,eAAO,MAAM,gCAAgC,UAAU,CAAC;AACxD,eAAO,MAAM,sCAAsC,gCACpB,CAAC;AAiChC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,sCAAsC,IAAI,MAAM,CAQ/D;AAED,wBAAgB,oCAAoC,CAClD,YAAY,EAAE,MAAM,GACnB,MAAM,CAQR;AAED,wBAAgB,4CAA4C,CAC1D,YAAY,EAAE,MAAM,GACnB,OAAO,CAET;AAED;;;GAGG;AACH,eAAO,MAAM,iCAAiC,kCACb,CAAC;AAElC;;;;;;GAMG;AACH,eAAO,MAAM,+BAA+B,oBAAoB,CAAC;AAEjE;;;;GAIG;AACH,wBAAgB,mCAAmC,IAAI,OAAO,CAsB7D;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,6BAA6B,IAAI,OAAO,CAsBvD;AAED,wBAAgB,2CAA2C,CACzD,MAAM,EAAE,OAAO,GACd,OAAO,CAOT;AAED,wBAAgB,2CAA2C,CACzD,OAAO,EAAE,OAAO,GACf,OAAO,CAKT;AAED,wBAAgB,iCAAiC,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,CAQzE;AAwCD;;;;;;;GAOG;AACH,wBAAgB,mCAAmC,CAAC,OAAO,CAAC,EAAE;IAC5D,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB,GAAG,OAAO,CAWV;AAED
|
|
1
|
+
{"version":3,"file":"durable-background.d.ts","sourceRoot":"","sources":["../../src/agent/durable-background.ts"],"names":[],"mappings":"AAgDA;;;;GAIG;AACH,eAAO,MAAM,2BAA2B,2CACE,CAAC;AAE3C;;;;;;;;GAQG;AACH,eAAO,MAAM,8BAA8B,4BAA4B,CAAC;AAExE;;;;;;;;;GASG;AACH,eAAO,MAAM,kCAAkC,gDAA0D,CAAC;AAE1G;;;;;GAKG;AACH,eAAO,MAAM,gCAAgC,2BAA2B,CAAC;AACzE,eAAO,MAAM,8BAA8B,QAAQ,CAAC;AACpD,eAAO,MAAM,gCAAgC,UAAU,CAAC;AACxD,eAAO,MAAM,sCAAsC,gCACpB,CAAC;AAiChC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,sCAAsC,IAAI,MAAM,CAQ/D;AAED,wBAAgB,oCAAoC,CAClD,YAAY,EAAE,MAAM,GACn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,GAAG,MAAM,GAAG,IAAI,CAahE;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,wBAAwB,CACtC,IAAI,EAAE,OAAO,EACb,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,QAAQ,GAAE,OAAe,GACxB,qBAAqB,CAqDvB"}
|
|
@@ -309,15 +309,16 @@ export function isAgentChatDurableBackgroundEnabled(options) {
|
|
|
309
309
|
hasConfiguredA2ASecret());
|
|
310
310
|
}
|
|
311
311
|
/**
|
|
312
|
-
* Env flag for the FOREGROUND server-driven self-chain. DEFAULT-
|
|
313
|
-
*
|
|
314
|
-
*
|
|
315
|
-
*
|
|
316
|
-
*
|
|
317
|
-
*
|
|
312
|
+
* Env flag for the FOREGROUND server-driven self-chain. DEFAULT-OFF: a hosted
|
|
313
|
+
* app must explicitly opt in with a truthy value (`true`/`1`/`yes`/`on`). A
|
|
314
|
+
* regular Netlify function has a fixed 60-second wall, and a self-dispatched
|
|
315
|
+
* successor can otherwise be killed before it persists its next continuation.
|
|
316
|
+
* Keep this separate from `AGENT_CHAT_DURABLE_BACKGROUND` so the experimental
|
|
317
|
+
* regular-function chain can be enabled independently after its deployment is
|
|
318
|
+
* proven safe.
|
|
318
319
|
*/
|
|
319
320
|
export const AGENT_CHAT_FOREGROUND_SELF_CHAIN_ENV = "AGENT_CHAT_FOREGROUND_SELF_CHAIN";
|
|
320
|
-
function
|
|
321
|
+
function isForegroundSelfChainExplicitlyEnabled() {
|
|
321
322
|
// Read the literal key (not `process.env[CONST]`) so guard:no-env-credentials
|
|
322
323
|
// can statically verify it against the allowlisted `AGENT_*` prefix. Keep this
|
|
323
324
|
// in sync with AGENT_CHAT_FOREGROUND_SELF_CHAIN_ENV.
|
|
@@ -325,10 +326,10 @@ function isForegroundSelfChainExplicitlyDisabled() {
|
|
|
325
326
|
if (raw == null)
|
|
326
327
|
return false;
|
|
327
328
|
const normalized = raw.trim().toLowerCase();
|
|
328
|
-
return (normalized === "
|
|
329
|
-
normalized === "
|
|
330
|
-
normalized === "
|
|
331
|
-
normalized === "
|
|
329
|
+
return (normalized === "1" ||
|
|
330
|
+
normalized === "true" ||
|
|
331
|
+
normalized === "yes" ||
|
|
332
|
+
normalized === "on");
|
|
332
333
|
}
|
|
333
334
|
/**
|
|
334
335
|
* Gate for the foreground self-chain: a normal (non-durable-background)
|
|
@@ -336,10 +337,9 @@ function isForegroundSelfChainExplicitlyDisabled() {
|
|
|
336
337
|
* server-side self-dispatch on the REGULAR function (not a Netlify
|
|
337
338
|
* `-background` function) instead of depending on the client to re-POST
|
|
338
339
|
* `auto_continue`. Composes exactly like `isAgentChatDurableBackgroundEnabled`:
|
|
339
|
-
* true when the
|
|
340
|
-
* handoff authenticates the
|
|
341
|
-
*
|
|
342
|
-
* `auto_continue` re-POST path is used unchanged, byte-for-byte.
|
|
340
|
+
* true only when the env flag is explicitly truthy, the runtime is hosted, and
|
|
341
|
+
* `A2A_SECRET` is configured (the HMAC handoff authenticates the dispatch).
|
|
342
|
+
* False means the existing client-driven `auto_continue` re-POST path is used.
|
|
343
343
|
*
|
|
344
344
|
* Deliberately independent of `isAgentChatDurableBackgroundEnabled`: an app can
|
|
345
345
|
* use this narrower capability without opting into the full 15-min
|
|
@@ -350,7 +350,7 @@ function isForegroundSelfChainExplicitlyDisabled() {
|
|
|
350
350
|
* existing `isBackgroundWorker` path, not this one.
|
|
351
351
|
*/
|
|
352
352
|
export function isAgentChatForegroundSelfChainEnabled() {
|
|
353
|
-
return (
|
|
353
|
+
return (isForegroundSelfChainExplicitlyEnabled() &&
|
|
354
354
|
isHostedRuntimeForDurableBackground() &&
|
|
355
355
|
hasConfiguredA2ASecret());
|
|
356
356
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"durable-background.js","sourceRoot":"","sources":["../../src/agent/durable-background.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,OAAO,EACL,sBAAsB,EAC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,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,CAAC,qBAAqB,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC;QAChD,wEAAwE;QACxE,yEAAyE;QACzE,0EAA0E;QAC1E,gEAAgE;QAChE,OAAO;YACL,EAAE,EAAE,KAAK;YACT,MAAM,EAAE,GAAG;YACX,KAAK,EACH,8IAA8I;YAChJ,KAAK;SACN,CAAC;IACJ,CAAC;IAED,qEAAqE;IACrE,wEAAwE;IACxE,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ,EAAE,CAAC;QAChD,MAAM,CAAC,+BAA+B,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC;IACtD,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAC3C,CAAC","sourcesContent":["/**\n * Durable background agent-chat runs (Netlify background functions).\n *\n * Off by default. When enabled, a long in-app agent-chat turn is dispatched\n * into a Netlify *background* function (15-min budget) instead of completing\n * synchronously under the ~40s soft-timeout. The foreground POST claims the\n * run slot, inserts the run row, fires an HMAC-signed self-dispatch to\n * `AGENT_CHAT_PROCESS_RUN_PATH`, and returns the existing SSE subscription so\n * the client streams the same events (via the cross-isolate SQL-poll path)\n * with no client change.\n *\n * This module owns ONLY the gating decision + shared constants so both the\n * HTTP handler (`production-agent.ts`) and the processor route\n * (`agent-chat-plugin.ts`) agree on when the path is active without a circular\n * import. The actual run machinery is reused verbatim from run-manager /\n * run-store / self-dispatch / internal-token.\n *\n * GUARDRAIL: when `isAgentChatDurableBackgroundEnabled()` returns false, the\n * agent-chat handler must behave byte-for-byte like the current synchronous\n * path. The gate is true only when ALL of these hold:\n * 1. `AGENT_CHAT_DURABLE_BACKGROUND` env is explicitly enabled, or a\n * workspace app's agent-chat plugin opts in with `durableBackgroundRuns`\n * where the workspace deploy emits a per-app background function by\n * default. Single-template Netlify deploys must set the env flag because\n * that same flag controls whether `server-agent-background` is emitted.\n * 2. The runtime is hosted/serverless (local dev keeps the inline path so SSE\n * stays a single live stream and no second function is needed).\n * 3. `A2A_SECRET` is configured (the HMAC handoff is required to authenticate\n * the background dispatch; without it the dispatch can't be trusted).\n *\n * Opt-in keeps the blast radius small while the worker path is still being\n * proven. And even when enabled, a *dispatch failure degrades to an inline run*:\n * if the self-dispatch self-POST can't be delivered (fast connection error or\n * fast non-2xx), the foreground handler runs the turn synchronously instead of\n * erroring (see `production-agent.ts` — the inline fallback claims the run row\n * atomically so a delayed delivery can never double-execute). So an app where\n * durable dispatch happens to fail still gets a working chat, just without the\n * 15-min budget.\n */\nimport {\n hasConfiguredA2ASecret,\n isTrustedLocalRuntime,\n} from \"../a2a/auth-policy.js\";\nimport {\n extractBearerToken,\n verifyInternalToken,\n} from \"../integrations/internal-token.js\";\n\n/**\n * Framework route the background function actually runs — sibling to\n * `AGENT_TEAM_PROCESS_RUN_PATH`. Reached *through* the Netlify background\n * function, so it inherits the 15-min budget.\n */\nexport const AGENT_CHAT_PROCESS_RUN_PATH =\n \"/_agent-native/agent-chat/_process-run\";\n\n/**\n * Name of the standalone Netlify background function the build emits (see\n * `emitSingleTemplateNetlifyBackgroundFunction` in deploy/build.ts). Shared so\n * the emit and the dispatch-path helper below can never drift on the name.\n *\n * MUST end in `-background` — both because that is the conventional Netlify\n * async-function suffix and because `isInBackgroundFunctionRuntime()` reads the\n * `AWS_LAMBDA_FUNCTION_NAME` `-background` suffix as a secondary runtime signal.\n */\nexport const AGENT_BACKGROUND_FUNCTION_NAME = \"server-agent-background\";\n\n/**\n * Default function URL of the background function on Netlify. Every Netlify\n * function is reachable at `/.netlify/functions/<name>` BY DEFAULT; that default\n * url is removed ONLY if the function declares a custom `config.path`. The\n * emitted background function declares NO custom `config.path` (it sets\n * `background: true` and nothing else routing-related), so it KEEPS this default\n * url — and the Nitro `server` function already excludes `/.netlify/*` from its\n * `/*` catch-all, so this namespace is never shadowed. The foreground therefore\n * dispatches HERE on hosted Netlify (see `resolveAgentChatProcessRunDispatchPath`).\n */\nexport const AGENT_BACKGROUND_FUNCTION_URL_PATH = `/.netlify/functions/${AGENT_BACKGROUND_FUNCTION_NAME}`;\n\n/**\n * Marker carried in a Netlify background-function body when the shared\n * long-running worker should route to a processor other than agent chat.\n * The emitted wrapper defaults to the normal agent-chat `_process-run` route;\n * A2A uses this marker to reuse the same 15-minute function for async tasks.\n */\nexport const AGENT_BACKGROUND_PROCESSOR_FIELD = \"__agentNativeProcessor\";\nexport const AGENT_BACKGROUND_PROCESSOR_A2A = \"a2a\";\nexport const AGENT_BACKGROUND_PROCESSOR_ROUTE = \"route\";\nexport const AGENT_BACKGROUND_PROCESSOR_ROUTE_FIELD =\n \"__agentNativeProcessorRoute\";\n\n/**\n * The per-app workspace background function URL path. Workspace deploy emits one\n * background function per app named `<app>-agent-background`, reachable at its\n * DEFAULT url `/.netlify/functions/<app>-agent-background` (no custom\n * `config.path`). The foreground resolves the current workspace app id from\n * `AGENT_NATIVE_WORKSPACE_APP_ID` (set by the workspace function entry) so it can\n * dispatch to the right per-app function url. Returns `null` when no workspace\n * app id is configured (single-template deploy).\n */\nfunction resolveWorkspaceBackgroundFunctionUrlPath(): string | null {\n const raw = process.env.AGENT_NATIVE_WORKSPACE_APP_ID;\n if (typeof raw !== \"string\") return null;\n // Mirror the workspace app-id normalization (resources/store.ts): take the\n // first path segment and accept only the safe slug shape used for function\n // names. Anything else falls back to the single-template name.\n const candidate = raw.trim().replace(/^\\/+/, \"\").split(\"/\")[0] ?? \"\";\n if (!/^[a-z0-9][a-z0-9-]{0,127}$/.test(candidate)) return null;\n return `/.netlify/functions/${candidate}-agent-background`;\n}\n\nfunction isNetlifyHostedRuntimeForDispatch(): boolean {\n if (process.env.NETLIFY_LOCAL === \"true\") return false;\n if (process.env.NETLIFY === \"false\") return false;\n if (process.env.NETLIFY && process.env.NETLIFY !== \"false\") return true;\n // Netlify sets AWS Lambda runtime env on deployed Functions, but the build-time\n // NETLIFY flag is not always present in the runtime isolate. Treat Lambda as\n // Netlify here unless Netlify was explicitly disabled above; non-Netlify AWS\n // falls back inline if the /.netlify/functions dispatch fast-fails.\n return Boolean(process.env.AWS_LAMBDA_FUNCTION_NAME);\n}\n\n/**\n * Resolve the path the foreground POST should self-dispatch the chat background\n * worker to.\n *\n * GROUNDED IN THE REAL NETLIFY BUILD OUTPUT + THE NETLIFY DOCS DEFAULT-URL RULE:\n * the background function is emitted INTO the scanned dir\n * (`.netlify/functions-internal/server-agent-background`, or per-app\n * `<app>-agent-background` for workspaces) with `export const config = {\n * background: true, ... }` and NO custom `config.path`. Because it has no custom\n * path, Netlify keeps its DEFAULT function url `/.netlify/functions/<name>`, and\n * `background: true` makes any invocation of that url ASYNC (immediate 202,\n * 15-min budget). The Nitro `server` function already excludes `/.netlify/*`\n * from its `/*` catch-all, so the default-url namespace is NEVER shadowed by the\n * synchronous function.\n *\n * Therefore on hosted Netlify the foreground dispatches to the function's DEFAULT\n * url (`/.netlify/functions/<name>`); the function entry then rewrites the\n * incoming pathname to `AGENT_CHAT_PROCESS_RUN_PATH` (base-path-prefixed for\n * workspaces) before delegating to the Nitro router, so the `_process-run`\n * plugin runs with the async 15-min budget. Everywhere else (local dev, `netlify\n * dev`, non-Netlify hosts where no second function exists) there is no second\n * function, so the foreground dispatches to the framework route\n * `AGENT_CHAT_PROCESS_RUN_PATH` and the same in-process catch-all handles it\n * inline. The HMAC token (signed over the runId) is unchanged either way.\n *\n * NOTE: this is the DOC-CORRECT approach. An earlier attempt gave the function a\n * custom `config.path` + a catch-all `excludedPath` patch; the custom path was\n * NOT honored as a route in prod (probe → 404). Using the default function url\n * (no custom path) is what Netlify documents and is simpler — there is nothing\n * to shadow because `/.netlify/*` is already excluded from the `server` catch-all.\n */\nexport function resolveAgentChatProcessRunDispatchPath(): string {\n if (isNetlifyHostedRuntimeForDispatch()) {\n return (\n resolveWorkspaceBackgroundFunctionUrlPath() ??\n AGENT_BACKGROUND_FUNCTION_URL_PATH\n );\n }\n return AGENT_CHAT_PROCESS_RUN_PATH;\n}\n\nexport function resolveDurableBackgroundDispatchPath(\n fallbackPath: string,\n): string {\n if (isNetlifyHostedRuntimeForDispatch()) {\n return (\n resolveWorkspaceBackgroundFunctionUrlPath() ??\n AGENT_BACKGROUND_FUNCTION_URL_PATH\n );\n }\n return fallbackPath;\n}\n\nexport function dispatchPathTargetsNetlifyBackgroundFunction(\n dispatchPath: string,\n): boolean {\n return dispatchPath.startsWith(\"/.netlify/functions/\");\n}\n\n/**\n * Env flag for durable background runs. DEFAULT-OFF (opt-in): unset means\n * disabled; an app opts IN with an explicit truthy value (`true`/`1`/`yes`/`on`).\n */\nexport const AGENT_CHAT_DURABLE_BACKGROUND_ENV =\n \"AGENT_CHAT_DURABLE_BACKGROUND\";\n\n/**\n * Body field the foreground handler injects when self-dispatching to the\n * background processor. Its presence is how the re-entered handler knows it is\n * the background worker (run inline with the background soft-timeout; do NOT\n * re-claim the slot or re-dispatch). Untrusted on its own — the route also\n * verifies the HMAC token before invoking the handler.\n */\nexport const AGENT_CHAT_BACKGROUND_RUN_FIELD = \"__backgroundRun\";\n\n/**\n * Mirror of run-manager's private `isHostedRuntime`. Kept in sync deliberately:\n * the durable-background gate must agree with the soft-timeout regime about\n * what \"hosted\" means.\n */\nexport function isHostedRuntimeForDurableBackground(): boolean {\n if (\n process.env.NETLIFY &&\n process.env.NETLIFY !== \"false\" &&\n process.env.NETLIFY_LOCAL !== \"true\"\n ) {\n return true;\n }\n if (\n process.env.AWS_LAMBDA_FUNCTION_NAME &&\n process.env.NETLIFY_LOCAL !== \"true\"\n ) {\n return true;\n }\n return Boolean(\n process.env.CF_PAGES ||\n process.env.VERCEL ||\n process.env.VERCEL_ENV ||\n process.env.RENDER ||\n process.env.FLY_APP_NAME ||\n process.env.K_SERVICE,\n );\n}\n\n/**\n * True when THIS process is actually executing inside a Netlify *background*\n * function (the long, 15-min-budget async function whose deployed name ends in\n * `-background`). Netlify runs functions on AWS Lambda and sets\n * `AWS_LAMBDA_FUNCTION_NAME` to the function's name, so a `-background` suffix is\n * the runtime proof that the ~60s synchronous wall does NOT apply here.\n *\n * This is the SAFETY GUARD for the soft-timeout regime. The `_process-run`\n * self-dispatch worker (`isBackgroundWorker`) is NOT enough on its own: if the\n * `-background` function was never emitted (deploy gate off, or Netlify routed\n * the path to the synchronous function), the self-POST lands on the regular\n * ~60s `server` function. A worker there MUST use the 40s soft-timeout and\n * checkpoint before the 60s wall — using the ~13min budget would overshoot the\n * hard wall and get killed at 60s, then re-dispatch/resume in a wasteful loop.\n * So the 13-min budget is taken ONLY when this returns true.\n *\n * The PRIMARY signal is a `globalThis` marker the emitted background function's\n * entry sets at cold start — the deployed Lambda name is not guaranteed to end\n * in `-background` on Netlify, so the entry marks its own runtime. A `globalThis`\n * flag (not `process.env`) keeps the no-env-mutation guard satisfied and carries\n * no cross-request state (set once per isolate). The `AWS_LAMBDA_FUNCTION_NAME`\n * suffix and the explicit `AGENT_CHAT_FORCE_BACKGROUND_RUNTIME` env (truthy) are\n * additional signals — the latter an operator escape hatch. Off by default.\n */\nexport function isInBackgroundFunctionRuntime(): boolean {\n // Set by the emitted `-background` function entry at cold start (the primary,\n // most reliable signal — see the emit in deploy/build.ts).\n if (\n (globalThis as Record<string, unknown>)\n .__AGENT_NATIVE_BACKGROUND_RUNTIME__ === true\n ) {\n return true;\n }\n const lambdaName = process.env.AWS_LAMBDA_FUNCTION_NAME;\n if (\n typeof lambdaName === \"string\" &&\n lambdaName.toLowerCase().endsWith(\"-background\")\n ) {\n return true;\n }\n const forced = process.env.AGENT_CHAT_FORCE_BACKGROUND_RUNTIME;\n if (forced != null) {\n const v = forced.trim().toLowerCase();\n return v === \"1\" || v === \"true\" || v === \"yes\" || v === \"on\";\n }\n return false;\n}\n\nexport function backgroundRunMarkerExpectsBackgroundRuntime(\n marker: unknown,\n): boolean {\n return (\n typeof marker === \"object\" &&\n marker !== null &&\n (marker as { backgroundFunctionRuntimeExpected?: unknown })\n .backgroundFunctionRuntimeExpected === true\n );\n}\n\nexport function shouldUseBackgroundFunctionTimeoutForWorker(\n _marker: unknown,\n): boolean {\n // The dispatch marker says which URL the foreground targeted, not where the\n // request actually landed. Only the worker runtime proof can safely lift the\n // hosted 40s clamp to the 15-minute background-function budget.\n return isInBackgroundFunctionRuntime();\n}\n\nexport function backgroundRuntimeDiagnosticDetail(marker: unknown): string {\n return [\n `markerExpected=${backgroundRunMarkerExpectsBackgroundRuntime(marker)}`,\n `runtimeDetected=${isInBackgroundFunctionRuntime()}`,\n `globalMarker=${(globalThis as Record<string, unknown>).__AGENT_NATIVE_BACKGROUND_RUNTIME__ === true}`,\n `lambdaNameEndsBackground=${typeof process.env.AWS_LAMBDA_FUNCTION_NAME === \"string\" && process.env.AWS_LAMBDA_FUNCTION_NAME.toLowerCase().endsWith(\"-background\")}`,\n `forceEnv=${typeof process.env.AGENT_CHAT_FORCE_BACKGROUND_RUNTIME === \"string\" && process.env.AGENT_CHAT_FORCE_BACKGROUND_RUNTIME.trim().length > 0}`,\n ].join(\" \");\n}\n\nfunction isFlagEnabled(): boolean {\n // Read the literal key (not `process.env[CONST]`) so guard:no-env-credentials\n // can statically verify it against the allowlisted `AGENT_*` prefix. Keep this\n // in sync with AGENT_CHAT_DURABLE_BACKGROUND_ENV.\n //\n // DEFAULT-OFF (opt-in): durable background runs are still being hardened. A\n // premature fleet-wide default-on caused real-user incidents (Assets/Analytics\n // hit \"Failed to dispatch\" + stalls, 2026-06-24) because the async background\n // worker path is not yet proven end-to-end and the deploy-time env opt-out is\n // not reliably baked into a given deploy. So an unset/empty/unknown flag means\n // OFF; an app opts IN only with an explicit truthy value\n // (AGENT_CHAT_DURABLE_BACKGROUND=true). This still composes with the hosted +\n // A2A_SECRET gates below. Flip back to default-on only after the 15-min\n // background-function worker is verified live in production (see the\n // project_durable_bg_prod_verified memory).\n const raw = process.env.AGENT_CHAT_DURABLE_BACKGROUND;\n if (raw == null) return false;\n const normalized = raw.trim().toLowerCase();\n return (\n normalized === \"1\" ||\n normalized === \"true\" ||\n normalized === \"yes\" ||\n normalized === \"on\"\n );\n}\n\nfunction isFlagExplicitlyDisabled(): boolean {\n const raw = process.env.AGENT_CHAT_DURABLE_BACKGROUND;\n if (raw == null) return false;\n const normalized = raw.trim().toLowerCase();\n return (\n normalized === \"0\" ||\n normalized === \"false\" ||\n normalized === \"no\" ||\n normalized === \"off\"\n );\n}\n\n/**\n * The single gate. True when the env flag is explicitly enabled, or a workspace\n * app opted in and has a per-app background-function target, AND the runtime is\n * hosted AND A2A_SECRET is configured. False otherwise — and false means the\n * current synchronous behavior is used unchanged. Single-template Netlify app\n * opt-ins deliberately require the env flag too because that flag controls\n * whether the `server-agent-background` function exists in the deploy output.\n */\nexport function isAgentChatDurableBackgroundEnabled(options?: {\n appOptIn?: boolean;\n}): boolean {\n 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 → require `isTrustedLocalRuntime({ loopback })` (see\n * auth-policy.ts): refuse (503) unless `A2A_ALLOW_UNSIGNED_INTERNAL=1` is\n * set. This function has no h3 `event` of its own, so callers that CAN\n * see the inbound socket peer (the route handler, which has the event)\n * should compute `loopback` from it and pass it through; callers that\n * can't determine the peer address should omit it (defaults to `false`\n * — never trust unsigned dispatch without an explicit opt-in).\n *\n * Extracted from the route handler so the auth + marker-prep decision is unit\n * testable without booting the whole Nitro plugin. The route only adds body\n * reading and the final handler invocation around this.\n */\nexport function prepareProcessRunRequest(\n body: unknown,\n authHeader: string | undefined,\n loopback: boolean = false,\n): ProcessRunPreparation {\n if (!body || typeof body !== \"object\") {\n return {\n ok: false,\n status: 400,\n error: \"Invalid request body\",\n runId: null,\n };\n }\n const record = body as Record<string, unknown>;\n const marker = record[AGENT_CHAT_BACKGROUND_RUN_FIELD] as\n | { runId?: unknown }\n | undefined;\n const runId =\n marker && typeof marker.runId === \"string\"\n ? marker.runId\n : typeof record.taskId === \"string\"\n ? (record.taskId as string)\n : \"\";\n if (!runId) {\n return { ok: false, status: 400, error: \"runId required\", runId: null };\n }\n\n if (hasConfiguredA2ASecret()) {\n const token = extractBearerToken(authHeader);\n if (!verifyInternalToken(runId, token ?? \"\")) {\n return {\n ok: false,\n status: 401,\n error: \"Invalid or expired processor token\",\n runId,\n };\n }\n } else if (!isTrustedLocalRuntime({ loopback })) {\n // Callers that can see the h3 `event` (the route handler) pass the real\n // loopback signal; callers without one default to non-loopback. Unsigned\n // dispatch is still allowed via A2A_ALLOW_UNSIGNED_INTERNAL=1 for trusted\n // local/dev setups; see auth-policy.ts `isTrustedLocalRuntime`.\n return {\n ok: false,\n status: 503,\n error:\n \"Agent chat background processor not configured — set A2A_SECRET on this deployment (or A2A_ALLOW_UNSIGNED_INTERNAL=1 for trusted local dev).\",\n runId,\n };\n }\n\n // Ensure the marker is present so the re-entered handler runs as the\n // background worker (reuses runId/turnId, no re-claim, no re-dispatch).\n if (!marker || typeof marker.runId !== \"string\") {\n record[AGENT_CHAT_BACKGROUND_RUN_FIELD] = { runId };\n }\n return { ok: true, runId, body: record };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"durable-background.js","sourceRoot":"","sources":["../../src/agent/durable-background.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,k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,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,CAAC,qBAAqB,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC;QAChD,wEAAwE;QACxE,yEAAyE;QACzE,0EAA0E;QAC1E,gEAAgE;QAChE,OAAO;YACL,EAAE,EAAE,KAAK;YACT,MAAM,EAAE,GAAG;YACX,KAAK,EACH,8IAA8I;YAChJ,KAAK;SACN,CAAC;IACJ,CAAC;IAED,qEAAqE;IACrE,wEAAwE;IACxE,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ,EAAE,CAAC;QAChD,MAAM,CAAC,+BAA+B,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC;IACtD,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAC3C,CAAC","sourcesContent":["/**\n * Durable background agent-chat runs (Netlify background functions).\n *\n * Off by default. When enabled, a long in-app agent-chat turn is dispatched\n * into a Netlify *background* function (15-min budget) instead of completing\n * synchronously under the ~40s soft-timeout. The foreground POST claims the\n * run slot, inserts the run row, fires an HMAC-signed self-dispatch to\n * `AGENT_CHAT_PROCESS_RUN_PATH`, and returns the existing SSE subscription so\n * the client streams the same events (via the cross-isolate SQL-poll path)\n * with no client change.\n *\n * This module owns ONLY the gating decision + shared constants so both the\n * HTTP handler (`production-agent.ts`) and the processor route\n * (`agent-chat-plugin.ts`) agree on when the path is active without a circular\n * import. The actual run machinery is reused verbatim from run-manager /\n * run-store / self-dispatch / internal-token.\n *\n * GUARDRAIL: when `isAgentChatDurableBackgroundEnabled()` returns false, the\n * agent-chat handler must behave byte-for-byte like the current synchronous\n * path. The gate is true only when ALL of these hold:\n * 1. `AGENT_CHAT_DURABLE_BACKGROUND` env is explicitly enabled, or a\n * workspace app's agent-chat plugin opts in with `durableBackgroundRuns`\n * where the workspace deploy emits a per-app background function by\n * default. Single-template Netlify deploys must set the env flag because\n * that same flag controls whether `server-agent-background` is emitted.\n * 2. The runtime is hosted/serverless (local dev keeps the inline path so SSE\n * stays a single live stream and no second function is needed).\n * 3. `A2A_SECRET` is configured (the HMAC handoff is required to authenticate\n * the background dispatch; without it the dispatch can't be trusted).\n *\n * Opt-in keeps the blast radius small while the worker path is still being\n * proven. And even when enabled, a *dispatch failure degrades to an inline run*:\n * if the self-dispatch self-POST can't be delivered (fast connection error or\n * fast non-2xx), the foreground handler runs the turn synchronously instead of\n * erroring (see `production-agent.ts` — the inline fallback claims the run row\n * atomically so a delayed delivery can never double-execute). So an app where\n * durable dispatch happens to fail still gets a working chat, just without the\n * 15-min budget.\n */\nimport {\n hasConfiguredA2ASecret,\n isTrustedLocalRuntime,\n} from \"../a2a/auth-policy.js\";\nimport {\n extractBearerToken,\n verifyInternalToken,\n} from \"../integrations/internal-token.js\";\n\n/**\n * Framework route the background function actually runs — sibling to\n * `AGENT_TEAM_PROCESS_RUN_PATH`. Reached *through* the Netlify background\n * function, so it inherits the 15-min budget.\n */\nexport const AGENT_CHAT_PROCESS_RUN_PATH =\n \"/_agent-native/agent-chat/_process-run\";\n\n/**\n * Name of the standalone Netlify background function the build emits (see\n * `emitSingleTemplateNetlifyBackgroundFunction` in deploy/build.ts). Shared so\n * the emit and the dispatch-path helper below can never drift on the name.\n *\n * MUST end in `-background` — both because that is the conventional Netlify\n * async-function suffix and because `isInBackgroundFunctionRuntime()` reads the\n * `AWS_LAMBDA_FUNCTION_NAME` `-background` suffix as a secondary runtime signal.\n */\nexport const AGENT_BACKGROUND_FUNCTION_NAME = \"server-agent-background\";\n\n/**\n * Default function URL of the background function on Netlify. Every Netlify\n * function is reachable at `/.netlify/functions/<name>` BY DEFAULT; that default\n * url is removed ONLY if the function declares a custom `config.path`. The\n * emitted background function declares NO custom `config.path` (it sets\n * `background: true` and nothing else routing-related), so it KEEPS this default\n * url — and the Nitro `server` function already excludes `/.netlify/*` from its\n * `/*` catch-all, so this namespace is never shadowed. The foreground therefore\n * dispatches HERE on hosted Netlify (see `resolveAgentChatProcessRunDispatchPath`).\n */\nexport const AGENT_BACKGROUND_FUNCTION_URL_PATH = `/.netlify/functions/${AGENT_BACKGROUND_FUNCTION_NAME}`;\n\n/**\n * Marker carried in a Netlify background-function body when the shared\n * long-running worker should route to a processor other than agent chat.\n * The emitted wrapper defaults to the normal agent-chat `_process-run` route;\n * A2A uses this marker to reuse the same 15-minute function for async tasks.\n */\nexport const AGENT_BACKGROUND_PROCESSOR_FIELD = \"__agentNativeProcessor\";\nexport const AGENT_BACKGROUND_PROCESSOR_A2A = \"a2a\";\nexport const AGENT_BACKGROUND_PROCESSOR_ROUTE = \"route\";\nexport const AGENT_BACKGROUND_PROCESSOR_ROUTE_FIELD =\n \"__agentNativeProcessorRoute\";\n\n/**\n * The per-app workspace background function URL path. Workspace deploy emits one\n * background function per app named `<app>-agent-background`, reachable at its\n * DEFAULT url `/.netlify/functions/<app>-agent-background` (no custom\n * `config.path`). The foreground resolves the current workspace app id from\n * `AGENT_NATIVE_WORKSPACE_APP_ID` (set by the workspace function entry) so it can\n * dispatch to the right per-app function url. Returns `null` when no workspace\n * app id is configured (single-template deploy).\n */\nfunction resolveWorkspaceBackgroundFunctionUrlPath(): string | null {\n const raw = process.env.AGENT_NATIVE_WORKSPACE_APP_ID;\n if (typeof raw !== \"string\") return null;\n // Mirror the workspace app-id normalization (resources/store.ts): take the\n // first path segment and accept only the safe slug shape used for function\n // names. Anything else falls back to the single-template name.\n const candidate = raw.trim().replace(/^\\/+/, \"\").split(\"/\")[0] ?? \"\";\n if (!/^[a-z0-9][a-z0-9-]{0,127}$/.test(candidate)) return null;\n return `/.netlify/functions/${candidate}-agent-background`;\n}\n\nfunction isNetlifyHostedRuntimeForDispatch(): boolean {\n if (process.env.NETLIFY_LOCAL === \"true\") return false;\n if (process.env.NETLIFY === \"false\") return false;\n if (process.env.NETLIFY && process.env.NETLIFY !== \"false\") return true;\n // Netlify sets AWS Lambda runtime env on deployed Functions, but the build-time\n // NETLIFY flag is not always present in the runtime isolate. Treat Lambda as\n // Netlify here unless Netlify was explicitly disabled above; non-Netlify AWS\n // falls back inline if the /.netlify/functions dispatch fast-fails.\n return Boolean(process.env.AWS_LAMBDA_FUNCTION_NAME);\n}\n\n/**\n * Resolve the path the foreground POST should self-dispatch the chat background\n * worker to.\n *\n * GROUNDED IN THE REAL NETLIFY BUILD OUTPUT + THE NETLIFY DOCS DEFAULT-URL RULE:\n * the background function is emitted INTO the scanned dir\n * (`.netlify/functions-internal/server-agent-background`, or per-app\n * `<app>-agent-background` for workspaces) with `export const config = {\n * background: true, ... }` and NO custom `config.path`. Because it has no custom\n * path, Netlify keeps its DEFAULT function url `/.netlify/functions/<name>`, and\n * `background: true` makes any invocation of that url ASYNC (immediate 202,\n * 15-min budget). The Nitro `server` function already excludes `/.netlify/*`\n * from its `/*` catch-all, so the default-url namespace is NEVER shadowed by the\n * synchronous function.\n *\n * Therefore on hosted Netlify the foreground dispatches to the function's DEFAULT\n * url (`/.netlify/functions/<name>`); the function entry then rewrites the\n * incoming pathname to `AGENT_CHAT_PROCESS_RUN_PATH` (base-path-prefixed for\n * workspaces) before delegating to the Nitro router, so the `_process-run`\n * plugin runs with the async 15-min budget. Everywhere else (local dev, `netlify\n * dev`, non-Netlify hosts where no second function exists) there is no second\n * function, so the foreground dispatches to the framework route\n * `AGENT_CHAT_PROCESS_RUN_PATH` and the same in-process catch-all handles it\n * inline. The HMAC token (signed over the runId) is unchanged either way.\n *\n * NOTE: this is the DOC-CORRECT approach. An earlier attempt gave the function a\n * custom `config.path` + a catch-all `excludedPath` patch; the custom path was\n * NOT honored as a route in prod (probe → 404). Using the default function url\n * (no custom path) is what Netlify documents and is simpler — there is nothing\n * to shadow because `/.netlify/*` is already excluded from the `server` catch-all.\n */\nexport function resolveAgentChatProcessRunDispatchPath(): string {\n if (isNetlifyHostedRuntimeForDispatch()) {\n return (\n resolveWorkspaceBackgroundFunctionUrlPath() ??\n AGENT_BACKGROUND_FUNCTION_URL_PATH\n );\n }\n return AGENT_CHAT_PROCESS_RUN_PATH;\n}\n\nexport function resolveDurableBackgroundDispatchPath(\n fallbackPath: string,\n): string {\n if (isNetlifyHostedRuntimeForDispatch()) {\n return (\n resolveWorkspaceBackgroundFunctionUrlPath() ??\n AGENT_BACKGROUND_FUNCTION_URL_PATH\n );\n }\n return fallbackPath;\n}\n\nexport function dispatchPathTargetsNetlifyBackgroundFunction(\n dispatchPath: string,\n): boolean {\n return dispatchPath.startsWith(\"/.netlify/functions/\");\n}\n\n/**\n * Env flag for durable background runs. DEFAULT-OFF (opt-in): unset means\n * disabled; an app opts IN with an explicit truthy value (`true`/`1`/`yes`/`on`).\n */\nexport const AGENT_CHAT_DURABLE_BACKGROUND_ENV =\n \"AGENT_CHAT_DURABLE_BACKGROUND\";\n\n/**\n * Body field the foreground handler injects when self-dispatching to the\n * background processor. Its presence is how the re-entered handler knows it is\n * the background worker (run inline with the background soft-timeout; do NOT\n * re-claim the slot or re-dispatch). Untrusted on its own — the route also\n * verifies the HMAC token before invoking the handler.\n */\nexport const AGENT_CHAT_BACKGROUND_RUN_FIELD = \"__backgroundRun\";\n\n/**\n * Mirror of run-manager's private `isHostedRuntime`. Kept in sync deliberately:\n * the durable-background gate must agree with the soft-timeout regime about\n * what \"hosted\" means.\n */\nexport function isHostedRuntimeForDurableBackground(): boolean {\n if (\n process.env.NETLIFY &&\n process.env.NETLIFY !== \"false\" &&\n process.env.NETLIFY_LOCAL !== \"true\"\n ) {\n return true;\n }\n if (\n process.env.AWS_LAMBDA_FUNCTION_NAME &&\n process.env.NETLIFY_LOCAL !== \"true\"\n ) {\n return true;\n }\n return Boolean(\n process.env.CF_PAGES ||\n process.env.VERCEL ||\n process.env.VERCEL_ENV ||\n process.env.RENDER ||\n process.env.FLY_APP_NAME ||\n process.env.K_SERVICE,\n );\n}\n\n/**\n * True when THIS process is actually executing inside a Netlify *background*\n * function (the long, 15-min-budget async function whose deployed name ends in\n * `-background`). Netlify runs functions on AWS Lambda and sets\n * `AWS_LAMBDA_FUNCTION_NAME` to the function's name, so a `-background` suffix is\n * the runtime proof that the ~60s synchronous wall does NOT apply here.\n *\n * This is the SAFETY GUARD for the soft-timeout regime. The `_process-run`\n * self-dispatch worker (`isBackgroundWorker`) is NOT enough on its own: if the\n * `-background` function was never emitted (deploy gate off, or Netlify routed\n * the path to the synchronous function), the self-POST lands on the regular\n * ~60s `server` function. A worker there MUST use the 40s soft-timeout and\n * checkpoint before the 60s wall — using the ~13min budget would overshoot the\n * hard wall and get killed at 60s, then re-dispatch/resume in a wasteful loop.\n * So the 13-min budget is taken ONLY when this returns true.\n *\n * The PRIMARY signal is a `globalThis` marker the emitted background function's\n * entry sets at cold start — the deployed Lambda name is not guaranteed to end\n * in `-background` on Netlify, so the entry marks its own runtime. A `globalThis`\n * flag (not `process.env`) keeps the no-env-mutation guard satisfied and carries\n * no cross-request state (set once per isolate). The `AWS_LAMBDA_FUNCTION_NAME`\n * suffix and the explicit `AGENT_CHAT_FORCE_BACKGROUND_RUNTIME` env (truthy) are\n * additional signals — the latter an operator escape hatch. Off by default.\n */\nexport function isInBackgroundFunctionRuntime(): boolean {\n // Set by the emitted `-background` function entry at cold start (the primary,\n // most reliable signal — see the emit in deploy/build.ts).\n if (\n (globalThis as Record<string, unknown>)\n .__AGENT_NATIVE_BACKGROUND_RUNTIME__ === true\n ) {\n return true;\n }\n const lambdaName = process.env.AWS_LAMBDA_FUNCTION_NAME;\n if (\n typeof lambdaName === \"string\" &&\n lambdaName.toLowerCase().endsWith(\"-background\")\n ) {\n return true;\n }\n const forced = process.env.AGENT_CHAT_FORCE_BACKGROUND_RUNTIME;\n if (forced != null) {\n const v = forced.trim().toLowerCase();\n return v === \"1\" || v === \"true\" || v === \"yes\" || v === \"on\";\n }\n return false;\n}\n\nexport function backgroundRunMarkerExpectsBackgroundRuntime(\n marker: unknown,\n): boolean {\n return (\n typeof marker === \"object\" &&\n marker !== null &&\n (marker as { backgroundFunctionRuntimeExpected?: unknown })\n .backgroundFunctionRuntimeExpected === true\n );\n}\n\nexport function shouldUseBackgroundFunctionTimeoutForWorker(\n _marker: unknown,\n): boolean {\n // The dispatch marker says which URL the foreground targeted, not where the\n // request actually landed. Only the worker runtime proof can safely lift the\n // hosted 40s clamp to the 15-minute background-function budget.\n return isInBackgroundFunctionRuntime();\n}\n\nexport function backgroundRuntimeDiagnosticDetail(marker: unknown): string {\n return [\n `markerExpected=${backgroundRunMarkerExpectsBackgroundRuntime(marker)}`,\n `runtimeDetected=${isInBackgroundFunctionRuntime()}`,\n `globalMarker=${(globalThis as Record<string, unknown>).__AGENT_NATIVE_BACKGROUND_RUNTIME__ === true}`,\n `lambdaNameEndsBackground=${typeof process.env.AWS_LAMBDA_FUNCTION_NAME === \"string\" && process.env.AWS_LAMBDA_FUNCTION_NAME.toLowerCase().endsWith(\"-background\")}`,\n `forceEnv=${typeof process.env.AGENT_CHAT_FORCE_BACKGROUND_RUNTIME === \"string\" && process.env.AGENT_CHAT_FORCE_BACKGROUND_RUNTIME.trim().length > 0}`,\n ].join(\" \");\n}\n\nfunction isFlagEnabled(): boolean {\n // Read the literal key (not `process.env[CONST]`) so guard:no-env-credentials\n // can statically verify it against the allowlisted `AGENT_*` prefix. Keep this\n // in sync with AGENT_CHAT_DURABLE_BACKGROUND_ENV.\n //\n // DEFAULT-OFF (opt-in): durable background runs are still being hardened. A\n // premature fleet-wide default-on caused real-user incidents (Assets/Analytics\n // hit \"Failed to dispatch\" + stalls, 2026-06-24) because the async background\n // worker path is not yet proven end-to-end and the deploy-time env opt-out is\n // not reliably baked into a given deploy. So an unset/empty/unknown flag means\n // OFF; an app opts IN only with an explicit truthy value\n // (AGENT_CHAT_DURABLE_BACKGROUND=true). This still composes with the hosted +\n // A2A_SECRET gates below. Flip back to default-on only after the 15-min\n // background-function worker is verified live in production (see the\n // project_durable_bg_prod_verified memory).\n const raw = process.env.AGENT_CHAT_DURABLE_BACKGROUND;\n if (raw == null) return false;\n const normalized = raw.trim().toLowerCase();\n return (\n normalized === \"1\" ||\n normalized === \"true\" ||\n normalized === \"yes\" ||\n normalized === \"on\"\n );\n}\n\nfunction isFlagExplicitlyDisabled(): boolean {\n const raw = process.env.AGENT_CHAT_DURABLE_BACKGROUND;\n if (raw == null) return false;\n const normalized = raw.trim().toLowerCase();\n return (\n normalized === \"0\" ||\n normalized === \"false\" ||\n normalized === \"no\" ||\n normalized === \"off\"\n );\n}\n\n/**\n * The single gate. True when the env flag is explicitly enabled, or a workspace\n * app opted in and has a per-app background-function target, AND the runtime is\n * hosted AND A2A_SECRET is configured. False otherwise — and false means the\n * current synchronous behavior is used unchanged. Single-template Netlify app\n * opt-ins deliberately require the env flag too because that flag controls\n * whether the `server-agent-background` function exists in the deploy output.\n */\nexport function isAgentChatDurableBackgroundEnabled(options?: {\n appOptIn?: boolean;\n}): boolean {\n const envOptIn = isFlagEnabled();\n const workspaceAppOptIn =\n options?.appOptIn === true &&\n !isFlagExplicitlyDisabled() &&\n resolveWorkspaceBackgroundFunctionUrlPath() !== null;\n return (\n (envOptIn || workspaceAppOptIn) &&\n isHostedRuntimeForDurableBackground() &&\n hasConfiguredA2ASecret()\n );\n}\n\n/**\n * Env flag for the FOREGROUND server-driven self-chain. DEFAULT-OFF: a hosted\n * app must explicitly opt in with a truthy value (`true`/`1`/`yes`/`on`). A\n * regular Netlify function has a fixed 60-second wall, and a self-dispatched\n * successor can otherwise be killed before it persists its next continuation.\n * Keep this separate from `AGENT_CHAT_DURABLE_BACKGROUND` so the experimental\n * regular-function chain can be enabled independently after its deployment is\n * proven safe.\n */\nexport const AGENT_CHAT_FOREGROUND_SELF_CHAIN_ENV =\n \"AGENT_CHAT_FOREGROUND_SELF_CHAIN\";\n\nfunction isForegroundSelfChainExplicitlyEnabled(): boolean {\n // Read the literal key (not `process.env[CONST]`) so guard:no-env-credentials\n // can statically verify it against the allowlisted `AGENT_*` prefix. Keep this\n // in sync with AGENT_CHAT_FOREGROUND_SELF_CHAIN_ENV.\n const raw = process.env.AGENT_CHAT_FOREGROUND_SELF_CHAIN;\n if (raw == null) return false;\n const normalized = raw.trim().toLowerCase();\n return (\n normalized === \"1\" ||\n normalized === \"true\" ||\n normalized === \"yes\" ||\n normalized === \"on\"\n );\n}\n\n/**\n * Gate for the foreground self-chain: a normal (non-durable-background)\n * agent-chat turn that hits its soft-timeout chunk boundary continues via a\n * server-side self-dispatch on the REGULAR function (not a Netlify\n * `-background` function) instead of depending on the client to re-POST\n * `auto_continue`. Composes exactly like `isAgentChatDurableBackgroundEnabled`:\n * true only when the env flag is explicitly truthy, the runtime is hosted, and\n * `A2A_SECRET` is configured (the HMAC handoff authenticates the dispatch).\n * False means the existing client-driven `auto_continue` re-POST path is used.\n *\n * Deliberately independent of `isAgentChatDurableBackgroundEnabled`: an app can\n * use this narrower capability without opting into the full 15-min\n * background-function worker path, and the two gates never need to agree.\n * When BOTH would be true for a given run, the durable-background dispatch\n * decision in `production-agent.ts` is evaluated first and takes precedence —\n * a run already dispatched to the durable background worker chains via the\n * existing `isBackgroundWorker` path, not this one.\n */\nexport function isAgentChatForegroundSelfChainEnabled(): boolean {\n return (\n isForegroundSelfChainExplicitlyEnabled() &&\n isHostedRuntimeForDurableBackground() &&\n hasConfiguredA2ASecret()\n );\n}\n\n/** Decision returned by `prepareProcessRunRequest`. */\nexport type ProcessRunPreparation =\n | {\n ok: true;\n /** The pre-claimed run id the background worker must reuse. */\n runId: string;\n /** Body to stash for the re-entered handler (marker guaranteed present). */\n body: Record<string, unknown>;\n }\n | {\n ok: false;\n /** HTTP status the route should return. */\n status: number;\n /** Error payload. */\n error: string;\n /**\n * The run id parsed from the body, when present. Carried even on failure\n * so the route can RECORD the auth/validation failure ONTO the run\n * (diag_stage) before returning the error status — otherwise a 401/503 in\n * the unreadable Netlify background function would leave the run to time\n * out with no clue why. Null when no run id could be parsed.\n */\n runId: string | null;\n };\n\n/**\n * Parse the run id from a `_process-run` request body without authenticating.\n * Mirrors the precedence in `prepareProcessRunRequest` (marker.runId, then\n * top-level taskId). Returns null when neither is a usable string. Used so the\n * route can attach a diagnostic to the run even on an auth/validation failure.\n */\nexport function extractProcessRunId(body: unknown): string | null {\n if (!body || typeof body !== \"object\") return null;\n const record = body as Record<string, unknown>;\n const marker = record[AGENT_CHAT_BACKGROUND_RUN_FIELD] as\n | { runId?: unknown }\n | undefined;\n if (marker && typeof marker.runId === \"string\" && marker.runId) {\n return marker.runId;\n }\n if (typeof record.taskId === \"string\" && record.taskId) {\n return record.taskId;\n }\n return null;\n}\n\n/**\n * Pure, transport-agnostic core of the `_process-run` route: validate the body,\n * authenticate the HMAC self-dispatch, and produce the body the re-entered\n * agent-chat handler should run as the background worker.\n *\n * Auth policy mirrors the agent-teams processor exactly:\n * - `A2A_SECRET` set → require a valid `verifyInternalToken(runId, token)`.\n * - no secret → require `isTrustedLocalRuntime({ loopback })` (see\n * auth-policy.ts): refuse (503) unless `A2A_ALLOW_UNSIGNED_INTERNAL=1` is\n * set. This function has no h3 `event` of its own, so callers that CAN\n * see the inbound socket peer (the route handler, which has the event)\n * should compute `loopback` from it and pass it through; callers that\n * can't determine the peer address should omit it (defaults to `false`\n * — never trust unsigned dispatch without an explicit opt-in).\n *\n * Extracted from the route handler so the auth + marker-prep decision is unit\n * testable without booting the whole Nitro plugin. The route only adds body\n * reading and the final handler invocation around this.\n */\nexport function prepareProcessRunRequest(\n body: unknown,\n authHeader: string | undefined,\n loopback: boolean = false,\n): ProcessRunPreparation {\n if (!body || typeof body !== \"object\") {\n return {\n ok: false,\n status: 400,\n error: \"Invalid request body\",\n runId: null,\n };\n }\n const record = body as Record<string, unknown>;\n const marker = record[AGENT_CHAT_BACKGROUND_RUN_FIELD] as\n | { runId?: unknown }\n | undefined;\n const runId =\n marker && typeof marker.runId === \"string\"\n ? marker.runId\n : typeof record.taskId === \"string\"\n ? (record.taskId as string)\n : \"\";\n if (!runId) {\n return { ok: false, status: 400, error: \"runId required\", runId: null };\n }\n\n if (hasConfiguredA2ASecret()) {\n const token = extractBearerToken(authHeader);\n if (!verifyInternalToken(runId, token ?? \"\")) {\n return {\n ok: false,\n status: 401,\n error: \"Invalid or expired processor token\",\n runId,\n };\n }\n } else if (!isTrustedLocalRuntime({ loopback })) {\n // Callers that can see the h3 `event` (the route handler) pass the real\n // loopback signal; callers without one default to non-loopback. Unsigned\n // dispatch is still allowed via A2A_ALLOW_UNSIGNED_INTERNAL=1 for trusted\n // local/dev setups; see auth-policy.ts `isTrustedLocalRuntime`.\n return {\n ok: false,\n status: 503,\n error:\n \"Agent chat background processor not configured — set A2A_SECRET on this deployment (or A2A_ALLOW_UNSIGNED_INTERNAL=1 for trusted local dev).\",\n runId,\n };\n }\n\n // Ensure the marker is present so the re-entered handler runs as the\n // background worker (reuses runId/turnId, no re-claim, no re-dispatch).\n if (!marker || typeof marker.runId !== \"string\") {\n record[AGENT_CHAT_BACKGROUND_RUN_FIELD] = { runId };\n }\n return { ok: true, runId, body: record };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai-sdk-engine.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/ai-sdk-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;
|
|
1
|
+
{"version":3,"file":"ai-sdk-engine.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/ai-sdk-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAYH,OAAO,E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earProviderCredentialAuthFailure, readDeployCredentialEnv, recordProviderCredentialAuthFailure, } from "../../server/credential-provider.js";
|
|
15
|
-
import { normalizeReasoningEffortForModel } from "../../shared/reasoning-effort.js";
|
|
15
|
+
import { anthropicManualThinkingBudget, normalizeReasoningEffortForModel, supportsClaudeAdaptiveThinking, } from "../../shared/reasoning-effort.js";
|
|
16
16
|
import { AI_SDK_MODEL_CONFIG } from "../model-config.js";
|
|
17
17
|
import { clampThinkingBudgetTokens, resolveMaxOutputTokensForEngine, } from "./output-tokens.js";
|
|
18
18
|
import { engineToolsToAISDK, engineMessagesToAISDK, aiSdkPartToEngineEvents, aiSdkStepToAssistantContent, } from "./translate-ai-sdk.js";
|
|
@@ -244,13 +244,24 @@ class AISDKEngine {
|
|
|
244
244
|
if (reasoningEffort) {
|
|
245
245
|
if (this.provider === "anthropic") {
|
|
246
246
|
const explicitThinking = providerOpts.anthropic?.thinking;
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
247
|
+
if (explicitThinking || supportsClaudeAdaptiveThinking(opts.model)) {
|
|
248
|
+
providerOpts.anthropic = {
|
|
249
|
+
...(providerOpts.anthropic ?? {}),
|
|
250
|
+
thinking: explicitThinking ?? { type: "adaptive" },
|
|
251
|
+
...(explicitThinking
|
|
252
|
+
? {}
|
|
253
|
+
: { outputConfig: { effort: reasoningEffort } }),
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
else {
|
|
257
|
+
const budgetTokens = clampThinkingBudgetTokens(anthropicManualThinkingBudget(reasoningEffort), resolvedMaxOutputTokens);
|
|
258
|
+
providerOpts.anthropic = {
|
|
259
|
+
...(providerOpts.anthropic ?? {}),
|
|
260
|
+
...(budgetTokens === undefined
|
|
261
|
+
? {}
|
|
262
|
+
: { thinking: { type: "enabled", budgetTokens } }),
|
|
263
|
+
};
|
|
264
|
+
}
|
|
254
265
|
}
|
|
255
266
|
else if (this.provider === "openai") {
|
|
256
267
|
providerOpts.openai = {
|
|
@@ -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,EACL,yBAAyB,EACzB,+BAA+B,GAChC,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,uBAAuB,EACvB,2BAA2B,GAC5B,MAAM,uBAAuB,CAAC;AAW/B,8EAA8E;AAC9E,uBAAuB;AACvB,8EAA8E;AAE9E,MAAM,qBAAqB,GAA8C;IACvE,SAAS,EAAE;QACT,QAAQ,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,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,IAAI,EAAE;QACJ,QAAQ,EAAE,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C,KAAK,QAAQ;YACX,OAAO,MAAM,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC;AACH,CAAC;AAED,SAAS,UAAU,CAAC,CAAS;IAC3B,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAChD,CAAC;AAED,SAAS,iBAAiB,CAAC,QAAuB;IAChD,MAAM,OAAO,GAAG,iBAAiB,CAAC,QAAQ,CAAC,CAAC;IAC5C,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACxB,MAAM,KAAK,GAAG,uBAAuB,CAAC,CAAC,CAAC,CAAC;QACzC,IAAI,KAAK;YAAE,OAAO,KAAK,CAAC;IAC1B,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,8EAA8E;AAC9E,oCAAoC;AACpC,8EAA8E;AAE9E,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,yBAAyB,EACzB,iBAAiB,EACjB,iBAAiB,GAClB,CAAC","sourcesContent":["/**\n * AISDKEngine — wraps the Vercel AI SDK (ai package) for multi-provider support.\n *\n * Supports Anthropic, OpenAI, Google Gemini, Groq, and any provider with an\n * @ai-sdk/* package. Provider is selected via the `provider` config option.\n *\n * When provider is \"anthropic\", Anthropic-native features (thinking, cacheControl)\n * are forwarded through the AI SDK's providerOptions mechanism — no fidelity loss\n * compared to the native AnthropicEngine.\n *\n * The ai package is an OPTIONAL peer dependency. This engine uses dynamic import()\n * so the core package remains installable without the AI SDK.\n */\n\nimport {\n clearProviderCredentialAuthFailure,\n readDeployCredentialEnv,\n recordProviderCredentialAuthFailure,\n} from \"../../server/credential-provider.js\";\nimport { normalizeReasoningEffortForModel } from \"../../shared/reasoning-effort.js\";\nimport { AI_SDK_MODEL_CONFIG, type AISDKProvider } from \"../model-config.js\";\nimport {\n clampThinkingBudgetTokens,\n resolveMaxOutputTokensForEngine,\n} from \"./output-tokens.js\";\nimport {\n engineToolsToAISDK,\n engineMessagesToAISDK,\n aiSdkPartToEngineEvents,\n aiSdkStepToAssistantContent,\n} from \"./translate-ai-sdk.js\";\nimport type {\n AgentEngine,\n EngineCapabilities,\n EngineStreamOptions,\n EngineEvent,\n EngineContentPart,\n} from \"./types.js\";\n\nexport type { AISDKProvider } from \"../model-config.js\";\n\n// ---------------------------------------------------------------------------\n// Provider definitions\n// ---------------------------------------------------------------------------\n\nconst PROVIDER_CAPABILITIES: Record<AISDKProvider, EngineCapabilities> = {\n anthropic: {\n thinking: true,\n promptCaching: true,\n vision: true,\n computerUse: false, // not exposed through AI SDK yet\n parallelToolCalls: true,\n },\n openai: {\n thinking: true,\n promptCaching: false,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n },\n openrouter: {\n thinking: true,\n promptCaching: true,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n },\n google: {\n thinking: true,\n promptCaching: false,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n },\n groq: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: true,\n },\n mistral: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: true,\n },\n cohere: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: true,\n },\n ollama: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: false,\n },\n};\n\nconst providerModelEntries = Object.entries(AI_SDK_MODEL_CONFIG) as Array<\n [AISDKProvider, (typeof AI_SDK_MODEL_CONFIG)[AISDKProvider]]\n>;\n\nconst PROVIDER_DEFAULT_MODELS = Object.fromEntries(\n providerModelEntries.map(([provider, config]) => [\n provider,\n config.defaultModel,\n ]),\n) as Record<AISDKProvider, string>;\n\nconst PROVIDER_SUPPORTED_MODELS = Object.fromEntries(\n providerModelEntries.map(([provider, config]) => [\n provider,\n config.supportedModels,\n ]),\n) as unknown as Record<AISDKProvider, readonly string[]>;\n\nconst PROVIDER_ENV_VARS: Record<AISDKProvider, string[]> = {\n anthropic: [\"ANTHROPIC_API_KEY\"],\n openai: [\"OPENAI_API_KEY\"],\n openrouter: [\"OPENROUTER_API_KEY\"],\n google: [\"GOOGLE_GENERATIVE_AI_API_KEY\"],\n groq: [\"GROQ_API_KEY\"],\n mistral: [\"MISTRAL_API_KEY\"],\n cohere: [\"COHERE_API_KEY\"],\n ollama: [], // runs locally\n};\n\nconst PROVIDER_PACKAGES: Record<AISDKProvider, string> = {\n anthropic: \"@ai-sdk/anthropic\",\n openai: \"@ai-sdk/openai\",\n openrouter: \"@openrouter/ai-sdk-provider\",\n google: \"@ai-sdk/google\",\n groq: \"@ai-sdk/groq\",\n mistral: \"@ai-sdk/mistral\",\n cohere: \"@ai-sdk/cohere\",\n ollama: \"ai-sdk-ollama\",\n};\n\n/** Factory export name per provider (not all follow `create<Provider>`). */\nconst PROVIDER_FACTORIES: Record<AISDKProvider, string> = {\n anthropic: \"createAnthropic\",\n openai: \"createOpenAI\",\n openrouter: \"createOpenRouter\",\n google: \"createGoogleGenerativeAI\",\n groq: \"createGroq\",\n mistral: \"createMistral\",\n cohere: \"createCohere\",\n ollama: \"createOllama\",\n};\n\nfunction googleThinkingBudget(effort: string) {\n if (effort === \"low\") return 1024;\n // \"medium\" is a normalized effort for Gemini models; without this case it\n // fell through to the -1 (\"dynamic/unlimited\") fallback, so selecting\n // medium effort silently uncapped the thinking budget.\n if (effort === \"medium\") return 4096;\n if (effort === \"high\") return 8000;\n if (effort === \"xhigh\") return 16_000;\n if (effort === \"max\") return 32_000;\n return -1;\n}\n\n/**\n * Map a reasoning effort level to Gemini 3.x thinkingLevel string.\n * Gemini 3 models (gemini-3.*) reject thinkingBudget and require thinkingLevel\n * with values 'low' | 'medium' | 'high'. Gemini 3.0 only supports 'low'/'high';\n * Gemini 3.1+ adds 'medium'. We always emit 'medium' for medium effort since it\n * is accepted by 3.1+, and 3.0 is expected to be phased out quickly.\n */\nfunction gemini3ThinkingLevel(effort: string): string {\n if (effort === \"low\") return \"low\";\n if (effort === \"medium\") return \"medium\";\n // high/xhigh/max 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 preserveCustomModels: boolean;\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.preserveCustomModels =\n provider === \"openai\" && Boolean(config.baseUrl);\n this.capabilities = PROVIDER_CAPABILITIES[provider];\n this.apiKey =\n config.apiKey ??\n (config.allowEnvFallback === false ? \"\" : getProviderApiKey(provider));\n this.baseUrl = config.baseUrl;\n this.appName = config.appName;\n this.appUrl = config.appUrl;\n }\n\n async *stream(opts: EngineStreamOptions): AsyncIterable<EngineEvent> {\n let aiModule: any;\n try {\n aiModule = await import(\"ai\");\n } catch {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `The \"ai\" package is not installed. Run: pnpm add ai ${PROVIDER_PACKAGES[this.provider]}`,\n };\n return;\n }\n\n const { streamText, jsonSchema } = aiModule;\n\n let providerModel: any;\n try {\n providerModel = await this.createProviderModel(opts.model);\n } catch (err: any) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: err?.message ?? String(err),\n };\n return;\n }\n\n const aiSdkTools =\n opts.tools.length > 0\n ? engineToolsToAISDK(opts.tools, jsonSchema)\n : undefined;\n const messages = engineMessagesToAISDK(opts.messages, {\n // Vision-capable provider translators (anthropic/openai/google/\n // openrouter) map image parts to native blocks; the rest stringify\n // tool-result content arrays, so images degrade to their text notes.\n toolResultImages: this.capabilities.vision,\n });\n\n // Resolved once so both `maxOutputTokens` (below, in the streamText call)\n // and the thinking-budget headroom clamp agree on the same ceiling.\n const resolvedMaxOutputTokens = resolveMaxOutputTokensForEngine(\n this.name,\n opts.maxOutputTokens,\n opts.model,\n );\n\n // Build providerOptions for Anthropic-native features when using Anthropic provider\n const providerOpts: Record<string, unknown> = {};\n if (this.provider === \"anthropic\" && opts.providerOptions?.anthropic) {\n const anthropicOpts = opts.providerOptions.anthropic;\n if (anthropicOpts.thinking) {\n // Only the \"enabled\" config carries a numeric budgetTokens; clamp it\n // so thinking can't consume the entire maxOutputTokens budget and\n // leave zero room for the actual response (\"adaptive\" thinking has\n // no budgetTokens field at all per @ai-sdk/anthropic's schema).\n providerOpts.anthropic = {\n ...((providerOpts.anthropic as object) ?? {}),\n thinking: {\n type: \"enabled\",\n budgetTokens:\n typeof anthropicOpts.thinking.budgetTokens === \"number\"\n ? clampThinkingBudgetTokens(\n anthropicOpts.thinking.budgetTokens,\n resolvedMaxOutputTokens,\n )\n : anthropicOpts.thinking.budgetTokens,\n },\n };\n }\n if (anthropicOpts.cacheControl) {\n providerOpts.anthropic = {\n ...((providerOpts.anthropic as object) ?? {}),\n cacheControl: anthropicOpts.cacheControl,\n };\n }\n }\n const reasoningEffort = normalizeReasoningEffortForModel(\n opts.model,\n opts.reasoningEffort,\n );\n if (reasoningEffort) {\n if (this.provider === \"anthropic\") {\n const explicitThinking = (\n providerOpts.anthropic as { thinking?: unknown } | undefined\n )?.thinking;\n providerOpts.anthropic = {\n ...((providerOpts.anthropic as object) ?? {}),\n thinking: explicitThinking ?? { type: \"adaptive\" },\n ...(explicitThinking\n ? {}\n : { outputConfig: { effort: reasoningEffort } }),\n };\n } else if (this.provider === \"openai\") {\n providerOpts.openai = {\n ...((providerOpts.openai as object) ?? {}),\n reasoningEffort,\n };\n } else if (this.provider === \"openrouter\") {\n providerOpts.openrouter = {\n ...((providerOpts.openrouter as object) ?? {}),\n reasoning: { effort: reasoningEffort },\n };\n } else if (this.provider === \"google\") {\n // Gemini 3.x models reject thinkingBudget — they require thinkingLevel.\n // Gemini 2.5.x models use thinkingBudget (integer token count or -1).\n const isGemini3 = /^gemini-3/.test(opts.model);\n const thinkingBudget = googleThinkingBudget(reasoningEffort);\n providerOpts.google = {\n ...((providerOpts.google as object) ?? {}),\n thinkingConfig: isGemini3\n ? { thinkingLevel: gemini3ThinkingLevel(reasoningEffort) }\n : {\n // Unlike Anthropic's adaptive thinking, Gemini 2.5's\n // thinkingBudget IS a concrete numeric token count, so the\n // same headroom clamp applies: at \"max\" effort this maps to\n // 32000 tokens, which can equal (or exceed) a small\n // maxOutputTokens cap and leave zero room for the actual\n // response. Preserve Gemini's -1 \"dynamic\" sentinel.\n thinkingBudget:\n thinkingBudget > 0\n ? clampThinkingBudgetTokens(\n thinkingBudget,\n resolvedMaxOutputTokens,\n )\n : thinkingBudget,\n },\n };\n }\n }\n\n let assistantContent: EngineContentPart[] = [];\n\n try {\n const result = streamText({\n model: providerModel,\n system: opts.systemPrompt,\n messages,\n tools: aiSdkTools,\n maxOutputTokens: resolvedMaxOutputTokens,\n ...(opts.temperature !== undefined\n ? { temperature: opts.temperature }\n : {}),\n abortSignal: opts.abortSignal,\n onStepFinish: (step: any) => {\n assistantContent = aiSdkStepToAssistantContent(step);\n },\n ...(Object.keys(providerOpts).length > 0\n ? { providerOptions: providerOpts }\n : {}),\n });\n\n // Buffer the terminal stop so assistant-content can be emitted just\n // before it, regardless of where `finish` arrives in the stream.\n let bufferedStop: EngineEvent | undefined;\n\n for await (const part of result.fullStream) {\n for (const event of aiSdkPartToEngineEvents(part)) {\n if (event.type === \"stop\") {\n bufferedStop = event;\n } else {\n yield event;\n }\n }\n }\n\n yield { type: \"assistant-content\", parts: assistantContent };\n await clearProviderCredentialAuthFailure({\n key: PROVIDER_ENV_VARS[this.provider][0],\n value: this.apiKey,\n });\n yield bufferedStop ?? { type: \"stop\", reason: \"end_turn\" };\n } catch (err: any) {\n // Surface structured fields from AI SDK's APICallError so\n // isRetryableError can check statusCode/providerRetryable directly\n // rather than keyword-matching the message string.\n const statusCode: number | undefined =\n typeof err?.statusCode === \"number\" ? err.statusCode : undefined;\n const errorMessage = err?.message ?? String(err);\n const isConnectionError =\n statusCode === undefined &&\n String(errorMessage).trim().toLowerCase() === \"connection error.\";\n const providerRetryable: boolean | undefined =\n typeof err?.isRetryable === \"boolean\"\n ? err.isRetryable\n : isConnectionError\n ? true\n : 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: errorMessage,\n });\n }\n yield {\n type: \"stop\",\n reason: \"error\",\n error: errorMessage,\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 : isConnectionError\n ? { errorCode: \"provider_network_error\" }\n : {}),\n ...(providerRetryable !== undefined ? { providerRetryable } : {}),\n };\n throw err;\n }\n }\n\n private async createProviderModel(model: string): Promise<any> {\n const pkg = PROVIDER_PACKAGES[this.provider];\n let providerModule: any;\n try {\n providerModule = await importProviderPackage(this.provider);\n } catch {\n throw new Error(\n `Provider package \"${pkg}\" is not installed. Run: pnpm add ai ${pkg}`,\n );\n }\n\n const fnName = PROVIDER_FACTORIES[this.provider];\n const createFn = providerModule[fnName] ?? providerModule.default;\n if (typeof createFn !== \"function\") {\n throw new Error(`\"${pkg}\" does not export ${fnName} or default`);\n }\n\n const config: Record<string, unknown> = {};\n if (this.apiKey !== undefined) config.apiKey = this.apiKey;\n if (this.baseUrl) config.baseURL = this.baseUrl;\n // Scoped to openrouter — other providers' factories may reject unknown keys.\n if (this.provider === \"openrouter\") {\n if (this.appName) config.appName = this.appName;\n if (this.appUrl) config.appUrl = this.appUrl;\n }\n\n const provider = createFn(config);\n // Let first-party OpenAI use the AI SDK's default Responses path so newer\n // GPT reasoning models get the API OpenAI recommends. If someone points\n // the OpenAI provider at an OpenAI-compatible gateway, keep using Chat\n // Completions because many gateway base URLs do not implement Responses.\n return this.provider === \"openai\" && this.baseUrl\n ? provider.chat(model)\n : provider(model);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory functions\n// ---------------------------------------------------------------------------\n\nexport function createAISDKEngine(\n provider: AISDKProvider,\n config: Record<string, unknown> = {},\n): AgentEngine {\n return new AISDKEngine(provider, config as AISDKEngineConfig);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n// Static string-literal imports so bundlers (Nitro/Rollup/Vercel) can analyze\n// and include provider packages. A variable-based `import(pkg)` gets skipped.\nasync function importProviderPackage(provider: AISDKProvider): Promise<any> {\n switch (provider) {\n case \"anthropic\":\n return import(\"@ai-sdk/anthropic\");\n case \"openai\":\n return import(\"@ai-sdk/openai\");\n case \"openrouter\":\n return import(\"@openrouter/ai-sdk-provider\");\n case \"google\":\n return import(\"@ai-sdk/google\");\n case \"groq\":\n return import(\"@ai-sdk/groq\");\n case \"mistral\":\n return import(\"@ai-sdk/mistral\");\n case \"cohere\":\n return import(\"@ai-sdk/cohere\");\n case \"ollama\":\n return import(\"ai-sdk-ollama\");\n }\n}\n\nfunction capitalize(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nfunction getProviderApiKey(provider: AISDKProvider): string | undefined {\n const envVars = PROVIDER_ENV_VARS[provider];\n for (const v of envVars) {\n const value = readDeployCredentialEnv(v);\n if (value) return value;\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Exports for registry registration\n// ---------------------------------------------------------------------------\n\nexport {\n PROVIDER_CAPABILITIES,\n PROVIDER_DEFAULT_MODELS,\n PROVIDER_SUPPORTED_MODELS,\n PROVIDER_ENV_VARS,\n PROVIDER_PACKAGES,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"ai-sdk-engine.js","sourceRoot":"","sources":["../../../src/agent/engine/ai-sdk-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,kCAAkC,EAClC,uBAAuB,EACvB,mCAAmC,GACpC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACL,6BAA6B,EAC7B,gCAAgC,EAChC,8BAA8B,GAC/B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAsB,MAAM,oBAAoB,CAAC;AAC7E,OAAO,EACL,yBAAyB,EACzB,+BAA+B,GAChC,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,uBAAuB,EACvB,2BAA2B,GAC5B,MAAM,uBAAuB,CAAC;AAW/B,8EAA8E;AAC9E,uBAAuB;AACvB,8EAA8E;AAE9E,MAAM,qBAAqB,GAA8C;IACvE,SAAS,EAAE;QACT,QAAQ,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,IAA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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 {\n anthropicManualThinkingBudget,\n normalizeReasoningEffortForModel,\n supportsClaudeAdaptiveThinking,\n} from \"../../shared/reasoning-effort.js\";\nimport { AI_SDK_MODEL_CONFIG, type AISDKProvider } from \"../model-config.js\";\nimport {\n clampThinkingBudgetTokens,\n resolveMaxOutputTokensForEngine,\n} from \"./output-tokens.js\";\nimport {\n engineToolsToAISDK,\n engineMessagesToAISDK,\n aiSdkPartToEngineEvents,\n aiSdkStepToAssistantContent,\n} from \"./translate-ai-sdk.js\";\nimport type {\n AgentEngine,\n EngineCapabilities,\n EngineStreamOptions,\n EngineEvent,\n EngineContentPart,\n} from \"./types.js\";\n\nexport type { AISDKProvider } from \"../model-config.js\";\n\n// ---------------------------------------------------------------------------\n// Provider definitions\n// ---------------------------------------------------------------------------\n\nconst PROVIDER_CAPABILITIES: Record<AISDKProvider, EngineCapabilities> = {\n anthropic: {\n thinking: true,\n promptCaching: true,\n vision: true,\n computerUse: false, // not exposed through AI SDK yet\n parallelToolCalls: true,\n },\n openai: {\n thinking: true,\n promptCaching: false,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n },\n openrouter: {\n thinking: true,\n promptCaching: true,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n },\n google: {\n thinking: true,\n promptCaching: false,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n },\n groq: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: true,\n },\n mistral: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: true,\n },\n cohere: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: true,\n },\n ollama: {\n thinking: false,\n promptCaching: false,\n vision: false,\n computerUse: false,\n parallelToolCalls: false,\n },\n};\n\nconst providerModelEntries = Object.entries(AI_SDK_MODEL_CONFIG) as Array<\n [AISDKProvider, (typeof AI_SDK_MODEL_CONFIG)[AISDKProvider]]\n>;\n\nconst PROVIDER_DEFAULT_MODELS = Object.fromEntries(\n providerModelEntries.map(([provider, config]) => [\n provider,\n config.defaultModel,\n ]),\n) as Record<AISDKProvider, string>;\n\nconst PROVIDER_SUPPORTED_MODELS = Object.fromEntries(\n providerModelEntries.map(([provider, config]) => [\n provider,\n config.supportedModels,\n ]),\n) as unknown as Record<AISDKProvider, readonly string[]>;\n\nconst PROVIDER_ENV_VARS: Record<AISDKProvider, string[]> = {\n anthropic: [\"ANTHROPIC_API_KEY\"],\n openai: [\"OPENAI_API_KEY\"],\n openrouter: [\"OPENROUTER_API_KEY\"],\n google: [\"GOOGLE_GENERATIVE_AI_API_KEY\"],\n groq: [\"GROQ_API_KEY\"],\n mistral: [\"MISTRAL_API_KEY\"],\n cohere: [\"COHERE_API_KEY\"],\n ollama: [], // runs locally\n};\n\nconst PROVIDER_PACKAGES: Record<AISDKProvider, string> = {\n anthropic: \"@ai-sdk/anthropic\",\n openai: \"@ai-sdk/openai\",\n openrouter: \"@openrouter/ai-sdk-provider\",\n google: \"@ai-sdk/google\",\n groq: \"@ai-sdk/groq\",\n mistral: \"@ai-sdk/mistral\",\n cohere: \"@ai-sdk/cohere\",\n ollama: \"ai-sdk-ollama\",\n};\n\n/** Factory export name per provider (not all follow `create<Provider>`). */\nconst PROVIDER_FACTORIES: Record<AISDKProvider, string> = {\n anthropic: \"createAnthropic\",\n openai: \"createOpenAI\",\n openrouter: \"createOpenRouter\",\n google: \"createGoogleGenerativeAI\",\n groq: \"createGroq\",\n mistral: \"createMistral\",\n cohere: \"createCohere\",\n ollama: \"createOllama\",\n};\n\nfunction googleThinkingBudget(effort: string) {\n if (effort === \"low\") return 1024;\n // \"medium\" is a normalized effort for Gemini models; without this case it\n // fell through to the -1 (\"dynamic/unlimited\") fallback, so selecting\n // medium effort silently uncapped the thinking budget.\n if (effort === \"medium\") return 4096;\n if (effort === \"high\") return 8000;\n if (effort === \"xhigh\") return 16_000;\n if (effort === \"max\") return 32_000;\n return -1;\n}\n\n/**\n * Map a reasoning effort level to Gemini 3.x thinkingLevel string.\n * Gemini 3 models (gemini-3.*) reject thinkingBudget and require thinkingLevel\n * with values 'low' | 'medium' | 'high'. Gemini 3.0 only supports 'low'/'high';\n * Gemini 3.1+ adds 'medium'. We always emit 'medium' for medium effort since it\n * is accepted by 3.1+, and 3.0 is expected to be phased out quickly.\n */\nfunction gemini3ThinkingLevel(effort: string): string {\n if (effort === \"low\") return \"low\";\n if (effort === \"medium\") return \"medium\";\n // high/xhigh/max 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 preserveCustomModels: boolean;\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.preserveCustomModels =\n provider === \"openai\" && Boolean(config.baseUrl);\n this.capabilities = PROVIDER_CAPABILITIES[provider];\n this.apiKey =\n config.apiKey ??\n (config.allowEnvFallback === false ? \"\" : getProviderApiKey(provider));\n this.baseUrl = config.baseUrl;\n this.appName = config.appName;\n this.appUrl = config.appUrl;\n }\n\n async *stream(opts: EngineStreamOptions): AsyncIterable<EngineEvent> {\n let aiModule: any;\n try {\n aiModule = await import(\"ai\");\n } catch {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `The \"ai\" package is not installed. Run: pnpm add ai ${PROVIDER_PACKAGES[this.provider]}`,\n };\n return;\n }\n\n const { streamText, jsonSchema } = aiModule;\n\n let providerModel: any;\n try {\n providerModel = await this.createProviderModel(opts.model);\n } catch (err: any) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: err?.message ?? String(err),\n };\n return;\n }\n\n const aiSdkTools =\n opts.tools.length > 0\n ? engineToolsToAISDK(opts.tools, jsonSchema)\n : undefined;\n const messages = engineMessagesToAISDK(opts.messages, {\n // Vision-capable provider translators (anthropic/openai/google/\n // openrouter) map image parts to native blocks; the rest stringify\n // tool-result content arrays, so images degrade to their text notes.\n toolResultImages: this.capabilities.vision,\n });\n\n // Resolved once so both `maxOutputTokens` (below, in the streamText call)\n // and the thinking-budget headroom clamp agree on the same ceiling.\n const resolvedMaxOutputTokens = resolveMaxOutputTokensForEngine(\n this.name,\n opts.maxOutputTokens,\n opts.model,\n );\n\n // Build providerOptions for Anthropic-native features when using Anthropic provider\n const providerOpts: Record<string, unknown> = {};\n if (this.provider === \"anthropic\" && opts.providerOptions?.anthropic) {\n const anthropicOpts = opts.providerOptions.anthropic;\n if (anthropicOpts.thinking) {\n // Only the \"enabled\" config carries a numeric budgetTokens; clamp it\n // so thinking can't consume the entire maxOutputTokens budget and\n // leave zero room for the actual response (\"adaptive\" thinking has\n // no budgetTokens field at all per @ai-sdk/anthropic's schema).\n providerOpts.anthropic = {\n ...((providerOpts.anthropic as object) ?? {}),\n thinking: {\n type: \"enabled\",\n budgetTokens:\n typeof anthropicOpts.thinking.budgetTokens === \"number\"\n ? clampThinkingBudgetTokens(\n anthropicOpts.thinking.budgetTokens,\n resolvedMaxOutputTokens,\n )\n : anthropicOpts.thinking.budgetTokens,\n },\n };\n }\n if (anthropicOpts.cacheControl) {\n providerOpts.anthropic = {\n ...((providerOpts.anthropic as object) ?? {}),\n cacheControl: anthropicOpts.cacheControl,\n };\n }\n }\n const reasoningEffort = normalizeReasoningEffortForModel(\n opts.model,\n opts.reasoningEffort,\n );\n if (reasoningEffort) {\n if (this.provider === \"anthropic\") {\n const explicitThinking = (\n providerOpts.anthropic as { thinking?: unknown } | undefined\n )?.thinking;\n if (explicitThinking || supportsClaudeAdaptiveThinking(opts.model)) {\n providerOpts.anthropic = {\n ...((providerOpts.anthropic as object) ?? {}),\n thinking: explicitThinking ?? { type: \"adaptive\" },\n ...(explicitThinking\n ? {}\n : { outputConfig: { effort: reasoningEffort } }),\n };\n } else {\n const budgetTokens = clampThinkingBudgetTokens(\n anthropicManualThinkingBudget(reasoningEffort),\n resolvedMaxOutputTokens,\n );\n providerOpts.anthropic = {\n ...((providerOpts.anthropic as object) ?? {}),\n ...(budgetTokens === undefined\n ? {}\n : { thinking: { type: \"enabled\", budgetTokens } }),\n };\n }\n } else if (this.provider === \"openai\") {\n providerOpts.openai = {\n ...((providerOpts.openai as object) ?? {}),\n reasoningEffort,\n };\n } else if (this.provider === \"openrouter\") {\n providerOpts.openrouter = {\n ...((providerOpts.openrouter as object) ?? {}),\n reasoning: { effort: reasoningEffort },\n };\n } else if (this.provider === \"google\") {\n // Gemini 3.x models reject thinkingBudget — they require thinkingLevel.\n // Gemini 2.5.x models use thinkingBudget (integer token count or -1).\n const isGemini3 = /^gemini-3/.test(opts.model);\n const thinkingBudget = googleThinkingBudget(reasoningEffort);\n providerOpts.google = {\n ...((providerOpts.google as object) ?? {}),\n thinkingConfig: isGemini3\n ? { thinkingLevel: gemini3ThinkingLevel(reasoningEffort) }\n : {\n // Unlike Anthropic's adaptive thinking, Gemini 2.5's\n // thinkingBudget IS a concrete numeric token count, so the\n // same headroom clamp applies: at \"max\" effort this maps to\n // 32000 tokens, which can equal (or exceed) a small\n // maxOutputTokens cap and leave zero room for the actual\n // response. Preserve Gemini's -1 \"dynamic\" sentinel.\n thinkingBudget:\n thinkingBudget > 0\n ? clampThinkingBudgetTokens(\n thinkingBudget,\n resolvedMaxOutputTokens,\n )\n : thinkingBudget,\n },\n };\n }\n }\n\n let assistantContent: EngineContentPart[] = [];\n\n try {\n const result = streamText({\n model: providerModel,\n system: opts.systemPrompt,\n messages,\n tools: aiSdkTools,\n maxOutputTokens: resolvedMaxOutputTokens,\n ...(opts.temperature !== undefined\n ? { temperature: opts.temperature }\n : {}),\n abortSignal: opts.abortSignal,\n onStepFinish: (step: any) => {\n assistantContent = aiSdkStepToAssistantContent(step);\n },\n ...(Object.keys(providerOpts).length > 0\n ? { providerOptions: providerOpts }\n : {}),\n });\n\n // Buffer the terminal stop so assistant-content can be emitted just\n // before it, regardless of where `finish` arrives in the stream.\n let bufferedStop: EngineEvent | undefined;\n\n for await (const part of result.fullStream) {\n for (const event of aiSdkPartToEngineEvents(part)) {\n if (event.type === \"stop\") {\n bufferedStop = event;\n } else {\n yield event;\n }\n }\n }\n\n yield { type: \"assistant-content\", parts: assistantContent };\n await clearProviderCredentialAuthFailure({\n key: PROVIDER_ENV_VARS[this.provider][0],\n value: this.apiKey,\n });\n yield bufferedStop ?? { type: \"stop\", reason: \"end_turn\" };\n } catch (err: any) {\n // Surface structured fields from AI SDK's APICallError so\n // isRetryableError can check statusCode/providerRetryable directly\n // rather than keyword-matching the message string.\n const statusCode: number | undefined =\n typeof err?.statusCode === \"number\" ? err.statusCode : undefined;\n const errorMessage = err?.message ?? String(err);\n const isConnectionError =\n statusCode === undefined &&\n String(errorMessage).trim().toLowerCase() === \"connection error.\";\n const providerRetryable: boolean | undefined =\n typeof err?.isRetryable === \"boolean\"\n ? err.isRetryable\n : isConnectionError\n ? true\n : 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: errorMessage,\n });\n }\n yield {\n type: \"stop\",\n reason: \"error\",\n error: errorMessage,\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 : isConnectionError\n ? { errorCode: \"provider_network_error\" }\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"]}
|