@agent-native/core 0.132.2 → 0.133.0
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 +161 -0
- package/corpus/core/package.json +1 -1
- package/corpus/core/src/a2a/correlation.ts +11 -1
- package/corpus/core/src/a2a/types.ts +11 -3
- package/corpus/core/src/agent/engine/ai-sdk-engine.ts +33 -46
- package/corpus/core/src/agent/engine/builder-engine.ts +22 -10
- package/corpus/core/src/agent/engine/error-detail.ts +184 -3
- package/corpus/core/src/agent/engine/failure-taxonomy.ts +123 -0
- package/corpus/core/src/agent/engine/index.ts +8 -0
- package/corpus/core/src/agent/engine/registry.ts +92 -8
- package/corpus/core/src/agent/engine/translate-ai-sdk.ts +17 -2
- package/corpus/core/src/agent/production-agent.ts +13 -33
- package/corpus/core/src/agent/run-loop-with-resume.ts +1 -1
- package/corpus/core/src/agent/run-manager.ts +43 -14
- package/corpus/core/src/agent/run-store.ts +30 -3
- package/corpus/core/src/agent/thread-data-builder.ts +36 -4
- package/corpus/core/src/cli/templates-meta.ts +13 -0
- package/corpus/core/src/cli/workspace-dev.ts +1 -0
- package/corpus/core/src/client/error-format.ts +12 -0
- package/corpus/core/src/credentials/index.ts +51 -12
- package/corpus/core/src/extensions/url-safety.ts +46 -12
- package/corpus/core/src/integrations/adapters/slack.ts +32 -10
- package/corpus/core/src/integrations/google-docs-poller.ts +12 -1
- package/corpus/core/src/integrations/installations-store.ts +30 -0
- package/corpus/core/src/integrations/plugin.ts +5 -5
- package/corpus/core/src/integrations/types.ts +7 -0
- package/corpus/core/src/integrations/webhook-handler.ts +24 -1
- package/corpus/core/src/jobs/background-automation-runner.ts +38 -1
- package/corpus/core/src/provider-api/index.ts +8 -2
- package/corpus/core/src/scripts/call-agent.ts +6 -0
- package/corpus/core/src/server/agent-chat-plugin.ts +30 -9
- package/corpus/core/src/server/agent-discovery.ts +2 -0
- package/corpus/core/src/server/builder-design-systems.ts +21 -0
- package/corpus/core/src/server/credential-provider.ts +51 -12
- package/corpus/core/src/server/index.ts +1 -0
- package/corpus/core/src/server/onboarding-html.ts +37 -2
- package/corpus/core/src/shared/reasoning-effort.ts +1 -1
- package/corpus/core/src/templates/workspace-core/.agents/skills/a2a-protocol/SKILL.md +11 -0
- package/corpus/templates/analytics/app/components/layout/Sidebar.tsx +6 -2
- package/corpus/templates/assets/app/components/layout/Sidebar.tsx +39 -19
- package/corpus/templates/assets/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
- package/corpus/templates/brain/app/components/layout/Sidebar.tsx +30 -3
- package/corpus/templates/brain/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
- package/corpus/templates/calendar/app/components/layout/AppLayout.tsx +1 -1
- package/corpus/templates/calendar/app/components/layout/Sidebar.tsx +54 -25
- package/corpus/templates/calendar/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
- package/corpus/templates/chat/app/components/layout/Sidebar.tsx +30 -3
- package/corpus/templates/chat/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
- package/corpus/templates/clips/app/components/library/library-layout.tsx +37 -21
- package/corpus/templates/clips/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
- package/corpus/templates/clips/desktop/src/hooks/useMediaDevices.ts +1 -1
- package/corpus/templates/clips/desktop/src/lib/media-capture-constraints.ts +1 -1
- package/corpus/templates/content/app/components/sidebar/DocumentSidebar.tsx +34 -17
- package/corpus/templates/content/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
- package/corpus/templates/design/.agents/skills/design-systems/SKILL.md +6 -2
- package/corpus/templates/design/actions/create-design-system.ts +1 -0
- package/corpus/templates/design/actions/set-default-design-system.ts +34 -26
- package/corpus/templates/design/app/components/layout/Sidebar.tsx +21 -4
- package/corpus/templates/design/app/i18n-data.ts +39 -0
- package/corpus/templates/design/app/pages/DesignSystemSetup.tsx +229 -12
- package/corpus/templates/design/app/pages/DesignSystems.tsx +10 -4
- package/corpus/templates/design/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
- package/corpus/templates/design/changelog/2026-07-31-design-system-indexing-keeps-your-chosen-name-when-you-uploa.md +6 -0
- package/corpus/templates/design/server/lib/builder-design-system-proxy.ts +19 -4
- package/corpus/templates/dispatch/AGENTS.md +4 -0
- package/corpus/templates/factory/.agents/skills/actions/SKILL.md +562 -0
- package/corpus/templates/factory/.agents/skills/adding-a-feature/SKILL.md +198 -0
- package/corpus/templates/factory/.agents/skills/agent-native-docs/SKILL.md +115 -0
- package/corpus/templates/factory/.agents/skills/agent-native-toolkit/SKILL.md +182 -0
- package/corpus/templates/factory/.agents/skills/capture-learnings/SKILL.md +89 -0
- package/corpus/templates/factory/.agents/skills/create-skill/SKILL.md +221 -0
- package/corpus/templates/factory/.agents/skills/customizing-agent-native/SKILL.md +220 -0
- package/corpus/templates/factory/.agents/skills/delegate-to-agent/SKILL.md +263 -0
- package/corpus/templates/factory/.agents/skills/factory-graphs/SKILL.md +52 -0
- package/corpus/templates/factory/.agents/skills/feature-flags/SKILL.md +169 -0
- package/corpus/templates/factory/.agents/skills/frontend-design/SKILL.md +174 -0
- package/corpus/templates/factory/.agents/skills/real-time-sync/SKILL.md +232 -0
- package/corpus/templates/factory/.agents/skills/security/SKILL.md +324 -0
- package/corpus/templates/factory/.agents/skills/self-modifying-code/SKILL.md +119 -0
- package/corpus/templates/factory/.agents/skills/shadcn-ui/SKILL.md +123 -0
- package/corpus/templates/factory/.agents/skills/sharing/SKILL.md +232 -0
- package/corpus/templates/factory/.agents/skills/storing-data/SKILL.md +178 -0
- package/corpus/templates/factory/.agents/skills/upgrade-agent-native/SKILL.md +122 -0
- package/corpus/templates/factory/.env.example +24 -0
- package/corpus/templates/factory/.ignore +0 -0
- package/corpus/templates/factory/.oxfmtrc.json +8 -0
- package/corpus/templates/factory/AGENTS.md +90 -0
- package/corpus/templates/factory/CHANGELOG.md +10 -0
- package/corpus/templates/factory/DEVELOPING.md +185 -0
- package/corpus/templates/factory/README.md +64 -0
- package/corpus/templates/factory/_gitignore +42 -0
- package/corpus/templates/factory/actions/add-factory-comment.ts +55 -0
- package/corpus/templates/factory/actions/approve-factory-item.ts +214 -0
- package/corpus/templates/factory/actions/babysit-pull-request.ts +126 -0
- package/corpus/templates/factory/actions/evaluate-triage-item.ts +172 -0
- package/corpus/templates/factory/actions/get-factory-graph.ts +62 -0
- package/corpus/templates/factory/actions/get-triage-config.ts +42 -0
- package/corpus/templates/factory/actions/get-triage-item.ts +74 -0
- package/corpus/templates/factory/actions/hello.ts +13 -0
- package/corpus/templates/factory/actions/ingest-github-observation.ts +100 -0
- package/corpus/templates/factory/actions/list-factories.ts +40 -0
- package/corpus/templates/factory/actions/list-factory-comments.ts +40 -0
- package/corpus/templates/factory/actions/list-triage-items.ts +85 -0
- package/corpus/templates/factory/actions/list-triage-rules.ts +44 -0
- package/corpus/templates/factory/actions/navigate.ts +41 -0
- package/corpus/templates/factory/actions/poll-slack-channel.ts +118 -0
- package/corpus/templates/factory/actions/reconcile-triage-run.ts +179 -0
- package/corpus/templates/factory/actions/record-triage-feedback.ts +58 -0
- package/corpus/templates/factory/actions/run.ts +2 -0
- package/corpus/templates/factory/actions/save-factory-graph.ts +129 -0
- package/corpus/templates/factory/actions/save-triage-config.ts +67 -0
- package/corpus/templates/factory/actions/save-triage-rule.ts +89 -0
- package/corpus/templates/factory/actions/suggest-factory-rules.ts +70 -0
- package/corpus/templates/factory/actions/view-screen.ts +73 -0
- package/corpus/templates/factory/app/components/factory/FactoryCanvas.tsx +441 -0
- package/corpus/templates/factory/app/components/factory/FactoryInspector.tsx +388 -0
- package/corpus/templates/factory/app/components/layout/Header.tsx +60 -0
- package/corpus/templates/factory/app/components/layout/Layout.tsx +190 -0
- package/corpus/templates/factory/app/components/layout/Sidebar.tsx +538 -0
- package/corpus/templates/factory/app/components/triage/triage-status-pill.tsx +28 -0
- package/corpus/templates/factory/app/components/ui/button.tsx +1 -0
- package/corpus/templates/factory/app/components/ui/card.tsx +1 -0
- package/corpus/templates/factory/app/components/ui/dropdown-menu.tsx +1 -0
- package/corpus/templates/factory/app/components/ui/input.tsx +1 -0
- package/corpus/templates/factory/app/components/ui/label.tsx +1 -0
- package/corpus/templates/factory/app/components/ui/sheet.tsx +1 -0
- package/corpus/templates/factory/app/components/ui/textarea.tsx +1 -0
- package/corpus/templates/factory/app/components/ui/toolkit-provider.tsx +17 -0
- package/corpus/templates/factory/app/components/ui/tooltip.tsx +1 -0
- package/corpus/templates/factory/app/design-system.ts +3 -0
- package/corpus/templates/factory/app/entry.client.tsx +22 -0
- package/corpus/templates/factory/app/entry.server.tsx +10 -0
- package/corpus/templates/factory/app/global.css +93 -0
- package/corpus/templates/factory/app/hooks/use-navigation-state.ts +113 -0
- package/corpus/templates/factory/app/i18n/en-US.ts +211 -0
- package/corpus/templates/factory/app/i18n/index.ts +34 -0
- package/corpus/templates/factory/app/i18n-data.ts +556 -0
- package/corpus/templates/factory/app/lib/agent-page.tsx +49 -0
- package/corpus/templates/factory/app/lib/app-config.ts +11 -0
- package/corpus/templates/factory/app/lib/tab-id.ts +1 -0
- package/corpus/templates/factory/app/lib/utils.ts +1 -0
- package/corpus/templates/factory/app/root.tsx +175 -0
- package/corpus/templates/factory/app/routes/_index.tsx +94 -0
- package/corpus/templates/factory/app/routes/agent.tsx +24 -0
- package/corpus/templates/factory/app/routes/chat.$threadId.tsx +1 -0
- package/corpus/templates/factory/app/routes/database.tsx +17 -0
- package/corpus/templates/factory/app/routes/extensions.$id.$slug.tsx +2 -0
- package/corpus/templates/factory/app/routes/extensions.$id.tsx +11 -0
- package/corpus/templates/factory/app/routes/extensions._index.tsx +11 -0
- package/corpus/templates/factory/app/routes/extensions.tsx +5 -0
- package/corpus/templates/factory/app/routes/factory.tsx +1003 -0
- package/corpus/templates/factory/app/routes/observability.tsx +19 -0
- package/corpus/templates/factory/app/routes/settings.tsx +89 -0
- package/corpus/templates/factory/app/routes/team.tsx +11 -0
- package/corpus/templates/factory/app/routes.ts +4 -0
- package/corpus/templates/factory/app/vite-env.d.ts +6 -0
- package/corpus/templates/factory/changelog/2026-06-24-a-new-settings-page-gives-quick-access-to-language-workspace.md +6 -0
- package/corpus/templates/factory/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/corpus/templates/factory/changelog/2026-06-27-traditional-chinese-copy-uses-taiwan-terminology.md +6 -0
- package/corpus/templates/factory/changelog/2026-06-28-left-sidebar-collapse-motion-and-footer-chrome-are-quieter.md +6 -0
- package/corpus/templates/factory/changelog/2026-06-29-chat-layouts-adapt-when-the-agent-sidebar-is-open.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-08-settings-are-cleaner-and-searchable.md +5 -0
- package/corpus/templates/factory/changelog/2026-07-10-chat-now-makes-ai-connection-setup-clear-without-shifting-th.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-13-a-full-agent-page-now-brings-context-files-connections-jobs-.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-14-chat-opens-reliably-on-hosted-deployments-instead-of-failing.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-14-fixed-chat-template-startup-with-older-core-versions.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-15-chat-navigation-focuses-on-chat-and-agent.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-17-the-agent-chat-sidebar-stays-closed-until-you-open-it-or-sta.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-22-compact-sidebar-footer.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-22-full-page-chat-keeps-the-active-conversation-when-moving-to-.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-22-recent-chats-are-easier-to-scan-and-expand.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-23-full-page-chat-is-better-centered-with-quieter-chat-history-.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-24-borderless-secondary-surfaces.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-24-sidebar-footer-controls-follow-a-consistent-order.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-29-sidebar-footers-now-keep-feedback-search-and-collapse-togeth.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-31-added-an-inspectable-observe-only-factory-queue-for-slack-.md +6 -0
- package/corpus/templates/factory/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
- package/corpus/templates/factory/components.json +20 -0
- package/corpus/templates/factory/data/sync-config.json +1 -0
- package/corpus/templates/factory/learnings.defaults.md +5 -0
- package/corpus/templates/factory/netlify.toml +10 -0
- package/corpus/templates/factory/package.json +105 -0
- package/corpus/templates/factory/public/agent-native-icon-dark.svg +10 -0
- package/corpus/templates/factory/public/agent-native-icon-light.svg +10 -0
- package/corpus/templates/factory/public/agent-native-logo-dark.svg +21 -0
- package/corpus/templates/factory/public/agent-native-logo-light.svg +21 -0
- package/corpus/templates/factory/public/favicon.svg +1 -0
- package/corpus/templates/factory/public/icon-180.svg +1 -0
- package/corpus/templates/factory/public/icon-192.svg +1 -0
- package/corpus/templates/factory/public/icon-512.svg +1 -0
- package/corpus/templates/factory/public/manifest.json +21 -0
- package/corpus/templates/factory/react-router.config.ts +7 -0
- package/corpus/templates/factory/server/connectors/credentials.ts +129 -0
- package/corpus/templates/factory/server/connectors/slack.ts +129 -0
- package/corpus/templates/factory/server/db/index.ts +6 -0
- package/corpus/templates/factory/server/db/schema.ts +193 -0
- package/corpus/templates/factory/server/factory-graph/contracts.ts +212 -0
- package/corpus/templates/factory/server/factory-graph/store.ts +121 -0
- package/corpus/templates/factory/server/lib/require-workspace-member.ts +55 -0
- package/corpus/templates/factory/server/middleware/auth.ts +15 -0
- package/corpus/templates/factory/server/plugins/agent-chat.ts +58 -0
- package/corpus/templates/factory/server/plugins/auth.ts +14 -0
- package/corpus/templates/factory/server/plugins/factory-migrations.ts +247 -0
- package/corpus/templates/factory/server/plugins/factory-scheduler-job.ts +116 -0
- package/corpus/templates/factory/server/plugins/integrations.ts +46 -0
- package/corpus/templates/factory/server/routes/[...page].get.ts +5 -0
- package/corpus/templates/factory/server/routes/_agent-native/factory/builder-callback.post.ts +116 -0
- package/corpus/templates/factory/server/triage/ai-services-git.ts +197 -0
- package/corpus/templates/factory/server/triage/builder-executor.ts +118 -0
- package/corpus/templates/factory/server/triage/contracts.ts +164 -0
- package/corpus/templates/factory/server/triage/github-ingestion.ts +35 -0
- package/corpus/templates/factory/server/triage/guards.ts +121 -0
- package/corpus/templates/factory/server/triage/ids.ts +27 -0
- package/corpus/templates/factory/server/triage/pr-babysit.ts +100 -0
- package/corpus/templates/factory/server/triage/pr-monitor.ts +220 -0
- package/corpus/templates/factory/server/triage/slack-client.ts +55 -0
- package/corpus/templates/factory/server/triage/slack-poller.ts +152 -0
- package/corpus/templates/factory/ssr-entry.ts +15 -0
- package/corpus/templates/factory/tsconfig.json +21 -0
- package/corpus/templates/factory/vite.config.ts +19 -0
- package/corpus/templates/forms/app/components/layout/Sidebar.tsx +55 -5
- package/corpus/templates/forms/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
- package/corpus/templates/macros/app/components/layout/AppLayout.tsx +6 -2
- package/corpus/templates/plan/app/components/layout/Sidebar.tsx +21 -6
- package/corpus/templates/plan/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
- package/corpus/templates/slides/.agents/skills/create-deck/SKILL.md +12 -0
- package/corpus/templates/slides/.agents/skills/design-systems/SKILL.md +9 -0
- package/corpus/templates/slides/.agents/skills/slide-editing/SKILL.md +11 -0
- package/corpus/templates/slides/AGENTS.md +5 -6
- package/corpus/templates/slides/actions/_await-fit-check.ts +20 -10
- package/corpus/templates/slides/actions/add-slide.ts +17 -4
- package/corpus/templates/slides/actions/create-design-system.ts +16 -4
- package/corpus/templates/slides/actions/delete-design-system.ts +18 -2
- package/corpus/templates/slides/actions/get-layout-overflows.ts +88 -0
- package/corpus/templates/slides/actions/import-file.ts +1 -0
- package/corpus/templates/slides/actions/index-design-system-with-builder.ts +8 -0
- package/corpus/templates/slides/actions/patch-deck.ts +48 -16
- package/corpus/templates/slides/actions/set-default-design-system.ts +49 -19
- package/corpus/templates/slides/actions/update-slide.ts +13 -3
- package/corpus/templates/slides/actions/view-screen.ts +87 -10
- package/corpus/templates/slides/app/components/deck/SlideRenderer.tsx +155 -28
- package/corpus/templates/slides/app/components/design-system/DesignSystemCard.tsx +21 -17
- package/corpus/templates/slides/app/components/design-system/DesignSystemSetup.tsx +849 -341
- package/corpus/templates/slides/app/components/editor/EditorSidebar.tsx +102 -2
- package/corpus/templates/slides/app/components/editor/PromptDialog.tsx +13 -16
- package/corpus/templates/slides/app/components/editor/SlideEditor.tsx +60 -12
- package/corpus/templates/slides/app/components/editor/SlideOverflowWarning.tsx +11 -1
- package/corpus/templates/slides/app/components/layout/Sidebar.tsx +66 -19
- package/corpus/templates/slides/app/i18n/en-US.ts +23 -0
- package/corpus/templates/slides/app/lib/normalize-slide-padding.ts +8 -15
- package/corpus/templates/slides/app/pages/DeckEditor.tsx +4 -3
- package/corpus/templates/slides/app/pages/DesignSystems.tsx +4 -3
- package/corpus/templates/slides/app/pages/Index.tsx +1 -1
- package/corpus/templates/slides/changelog/2026-07-31-design-system-details-now-show-their-source-and-indexing-sta.md +6 -0
- package/corpus/templates/slides/changelog/2026-07-31-design-system-indexing-keeps-your-chosen-name-when-you-uploa.md +6 -0
- package/corpus/templates/slides/changelog/2026-07-31-design-system-setup-keeps-focus-rings-visible-and-uses-a-sim.md +6 -0
- package/corpus/templates/slides/changelog/2026-07-31-skip-prompt-is-now-available-in-the-new-deck-prompt-header.md +6 -0
- package/corpus/templates/slides/changelog/2026-07-31-slides-now-detect-real-text-and-box-overflow-across-the-deck.md +6 -0
- package/corpus/templates/slides/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
- package/corpus/templates/slides/server/handlers/design-systems.ts +1 -0
- package/corpus/templates/slides/server/handlers/index-design-system-sources.ts +1 -0
- package/corpus/templates/slides/server/lib/builder-design-system-proxy.ts +23 -4
- package/corpus/templates/slides/server/plugins/agent-chat.ts +5 -0
- package/corpus/templates/slides/server/plugins/creative-context.ts +16 -3
- package/corpus/templates/slides/server/workspace-defaults.ts +5 -1
- package/corpus/templates/slides/shared/slide-fit.ts +26 -0
- package/corpus/templates/tasks/app/components/layout/Sidebar.tsx +30 -3
- package/corpus/templates/tasks/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
- package/dist/a2a/correlation.d.ts +4 -1
- package/dist/a2a/correlation.d.ts.map +1 -1
- package/dist/a2a/correlation.js +8 -1
- package/dist/a2a/correlation.js.map +1 -1
- package/dist/a2a/types.d.ts +11 -3
- package/dist/a2a/types.d.ts.map +1 -1
- package/dist/a2a/types.js.map +1 -1
- package/dist/agent/engine/ai-sdk-engine.d.ts.map +1 -1
- package/dist/agent/engine/ai-sdk-engine.js +27 -41
- package/dist/agent/engine/ai-sdk-engine.js.map +1 -1
- package/dist/agent/engine/builder-engine.d.ts.map +1 -1
- package/dist/agent/engine/builder-engine.js +18 -8
- package/dist/agent/engine/builder-engine.js.map +1 -1
- package/dist/agent/engine/error-detail.d.ts +61 -0
- package/dist/agent/engine/error-detail.d.ts.map +1 -1
- package/dist/agent/engine/error-detail.js +145 -3
- package/dist/agent/engine/error-detail.js.map +1 -1
- package/dist/agent/engine/failure-taxonomy.d.ts +24 -0
- package/dist/agent/engine/failure-taxonomy.d.ts.map +1 -0
- package/dist/agent/engine/failure-taxonomy.js +88 -0
- package/dist/agent/engine/failure-taxonomy.js.map +1 -0
- package/dist/agent/engine/index.d.ts +2 -1
- package/dist/agent/engine/index.d.ts.map +1 -1
- package/dist/agent/engine/index.js +2 -1
- package/dist/agent/engine/index.js.map +1 -1
- package/dist/agent/engine/registry.d.ts +16 -0
- package/dist/agent/engine/registry.d.ts.map +1 -1
- package/dist/agent/engine/registry.js +71 -6
- package/dist/agent/engine/registry.js.map +1 -1
- package/dist/agent/engine/translate-ai-sdk.d.ts.map +1 -1
- package/dist/agent/engine/translate-ai-sdk.js +14 -2
- package/dist/agent/engine/translate-ai-sdk.js.map +1 -1
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +13 -24
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/agent/run-loop-with-resume.js +1 -1
- package/dist/agent/run-loop-with-resume.js.map +1 -1
- package/dist/agent/run-manager.d.ts.map +1 -1
- package/dist/agent/run-manager.js +39 -10
- package/dist/agent/run-manager.js.map +1 -1
- package/dist/agent/run-store.d.ts +10 -0
- package/dist/agent/run-store.d.ts.map +1 -1
- package/dist/agent/run-store.js +20 -3
- package/dist/agent/run-store.js.map +1 -1
- package/dist/agent/thread-data-builder.d.ts.map +1 -1
- package/dist/agent/thread-data-builder.js +28 -4
- package/dist/agent/thread-data-builder.js.map +1 -1
- package/dist/cli/templates-meta.d.ts.map +1 -1
- package/dist/cli/templates-meta.js +13 -0
- package/dist/cli/templates-meta.js.map +1 -1
- package/dist/cli/workspace-dev.d.ts.map +1 -1
- package/dist/cli/workspace-dev.js +1 -0
- package/dist/cli/workspace-dev.js.map +1 -1
- package/dist/client/error-format.d.ts.map +1 -1
- package/dist/client/error-format.js +10 -0
- package/dist/client/error-format.js.map +1 -1
- package/dist/collab/awareness.d.ts +2 -2
- package/dist/collab/awareness.d.ts.map +1 -1
- package/dist/credentials/index.d.ts +9 -2
- package/dist/credentials/index.d.ts.map +1 -1
- package/dist/credentials/index.js +50 -8
- package/dist/credentials/index.js.map +1 -1
- package/dist/extensions/url-safety.d.ts.map +1 -1
- package/dist/extensions/url-safety.js +38 -12
- package/dist/extensions/url-safety.js.map +1 -1
- package/dist/integrations/adapters/slack.d.ts.map +1 -1
- package/dist/integrations/adapters/slack.js +25 -8
- package/dist/integrations/adapters/slack.js.map +1 -1
- package/dist/integrations/google-docs-poller.d.ts.map +1 -1
- package/dist/integrations/google-docs-poller.js +13 -1
- package/dist/integrations/google-docs-poller.js.map +1 -1
- package/dist/integrations/installations-store.d.ts +10 -0
- package/dist/integrations/installations-store.d.ts.map +1 -1
- package/dist/integrations/installations-store.js +24 -0
- package/dist/integrations/installations-store.js.map +1 -1
- package/dist/integrations/plugin.d.ts.map +1 -1
- package/dist/integrations/plugin.js +6 -5
- package/dist/integrations/plugin.js.map +1 -1
- package/dist/integrations/types.d.ts +7 -0
- package/dist/integrations/types.d.ts.map +1 -1
- package/dist/integrations/types.js.map +1 -1
- package/dist/integrations/webhook-handler.d.ts.map +1 -1
- package/dist/integrations/webhook-handler.js +16 -1
- package/dist/integrations/webhook-handler.js.map +1 -1
- package/dist/jobs/background-automation-runner.d.ts.map +1 -1
- package/dist/jobs/background-automation-runner.js +35 -2
- package/dist/jobs/background-automation-runner.js.map +1 -1
- package/dist/mcp/screen-memory-stdio.d.ts +7 -7
- package/dist/mcp/screen-memory-stdio.d.ts.map +1 -1
- package/dist/notifications/routes.d.ts +3 -3
- package/dist/observability/routes.d.ts +3 -3
- package/dist/provider-api/actions/custom-provider-registration.d.ts +14 -14
- package/dist/provider-api/actions/provider-api.d.ts +8 -8
- package/dist/provider-api/index.js +7 -3
- package/dist/provider-api/index.js.map +1 -1
- package/dist/scripts/call-agent.d.ts.map +1 -1
- package/dist/scripts/call-agent.js +6 -1
- package/dist/scripts/call-agent.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +25 -7
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/agent-discovery.d.ts +2 -0
- package/dist/server/agent-discovery.d.ts.map +1 -1
- package/dist/server/agent-discovery.js.map +1 -1
- package/dist/server/builder-design-systems.d.ts +4 -1
- package/dist/server/builder-design-systems.d.ts.map +1 -1
- package/dist/server/builder-design-systems.js +11 -1
- package/dist/server/builder-design-systems.js.map +1 -1
- package/dist/server/credential-provider.d.ts.map +1 -1
- package/dist/server/credential-provider.js +49 -12
- package/dist/server/credential-provider.js.map +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js.map +1 -1
- package/dist/server/onboarding-html.d.ts.map +1 -1
- package/dist/server/onboarding-html.js +37 -2
- package/dist/server/onboarding-html.js.map +1 -1
- package/dist/server/transcribe-voice.d.ts +1 -1
- package/dist/shared/reasoning-effort.d.ts +1 -0
- package/dist/shared/reasoning-effort.d.ts.map +1 -1
- package/dist/shared/reasoning-effort.js +1 -1
- package/dist/shared/reasoning-effort.js.map +1 -1
- package/dist/templates/chat/app/components/layout/Sidebar.tsx +30 -3
- package/dist/templates/chat/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
- package/dist/templates/workspace-core/.agents/skills/a2a-protocol/SKILL.md +11 -0
- package/package.json +1 -1
- package/src/a2a/correlation.ts +11 -1
- package/src/a2a/types.ts +11 -3
- package/src/agent/engine/ai-sdk-engine.ts +33 -46
- package/src/agent/engine/builder-engine.ts +22 -10
- package/src/agent/engine/error-detail.ts +184 -3
- package/src/agent/engine/failure-taxonomy.ts +123 -0
- package/src/agent/engine/index.ts +8 -0
- package/src/agent/engine/registry.ts +92 -8
- package/src/agent/engine/translate-ai-sdk.ts +17 -2
- package/src/agent/production-agent.ts +13 -33
- package/src/agent/run-loop-with-resume.ts +1 -1
- package/src/agent/run-manager.ts +43 -14
- package/src/agent/run-store.ts +30 -3
- package/src/agent/thread-data-builder.ts +36 -4
- package/src/cli/templates-meta.ts +13 -0
- package/src/cli/workspace-dev.ts +1 -0
- package/src/client/error-format.ts +12 -0
- package/src/credentials/index.ts +51 -12
- package/src/extensions/url-safety.ts +46 -12
- package/src/integrations/adapters/slack.ts +32 -10
- package/src/integrations/google-docs-poller.ts +12 -1
- package/src/integrations/installations-store.ts +30 -0
- package/src/integrations/plugin.ts +5 -5
- package/src/integrations/types.ts +7 -0
- package/src/integrations/webhook-handler.ts +24 -1
- package/src/jobs/background-automation-runner.ts +38 -1
- package/src/provider-api/index.ts +8 -2
- package/src/scripts/call-agent.ts +6 -0
- package/src/server/agent-chat-plugin.ts +30 -9
- package/src/server/agent-discovery.ts +2 -0
- package/src/server/builder-design-systems.ts +21 -0
- package/src/server/credential-provider.ts +51 -12
- package/src/server/index.ts +1 -0
- package/src/server/onboarding-html.ts +37 -2
- package/src/shared/reasoning-effort.ts +1 -1
- package/src/templates/chat/app/components/layout/Sidebar.tsx +30 -3
- package/src/templates/chat/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
- package/src/templates/workspace-core/.agents/skills/a2a-protocol/SKILL.md +11 -0
- package/corpus/templates/clips/desktop/src/lib/media-device-selection.ts +0 -157
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builder-engine.js","sourceRoot":"","sources":["../../../src/agent/engine/builder-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC7D,OAAO,EACL,iCAAiC,EACjC,yBAAyB,EACzB,wBAAwB,EACxB,kCAAkC,GACnC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,6BAA6B,EAAE,MAAM,uCAAuC,CAAC;AACtF,OAAO,EACL,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,6BAA6B,EAAE,MAAM,0BAA0B,CAAC;AACzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC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C3B;QACD,QAAQ,EAAE;YACR,cAAc,EAAE;gBACd,KAAK,EAAE,QAAQ;gBACf,KAAK,EAAE,OAAO,CAAC,KAAK;gBACpB,aAAa,EAAE,OAAO,CAAC,UAAU,EAAE,MAAM;gBACzC,WAAW,EAAE,OAAO,CAAC,UAAU,EAAE,QAAQ;gBACzC,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,SAAS,EAAE,uBAAuB;aACnC;SACF;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * BuilderEngine — HTTP client for the Builder.io managed LLM gateway.\n *\n * The gateway accepts an Anthropic-shaped request body and streams events as\n * JSONL. This engine translates the framework's EngineStreamOptions into the\n * gateway request, parses the streamed events into EngineEvent items, and\n * maps gateway error responses (402 quota, 403 disabled, 401 auth, 429\n * concurrency) into structured stop events that carry an upgrade URL when\n * the chat UI needs to prompt the user to upgrade.\n *\n * Credentials come from BUILDER_PRIVATE_KEY + BUILDER_PUBLIC_KEY (set via the\n * Builder CLI-auth onboarding flow). Base URL is overridable via\n * BUILDER_GATEWAY_BASE_URL.\n */\n\nimport { captureError } from \"../../server/capture-error.js\";\nimport {\n clearBuilderCredentialAuthFailure,\n resolveBuilderCredentials,\n getBuilderGatewayBaseUrl,\n recordBuilderCredentialAuthFailure,\n} from \"../../server/credential-provider.js\";\nimport { applyBuilderUtmTrackingParams } from \"../../shared/builder-link-tracking.js\";\nimport {\n normalizeReasoningEffortForModel,\n type ReasoningEffort,\n} from \"../../shared/reasoning-effort.js\";\nimport { isInBackgroundFunctionRuntime } from \"../durable-background.js\";\nimport { BUILDER_MODEL_CONFIG } from \"../model-config.js\";\nimport { getBuilderGatewayRequestHeaders } from \"./builder-gateway-headers.js\";\nimport {\n LLM_MISSING_CREDENTIALS_ERROR_CODE,\n LLM_MISSING_CREDENTIALS_MESSAGE,\n} from \"./credential-errors.js\";\nimport { describeErrorWithCauses } from \"./error-detail.js\";\nimport { FIRST_STREAM_EVENT_TIMEOUT_MS } from \"./first-event-timeout.js\";\nimport { resolveMaxOutputTokensForEngine } from \"./output-tokens.js\";\nimport {\n splitSystemPromptForCache,\n stablePrefixCacheControl,\n} from \"./prompt-cache.js\";\nimport {\n createStreamedToolInputState,\n engineMessagesToBuilderGatewayAnthropic,\n engineToolsToAnthropic,\n finalizeStreamedToolInputs,\n observeStreamedToolInput,\n} from \"./translate-anthropic.js\";\nimport type {\n AgentEngine,\n EngineCapabilities,\n EngineContentPart,\n EngineEvent,\n EngineStreamOptions,\n} from \"./types.js\";\n\nexport const BUILDER_CAPABILITIES: EngineCapabilities = {\n thinking: true,\n promptCaching: true,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n};\n\nexport const BUILDER_SUPPORTED_MODELS = BUILDER_MODEL_CONFIG.supportedModels;\n\n// Keep the foreground hosted gateway timeout below the synchronous serverless\n// wall so the agent loop can append a continuation and persist terminal state\n// before the host hard-kills the invocation.\nconst DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS = 45_000;\nconst MAX_HOSTED_FOREGROUND_BUILDER_GATEWAY_TIMEOUT_MS = 45_000;\n/**\n * Netlify background functions have a 15-minute wall. Keep the Builder gateway\n * ceiling below that, but above the run-manager's 13-minute soft-timeout so\n * durable background runs checkpoint before this timer wins.\n */\nconst MAX_BACKGROUND_BUILDER_GATEWAY_TIMEOUT_MS = 14 * 60_000;\n/** Local and non-hosted runtimes have no synchronous serverless wall. */\nconst MAX_LOCAL_BUILDER_GATEWAY_TIMEOUT_MS =\n MAX_BACKGROUND_BUILDER_GATEWAY_TIMEOUT_MS;\nconst BUILDER_GATEWAY_NETWORK_ERROR_CODE = \"builder_gateway_network_error\";\nexport const BUILDER_MODEL_UNAUTHORIZED_ERROR_CODE =\n \"builder_model_unauthorized\";\n\nexport const BUILDER_DEFAULT_MODEL = BUILDER_MODEL_CONFIG.defaultModel;\n\n/**\n * Bucket an Anthropic `thinking.budgetTokens` value into the gateway's\n * legacy three-level `reasoning_effort` enum.\n *\n * The thresholds are chosen to align with typical Anthropic extended-thinking\n * budgets we see in the wild:\n * • < 2000 → short one-step reasoning (\"low\")\n * • 2000–8000 → multi-step thinking (\"medium\")\n * • ≥ 8000 → deep planning / long chains (\"high\")\n *\n * 8000 is Anthropic's documented default in our framework (see\n * engine/types.ts:195), so callers that don't explicitly set\n * `budgetTokens` map to \"high\" via the default. If the gateway later\n * exposes more granular knobs or different thresholds, revisit this map.\n */\nfunction mapReasoningEffort(budgetTokens: number): ReasoningEffort {\n if (budgetTokens < 2000) return \"low\";\n if (budgetTokens < 8000) return \"medium\";\n return \"high\";\n}\n\n/**\n * Build the URL the chat UI should link to when a user hits a quota error.\n *\n * We can't deep-link to a per-org billing page from `BUILDER_ORG_NAME` because\n * that field is the org's display name (e.g. \"Nicholas kipchumba Space\"), not\n * a URL-safe slug or id. URL-encoding the display name produces segments like\n * `/app/organizations/Nicholas%20kipchumba%20Space/billing` which Builder's\n * router treats as unknown and silently bounces to `/app/projects`. The\n * Builder CLI-auth callback doesn't expose the org slug/id today, so we route\n * to the org-agnostic subscription page. Agent Native attribution lets Builder\n * skip generic onboarding for new users who land there from an upgrade CTA.\n */\nasync function buildUpgradeUrl(): Promise<string> {\n const url = new URL(\"https://builder.io/account/subscription\");\n url.searchParams.set(\"signupSource\", \"agent-native\");\n url.searchParams.set(\"agentNativeConnectSource\", \"gateway_quota_upgrade\");\n url.searchParams.set(\"agentNativeFlow\", \"connect_llm\");\n url.searchParams.set(\"framework\", \"agent-native\");\n applyBuilderUtmTrackingParams(url.searchParams, {\n content: \"gateway_quota_upgrade\",\n });\n return url.toString();\n}\n\ninterface GatewayErrorBody {\n code?: string;\n message?: string;\n usageInfo?: {\n plan?: string;\n limitExceeded?: string;\n isEnterprise?: boolean;\n };\n}\n\nclass BuilderEngine implements AgentEngine {\n readonly name = \"builder\";\n readonly label = \"Builder.io Gateway\";\n readonly defaultModel = BUILDER_DEFAULT_MODEL;\n readonly supportedModels = BUILDER_SUPPORTED_MODELS;\n readonly capabilities = BUILDER_CAPABILITIES;\n\n async *stream(opts: EngineStreamOptions): AsyncIterable<EngineEvent> {\n const creds = await resolveBuilderCredentials();\n const authHeader = creds.privateKey ? `Bearer ${creds.privateKey}` : null;\n const spaceId = creds.publicKey;\n const builderUserId = creds.userId;\n if (!authHeader || !spaceId) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: LLM_MISSING_CREDENTIALS_MESSAGE,\n errorCode: LLM_MISSING_CREDENTIALS_ERROR_CODE,\n };\n return;\n }\n\n const messages = engineMessagesToBuilderGatewayAnthropic(opts.messages);\n const tools = engineToolsToAnthropic(opts.tools);\n const thinkingBudget =\n opts.providerOptions?.anthropic?.thinking?.budgetTokens;\n const reasoningEffort = normalizeReasoningEffortForModel(\n opts.model,\n opts.reasoningEffort ??\n (typeof thinkingBudget === \"number\"\n ? mapReasoningEffort(thinkingBudget)\n : undefined),\n );\n\n // Apply prompt caching to system + tools (stable prefix) and to the last\n // user message (moving cache breakpoint so growing history gets cached\n // across tool-loop iterations at ~90% off input cost).\n // Templates can opt out by setting providerOptions.anthropic.cacheControl=false.\n const cacheEnabled =\n opts.providerOptions?.anthropic?.cacheControl !== false;\n\n // System: split into a stable block carrying the breakpoint and a volatile\n // tail (resources, app extras, model overlay, runtime context) without one,\n // so mid-turn resource churn no longer invalidates system + tools.\n const { stable, volatile } = splitSystemPromptForCache(\n opts.systemPrompt ?? \"\",\n );\n const systemValue: unknown = opts.systemPrompt\n ? cacheEnabled\n ? [\n {\n type: \"text\",\n text: stable,\n cache_control: stablePrefixCacheControl(),\n },\n ...(volatile ? [{ type: \"text\", text: volatile }] : []),\n ]\n : stable + volatile\n : undefined;\n\n // Tools: add cache_control to the last tool definition.\n let cachedTools = tools;\n if (cacheEnabled && tools.length > 0) {\n cachedTools = [...tools];\n const last = { ...cachedTools[cachedTools.length - 1] } as any;\n last.cache_control = stablePrefixCacheControl();\n cachedTools[cachedTools.length - 1] = last;\n }\n\n // Messages: add a moving cache breakpoint on the last user message's last\n // content block so the entire conversation prefix is cached. Stays on the\n // default 5m TTL — it moves every iteration, so a longer-lived entry would\n // only pay the higher write premium.\n let cachedMessages = messages;\n if (cacheEnabled && messages.length > 0) {\n let lastUserIdx = -1;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n if ((messages[i] as any).role === \"user\") {\n lastUserIdx = i;\n break;\n }\n }\n if (lastUserIdx >= 0) {\n cachedMessages = [...messages];\n const lastMsg = { ...cachedMessages[lastUserIdx] } as any;\n if (Array.isArray(lastMsg.content) && lastMsg.content.length > 0) {\n const content = [...lastMsg.content];\n const lastBlock = { ...content[content.length - 1] } as any;\n lastBlock.cache_control = { type: \"ephemeral\" };\n content[content.length - 1] = lastBlock;\n lastMsg.content = content;\n cachedMessages[lastUserIdx] = lastMsg;\n }\n }\n }\n\n const body: Record<string, unknown> = {\n model: opts.model,\n messages: cachedMessages,\n ...(systemValue !== undefined ? { system: systemValue } : {}),\n ...(cachedTools.length > 0 ? { tools: cachedTools } : {}),\n max_tokens: resolveMaxOutputTokensForEngine(\n this.name,\n opts.maxOutputTokens,\n opts.model,\n ),\n ...(typeof opts.temperature === \"number\"\n ? { temperature: opts.temperature }\n : {}),\n ...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),\n };\n\n const gatewayBaseUrl = getBuilderGatewayBaseUrl();\n const gatewayUrl = new URL(\n \"messages\",\n gatewayBaseUrl.endsWith(\"/\") ? gatewayBaseUrl : `${gatewayBaseUrl}/`,\n );\n gatewayUrl.searchParams.set(\"apiKey\", spaceId);\n const orgLabel = creds.orgName || \"unknown-org\";\n const tStart = Date.now();\n console.log(\n `[builder-engine] → POST ${gatewayUrl.origin}${gatewayUrl.pathname} model=${opts.model} tools=${tools.length} org=${orgLabel}`,\n );\n\n const gatewayTimeoutMs = getBuilderGatewayTimeoutMs();\n const gatewayAbort = createGatewayAbortSignal(\n opts.abortSignal,\n gatewayTimeoutMs,\n );\n try {\n let response: Response;\n try {\n response = await fetch(gatewayUrl.toString(), {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: authHeader,\n \"x-builder-api-key\": spaceId,\n ...getBuilderGatewayRequestHeaders(),\n ...(builderUserId ? { \"x-builder-user-id\": builderUserId } : {}),\n },\n body: JSON.stringify(body),\n signal: gatewayAbort.signal,\n });\n } catch (err) {\n const timedOut = gatewayAbort.didTimeout();\n if (gatewayAbort.didTimeout()) {\n console.warn(\n `[builder-engine] gateway timed out after ${Date.now() - tStart}ms`,\n );\n }\n if (timedOut || isBuilderGatewayNetworkError(err)) {\n captureBuilderGatewayTransportError(err, {\n phase: \"request\",\n model: opts.model,\n gatewayUrl,\n timeoutMs: gatewayAbort.effectiveTimeoutMs(),\n timedOut,\n elapsedMs: Date.now() - tStart,\n });\n }\n yield createBuilderGatewayTimeoutStop(\n err,\n timedOut,\n gatewayAbort.effectiveTimeoutMs(),\n );\n return;\n }\n\n console.log(\n `[builder-engine] ← ${response.status} ${response.statusText} in ${Date.now() - tStart}ms`,\n );\n\n if (!response.ok) {\n yield* emitHttpError(response);\n return;\n }\n\n // A successful gateway call proves the connected credentials are valid\n // again. Clear any prior auth-failure marker so status / chat-card\n // surfaces stop flagging the connection as broken. This is the only\n // self-healing path for workspace/env-managed credentials, which never\n // flow through writeBuilderCredentials.\n try {\n const creds = await resolveBuilderCredentials();\n await clearBuilderCredentialAuthFailure({\n privateKey: creds.privateKey,\n publicKey: creds.publicKey,\n });\n } catch {\n // Marker clearing is best-effort; a stale marker just means the user\n // sees \"reconnect Builder\" until the next successful call clears it.\n }\n\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"text/html\")) {\n const rawText = await response.text().catch(() => \"\");\n yield {\n type: \"stop\",\n reason: \"error\",\n error: normalizeGatewayErrorText(rawText, response.status || 502),\n errorCode: `http_${response.status || 502}`,\n };\n return;\n }\n\n const reader = response.body?.getReader();\n if (!reader) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: \"Builder gateway response has no body\",\n };\n return;\n }\n\n yield* parseJsonlStream(reader, opts.model, {\n abortSignal: gatewayAbort.signal,\n didGatewayTimeout: gatewayAbort.didTimeout,\n getGatewayTimeoutMs: gatewayAbort.effectiveTimeoutMs,\n onFirstEvent: gatewayAbort.markFirstEvent,\n gatewayUrl,\n requestStartedAt: tStart,\n });\n } finally {\n gatewayAbort.cleanup();\n }\n }\n}\n\nasync function* emitHttpError(response: Response): AsyncIterable<EngineEvent> {\n const status = response.status;\n // Read the body once as text and then try to parse — calling `.json()`\n // and then `.text()` as a fallback fails because the body stream is\n // already consumed (TypeError: Body has already been read), so we'd\n // silently lose non-JSON error payloads like HTML proxy 502s.\n let errBody: GatewayErrorBody = {};\n const rawText = await response.text().catch(() => \"\");\n if (rawText) {\n try {\n errBody = JSON.parse(rawText) as GatewayErrorBody;\n } catch {\n errBody.message = normalizeGatewayErrorText(rawText, status);\n }\n }\n const code = errBody.code ?? `http_${status}`;\n const message = errBody.message ?? `Builder gateway returned ${status}`;\n\n // Belt-and-suspenders: 402 without a structured `credits-limit` code\n // (e.g. bare proxy response) still means quota → show upgrade CTA.\n if (code.startsWith(\"credits-limit\") || status === 402) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n upgradeUrl: await buildUpgradeUrl(),\n };\n return;\n }\n if (code === \"gateway_not_enabled\") {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n };\n return;\n }\n if (status === 401 || code === \"unauthorized\") {\n await recordBuilderCredentialAuthFailure({ status, code, message });\n yield {\n type: \"stop\",\n reason: \"error\",\n error: \"Builder authentication failed. Reconnect Builder via Settings.\",\n errorCode: \"builder_auth_error\",\n };\n return;\n }\n if (status === 403 && isBuilderCredentialAuthError(message)) {\n await recordBuilderCredentialAuthFailure({ status, code, message });\n yield {\n type: \"stop\",\n reason: \"error\",\n error: \"Builder authentication failed. Reconnect Builder via Settings.\",\n errorCode: \"builder_auth_error\",\n };\n return;\n }\n if (status === 403) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n };\n return;\n }\n if (code === \"rate_limit_exceeded\") {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n };\n return;\n }\n if (status === 429 || code === \"too_many_concurrent_requests\") {\n // Include \"too many requests\" in the message so production-agent's\n // isRetryableError picks up transient concurrency throttles and retries\n // the turn. Daily gateway caps use `rate_limit_exceeded` above and must\n // not loop.\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `${message} (too many requests)`,\n errorCode: code,\n };\n return;\n }\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n };\n}\n\n// Yields one non-empty JSONL line at a time. Flushes any trailing content\n// after the stream ends so a final event without a newline terminator\n// isn't silently dropped — some gateway proxies close the connection on\n// a complete line and the client must still process it.\nasync function* readJsonlLines(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n abortSignal?: AbortSignal,\n): AsyncIterable<string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n while (true) {\n const { done, value } = await readStreamChunk(reader, abortSignal);\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let newlineIdx = buffer.indexOf(\"\\n\");\n while (newlineIdx !== -1) {\n const line = buffer.slice(0, newlineIdx).trim();\n buffer = buffer.slice(newlineIdx + 1);\n newlineIdx = buffer.indexOf(\"\\n\");\n if (line) yield line;\n }\n }\n // Flush any bytes the streaming decoder buffered for an incomplete multibyte\n // sequence at the end of the stream; otherwise a trailing multibyte char in\n // the final chunk is silently dropped from the last line.\n buffer += decoder.decode();\n const tail = buffer.trim();\n if (tail) yield tail;\n}\n\nasync function* parseJsonlStream(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n model: string,\n captureContext: {\n abortSignal?: AbortSignal;\n didGatewayTimeout?: () => boolean;\n getGatewayTimeoutMs?: () => number;\n onFirstEvent?: () => void;\n gatewayUrl?: URL;\n requestStartedAt?: number;\n } = {},\n): AsyncIterable<EngineEvent> {\n const parts: EngineContentPart[] = [];\n let pendingText = \"\";\n let pendingThinking: { text: string; signature?: string } | null = null;\n\n const flushPendingText = () => {\n if (pendingText) {\n parts.push({ type: \"text\", text: pendingText });\n pendingText = \"\";\n }\n };\n\n const flushPendingThinking = () => {\n if (pendingThinking) {\n parts.push({\n type: \"thinking\",\n text: pendingThinking.text,\n ...(pendingThinking.signature !== undefined\n ? { signature: pendingThinking.signature }\n : {}),\n });\n pendingThinking = null;\n }\n };\n\n const flushPending = () => {\n flushPendingText();\n flushPendingThinking();\n };\n\n const toolInputs = createStreamedToolInputState();\n\n // The gateway can announce a tool call through `tool-call-delta` frames and\n // then die before the terminal `tool-call` frame. Assemble what streamed, or\n // hand the model an in-band error — never end the turn advertising a call\n // that was silently dropped.\n const recoverUndeliveredToolCalls = (): EngineEvent[] => {\n const events = finalizeStreamedToolInputs(toolInputs);\n for (const event of events) {\n if (event.type === \"tool-call\") {\n parts.push({\n type: \"tool-call\",\n id: event.id,\n name: event.name,\n input: event.input,\n });\n }\n }\n return events;\n };\n\n try {\n for await (const line of readJsonlLines(\n reader,\n captureContext.abortSignal,\n )) {\n let event: any;\n try {\n event = JSON.parse(line);\n } catch {\n const normalized = normalizeGatewayErrorText(line, 502);\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `Builder gateway returned invalid JSONL: ${normalized.slice(\n 0,\n 240,\n )}`,\n errorCode: \"http_502\",\n };\n return;\n }\n\n // Heartbeats are transport-level keepalives, not proof the model is\n // producing output — every other parsed event counts as first progress.\n if (event?.type !== \"heartbeat\") {\n captureContext.onFirstEvent?.();\n }\n\n switch (event.type) {\n case \"text-delta\": {\n const text = event.text ?? \"\";\n flushPendingThinking();\n pendingText += text;\n yield { type: \"text-delta\", text };\n break;\n }\n\n case \"thinking-delta\":\n case \"reasoning-delta\": {\n const text = event.text ?? \"\";\n flushPendingText();\n if (!pendingThinking) pendingThinking = { text: \"\" };\n pendingThinking.text += text;\n if (event.signature) pendingThinking.signature = event.signature;\n yield {\n type: \"thinking-delta\",\n text,\n ...(event.signature ? { signature: event.signature } : {}),\n };\n break;\n }\n\n case \"tool-call-delta\": {\n const delta: EngineEvent = {\n type: \"tool-input-delta\",\n id: event.id,\n name: event.name,\n text:\n typeof event.argsTextDelta === \"string\"\n ? event.argsTextDelta\n : typeof event.delta === \"string\"\n ? event.delta\n : \"\",\n };\n observeStreamedToolInput(toolInputs, delta);\n yield delta;\n break;\n }\n\n case \"heartbeat\":\n yield { type: \"gateway-heartbeat\" };\n break;\n\n case \"tool-call\": {\n flushPending();\n const call = {\n type: \"tool-call\" as const,\n id: event.id,\n name: event.name,\n input: event.input,\n };\n parts.push(call);\n observeStreamedToolInput(toolInputs, call);\n yield { ...call };\n break;\n }\n\n case \"usage\": {\n const cacheWrite =\n (event.cacheCreatedTokens ?? 0) + (event.cacheCreated1hTokens ?? 0);\n yield {\n type: \"usage\",\n inputTokens: event.inputTokens ?? 0,\n outputTokens: event.outputTokens ?? 0,\n ...(event.cacheInputTokens !== undefined\n ? { cacheReadTokens: event.cacheInputTokens }\n : {}),\n ...(cacheWrite > 0 ? { cacheWriteTokens: cacheWrite } : {}),\n };\n break;\n }\n\n case \"stop\": {\n flushPending();\n yield* recoverUndeliveredToolCalls();\n yield { type: \"assistant-content\", parts };\n\n const reason = event.reason ?? \"end_turn\";\n if (reason === \"rate_limited\") {\n // Include \"rate_limit\" in the message so production-agent's\n // isRetryableError picks it up and retries.\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `rate_limit exceeded: ${event.error ?? \"upstream provider rate limited\"}`,\n errorCode: \"rate_limited\",\n };\n } else if (reason === \"invalid_request\") {\n // errorCode has no retry-trigger keywords, so isRetryableError\n // won't loop on broken history.\n const errMsg =\n event.error ||\n event.message ||\n \"Builder gateway rejected the request as malformed.\";\n const errCode =\n typeof event.errorCode === \"string\"\n ? event.errorCode\n : typeof event.code === \"string\"\n ? event.code\n : \"invalid_request\";\n console.warn(\n `[builder-engine] stop reason=invalid_request model=${model} code=${errCode} error=${errMsg}`,\n );\n yield {\n type: \"stop\",\n reason: \"error\",\n error: errMsg,\n errorCode: errCode,\n };\n } else if (reason === \"error\") {\n // Surface every diagnostic the gateway gave us so the user (and\n // our logs) get more than a bare \"Gateway error\". The gateway\n // sometimes emits an error stop event with no message — most\n // commonly when the upstream provider rejects the model for\n // this account (Opus quotas have hit this in practice).\n const explicitErrMsg = event.error || event.message || event.detail;\n const errMsg =\n explicitErrMsg ??\n `Gateway error (no detail; raw event: ${JSON.stringify(event)})`;\n const gatewayErrCode = event.errorCode ?? event.code;\n // The gateway already authenticated this request before streaming,\n // so a bare \"Unauthorized\" here means the account cannot use this\n // model — not that the connection is broken. Only a message that\n // names the credential may tear down the Builder connection.\n const isCredentialAuthError =\n Boolean(explicitErrMsg) &&\n isBuilderCredentialAuthErrorInStream(String(errMsg));\n const isModelAuthError =\n Boolean(explicitErrMsg) &&\n !isCredentialAuthError &&\n isBuilderCredentialAuthError(String(errMsg));\n // Providers can report a bare \"Connection error.\" or AI SDK's\n // retry-wrapped \"Cannot connect to API\" without a gateway code.\n // Tag both as network errors so retries can recover the turn.\n const isProviderConnectionError =\n typeof explicitErrMsg === \"string\" &&\n isProviderConnectionErrorMessage(String(explicitErrMsg));\n const errCode = isCredentialAuthError\n ? \"builder_auth_error\"\n : isModelAuthError\n ? BUILDER_MODEL_UNAUTHORIZED_ERROR_CODE\n : isProviderConnectionError\n ? BUILDER_GATEWAY_NETWORK_ERROR_CODE\n : (gatewayErrCode ??\n (!explicitErrMsg ? \"builder_gateway_error\" : undefined));\n console.error(\n `[builder-engine] stop reason=error model=${model} code=${errCode ?? \"(none)\"} error=${errMsg}`,\n );\n if (isCredentialAuthError) {\n await recordBuilderCredentialAuthFailure({\n code:\n typeof gatewayErrCode === \"string\" ? gatewayErrCode : errCode,\n message: String(errMsg),\n });\n }\n // No-detail gateway errors are opaque to the chat client — the\n // only way to debug them is from the gateway side. Capture rich\n // tags here (model, gatewayOrigin, requestId) so the gateway\n // team can search Sentry by requestId or filter by model. The\n // downstream run-manager will also capture the EngineError once\n // it's thrown, but without these tags.\n if (!explicitErrMsg) {\n captureBuilderGatewayNoDetailError({\n requestId:\n typeof event.requestId === \"string\"\n ? event.requestId\n : undefined,\n model,\n gatewayUrl: captureContext.gatewayUrl,\n rawEvent: event,\n });\n }\n yield {\n type: \"stop\",\n reason: \"error\",\n error: errMsg,\n ...(errCode ? { errorCode: errCode } : {}),\n };\n } else if (\n reason === \"end_turn\" ||\n reason === \"tool_use\" ||\n reason === \"max_tokens\" ||\n reason === \"stop_sequence\"\n ) {\n yield { type: \"stop\", reason };\n } else {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `Unknown stop reason: ${reason}`,\n };\n }\n return;\n }\n\n default:\n // Unknown event type — ignore for forward compat.\n break;\n }\n }\n\n // Stream ended without a stop event — synthesize one so callers don't hang.\n flushPending();\n yield* recoverUndeliveredToolCalls();\n yield { type: \"assistant-content\", parts };\n yield {\n type: \"stop\",\n reason: \"error\",\n error: \"Builder gateway stream ended without a stop event\",\n };\n } catch (err) {\n const timedOut = captureContext.didGatewayTimeout?.() ?? false;\n const gatewayTimeoutMs =\n captureContext.getGatewayTimeoutMs?.() ??\n DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS;\n if (timedOut || isBuilderGatewayNetworkError(err)) {\n captureBuilderGatewayTransportError(err, {\n phase: \"stream\",\n model,\n gatewayUrl: captureContext.gatewayUrl,\n timeoutMs: gatewayTimeoutMs,\n timedOut,\n elapsedMs:\n typeof captureContext.requestStartedAt === \"number\"\n ? Date.now() - captureContext.requestStartedAt\n : undefined,\n });\n }\n yield createBuilderGatewayTimeoutStop(err, timedOut, gatewayTimeoutMs);\n } finally {\n // Release the reader on every exit path — early returns (invalid JSONL,\n // stop event) and generator abandonment both leave the underlying\n // Response body locked otherwise. cancel() also closes the socket.\n try {\n await reader.cancel();\n } catch {\n // Already cancelled or closed\n }\n }\n}\n\nfunction readStreamChunk(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n abortSignal?: AbortSignal,\n): Promise<ReadableStreamReadResult<Uint8Array>> {\n if (!abortSignal) return reader.read();\n if (abortSignal.aborted) {\n return Promise.reject(abortSignal.reason ?? new Error(\"Stream aborted\"));\n }\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n reject(abortSignal.reason ?? new Error(\"Stream aborted\"));\n };\n abortSignal.addEventListener(\"abort\", onAbort, { once: true });\n reader.read().then(\n (value) => {\n abortSignal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (err) => {\n abortSignal.removeEventListener(\"abort\", onAbort);\n reject(err);\n },\n );\n });\n}\n\nfunction normalizeGatewayErrorText(raw: string, status: number): string {\n const text = raw.trim();\n const looksHtml = /<html[\\s>]|<body[\\s>]|<head[\\s>]/i.test(text);\n const readable = looksHtml ? htmlToText(text) : text;\n if (/inactivity timeout/i.test(readable)) {\n return `Builder gateway returned ${status}: Inactivity Timeout. The upstream connection was idle too long before sending data.`;\n }\n if (looksHtml) {\n return `Builder gateway returned ${status}: ${readable.slice(0, 240)}`;\n }\n return readable;\n}\n\nfunction htmlToText(html: string): string {\n return html\n .replace(/<script[\\s\\S]*?<\\/script>/gi, \" \")\n .replace(/<style[\\s\\S]*?<\\/style>/gi, \" \")\n .replace(/<br\\s*\\/?>/gi, \"\\n\")\n .replace(/<\\/(p|div|h1|h2|h3|li|tr)>/gi, \"\\n\")\n .replace(/<[^>]+>/g, \" \")\n .replace(/ /gi, \" \")\n .replace(/</gi, \"<\")\n .replace(/>/gi, \">\")\n .replace(/&/gi, \"&\")\n .replace(/"/gi, '\"')\n .replace(/'/gi, \"'\")\n .replace(/[ \\t]+/g, \" \")\n .replace(/\\n\\s+/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\nexport function createBuilderEngine(\n _config: Record<string, unknown> = {},\n): AgentEngine {\n return new BuilderEngine();\n}\n\nfunction resolveMaxBuilderGatewayTimeoutMs(): number {\n if (isInBackgroundFunctionRuntime()) {\n return MAX_BACKGROUND_BUILDER_GATEWAY_TIMEOUT_MS;\n }\n\n if (!isHostedBuilderRuntime()) {\n return MAX_LOCAL_BUILDER_GATEWAY_TIMEOUT_MS;\n }\n\n try {\n const base = getBuilderGatewayBaseUrl();\n if (/^https?:\\/\\/(localhost|127\\.0\\.0\\.1)([:/]|$)/i.test(base)) {\n return MAX_LOCAL_BUILDER_GATEWAY_TIMEOUT_MS;\n }\n } catch {\n // ignore malformed override\n }\n return MAX_HOSTED_FOREGROUND_BUILDER_GATEWAY_TIMEOUT_MS;\n}\n\nfunction isHostedBuilderRuntime(): 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\nfunction getBuilderGatewayTimeoutMs(): number {\n const raw = process.env.AGENT_NATIVE_BUILDER_GATEWAY_TIMEOUT_MS;\n const maxMs = resolveMaxBuilderGatewayTimeoutMs();\n if (!raw) return maxMs;\n const parsed = Number(raw);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n return maxMs;\n }\n return Math.min(parsed, maxMs);\n}\n\n/**\n * Two-stage abort deadline: until the first real stream event arrives, the\n * effective deadline is min(totalTimeoutMs, FIRST_STREAM_EVENT_TIMEOUT_MS) —\n * a wedged gateway that never streams anything gets cut off in ~2 minutes\n * instead of riding the full flat timeout. Once `markFirstEvent()` fires, the\n * timer reschedules for whatever remains of the original total deadline, so\n * a request that starts streaming still gets the full budget it always did.\n */\nfunction createGatewayAbortSignal(\n parentSignal: AbortSignal,\n totalTimeoutMs: number,\n): {\n signal: AbortSignal;\n didTimeout: () => boolean;\n effectiveTimeoutMs: () => number;\n markFirstEvent: () => void;\n cleanup: () => void;\n} {\n const controller = new AbortController();\n let timedOut = false;\n let firstEventSeen = false;\n const startedAt = Date.now();\n\n const abortFromParent = () => {\n if (!controller.signal.aborted) {\n controller.abort(parentSignal.reason);\n }\n };\n\n const fireTimeout = () => {\n timedOut = true;\n if (!controller.signal.aborted) {\n controller.abort(new Error(\"Builder gateway request timed out\"));\n }\n };\n\n const firstEventDeadlineMs = Math.min(\n totalTimeoutMs,\n FIRST_STREAM_EVENT_TIMEOUT_MS,\n );\n let timeout = setTimeout(fireTimeout, firstEventDeadlineMs);\n\n if (parentSignal.aborted) abortFromParent();\n parentSignal.addEventListener(\"abort\", abortFromParent, { once: true });\n\n return {\n signal: controller.signal,\n didTimeout: () => timedOut,\n effectiveTimeoutMs: () =>\n firstEventSeen ? totalTimeoutMs : firstEventDeadlineMs,\n markFirstEvent: () => {\n if (firstEventSeen || timedOut) return;\n firstEventSeen = true;\n // The first-event window was already the binding constraint (total\n // timeout <= it) — nothing to reschedule.\n if (firstEventDeadlineMs >= totalTimeoutMs) return;\n clearTimeout(timeout);\n const remainingMs = Math.max(\n 0,\n totalTimeoutMs - (Date.now() - startedAt),\n );\n timeout = setTimeout(fireTimeout, remainingMs);\n },\n cleanup: () => {\n clearTimeout(timeout);\n parentSignal.removeEventListener(\"abort\", abortFromParent);\n },\n };\n}\n\nfunction isBuilderCredentialAuthError(message: string): boolean {\n const lowerMessage = message.toLowerCase();\n const referencesAccessToken =\n lowerMessage.includes(\"personal access token\") ||\n lowerMessage.includes(\"access token\");\n const rejectedToken =\n lowerMessage.includes(\"invalid\") ||\n lowerMessage.includes(\"inactive\") ||\n lowerMessage.includes(\"expired\") ||\n lowerMessage.includes(\"revoked\");\n return (\n lowerMessage.includes(\"unauthorized\") ||\n lowerMessage.includes(\"private key\") ||\n lowerMessage.includes(\"invalid token\") ||\n lowerMessage.includes(\"invalid_token\") ||\n lowerMessage.includes(\"token invalid\") ||\n (referencesAccessToken && rejectedToken)\n );\n}\n\n/**\n * Stricter than {@link isBuilderCredentialAuthError} for errors that arrive\n * inside an already-authenticated stream, where a bare \"unauthorized\" is far\n * more likely to be a per-model entitlement rejection than a bad credential.\n * Misreading one there disconnects Builder for every model, including the ones\n * that still work.\n */\nfunction isBuilderCredentialAuthErrorInStream(message: string): boolean {\n if (!isBuilderCredentialAuthError(message)) return false;\n const lowerMessage = message.toLowerCase();\n return (\n lowerMessage.includes(\"private key\") ||\n lowerMessage.includes(\"access token\") ||\n lowerMessage.includes(\"invalid token\") ||\n lowerMessage.includes(\"invalid_token\") ||\n lowerMessage.includes(\"token invalid\")\n );\n}\n\nfunction normalizeBuilderGatewayFetchError(\n err: unknown,\n timedOut: boolean,\n timeoutMs: number,\n): string {\n if (timedOut) {\n return `Builder gateway timed out after ${formatTimeoutMs(\n timeoutMs,\n )} before the hosting function limit. Please retry; if this keeps happening, reduce the prompt size or try again when the gateway is less busy.`;\n }\n const message = errorMessage(err);\n if (isBuilderGatewayNetworkError(err)) {\n return `Builder gateway network error: ${message}`;\n }\n return message;\n}\n\nfunction createBuilderGatewayTimeoutStop(\n err: unknown,\n timedOut: boolean,\n timeoutMs: number,\n): EngineEvent {\n const networkError = !timedOut && isBuilderGatewayNetworkError(err);\n return {\n type: \"stop\",\n reason: \"error\",\n error: normalizeBuilderGatewayFetchError(err, timedOut, timeoutMs),\n ...(timedOut\n ? { errorCode: \"builder_gateway_timeout\" }\n : networkError\n ? { errorCode: BUILDER_GATEWAY_NETWORK_ERROR_CODE }\n : {}),\n };\n}\n\nfunction formatTimeoutMs(timeoutMs: number): string {\n if (timeoutMs < 1000) return `${timeoutMs}ms`;\n return `${Math.round(timeoutMs / 1000)}s`;\n}\n\nfunction errorMessage(err: unknown): string {\n return describeErrorWithCauses(err);\n}\n\nfunction errorSearchText(err: unknown): string {\n const parts: string[] = [];\n if (err instanceof Error) {\n parts.push(err.name, err.message);\n const maybe = err as Error & {\n code?: unknown;\n cause?: unknown;\n };\n if (typeof maybe.code === \"string\") parts.push(maybe.code);\n if (maybe.cause) parts.push(errorSearchText(maybe.cause));\n } else {\n parts.push(String(err));\n }\n return parts.join(\" \").toLowerCase();\n}\n\nfunction isBuilderGatewayNetworkError(err: unknown): boolean {\n const text = errorSearchText(err);\n return (\n text.includes(\"socket hang up\") ||\n text.includes(\"econnreset\") ||\n text.includes(\"enetreset\") ||\n text.includes(\"econnaborted\") ||\n text.includes(\"fetch failed\") ||\n text.includes(\"network error\") ||\n // Anthropic SDK's APIConnectionError default (\"Connection error.\") is\n // often forwarded by the Builder gateway as a stop event with no code.\n text.includes(\"connection error\") ||\n text.includes(\"connection reset\") ||\n text.includes(\"connection closed\") ||\n text.includes(\"stream closed\") ||\n text.includes(\"terminated\")\n );\n}\n\nfunction isProviderConnectionErrorMessage(message: string): boolean {\n const normalized = message.trim().toLowerCase();\n return (\n normalized === \"connection error.\" ||\n normalized.includes(\"cannot connect to api:\")\n );\n}\n\nfunction captureBuilderGatewayTransportError(\n err: unknown,\n context: {\n phase: \"request\" | \"stream\";\n model: string;\n gatewayUrl?: URL;\n timeoutMs: number;\n timedOut: boolean;\n elapsedMs?: number;\n },\n): void {\n captureError(err, {\n route: \"/_agent-native/agent-chat\",\n tags: {\n source: \"builder-engine\",\n phase: context.phase,\n model: context.model,\n timedOut: context.timedOut ? \"true\" : \"false\",\n errorCode: context.timedOut\n ? \"builder_gateway_timeout\"\n : BUILDER_GATEWAY_NETWORK_ERROR_CODE,\n },\n extra: {\n gatewayOrigin: context.gatewayUrl?.origin,\n gatewayPath: context.gatewayUrl?.pathname,\n timeoutMs: context.timeoutMs,\n elapsedMs: context.elapsedMs,\n },\n contexts: {\n builderGateway: {\n phase: context.phase,\n model: context.model,\n gatewayOrigin: context.gatewayUrl?.origin,\n gatewayPath: context.gatewayUrl?.pathname,\n timeoutMs: context.timeoutMs,\n timedOut: context.timedOut,\n elapsedMs: context.elapsedMs,\n },\n },\n });\n}\n\n/**\n * Capture a Builder-gateway no-detail stop event to Sentry with the request\n * context the run-manager doesn't have. The gateway emits\n * `{type:\"stop\",reason:\"error\",requestId:\"...\"}` with no diagnostic — the\n * only way to debug it is from the gateway side, so we surface model,\n * gatewayOrigin, and requestId as searchable tags.\n */\nfunction captureBuilderGatewayNoDetailError(context: {\n requestId?: string;\n model: string;\n gatewayUrl?: URL;\n rawEvent: unknown;\n}): void {\n const err = new Error(\n context.requestId\n ? `Builder gateway stop reason=error with no detail (requestId=${context.requestId})`\n : \"Builder gateway stop reason=error with no detail\",\n );\n err.name = \"BuilderGatewayNoDetailError\";\n captureError(err, {\n route: \"/_agent-native/agent-chat\",\n tags: {\n source: \"builder-engine\",\n phase: \"stream\",\n model: context.model,\n errorCode: \"builder_gateway_error\",\n ...(context.requestId ? { gatewayRequestId: context.requestId } : {}),\n },\n extra: {\n gatewayOrigin: context.gatewayUrl?.origin,\n gatewayPath: context.gatewayUrl?.pathname,\n rawEvent: context.rawEvent,\n },\n contexts: {\n builderGateway: {\n phase: \"stream\",\n model: context.model,\n gatewayOrigin: context.gatewayUrl?.origin,\n gatewayPath: context.gatewayUrl?.pathname,\n requestId: context.requestId,\n errorCode: \"builder_gateway_error\",\n },\n },\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"builder-engine.js","sourceRoot":"","sources":["../../../src/agent/engine/builder-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC7D,OAAO,EACL,iCAAiC,EACjC,yBAAyB,EACzB,wBAAwB,EACxB,kCAAkC,GACnC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,6BAA6B,EAAE,MAAM,uCAAuC,CAAC;AACtF,OAAO,EACL,mBAAmB,EACnB,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,6BAA6B,EAAE,MAAM,0BAA0B,CAAC;AACzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA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AAE,MAAM;YACzC,WAAW,EAAE,OAAO,CAAC,UAAU,EAAE,QAAQ;YACzC,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B;QACD,QAAQ,EAAE;YACR,cAAc,EAAE;gBACd,KAAK,EAAE,QAAQ;gBACf,KAAK,EAAE,OAAO,CAAC,KAAK;gBACpB,aAAa,EAAE,OAAO,CAAC,UAAU,EAAE,MAAM;gBACzC,WAAW,EAAE,OAAO,CAAC,UAAU,EAAE,QAAQ;gBACzC,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,SAAS,EAAE,uBAAuB;aACnC;SACF;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * BuilderEngine — HTTP client for the Builder.io managed LLM gateway.\n *\n * The gateway accepts an Anthropic-shaped request body and streams events as\n * JSONL. This engine translates the framework's EngineStreamOptions into the\n * gateway request, parses the streamed events into EngineEvent items, and\n * maps gateway error responses (402 quota, 403 disabled, 401 auth, 429\n * concurrency) into structured stop events that carry an upgrade URL when\n * the chat UI needs to prompt the user to upgrade.\n *\n * Credentials come from BUILDER_PRIVATE_KEY + BUILDER_PUBLIC_KEY (set via the\n * Builder CLI-auth onboarding flow). Base URL is overridable via\n * BUILDER_GATEWAY_BASE_URL.\n */\n\nimport { captureError } from \"../../server/capture-error.js\";\nimport {\n clearBuilderCredentialAuthFailure,\n resolveBuilderCredentials,\n getBuilderGatewayBaseUrl,\n recordBuilderCredentialAuthFailure,\n} from \"../../server/credential-provider.js\";\nimport { applyBuilderUtmTrackingParams } from \"../../shared/builder-link-tracking.js\";\nimport {\n isGPTReasoningModel,\n normalizeReasoningEffortForModel,\n type ReasoningEffort,\n} from \"../../shared/reasoning-effort.js\";\nimport { isInBackgroundFunctionRuntime } from \"../durable-background.js\";\nimport { BUILDER_MODEL_CONFIG } from \"../model-config.js\";\nimport { getBuilderGatewayRequestHeaders } from \"./builder-gateway-headers.js\";\nimport {\n LLM_MISSING_CREDENTIALS_ERROR_CODE,\n LLM_MISSING_CREDENTIALS_MESSAGE,\n} from \"./credential-errors.js\";\nimport {\n describeErrorWithCauses,\n isProviderConnectionErrorMessage,\n} from \"./error-detail.js\";\nimport { FIRST_STREAM_EVENT_TIMEOUT_MS } from \"./first-event-timeout.js\";\nimport { resolveMaxOutputTokensForEngine } from \"./output-tokens.js\";\nimport {\n splitSystemPromptForCache,\n stablePrefixCacheControl,\n} from \"./prompt-cache.js\";\nimport {\n createStreamedToolInputState,\n engineMessagesToBuilderGatewayAnthropic,\n engineToolsToAnthropic,\n finalizeStreamedToolInputs,\n observeStreamedToolInput,\n} from \"./translate-anthropic.js\";\nimport type {\n AgentEngine,\n EngineCapabilities,\n EngineContentPart,\n EngineEvent,\n EngineStreamOptions,\n} from \"./types.js\";\n\nexport const BUILDER_CAPABILITIES: EngineCapabilities = {\n thinking: true,\n promptCaching: true,\n vision: true,\n computerUse: false,\n parallelToolCalls: true,\n};\n\nexport const BUILDER_SUPPORTED_MODELS = BUILDER_MODEL_CONFIG.supportedModels;\n\n// Keep the foreground hosted gateway timeout below the synchronous serverless\n// wall so the agent loop can append a continuation and persist terminal state\n// before the host hard-kills the invocation.\nconst DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS = 45_000;\nconst MAX_HOSTED_FOREGROUND_BUILDER_GATEWAY_TIMEOUT_MS = 45_000;\n/**\n * Netlify background functions have a 15-minute wall. Keep the Builder gateway\n * ceiling below that, but above the run-manager's 13-minute soft-timeout so\n * durable background runs checkpoint before this timer wins.\n */\nconst MAX_BACKGROUND_BUILDER_GATEWAY_TIMEOUT_MS = 14 * 60_000;\n/** Local and non-hosted runtimes have no synchronous serverless wall. */\nconst MAX_LOCAL_BUILDER_GATEWAY_TIMEOUT_MS =\n MAX_BACKGROUND_BUILDER_GATEWAY_TIMEOUT_MS;\nconst BUILDER_GATEWAY_NETWORK_ERROR_CODE = \"builder_gateway_network_error\";\nexport const BUILDER_MODEL_UNAUTHORIZED_ERROR_CODE =\n \"builder_model_unauthorized\";\n\nexport const BUILDER_DEFAULT_MODEL = BUILDER_MODEL_CONFIG.defaultModel;\n\n/**\n * Bucket an Anthropic `thinking.budgetTokens` value into the gateway's\n * legacy three-level `reasoning_effort` enum.\n *\n * The thresholds are chosen to align with typical Anthropic extended-thinking\n * budgets we see in the wild:\n * • < 2000 → short one-step reasoning (\"low\")\n * • 2000–8000 → multi-step thinking (\"medium\")\n * • ≥ 8000 → deep planning / long chains (\"high\")\n *\n * 8000 is Anthropic's documented default in our framework (see\n * engine/types.ts:195), so callers that don't explicitly set\n * `budgetTokens` map to \"high\" via the default. If the gateway later\n * exposes more granular knobs or different thresholds, revisit this map.\n */\nfunction mapReasoningEffort(budgetTokens: number): ReasoningEffort {\n if (budgetTokens < 2000) return \"low\";\n if (budgetTokens < 8000) return \"medium\";\n return \"high\";\n}\n\n/**\n * Build the URL the chat UI should link to when a user hits a quota error.\n *\n * We can't deep-link to a per-org billing page from `BUILDER_ORG_NAME` because\n * that field is the org's display name (e.g. \"Nicholas kipchumba Space\"), not\n * a URL-safe slug or id. URL-encoding the display name produces segments like\n * `/app/organizations/Nicholas%20kipchumba%20Space/billing` which Builder's\n * router treats as unknown and silently bounces to `/app/projects`. The\n * Builder CLI-auth callback doesn't expose the org slug/id today, so we route\n * to the org-agnostic subscription page. Agent Native attribution lets Builder\n * skip generic onboarding for new users who land there from an upgrade CTA.\n */\nasync function buildUpgradeUrl(): Promise<string> {\n const url = new URL(\"https://builder.io/account/subscription\");\n url.searchParams.set(\"signupSource\", \"agent-native\");\n url.searchParams.set(\"agentNativeConnectSource\", \"gateway_quota_upgrade\");\n url.searchParams.set(\"agentNativeFlow\", \"connect_llm\");\n url.searchParams.set(\"framework\", \"agent-native\");\n applyBuilderUtmTrackingParams(url.searchParams, {\n content: \"gateway_quota_upgrade\",\n });\n return url.toString();\n}\n\ninterface GatewayErrorBody {\n code?: string;\n message?: string;\n usageInfo?: {\n plan?: string;\n limitExceeded?: string;\n isEnterprise?: boolean;\n };\n}\n\nclass BuilderEngine implements AgentEngine {\n readonly name = \"builder\";\n readonly label = \"Builder.io Gateway\";\n readonly defaultModel = BUILDER_DEFAULT_MODEL;\n readonly supportedModels = BUILDER_SUPPORTED_MODELS;\n readonly capabilities = BUILDER_CAPABILITIES;\n\n async *stream(opts: EngineStreamOptions): AsyncIterable<EngineEvent> {\n const creds = await resolveBuilderCredentials();\n const authHeader = creds.privateKey ? `Bearer ${creds.privateKey}` : null;\n const spaceId = creds.publicKey;\n const builderUserId = creds.userId;\n if (!authHeader || !spaceId) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: LLM_MISSING_CREDENTIALS_MESSAGE,\n errorCode: LLM_MISSING_CREDENTIALS_ERROR_CODE,\n };\n return;\n }\n\n const messages = engineMessagesToBuilderGatewayAnthropic(opts.messages);\n const tools = engineToolsToAnthropic(opts.tools);\n const thinkingBudget =\n opts.providerOptions?.anthropic?.thinking?.budgetTokens;\n const reasoningEffort = normalizeReasoningEffortForModel(\n opts.model,\n opts.reasoningEffort ??\n (typeof thinkingBudget === \"number\"\n ? mapReasoningEffort(thinkingBudget)\n : undefined),\n );\n\n // Apply prompt caching to system + tools (stable prefix) and to the last\n // user message (moving cache breakpoint so growing history gets cached\n // across tool-loop iterations at ~90% off input cost).\n // Templates can opt out by setting providerOptions.anthropic.cacheControl=false.\n const cacheEnabled =\n opts.providerOptions?.anthropic?.cacheControl !== false;\n\n // System: split into a stable block carrying the breakpoint and a volatile\n // tail (resources, app extras, model overlay, runtime context) without one,\n // so mid-turn resource churn no longer invalidates system + tools.\n const { stable, volatile } = splitSystemPromptForCache(\n opts.systemPrompt ?? \"\",\n );\n const systemValue: unknown = opts.systemPrompt\n ? cacheEnabled\n ? [\n {\n type: \"text\",\n text: stable,\n cache_control: stablePrefixCacheControl(),\n },\n ...(volatile ? [{ type: \"text\", text: volatile }] : []),\n ]\n : stable + volatile\n : undefined;\n\n // Tools: add cache_control to the last tool definition.\n let cachedTools = tools;\n if (cacheEnabled && tools.length > 0) {\n cachedTools = [...tools];\n const last = { ...cachedTools[cachedTools.length - 1] } as any;\n last.cache_control = stablePrefixCacheControl();\n cachedTools[cachedTools.length - 1] = last;\n }\n\n // Messages: add a moving cache breakpoint on the last user message's last\n // content block so the entire conversation prefix is cached. Stays on the\n // default 5m TTL — it moves every iteration, so a longer-lived entry would\n // only pay the higher write premium.\n let cachedMessages = messages;\n if (cacheEnabled && messages.length > 0) {\n let lastUserIdx = -1;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n if ((messages[i] as any).role === \"user\") {\n lastUserIdx = i;\n break;\n }\n }\n if (lastUserIdx >= 0) {\n cachedMessages = [...messages];\n const lastMsg = { ...cachedMessages[lastUserIdx] } as any;\n if (Array.isArray(lastMsg.content) && lastMsg.content.length > 0) {\n const content = [...lastMsg.content];\n const lastBlock = { ...content[content.length - 1] } as any;\n lastBlock.cache_control = { type: \"ephemeral\" };\n content[content.length - 1] = lastBlock;\n lastMsg.content = content;\n cachedMessages[lastUserIdx] = lastMsg;\n }\n }\n }\n\n const gptToolsRequireExplicitNoReasoning =\n cachedTools.length > 0 && isGPTReasoningModel(opts.model);\n const body: Record<string, unknown> = {\n model: opts.model,\n messages: cachedMessages,\n ...(systemValue !== undefined ? { system: systemValue } : {}),\n ...(cachedTools.length > 0 ? { tools: cachedTools } : {}),\n max_tokens: resolveMaxOutputTokensForEngine(\n this.name,\n opts.maxOutputTokens,\n opts.model,\n ),\n ...(typeof opts.temperature === \"number\"\n ? { temperature: opts.temperature }\n : {}),\n // OpenAI rejects `reasoning_effort` alongside function tools on Chat\n // Completions (\"Function tools with reasoning_effort are not supported\n // for <model> in /v1/chat/completions … or set reasoning_effort to\n // 'none'\"), and the gateway routes GPT models there. Every chat on a\n // gpt-5.x model failed deterministically because of this. Omitting the\n // field does NOT help — OpenAI then applies the model's own default\n // effort and rejects identically; only the explicit \"none\" clears it.\n // Same guard as the ai-sdk engine's forced-Chat-Completions path.\n ...(reasoningEffort || gptToolsRequireExplicitNoReasoning\n ? {\n reasoning_effort: gptToolsRequireExplicitNoReasoning\n ? \"none\"\n : reasoningEffort,\n }\n : {}),\n };\n\n const gatewayBaseUrl = getBuilderGatewayBaseUrl();\n const gatewayUrl = new URL(\n \"messages\",\n gatewayBaseUrl.endsWith(\"/\") ? gatewayBaseUrl : `${gatewayBaseUrl}/`,\n );\n gatewayUrl.searchParams.set(\"apiKey\", spaceId);\n const orgLabel = creds.orgName || \"unknown-org\";\n const tStart = Date.now();\n console.log(\n `[builder-engine] → POST ${gatewayUrl.origin}${gatewayUrl.pathname} model=${opts.model} tools=${tools.length} org=${orgLabel}`,\n );\n\n const gatewayTimeoutMs = getBuilderGatewayTimeoutMs();\n const gatewayAbort = createGatewayAbortSignal(\n opts.abortSignal,\n gatewayTimeoutMs,\n );\n try {\n let response: Response;\n try {\n response = await fetch(gatewayUrl.toString(), {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: authHeader,\n \"x-builder-api-key\": spaceId,\n ...getBuilderGatewayRequestHeaders(),\n ...(builderUserId ? { \"x-builder-user-id\": builderUserId } : {}),\n },\n body: JSON.stringify(body),\n signal: gatewayAbort.signal,\n });\n } catch (err) {\n const timedOut = gatewayAbort.didTimeout();\n if (gatewayAbort.didTimeout()) {\n console.warn(\n `[builder-engine] gateway timed out after ${Date.now() - tStart}ms`,\n );\n }\n if (timedOut || isBuilderGatewayNetworkError(err)) {\n captureBuilderGatewayTransportError(err, {\n phase: \"request\",\n model: opts.model,\n gatewayUrl,\n timeoutMs: gatewayAbort.effectiveTimeoutMs(),\n timedOut,\n elapsedMs: Date.now() - tStart,\n });\n }\n yield createBuilderGatewayTimeoutStop(\n err,\n timedOut,\n gatewayAbort.effectiveTimeoutMs(),\n );\n return;\n }\n\n console.log(\n `[builder-engine] ← ${response.status} ${response.statusText} in ${Date.now() - tStart}ms`,\n );\n\n if (!response.ok) {\n yield* emitHttpError(response);\n return;\n }\n\n // A successful gateway call proves the connected credentials are valid\n // again. Clear any prior auth-failure marker so status / chat-card\n // surfaces stop flagging the connection as broken. This is the only\n // self-healing path for workspace/env-managed credentials, which never\n // flow through writeBuilderCredentials.\n try {\n const creds = await resolveBuilderCredentials();\n await clearBuilderCredentialAuthFailure({\n privateKey: creds.privateKey,\n publicKey: creds.publicKey,\n });\n } catch {\n // Marker clearing is best-effort; a stale marker just means the user\n // sees \"reconnect Builder\" until the next successful call clears it.\n }\n\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"text/html\")) {\n const rawText = await response.text().catch(() => \"\");\n yield {\n type: \"stop\",\n reason: \"error\",\n error: normalizeGatewayErrorText(rawText, response.status || 502),\n errorCode: `http_${response.status || 502}`,\n };\n return;\n }\n\n const reader = response.body?.getReader();\n if (!reader) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: \"Builder gateway response has no body\",\n };\n return;\n }\n\n yield* parseJsonlStream(reader, opts.model, {\n abortSignal: gatewayAbort.signal,\n didGatewayTimeout: gatewayAbort.didTimeout,\n getGatewayTimeoutMs: gatewayAbort.effectiveTimeoutMs,\n onFirstEvent: gatewayAbort.markFirstEvent,\n gatewayUrl,\n requestStartedAt: tStart,\n });\n } finally {\n gatewayAbort.cleanup();\n }\n }\n}\n\nasync function* emitHttpError(response: Response): AsyncIterable<EngineEvent> {\n const status = response.status;\n // Read the body once as text and then try to parse — calling `.json()`\n // and then `.text()` as a fallback fails because the body stream is\n // already consumed (TypeError: Body has already been read), so we'd\n // silently lose non-JSON error payloads like HTML proxy 502s.\n let errBody: GatewayErrorBody = {};\n const rawText = await response.text().catch(() => \"\");\n if (rawText) {\n try {\n errBody = JSON.parse(rawText) as GatewayErrorBody;\n } catch {\n errBody.message = normalizeGatewayErrorText(rawText, status);\n }\n }\n const code = errBody.code ?? `http_${status}`;\n const message = errBody.message ?? `Builder gateway returned ${status}`;\n\n // Belt-and-suspenders: 402 without a structured `credits-limit` code\n // (e.g. bare proxy response) still means quota → show upgrade CTA.\n if (code.startsWith(\"credits-limit\") || status === 402) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n upgradeUrl: await buildUpgradeUrl(),\n };\n return;\n }\n if (code === \"gateway_not_enabled\") {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n };\n return;\n }\n if (status === 401 || code === \"unauthorized\") {\n await recordBuilderCredentialAuthFailure({ status, code, message });\n yield {\n type: \"stop\",\n reason: \"error\",\n error: \"Builder authentication failed. Reconnect Builder via Settings.\",\n errorCode: \"builder_auth_error\",\n };\n return;\n }\n if (status === 403 && isBuilderCredentialAuthError(message)) {\n await recordBuilderCredentialAuthFailure({ status, code, message });\n yield {\n type: \"stop\",\n reason: \"error\",\n error: \"Builder authentication failed. Reconnect Builder via Settings.\",\n errorCode: \"builder_auth_error\",\n };\n return;\n }\n if (status === 403) {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n };\n return;\n }\n if (code === \"rate_limit_exceeded\") {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n };\n return;\n }\n if (status === 429 || code === \"too_many_concurrent_requests\") {\n // Include \"too many requests\" in the message so production-agent's\n // isRetryableError picks up transient concurrency throttles and retries\n // the turn. Daily gateway caps use `rate_limit_exceeded` above and must\n // not loop.\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `${message} (too many requests)`,\n errorCode: code,\n };\n return;\n }\n yield {\n type: \"stop\",\n reason: \"error\",\n error: message,\n errorCode: code,\n };\n}\n\n// Yields one non-empty JSONL line at a time. Flushes any trailing content\n// after the stream ends so a final event without a newline terminator\n// isn't silently dropped — some gateway proxies close the connection on\n// a complete line and the client must still process it.\nasync function* readJsonlLines(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n abortSignal?: AbortSignal,\n): AsyncIterable<string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n while (true) {\n const { done, value } = await readStreamChunk(reader, abortSignal);\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let newlineIdx = buffer.indexOf(\"\\n\");\n while (newlineIdx !== -1) {\n const line = buffer.slice(0, newlineIdx).trim();\n buffer = buffer.slice(newlineIdx + 1);\n newlineIdx = buffer.indexOf(\"\\n\");\n if (line) yield line;\n }\n }\n // Flush any bytes the streaming decoder buffered for an incomplete multibyte\n // sequence at the end of the stream; otherwise a trailing multibyte char in\n // the final chunk is silently dropped from the last line.\n buffer += decoder.decode();\n const tail = buffer.trim();\n if (tail) yield tail;\n}\n\nasync function* parseJsonlStream(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n model: string,\n captureContext: {\n abortSignal?: AbortSignal;\n didGatewayTimeout?: () => boolean;\n getGatewayTimeoutMs?: () => number;\n onFirstEvent?: () => void;\n gatewayUrl?: URL;\n requestStartedAt?: number;\n } = {},\n): AsyncIterable<EngineEvent> {\n const parts: EngineContentPart[] = [];\n let pendingText = \"\";\n let pendingThinking: { text: string; signature?: string } | null = null;\n\n const flushPendingText = () => {\n if (pendingText) {\n parts.push({ type: \"text\", text: pendingText });\n pendingText = \"\";\n }\n };\n\n const flushPendingThinking = () => {\n if (pendingThinking) {\n parts.push({\n type: \"thinking\",\n text: pendingThinking.text,\n ...(pendingThinking.signature !== undefined\n ? { signature: pendingThinking.signature }\n : {}),\n });\n pendingThinking = null;\n }\n };\n\n const flushPending = () => {\n flushPendingText();\n flushPendingThinking();\n };\n\n const toolInputs = createStreamedToolInputState();\n\n // The gateway can announce a tool call through `tool-call-delta` frames and\n // then die before the terminal `tool-call` frame. Assemble what streamed, or\n // hand the model an in-band error — never end the turn advertising a call\n // that was silently dropped.\n const recoverUndeliveredToolCalls = (): EngineEvent[] => {\n const events = finalizeStreamedToolInputs(toolInputs);\n for (const event of events) {\n if (event.type === \"tool-call\") {\n parts.push({\n type: \"tool-call\",\n id: event.id,\n name: event.name,\n input: event.input,\n });\n }\n }\n return events;\n };\n\n try {\n for await (const line of readJsonlLines(\n reader,\n captureContext.abortSignal,\n )) {\n let event: any;\n try {\n event = JSON.parse(line);\n } catch {\n const normalized = normalizeGatewayErrorText(line, 502);\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `Builder gateway returned invalid JSONL: ${normalized.slice(\n 0,\n 240,\n )}`,\n errorCode: \"http_502\",\n };\n return;\n }\n\n // Heartbeats are transport-level keepalives, not proof the model is\n // producing output — every other parsed event counts as first progress.\n if (event?.type !== \"heartbeat\") {\n captureContext.onFirstEvent?.();\n }\n\n switch (event.type) {\n case \"text-delta\": {\n const text = event.text ?? \"\";\n flushPendingThinking();\n pendingText += text;\n yield { type: \"text-delta\", text };\n break;\n }\n\n case \"thinking-delta\":\n case \"reasoning-delta\": {\n const text = event.text ?? \"\";\n flushPendingText();\n if (!pendingThinking) pendingThinking = { text: \"\" };\n pendingThinking.text += text;\n if (event.signature) pendingThinking.signature = event.signature;\n yield {\n type: \"thinking-delta\",\n text,\n ...(event.signature ? { signature: event.signature } : {}),\n };\n break;\n }\n\n case \"tool-call-delta\": {\n const delta: EngineEvent = {\n type: \"tool-input-delta\",\n id: event.id,\n name: event.name,\n text:\n typeof event.argsTextDelta === \"string\"\n ? event.argsTextDelta\n : typeof event.delta === \"string\"\n ? event.delta\n : \"\",\n };\n observeStreamedToolInput(toolInputs, delta);\n yield delta;\n break;\n }\n\n case \"heartbeat\":\n yield { type: \"gateway-heartbeat\" };\n break;\n\n case \"tool-call\": {\n flushPending();\n const call = {\n type: \"tool-call\" as const,\n id: event.id,\n name: event.name,\n input: event.input,\n };\n parts.push(call);\n observeStreamedToolInput(toolInputs, call);\n yield { ...call };\n break;\n }\n\n case \"usage\": {\n const cacheWrite =\n (event.cacheCreatedTokens ?? 0) + (event.cacheCreated1hTokens ?? 0);\n yield {\n type: \"usage\",\n inputTokens: event.inputTokens ?? 0,\n outputTokens: event.outputTokens ?? 0,\n ...(event.cacheInputTokens !== undefined\n ? { cacheReadTokens: event.cacheInputTokens }\n : {}),\n ...(cacheWrite > 0 ? { cacheWriteTokens: cacheWrite } : {}),\n };\n break;\n }\n\n case \"stop\": {\n flushPending();\n yield* recoverUndeliveredToolCalls();\n yield { type: \"assistant-content\", parts };\n\n const reason = event.reason ?? \"end_turn\";\n if (reason === \"rate_limited\") {\n // Include \"rate_limit\" in the message so production-agent's\n // isRetryableError picks it up and retries.\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `rate_limit exceeded: ${event.error ?? \"upstream provider rate limited\"}`,\n errorCode: \"rate_limited\",\n };\n } else if (reason === \"invalid_request\") {\n // errorCode has no retry-trigger keywords, so isRetryableError\n // won't loop on broken history.\n const errMsg =\n event.error ||\n event.message ||\n \"Builder gateway rejected the request as malformed.\";\n const errCode =\n typeof event.errorCode === \"string\"\n ? event.errorCode\n : typeof event.code === \"string\"\n ? event.code\n : \"invalid_request\";\n console.warn(\n `[builder-engine] stop reason=invalid_request model=${model} code=${errCode} error=${errMsg}`,\n );\n yield {\n type: \"stop\",\n reason: \"error\",\n error: errMsg,\n errorCode: errCode,\n };\n } else if (reason === \"error\") {\n // Surface every diagnostic the gateway gave us so the user (and\n // our logs) get more than a bare \"Gateway error\". The gateway\n // sometimes emits an error stop event with no message — most\n // commonly when the upstream provider rejects the model for\n // this account (Opus quotas have hit this in practice).\n const explicitErrMsg = event.error || event.message || event.detail;\n const errMsg =\n explicitErrMsg ??\n `Gateway error (no detail; raw event: ${JSON.stringify(event)})`;\n const gatewayErrCode = event.errorCode ?? event.code;\n // The gateway already authenticated this request before streaming,\n // so a bare \"Unauthorized\" here means the account cannot use this\n // model — not that the connection is broken. Only a message that\n // names the credential may tear down the Builder connection.\n const isCredentialAuthError =\n Boolean(explicitErrMsg) &&\n isBuilderCredentialAuthErrorInStream(String(errMsg));\n const isModelAuthError =\n Boolean(explicitErrMsg) &&\n !isCredentialAuthError &&\n isBuilderCredentialAuthError(String(errMsg));\n // Providers can report a bare \"Connection error.\" or AI SDK's\n // retry-wrapped \"Cannot connect to API\" without a gateway code.\n // Tag both as network errors so retries can recover the turn.\n const isProviderConnectionError =\n typeof explicitErrMsg === \"string\" &&\n isProviderConnectionErrorMessage(String(explicitErrMsg));\n const errCode = isCredentialAuthError\n ? \"builder_auth_error\"\n : isModelAuthError\n ? BUILDER_MODEL_UNAUTHORIZED_ERROR_CODE\n : isProviderConnectionError\n ? BUILDER_GATEWAY_NETWORK_ERROR_CODE\n : (gatewayErrCode ??\n (!explicitErrMsg ? \"builder_gateway_error\" : undefined));\n console.error(\n `[builder-engine] stop reason=error model=${model} code=${errCode ?? \"(none)\"} error=${errMsg}`,\n );\n if (isCredentialAuthError) {\n await recordBuilderCredentialAuthFailure({\n code:\n typeof gatewayErrCode === \"string\" ? gatewayErrCode : errCode,\n message: String(errMsg),\n });\n }\n // No-detail gateway errors are opaque to the chat client — the\n // only way to debug them is from the gateway side. Capture rich\n // tags here (model, gatewayOrigin, requestId) so the gateway\n // team can search Sentry by requestId or filter by model. The\n // downstream run-manager will also capture the EngineError once\n // it's thrown, but without these tags.\n if (!explicitErrMsg) {\n captureBuilderGatewayNoDetailError({\n requestId:\n typeof event.requestId === \"string\"\n ? event.requestId\n : undefined,\n model,\n gatewayUrl: captureContext.gatewayUrl,\n rawEvent: event,\n });\n }\n yield {\n type: \"stop\",\n reason: \"error\",\n error: errMsg,\n ...(errCode ? { errorCode: errCode } : {}),\n };\n } else if (\n reason === \"end_turn\" ||\n reason === \"tool_use\" ||\n reason === \"max_tokens\" ||\n reason === \"stop_sequence\"\n ) {\n yield { type: \"stop\", reason };\n } else {\n yield {\n type: \"stop\",\n reason: \"error\",\n error: `Unknown stop reason: ${reason}`,\n };\n }\n return;\n }\n\n default:\n // Unknown event type — ignore for forward compat.\n break;\n }\n }\n\n // Stream ended without a stop event — synthesize one so callers don't hang.\n flushPending();\n yield* recoverUndeliveredToolCalls();\n yield { type: \"assistant-content\", parts };\n yield {\n type: \"stop\",\n reason: \"error\",\n error: \"Builder gateway stream ended without a stop event\",\n };\n } catch (err) {\n const timedOut = captureContext.didGatewayTimeout?.() ?? false;\n const gatewayTimeoutMs =\n captureContext.getGatewayTimeoutMs?.() ??\n DEFAULT_BUILDER_GATEWAY_TIMEOUT_MS;\n if (timedOut || isBuilderGatewayNetworkError(err)) {\n captureBuilderGatewayTransportError(err, {\n phase: \"stream\",\n model,\n gatewayUrl: captureContext.gatewayUrl,\n timeoutMs: gatewayTimeoutMs,\n timedOut,\n elapsedMs:\n typeof captureContext.requestStartedAt === \"number\"\n ? Date.now() - captureContext.requestStartedAt\n : undefined,\n });\n }\n yield createBuilderGatewayTimeoutStop(err, timedOut, gatewayTimeoutMs);\n } finally {\n // Release the reader on every exit path — early returns (invalid JSONL,\n // stop event) and generator abandonment both leave the underlying\n // Response body locked otherwise. cancel() also closes the socket.\n try {\n await reader.cancel();\n } catch {\n // Already cancelled or closed\n }\n }\n}\n\nfunction readStreamChunk(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n abortSignal?: AbortSignal,\n): Promise<ReadableStreamReadResult<Uint8Array>> {\n if (!abortSignal) return reader.read();\n if (abortSignal.aborted) {\n return Promise.reject(abortSignal.reason ?? new Error(\"Stream aborted\"));\n }\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n reject(abortSignal.reason ?? new Error(\"Stream aborted\"));\n };\n abortSignal.addEventListener(\"abort\", onAbort, { once: true });\n reader.read().then(\n (value) => {\n abortSignal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (err) => {\n abortSignal.removeEventListener(\"abort\", onAbort);\n reject(err);\n },\n );\n });\n}\n\nfunction normalizeGatewayErrorText(raw: string, status: number): string {\n const text = raw.trim();\n const looksHtml = /<html[\\s>]|<body[\\s>]|<head[\\s>]/i.test(text);\n const readable = looksHtml ? htmlToText(text) : text;\n if (/inactivity timeout/i.test(readable)) {\n return `Builder gateway returned ${status}: Inactivity Timeout. The upstream connection was idle too long before sending data.`;\n }\n if (looksHtml) {\n return `Builder gateway returned ${status}: ${readable.slice(0, 240)}`;\n }\n return readable;\n}\n\nfunction htmlToText(html: string): string {\n return html\n .replace(/<script[\\s\\S]*?<\\/script>/gi, \" \")\n .replace(/<style[\\s\\S]*?<\\/style>/gi, \" \")\n .replace(/<br\\s*\\/?>/gi, \"\\n\")\n .replace(/<\\/(p|div|h1|h2|h3|li|tr)>/gi, \"\\n\")\n .replace(/<[^>]+>/g, \" \")\n .replace(/ /gi, \" \")\n .replace(/</gi, \"<\")\n .replace(/>/gi, \">\")\n .replace(/&/gi, \"&\")\n .replace(/"/gi, '\"')\n .replace(/'/gi, \"'\")\n .replace(/[ \\t]+/g, \" \")\n .replace(/\\n\\s+/g, \"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\nexport function createBuilderEngine(\n _config: Record<string, unknown> = {},\n): AgentEngine {\n return new BuilderEngine();\n}\n\nfunction resolveMaxBuilderGatewayTimeoutMs(): number {\n if (isInBackgroundFunctionRuntime()) {\n return MAX_BACKGROUND_BUILDER_GATEWAY_TIMEOUT_MS;\n }\n\n if (!isHostedBuilderRuntime()) {\n return MAX_LOCAL_BUILDER_GATEWAY_TIMEOUT_MS;\n }\n\n try {\n const base = getBuilderGatewayBaseUrl();\n if (/^https?:\\/\\/(localhost|127\\.0\\.0\\.1)([:/]|$)/i.test(base)) {\n return MAX_LOCAL_BUILDER_GATEWAY_TIMEOUT_MS;\n }\n } catch {\n // ignore malformed override\n }\n return MAX_HOSTED_FOREGROUND_BUILDER_GATEWAY_TIMEOUT_MS;\n}\n\nfunction isHostedBuilderRuntime(): 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\nfunction getBuilderGatewayTimeoutMs(): number {\n const raw = process.env.AGENT_NATIVE_BUILDER_GATEWAY_TIMEOUT_MS;\n const maxMs = resolveMaxBuilderGatewayTimeoutMs();\n if (!raw) return maxMs;\n const parsed = Number(raw);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n return maxMs;\n }\n return Math.min(parsed, maxMs);\n}\n\n/**\n * Two-stage abort deadline: until the first real stream event arrives, the\n * effective deadline is min(totalTimeoutMs, FIRST_STREAM_EVENT_TIMEOUT_MS) —\n * a wedged gateway that never streams anything gets cut off in ~2 minutes\n * instead of riding the full flat timeout. Once `markFirstEvent()` fires, the\n * timer reschedules for whatever remains of the original total deadline, so\n * a request that starts streaming still gets the full budget it always did.\n */\nfunction createGatewayAbortSignal(\n parentSignal: AbortSignal,\n totalTimeoutMs: number,\n): {\n signal: AbortSignal;\n didTimeout: () => boolean;\n effectiveTimeoutMs: () => number;\n markFirstEvent: () => void;\n cleanup: () => void;\n} {\n const controller = new AbortController();\n let timedOut = false;\n let firstEventSeen = false;\n const startedAt = Date.now();\n\n const abortFromParent = () => {\n if (!controller.signal.aborted) {\n controller.abort(parentSignal.reason);\n }\n };\n\n const fireTimeout = () => {\n timedOut = true;\n if (!controller.signal.aborted) {\n controller.abort(new Error(\"Builder gateway request timed out\"));\n }\n };\n\n const firstEventDeadlineMs = Math.min(\n totalTimeoutMs,\n FIRST_STREAM_EVENT_TIMEOUT_MS,\n );\n let timeout = setTimeout(fireTimeout, firstEventDeadlineMs);\n\n if (parentSignal.aborted) abortFromParent();\n parentSignal.addEventListener(\"abort\", abortFromParent, { once: true });\n\n return {\n signal: controller.signal,\n didTimeout: () => timedOut,\n effectiveTimeoutMs: () =>\n firstEventSeen ? totalTimeoutMs : firstEventDeadlineMs,\n markFirstEvent: () => {\n if (firstEventSeen || timedOut) return;\n firstEventSeen = true;\n // The first-event window was already the binding constraint (total\n // timeout <= it) — nothing to reschedule.\n if (firstEventDeadlineMs >= totalTimeoutMs) return;\n clearTimeout(timeout);\n const remainingMs = Math.max(\n 0,\n totalTimeoutMs - (Date.now() - startedAt),\n );\n timeout = setTimeout(fireTimeout, remainingMs);\n },\n cleanup: () => {\n clearTimeout(timeout);\n parentSignal.removeEventListener(\"abort\", abortFromParent);\n },\n };\n}\n\nfunction isBuilderCredentialAuthError(message: string): boolean {\n const lowerMessage = message.toLowerCase();\n const referencesAccessToken =\n lowerMessage.includes(\"personal access token\") ||\n lowerMessage.includes(\"access token\");\n const rejectedToken =\n lowerMessage.includes(\"invalid\") ||\n lowerMessage.includes(\"inactive\") ||\n lowerMessage.includes(\"expired\") ||\n lowerMessage.includes(\"revoked\");\n return (\n lowerMessage.includes(\"unauthorized\") ||\n lowerMessage.includes(\"private key\") ||\n lowerMessage.includes(\"invalid token\") ||\n lowerMessage.includes(\"invalid_token\") ||\n lowerMessage.includes(\"token invalid\") ||\n (referencesAccessToken && rejectedToken)\n );\n}\n\n/**\n * Stricter than {@link isBuilderCredentialAuthError} for errors that arrive\n * inside an already-authenticated stream, where a bare \"unauthorized\" is far\n * more likely to be a per-model entitlement rejection than a bad credential.\n * Misreading one there disconnects Builder for every model, including the ones\n * that still work.\n */\nfunction isBuilderCredentialAuthErrorInStream(message: string): boolean {\n if (!isBuilderCredentialAuthError(message)) return false;\n const lowerMessage = message.toLowerCase();\n return (\n lowerMessage.includes(\"private key\") ||\n lowerMessage.includes(\"access token\") ||\n lowerMessage.includes(\"invalid token\") ||\n lowerMessage.includes(\"invalid_token\") ||\n lowerMessage.includes(\"token invalid\")\n );\n}\n\nfunction normalizeBuilderGatewayFetchError(\n err: unknown,\n timedOut: boolean,\n timeoutMs: number,\n): string {\n if (timedOut) {\n return `Builder gateway timed out after ${formatTimeoutMs(\n timeoutMs,\n )} before the hosting function limit. Please retry; if this keeps happening, reduce the prompt size or try again when the gateway is less busy.`;\n }\n const message = errorMessage(err);\n if (isBuilderGatewayNetworkError(err)) {\n return `Builder gateway network error: ${message}`;\n }\n return message;\n}\n\nfunction createBuilderGatewayTimeoutStop(\n err: unknown,\n timedOut: boolean,\n timeoutMs: number,\n): EngineEvent {\n const networkError = !timedOut && isBuilderGatewayNetworkError(err);\n return {\n type: \"stop\",\n reason: \"error\",\n error: normalizeBuilderGatewayFetchError(err, timedOut, timeoutMs),\n ...(timedOut\n ? { errorCode: \"builder_gateway_timeout\" }\n : networkError\n ? { errorCode: BUILDER_GATEWAY_NETWORK_ERROR_CODE }\n : {}),\n };\n}\n\nfunction formatTimeoutMs(timeoutMs: number): string {\n if (timeoutMs < 1000) return `${timeoutMs}ms`;\n return `${Math.round(timeoutMs / 1000)}s`;\n}\n\nfunction errorMessage(err: unknown): string {\n return describeErrorWithCauses(err);\n}\n\nfunction errorSearchText(err: unknown): string {\n const parts: string[] = [];\n if (err instanceof Error) {\n parts.push(err.name, err.message);\n const maybe = err as Error & {\n code?: unknown;\n cause?: unknown;\n };\n if (typeof maybe.code === \"string\") parts.push(maybe.code);\n if (maybe.cause) parts.push(errorSearchText(maybe.cause));\n } else {\n parts.push(String(err));\n }\n return parts.join(\" \").toLowerCase();\n}\n\nfunction isBuilderGatewayNetworkError(err: unknown): boolean {\n const text = errorSearchText(err);\n return (\n text.includes(\"socket hang up\") ||\n text.includes(\"econnreset\") ||\n text.includes(\"enetreset\") ||\n text.includes(\"econnaborted\") ||\n text.includes(\"fetch failed\") ||\n text.includes(\"network error\") ||\n // Anthropic SDK's APIConnectionError default (\"Connection error.\") is\n // often forwarded by the Builder gateway as a stop event with no code.\n text.includes(\"connection error\") ||\n text.includes(\"connection reset\") ||\n text.includes(\"connection closed\") ||\n text.includes(\"stream closed\") ||\n text.includes(\"terminated\")\n );\n}\n\nfunction captureBuilderGatewayTransportError(\n err: unknown,\n context: {\n phase: \"request\" | \"stream\";\n model: string;\n gatewayUrl?: URL;\n timeoutMs: number;\n timedOut: boolean;\n elapsedMs?: number;\n },\n): void {\n captureError(err, {\n route: \"/_agent-native/agent-chat\",\n tags: {\n source: \"builder-engine\",\n phase: context.phase,\n model: context.model,\n timedOut: context.timedOut ? \"true\" : \"false\",\n errorCode: context.timedOut\n ? \"builder_gateway_timeout\"\n : BUILDER_GATEWAY_NETWORK_ERROR_CODE,\n },\n extra: {\n gatewayOrigin: context.gatewayUrl?.origin,\n gatewayPath: context.gatewayUrl?.pathname,\n timeoutMs: context.timeoutMs,\n elapsedMs: context.elapsedMs,\n },\n contexts: {\n builderGateway: {\n phase: context.phase,\n model: context.model,\n gatewayOrigin: context.gatewayUrl?.origin,\n gatewayPath: context.gatewayUrl?.pathname,\n timeoutMs: context.timeoutMs,\n timedOut: context.timedOut,\n elapsedMs: context.elapsedMs,\n },\n },\n });\n}\n\n/**\n * Capture a Builder-gateway no-detail stop event to Sentry with the request\n * context the run-manager doesn't have. The gateway emits\n * `{type:\"stop\",reason:\"error\",requestId:\"...\"}` with no diagnostic — the\n * only way to debug it is from the gateway side, so we surface model,\n * gatewayOrigin, and requestId as searchable tags.\n */\nfunction captureBuilderGatewayNoDetailError(context: {\n requestId?: string;\n model: string;\n gatewayUrl?: URL;\n rawEvent: unknown;\n}): void {\n const err = new Error(\n context.requestId\n ? `Builder gateway stop reason=error with no detail (requestId=${context.requestId})`\n : \"Builder gateway stop reason=error with no detail\",\n );\n err.name = \"BuilderGatewayNoDetailError\";\n captureError(err, {\n route: \"/_agent-native/agent-chat\",\n tags: {\n source: \"builder-engine\",\n phase: \"stream\",\n model: context.model,\n errorCode: \"builder_gateway_error\",\n ...(context.requestId ? { gatewayRequestId: context.requestId } : {}),\n },\n extra: {\n gatewayOrigin: context.gatewayUrl?.origin,\n gatewayPath: context.gatewayUrl?.pathname,\n rawEvent: context.rawEvent,\n },\n contexts: {\n builderGateway: {\n phase: \"stream\",\n model: context.model,\n gatewayOrigin: context.gatewayUrl?.origin,\n gatewayPath: context.gatewayUrl?.pathname,\n requestId: context.requestId,\n errorCode: \"builder_gateway_error\",\n },\n },\n });\n}\n"]}
|
|
@@ -1,2 +1,63 @@
|
|
|
1
1
|
export declare function describeErrorWithCauses(err: unknown, maxLinks?: number): string;
|
|
2
|
+
/**
|
|
3
|
+
* The single provider-transport-failure classifier. Every layer that decides
|
|
4
|
+
* "is this a network blip?" — engine error codes, run-level retry, Sentry
|
|
5
|
+
* suppression — must call THIS, on `describeErrorWithCauses(err)` rather than
|
|
6
|
+
* on a bare `err.message`.
|
|
7
|
+
*
|
|
8
|
+
* Four divergent copies of this predicate existed, and they disagreed on
|
|
9
|
+
* exactly the string production actually throws. The AI SDK's `RetryError`
|
|
10
|
+
* reports `"Failed after 2 attempts. Last error: Cannot connect to API: …"`,
|
|
11
|
+
* so a copy anchored with `startsWith` scored it as unclassified while a copy
|
|
12
|
+
* using `includes` scored it as retryable. The result was a split brain: the
|
|
13
|
+
* agent loop retried the turn, but the run persisted `error_code = 'unknown'`,
|
|
14
|
+
* which the client does not list as auto-recoverable — so a transient TLS
|
|
15
|
+
* reset ended the user's chat with a dead error instead of resuming. That one
|
|
16
|
+
* mismatch accounted for ~150 failed production runs in a week.
|
|
17
|
+
*
|
|
18
|
+
* Substring matching is deliberate: the real message is always a provider SDK
|
|
19
|
+
* wrapper around the transport error, never bare, and the wrapper prefix
|
|
20
|
+
* differs per SDK and per version.
|
|
21
|
+
*/
|
|
22
|
+
export declare function isProviderConnectionErrorMessage(message: string): boolean;
|
|
23
|
+
/** `isProviderConnectionErrorMessage` over an error's full cause chain. */
|
|
24
|
+
export declare function isProviderConnectionError(err: unknown): boolean;
|
|
25
|
+
/** Classification fields an AI SDK provider failure carries. */
|
|
26
|
+
export interface ProviderErrorClassification {
|
|
27
|
+
errorCode?: string;
|
|
28
|
+
statusCode?: number;
|
|
29
|
+
providerRetryable?: boolean;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Classify a provider error from the AI SDK, whichever way it surfaced.
|
|
33
|
+
*
|
|
34
|
+
* `streamText` does not throw for a failed provider request — it emits an
|
|
35
|
+
* `error` part on `fullStream` — so there are two arrival paths, and only the
|
|
36
|
+
* thrown one used to be classified. The stream-part path discarded
|
|
37
|
+
* `statusCode`, `errorCode`, and `isRetryable` entirely, which is why every
|
|
38
|
+
* provider HTTP failure on an ai-sdk engine landed as `unknown`: a 429 was only
|
|
39
|
+
* retried if its prose happened to contain "rate_limit", and a
|
|
40
|
+
* 100%-reproducible config 400 was indistinguishable from any other unclassified
|
|
41
|
+
* failure, so it had no signature to alert on. Both call sites go through here.
|
|
42
|
+
*
|
|
43
|
+
* `timedOut` is the caller's own first-event deadline, which only the streaming
|
|
44
|
+
* path can know.
|
|
45
|
+
*/
|
|
46
|
+
export declare function classifyProviderError(err: unknown, timedOut?: boolean): ProviderErrorClassification;
|
|
47
|
+
/**
|
|
48
|
+
* Last-resort error code for a terminal error that reached persistence with no
|
|
49
|
+
* structured code. Persisting `"unknown"` is not a neutral default: the client
|
|
50
|
+
* auto-recovers a fixed list of transport codes, so an unclassified transient
|
|
51
|
+
* blip ends the user's chat while the identical failure carrying its real code
|
|
52
|
+
* resumes. Over four days that gap was 28% of ALL production chat turns.
|
|
53
|
+
*
|
|
54
|
+
* The invariant is NOT "only transport failures may be named". It is: a code
|
|
55
|
+
* returned here must be absent from the client's recoverable list unless a
|
|
56
|
+
* fresh attempt genuinely helps. Naming a deterministic failure is what stops
|
|
57
|
+
* it from reaching the user as raw provider text and hiding inside `unknown`;
|
|
58
|
+
* naming it *recoverable* is what buys a retry spiral. Those are different
|
|
59
|
+
* decisions, and `error-detail.spec.ts` asserts the deterministic codes below
|
|
60
|
+
* stay non-recoverable.
|
|
61
|
+
*/
|
|
62
|
+
export declare function classifyTerminalErrorCode(message: string | undefined): string | undefined;
|
|
2
63
|
//# sourceMappingURL=error-detail.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-detail.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/error-detail.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"error-detail.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/error-detail.ts"],"names":[],"mappings":"AAcA,wBAAgB,uBAAuB,CACrC,GAAG,EAAE,OAAO,EACZ,QAAQ,GAAE,MAAgC,GACzC,MAAM,CAkBR;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,gCAAgC,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAMzE;AAED,2EAA2E;AAC3E,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAE/D;AAED,gEAAgE;AAChE,MAAM,WAAW,2BAA2B;IAC1C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,qBAAqB,CACnC,GAAG,EAAE,OAAO,EACZ,QAAQ,UAAQ,GACf,2BAA2B,CAuD7B;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,MAAM,GAAG,SAAS,GAC1B,MAAM,GAAG,SAAS,CAkDpB"}
|
|
@@ -8,9 +8,6 @@
|
|
|
8
8
|
* `.cause`. Recording `err.message` alone makes every one of them
|
|
9
9
|
* indistinguishable after the fact, which is how a whole class of production
|
|
10
10
|
* failures becomes undiagnosable.
|
|
11
|
-
*
|
|
12
|
-
* Classification (`isConnectionError`, `isRetryableError`) must keep matching
|
|
13
|
-
* on the bare `err.message` — this is for the RECORDED detail only.
|
|
14
11
|
*/
|
|
15
12
|
const DEFAULT_MAX_CAUSE_LINKS = 4;
|
|
16
13
|
const MAX_CAUSE_LINK_CHARS = 200;
|
|
@@ -34,4 +31,149 @@ export function describeErrorWithCauses(err, maxLinks = DEFAULT_MAX_CAUSE_LINKS)
|
|
|
34
31
|
}
|
|
35
32
|
return links.length > 0 ? `${head} (cause: ${links.join(" <- ")})` : head;
|
|
36
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* The single provider-transport-failure classifier. Every layer that decides
|
|
36
|
+
* "is this a network blip?" — engine error codes, run-level retry, Sentry
|
|
37
|
+
* suppression — must call THIS, on `describeErrorWithCauses(err)` rather than
|
|
38
|
+
* on a bare `err.message`.
|
|
39
|
+
*
|
|
40
|
+
* Four divergent copies of this predicate existed, and they disagreed on
|
|
41
|
+
* exactly the string production actually throws. The AI SDK's `RetryError`
|
|
42
|
+
* reports `"Failed after 2 attempts. Last error: Cannot connect to API: …"`,
|
|
43
|
+
* so a copy anchored with `startsWith` scored it as unclassified while a copy
|
|
44
|
+
* using `includes` scored it as retryable. The result was a split brain: the
|
|
45
|
+
* agent loop retried the turn, but the run persisted `error_code = 'unknown'`,
|
|
46
|
+
* which the client does not list as auto-recoverable — so a transient TLS
|
|
47
|
+
* reset ended the user's chat with a dead error instead of resuming. That one
|
|
48
|
+
* mismatch accounted for ~150 failed production runs in a week.
|
|
49
|
+
*
|
|
50
|
+
* Substring matching is deliberate: the real message is always a provider SDK
|
|
51
|
+
* wrapper around the transport error, never bare, and the wrapper prefix
|
|
52
|
+
* differs per SDK and per version.
|
|
53
|
+
*/
|
|
54
|
+
export function isProviderConnectionErrorMessage(message) {
|
|
55
|
+
const normalized = message.toLowerCase();
|
|
56
|
+
return (normalized.includes("connection error") ||
|
|
57
|
+
normalized.includes("cannot connect to api"));
|
|
58
|
+
}
|
|
59
|
+
/** `isProviderConnectionErrorMessage` over an error's full cause chain. */
|
|
60
|
+
export function isProviderConnectionError(err) {
|
|
61
|
+
return isProviderConnectionErrorMessage(describeErrorWithCauses(err));
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Classify a provider error from the AI SDK, whichever way it surfaced.
|
|
65
|
+
*
|
|
66
|
+
* `streamText` does not throw for a failed provider request — it emits an
|
|
67
|
+
* `error` part on `fullStream` — so there are two arrival paths, and only the
|
|
68
|
+
* thrown one used to be classified. The stream-part path discarded
|
|
69
|
+
* `statusCode`, `errorCode`, and `isRetryable` entirely, which is why every
|
|
70
|
+
* provider HTTP failure on an ai-sdk engine landed as `unknown`: a 429 was only
|
|
71
|
+
* retried if its prose happened to contain "rate_limit", and a
|
|
72
|
+
* 100%-reproducible config 400 was indistinguishable from any other unclassified
|
|
73
|
+
* failure, so it had no signature to alert on. Both call sites go through here.
|
|
74
|
+
*
|
|
75
|
+
* `timedOut` is the caller's own first-event deadline, which only the streaming
|
|
76
|
+
* path can know.
|
|
77
|
+
*/
|
|
78
|
+
export function classifyProviderError(err, timedOut = false) {
|
|
79
|
+
// The AI SDK wraps exhausted retries in RetryError and keeps the final
|
|
80
|
+
// APICallError on `lastError`.
|
|
81
|
+
const wrapped = err;
|
|
82
|
+
const providerError = (wrapped?.lastError instanceof Error ? wrapped.lastError : err);
|
|
83
|
+
const statusCode = typeof providerError?.statusCode === "number"
|
|
84
|
+
? providerError.statusCode
|
|
85
|
+
: undefined;
|
|
86
|
+
// Classify on the cause chain of the ORIGINAL error, not the unwrapped one:
|
|
87
|
+
// when RetryError does not expose `lastError` as an Error the unwrap falls
|
|
88
|
+
// back to the wrapper, whose message ("Failed after 2 attempts. Last error:
|
|
89
|
+
// …") only *embeds* the transport failure. Matching the wrapper is the point.
|
|
90
|
+
const described = describeErrorWithCauses(err);
|
|
91
|
+
const isConnectionError = !timedOut &&
|
|
92
|
+
statusCode === undefined &&
|
|
93
|
+
(isProviderConnectionErrorMessage(described) ||
|
|
94
|
+
isProviderConnectionErrorMessage(typeof providerError?.message === "string"
|
|
95
|
+
? providerError.message
|
|
96
|
+
: String(providerError)));
|
|
97
|
+
const providerRetryable = typeof providerError?.isRetryable === "boolean"
|
|
98
|
+
? providerError.isRetryable
|
|
99
|
+
: isConnectionError || timedOut
|
|
100
|
+
? true
|
|
101
|
+
: undefined;
|
|
102
|
+
return {
|
|
103
|
+
// Tag every known status as `http_<status>` (not just 401) so a rate limit
|
|
104
|
+
// surfaces as `http_429`: the structured statusCode drives turn-level
|
|
105
|
+
// retries, but run-level continuation keys off the errorCode.
|
|
106
|
+
...(statusCode !== undefined
|
|
107
|
+
? { errorCode: `http_${statusCode}`, statusCode }
|
|
108
|
+
: isConnectionError || timedOut
|
|
109
|
+
? { errorCode: "provider_network_error" }
|
|
110
|
+
: // Nothing structured — fall back to reading the message, so a
|
|
111
|
+
// stream-part 529/timeout is not silently unclassified.
|
|
112
|
+
(() => {
|
|
113
|
+
const code = classifyTerminalErrorCode(described);
|
|
114
|
+
return code ? { errorCode: code } : {};
|
|
115
|
+
})()),
|
|
116
|
+
...(providerRetryable !== undefined ? { providerRetryable } : {}),
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Last-resort error code for a terminal error that reached persistence with no
|
|
121
|
+
* structured code. Persisting `"unknown"` is not a neutral default: the client
|
|
122
|
+
* auto-recovers a fixed list of transport codes, so an unclassified transient
|
|
123
|
+
* blip ends the user's chat while the identical failure carrying its real code
|
|
124
|
+
* resumes. Over four days that gap was 28% of ALL production chat turns.
|
|
125
|
+
*
|
|
126
|
+
* The invariant is NOT "only transport failures may be named". It is: a code
|
|
127
|
+
* returned here must be absent from the client's recoverable list unless a
|
|
128
|
+
* fresh attempt genuinely helps. Naming a deterministic failure is what stops
|
|
129
|
+
* it from reaching the user as raw provider text and hiding inside `unknown`;
|
|
130
|
+
* naming it *recoverable* is what buys a retry spiral. Those are different
|
|
131
|
+
* decisions, and `error-detail.spec.ts` asserts the deterministic codes below
|
|
132
|
+
* stay non-recoverable.
|
|
133
|
+
*/
|
|
134
|
+
export function classifyTerminalErrorCode(message) {
|
|
135
|
+
if (!message)
|
|
136
|
+
return undefined;
|
|
137
|
+
const msg = message.toLowerCase();
|
|
138
|
+
if (isProviderConnectionErrorMessage(msg))
|
|
139
|
+
return "provider_network_error";
|
|
140
|
+
// Word-bounded: request ids and hashes routinely contain a bare "529".
|
|
141
|
+
if (msg.includes("overloaded") || /\b529\b/.test(msg)) {
|
|
142
|
+
return "overloaded_error";
|
|
143
|
+
}
|
|
144
|
+
if (msg.includes("too many requests") || /\b429\b/.test(msg)) {
|
|
145
|
+
return "http_429";
|
|
146
|
+
}
|
|
147
|
+
if (msg.includes("timed out") ||
|
|
148
|
+
msg.includes("timeout") ||
|
|
149
|
+
msg.includes("too much time has passed without sending any data")) {
|
|
150
|
+
return "timeout";
|
|
151
|
+
}
|
|
152
|
+
if (msg.includes("stream ended without a stop event")) {
|
|
153
|
+
return "builder_gateway_network_error";
|
|
154
|
+
}
|
|
155
|
+
// Deterministic below this line — named so they stop landing in `unknown`,
|
|
156
|
+
// never retried. Both were measured against the 13 prod app DBs over
|
|
157
|
+
// 2026-07-24..31: 27 turns/week and 14 turns/week respectively, each with
|
|
158
|
+
// exactly 1.00 runs/turn, i.e. the chat died on the first attempt showing
|
|
159
|
+
// the raw provider sentence.
|
|
160
|
+
//
|
|
161
|
+
// The request side already avoids emitting reasoning_effort alongside tools
|
|
162
|
+
// (see ai-sdk-engine.ts). This classifies the failure for the paths that
|
|
163
|
+
// still reach the provider — another gateway, a stale deploy — so it reads
|
|
164
|
+
// as a configuration problem rather than a mystery.
|
|
165
|
+
if (msg.includes("reasoning_effort are not supported") ||
|
|
166
|
+
msg.includes("reasoning_effort to 'none'") ||
|
|
167
|
+
(msg.includes("reasoning_effort") &&
|
|
168
|
+
(msg.includes("tools") || msg.includes("function")))) {
|
|
169
|
+
return "provider_config_error";
|
|
170
|
+
}
|
|
171
|
+
if (msg.includes("missing authentication header") || msg === "unauthorized") {
|
|
172
|
+
return "authentication_error";
|
|
173
|
+
}
|
|
174
|
+
if (/(?:err_)?ssl|tlsv?\d|tls handshake|ssl routines|econnreset|econnrefused|und_err_socket|socket hang up/i.test(message)) {
|
|
175
|
+
return "provider_network_error";
|
|
176
|
+
}
|
|
177
|
+
return undefined;
|
|
178
|
+
}
|
|
37
179
|
//# sourceMappingURL=error-detail.js.map
|