@agent-native/core 0.75.5 → 0.76.1
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 +48 -0
- package/corpus/core/docs/AGENTS.md +1 -0
- package/corpus/core/docs/content/client.md +15 -0
- package/corpus/core/docs/content/internationalization.md +145 -0
- package/corpus/core/docs/content/locales/ar-SA/internationalization.md +102 -0
- package/corpus/core/docs/content/locales/de-DE/internationalization.md +102 -0
- package/corpus/core/docs/content/locales/es-ES/internationalization.md +102 -0
- package/corpus/core/docs/content/locales/fr-FR/internationalization.md +102 -0
- package/corpus/core/docs/content/locales/hi-IN/internationalization.md +102 -0
- package/corpus/core/docs/content/locales/ja-JP/internationalization.md +114 -0
- package/corpus/core/docs/content/locales/ko-KR/internationalization.md +102 -0
- package/corpus/core/docs/content/locales/pt-BR/internationalization.md +102 -0
- package/corpus/core/docs/content/locales/zh-CN/internationalization.md +102 -0
- package/corpus/core/docs/content/skills-guide.md +19 -18
- package/corpus/core/package.json +7 -1
- package/corpus/core/src/agent/durable-background.ts +38 -2
- package/corpus/core/src/agent/production-agent.ts +54 -0
- package/corpus/core/src/agent/run-manager.ts +27 -0
- package/corpus/core/src/agent/run-store.ts +185 -4
- package/corpus/core/src/client/CommandMenu.tsx +16 -0
- package/corpus/core/src/client/app-providers.tsx +26 -1
- package/corpus/core/src/client/i18n.tsx +605 -0
- package/corpus/core/src/client/index.ts +28 -0
- package/corpus/core/src/index.browser.ts +25 -0
- package/corpus/core/src/localization/actions/get-localization-preference.ts +23 -0
- package/corpus/core/src/localization/actions/set-localization-preference.ts +30 -0
- package/corpus/core/src/localization/index.ts +2 -0
- package/corpus/core/src/localization/server.ts +131 -0
- package/corpus/core/src/localization/shared.ts +163 -0
- package/corpus/core/src/server/action-discovery.ts +8 -0
- package/corpus/core/src/server/agent-chat-plugin.ts +71 -0
- package/corpus/core/src/server/auth.ts +13 -0
- package/corpus/core/src/server/index.ts +8 -0
- package/corpus/core/src/templates/default/.agents/skills/adding-a-feature/SKILL.md +5 -0
- package/corpus/core/src/templates/default/.agents/skills/internationalization/SKILL.md +77 -0
- package/corpus/core/src/templates/default/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/corpus/core/src/templates/default/AGENTS.md +16 -15
- package/corpus/core/src/templates/default/app/i18n/en-US.ts +29 -0
- package/corpus/core/src/templates/default/app/i18n/index.ts +13 -0
- package/corpus/core/src/templates/default/app/root.tsx +20 -1
- package/corpus/core/src/templates/default/app/routes/_index.tsx +24 -9
- package/corpus/core/src/templates/default/app/routes/settings.tsx +67 -0
- package/corpus/core/src/templates/workspace-core/.agents/skills/adding-a-feature/SKILL.md +5 -0
- package/corpus/core/src/templates/workspace-core/.agents/skills/internationalization/SKILL.md +77 -0
- package/corpus/core/src/templates/workspace-core/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/corpus/core/src/vite/action-types-plugin.ts +10 -0
- package/corpus/templates/analytics/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/corpus/templates/analytics/app/components/layout/CommandPalette.tsx +12 -12
- package/corpus/templates/analytics/app/components/layout/Header.tsx +18 -15
- package/corpus/templates/analytics/app/components/layout/Layout.tsx +7 -5
- package/corpus/templates/analytics/app/components/layout/MobileNav.tsx +9 -3
- package/corpus/templates/analytics/app/components/layout/Sidebar.tsx +28 -26
- package/corpus/templates/analytics/app/i18n/ar-SA.ts +3 -0
- package/corpus/templates/analytics/app/i18n/de-DE.ts +3 -0
- package/corpus/templates/analytics/app/i18n/en-US.ts +3 -0
- package/corpus/templates/analytics/app/i18n/es-ES.ts +3 -0
- package/corpus/templates/analytics/app/i18n/fr-FR.ts +3 -0
- package/corpus/templates/analytics/app/i18n/hi-IN.ts +3 -0
- package/corpus/templates/analytics/app/i18n/index.ts +31 -0
- package/corpus/templates/analytics/app/i18n/ja-JP.ts +3 -0
- package/corpus/templates/analytics/app/i18n/ko-KR.ts +3 -0
- package/corpus/templates/analytics/app/i18n/pt-BR.ts +3 -0
- package/corpus/templates/analytics/app/i18n/zh-CN.ts +3 -0
- package/corpus/templates/analytics/app/i18n-data.ts +433 -0
- package/corpus/templates/analytics/app/pages/Settings.tsx +50 -16
- package/corpus/templates/analytics/app/pages/analyses/AnalysesList.tsx +2 -2
- package/corpus/templates/analytics/app/root.tsx +14 -1
- package/corpus/templates/analytics/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/corpus/templates/analytics/changelog/2026-06-24-settings-now-link-directly-to-agent-settings-for-model-api-k.md +6 -0
- package/corpus/templates/assets/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/corpus/templates/assets/app/components/layout/Header.tsx +17 -8
- package/corpus/templates/assets/app/components/layout/Layout.tsx +10 -6
- package/corpus/templates/assets/app/components/layout/Sidebar.tsx +40 -23
- package/corpus/templates/assets/app/i18n/ar-SA.ts +3 -0
- package/corpus/templates/assets/app/i18n/de-DE.ts +3 -0
- package/corpus/templates/assets/app/i18n/en-US.ts +3 -0
- package/corpus/templates/assets/app/i18n/es-ES.ts +3 -0
- package/corpus/templates/assets/app/i18n/fr-FR.ts +3 -0
- package/corpus/templates/assets/app/i18n/hi-IN.ts +3 -0
- package/corpus/templates/assets/app/i18n/index.ts +31 -0
- package/corpus/templates/assets/app/i18n/ja-JP.ts +3 -0
- package/corpus/templates/assets/app/i18n/ko-KR.ts +3 -0
- package/corpus/templates/assets/app/i18n/pt-BR.ts +3 -0
- package/corpus/templates/assets/app/i18n/zh-CN.ts +3 -0
- package/corpus/templates/assets/app/i18n-data.ts +668 -0
- package/corpus/templates/assets/app/root.tsx +40 -15
- package/corpus/templates/assets/app/routes/_index.tsx +9 -10
- package/corpus/templates/assets/app/routes/settings.tsx +37 -6
- package/corpus/templates/assets/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/corpus/templates/assets/changelog/2026-06-24-settings-now-link-directly-to-agent-settings-for-model-api-k.md +6 -0
- package/corpus/templates/brain/.agents/skills/adding-a-feature/SKILL.md +5 -0
- package/corpus/templates/brain/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/corpus/templates/brain/app/components/layout/Layout.tsx +12 -8
- package/corpus/templates/brain/app/components/layout/Sidebar.tsx +23 -12
- package/corpus/templates/brain/app/i18n/ar-SA.ts +3 -0
- package/corpus/templates/brain/app/i18n/de-DE.ts +3 -0
- package/corpus/templates/brain/app/i18n/en-US.ts +3 -0
- package/corpus/templates/brain/app/i18n/es-ES.ts +3 -0
- package/corpus/templates/brain/app/i18n/fr-FR.ts +3 -0
- package/corpus/templates/brain/app/i18n/hi-IN.ts +3 -0
- package/corpus/templates/brain/app/i18n/index.ts +31 -0
- package/corpus/templates/brain/app/i18n/ja-JP.ts +3 -0
- package/corpus/templates/brain/app/i18n/ko-KR.ts +3 -0
- package/corpus/templates/brain/app/i18n/pt-BR.ts +3 -0
- package/corpus/templates/brain/app/i18n/zh-CN.ts +3 -0
- package/corpus/templates/brain/app/i18n-data.ts +624 -0
- package/corpus/templates/brain/app/root.tsx +27 -12
- package/corpus/templates/brain/app/routes/knowledge.tsx +6 -6
- package/corpus/templates/brain/app/routes/ops.tsx +4 -4
- package/corpus/templates/brain/app/routes/search.tsx +4 -4
- package/corpus/templates/brain/app/routes/settings.tsx +48 -11
- package/corpus/templates/brain/app/routes/sources.tsx +3 -3
- package/corpus/templates/brain/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/corpus/templates/brain/changelog/2026-06-24-settings-now-link-directly-to-agent-settings-for-model-api-k.md +6 -0
- package/corpus/templates/calendar/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/corpus/templates/calendar/app/components/layout/AppLayout.tsx +2 -0
- package/corpus/templates/calendar/app/components/layout/Sidebar.tsx +16 -9
- package/corpus/templates/calendar/app/i18n/ar-SA.ts +57 -0
- package/corpus/templates/calendar/app/i18n/de-DE.ts +58 -0
- package/corpus/templates/calendar/app/i18n/en-US.ts +57 -0
- package/corpus/templates/calendar/app/i18n/es-ES.ts +58 -0
- package/corpus/templates/calendar/app/i18n/fr-FR.ts +58 -0
- package/corpus/templates/calendar/app/i18n/hi-IN.ts +57 -0
- package/corpus/templates/calendar/app/i18n/index.ts +31 -0
- package/corpus/templates/calendar/app/i18n/ja-JP.ts +58 -0
- package/corpus/templates/calendar/app/i18n/ko-KR.ts +57 -0
- package/corpus/templates/calendar/app/i18n/pt-BR.ts +57 -0
- package/corpus/templates/calendar/app/i18n/zh-CN.ts +57 -0
- package/corpus/templates/calendar/app/i18n-data.ts +516 -0
- package/corpus/templates/calendar/app/pages/CalendarView.tsx +2 -0
- package/corpus/templates/calendar/app/pages/Settings.tsx +63 -28
- package/corpus/templates/calendar/app/root.tsx +78 -7
- package/corpus/templates/calendar/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/corpus/templates/calendar/changelog/2026-06-24-settings-now-link-directly-to-agent-settings-for-model-api-k.md +6 -0
- package/corpus/templates/chat/.agents/skills/adding-a-feature/SKILL.md +5 -0
- package/corpus/templates/chat/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/corpus/templates/chat/app/components/layout/Header.tsx +17 -11
- package/corpus/templates/chat/app/components/layout/Layout.tsx +12 -8
- package/corpus/templates/chat/app/components/layout/Sidebar.tsx +47 -18
- package/corpus/templates/chat/app/i18n/ar-SA.ts +62 -0
- package/corpus/templates/chat/app/i18n/de-DE.ts +63 -0
- package/corpus/templates/chat/app/i18n/en-US.ts +63 -0
- package/corpus/templates/chat/app/i18n/es-ES.ts +63 -0
- package/corpus/templates/chat/app/i18n/fr-FR.ts +63 -0
- package/corpus/templates/chat/app/i18n/hi-IN.ts +63 -0
- package/corpus/templates/chat/app/i18n/index.ts +31 -0
- package/corpus/templates/chat/app/i18n/ja-JP.ts +63 -0
- package/corpus/templates/chat/app/i18n/ko-KR.ts +63 -0
- package/corpus/templates/chat/app/i18n/pt-BR.ts +63 -0
- package/corpus/templates/chat/app/i18n/zh-CN.ts +61 -0
- package/corpus/templates/chat/app/i18n-data.ts +475 -0
- package/corpus/templates/chat/app/root.tsx +18 -5
- package/corpus/templates/chat/app/routes/_index.tsx +9 -8
- package/corpus/templates/chat/app/routes/settings.tsx +86 -0
- package/corpus/templates/chat/changelog/2026-06-24-a-new-settings-page-gives-quick-access-to-language-workspace.md +6 -0
- package/corpus/templates/chat/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/corpus/templates/clips/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/corpus/templates/clips/app/components/layout/Header.tsx +23 -17
- package/corpus/templates/clips/app/components/library/empty-state.tsx +10 -34
- package/corpus/templates/clips/app/components/library/library-layout.tsx +45 -34
- package/corpus/templates/clips/app/i18n/ar-SA.ts +182 -0
- package/corpus/templates/clips/app/i18n/de-DE.ts +184 -0
- package/corpus/templates/clips/app/i18n/en-US.ts +179 -0
- package/corpus/templates/clips/app/i18n/es-ES.ts +183 -0
- package/corpus/templates/clips/app/i18n/fr-FR.ts +184 -0
- package/corpus/templates/clips/app/i18n/hi-IN.ts +180 -0
- package/corpus/templates/clips/app/i18n/index.ts +41 -0
- package/corpus/templates/clips/app/i18n/ja-JP.ts +180 -0
- package/corpus/templates/clips/app/i18n/ko-KR.ts +178 -0
- package/corpus/templates/clips/app/i18n/pt-BR.ts +183 -0
- package/corpus/templates/clips/app/i18n/zh-CN.ts +173 -0
- package/corpus/templates/clips/app/root.tsx +104 -10
- package/corpus/templates/clips/app/routes/_app.settings._index.tsx +154 -95
- package/corpus/templates/clips/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/corpus/templates/clips/changelog/2026-06-24-clips-now-includes-a-language-picker-and-simplified-chinese-ui.md +6 -0
- package/corpus/templates/clips/changelog/2026-06-24-settings-now-link-directly-to-agent-settings-for-model-api-k.md +6 -0
- package/corpus/templates/content/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/corpus/templates/content/app/components/EmptyState.tsx +7 -5
- package/corpus/templates/content/app/components/ThemeToggle.tsx +4 -2
- package/corpus/templates/content/app/components/layout/Header.tsx +2 -0
- package/corpus/templates/content/app/components/layout/Layout.tsx +8 -7
- package/corpus/templates/content/app/components/sidebar/DocumentSidebar.tsx +41 -1
- package/corpus/templates/content/app/i18n/ar-SA.ts +3 -0
- package/corpus/templates/content/app/i18n/de-DE.ts +3 -0
- package/corpus/templates/content/app/i18n/en-US.ts +3 -0
- package/corpus/templates/content/app/i18n/es-ES.ts +3 -0
- package/corpus/templates/content/app/i18n/fr-FR.ts +3 -0
- package/corpus/templates/content/app/i18n/hi-IN.ts +3 -0
- package/corpus/templates/content/app/i18n/index.ts +31 -0
- package/corpus/templates/content/app/i18n/ja-JP.ts +3 -0
- package/corpus/templates/content/app/i18n/ko-KR.ts +3 -0
- package/corpus/templates/content/app/i18n/pt-BR.ts +3 -0
- package/corpus/templates/content/app/i18n/zh-CN.ts +3 -0
- package/corpus/templates/content/app/i18n-data.ts +490 -0
- package/corpus/templates/content/app/root.tsx +110 -23
- package/corpus/templates/content/app/routes/_app.settings.tsx +84 -0
- package/corpus/templates/content/changelog/2026-06-24-a-new-settings-page-gives-quick-access-to-language-workspace.md +6 -0
- package/corpus/templates/content/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/corpus/templates/design/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/corpus/templates/design/app/components/layout/Header.tsx +16 -8
- package/corpus/templates/design/app/components/layout/Layout.tsx +8 -6
- package/corpus/templates/design/app/components/layout/Sidebar.tsx +25 -9
- package/corpus/templates/design/app/i18n/ar-SA.ts +3 -0
- package/corpus/templates/design/app/i18n/de-DE.ts +3 -0
- package/corpus/templates/design/app/i18n/en-US.ts +3 -0
- package/corpus/templates/design/app/i18n/es-ES.ts +3 -0
- package/corpus/templates/design/app/i18n/fr-FR.ts +3 -0
- package/corpus/templates/design/app/i18n/hi-IN.ts +3 -0
- package/corpus/templates/design/app/i18n/index.ts +31 -0
- package/corpus/templates/design/app/i18n/ja-JP.ts +3 -0
- package/corpus/templates/design/app/i18n/ko-KR.ts +3 -0
- package/corpus/templates/design/app/i18n/pt-BR.ts +3 -0
- package/corpus/templates/design/app/i18n/zh-CN.ts +3 -0
- package/corpus/templates/design/app/i18n-data.ts +350 -0
- package/corpus/templates/design/app/root.tsx +40 -15
- package/corpus/templates/design/app/routes/settings.tsx +43 -0
- package/corpus/templates/design/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/corpus/templates/design/changelog/2026-06-24-settings-now-link-directly-to-agent-settings-for-model-api-k.md +6 -0
- package/corpus/templates/dispatch/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/corpus/templates/dispatch/app/i18n/ar-SA.ts +3 -0
- package/corpus/templates/dispatch/app/i18n/de-DE.ts +3 -0
- package/corpus/templates/dispatch/app/i18n/en-US.ts +3 -0
- package/corpus/templates/dispatch/app/i18n/es-ES.ts +3 -0
- package/corpus/templates/dispatch/app/i18n/fr-FR.ts +3 -0
- package/corpus/templates/dispatch/app/i18n/hi-IN.ts +3 -0
- package/corpus/templates/dispatch/app/i18n/index.ts +31 -0
- package/corpus/templates/dispatch/app/i18n/ja-JP.ts +3 -0
- package/corpus/templates/dispatch/app/i18n/ko-KR.ts +3 -0
- package/corpus/templates/dispatch/app/i18n/pt-BR.ts +3 -0
- package/corpus/templates/dispatch/app/i18n/zh-CN.ts +3 -0
- package/corpus/templates/dispatch/app/i18n-data.ts +267 -0
- package/corpus/templates/dispatch/app/root.tsx +18 -4
- package/corpus/templates/dispatch/app/routes/settings.tsx +86 -0
- package/corpus/templates/dispatch/changelog/2026-06-24-a-new-settings-page-gives-quick-access-to-language-workspace.md +6 -0
- package/corpus/templates/dispatch/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/corpus/templates/forms/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/corpus/templates/forms/app/components/layout/Header.tsx +16 -9
- package/corpus/templates/forms/app/components/layout/Layout.tsx +6 -4
- package/corpus/templates/forms/app/components/layout/Sidebar.tsx +34 -17
- package/corpus/templates/forms/app/i18n/ar-SA.ts +58 -0
- package/corpus/templates/forms/app/i18n/de-DE.ts +59 -0
- package/corpus/templates/forms/app/i18n/en-US.ts +59 -0
- package/corpus/templates/forms/app/i18n/es-ES.ts +59 -0
- package/corpus/templates/forms/app/i18n/fr-FR.ts +59 -0
- package/corpus/templates/forms/app/i18n/hi-IN.ts +59 -0
- package/corpus/templates/forms/app/i18n/index.ts +31 -0
- package/corpus/templates/forms/app/i18n/ja-JP.ts +59 -0
- package/corpus/templates/forms/app/i18n/ko-KR.ts +59 -0
- package/corpus/templates/forms/app/i18n/pt-BR.ts +59 -0
- package/corpus/templates/forms/app/i18n/zh-CN.ts +56 -0
- package/corpus/templates/forms/app/root.tsx +65 -16
- package/corpus/templates/forms/app/routes/_app.settings.tsx +85 -0
- package/corpus/templates/forms/changelog/2026-06-24-a-new-settings-page-gives-quick-access-to-language-workspace.md +6 -0
- package/corpus/templates/forms/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/corpus/templates/macros/app/components/layout/AppLayout.tsx +29 -17
- package/corpus/templates/macros/app/components/layout/Header.tsx +16 -10
- package/corpus/templates/macros/app/i18n/ar-SA.ts +54 -0
- package/corpus/templates/macros/app/i18n/de-DE.ts +55 -0
- package/corpus/templates/macros/app/i18n/en-US.ts +55 -0
- package/corpus/templates/macros/app/i18n/es-ES.ts +55 -0
- package/corpus/templates/macros/app/i18n/fr-FR.ts +55 -0
- package/corpus/templates/macros/app/i18n/hi-IN.ts +55 -0
- package/corpus/templates/macros/app/i18n/index.ts +31 -0
- package/corpus/templates/macros/app/i18n/ja-JP.ts +55 -0
- package/corpus/templates/macros/app/i18n/ko-KR.ts +55 -0
- package/corpus/templates/macros/app/i18n/pt-BR.ts +55 -0
- package/corpus/templates/macros/app/i18n/zh-CN.ts +53 -0
- package/corpus/templates/macros/app/root.tsx +65 -15
- package/corpus/templates/macros/app/routes/settings.tsx +85 -0
- package/corpus/templates/macros/changelog/2026-06-24-a-new-settings-page-gives-quick-access-to-language-workspace.md +6 -0
- package/corpus/templates/macros/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/corpus/templates/mail/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/corpus/templates/mail/app/components/layout/AppLayout.tsx +9 -4
- package/corpus/templates/mail/app/i18n/ar-SA.ts +33 -0
- package/corpus/templates/mail/app/i18n/de-DE.ts +33 -0
- package/corpus/templates/mail/app/i18n/en-US.ts +32 -0
- package/corpus/templates/mail/app/i18n/es-ES.ts +33 -0
- package/corpus/templates/mail/app/i18n/fr-FR.ts +33 -0
- package/corpus/templates/mail/app/i18n/hi-IN.ts +32 -0
- package/corpus/templates/mail/app/i18n/index.ts +31 -0
- package/corpus/templates/mail/app/i18n/ja-JP.ts +32 -0
- package/corpus/templates/mail/app/i18n/ko-KR.ts +33 -0
- package/corpus/templates/mail/app/i18n/pt-BR.ts +34 -0
- package/corpus/templates/mail/app/i18n/zh-CN.ts +32 -0
- package/corpus/templates/mail/app/pages/SettingsPage.tsx +67 -13
- package/corpus/templates/mail/app/root.tsx +20 -0
- package/corpus/templates/mail/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/corpus/templates/mail/changelog/2026-06-24-settings-now-link-directly-to-agent-settings-for-model-api-k.md +6 -0
- package/corpus/templates/plan/.agents/skills/adding-a-feature/SKILL.md +5 -0
- package/corpus/templates/plan/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/corpus/templates/plan/app/components/layout/Header.tsx +19 -12
- package/corpus/templates/plan/app/components/layout/Layout.tsx +11 -7
- package/corpus/templates/plan/app/components/layout/Sidebar.tsx +41 -28
- package/corpus/templates/plan/app/i18n/ar-SA.ts +77 -0
- package/corpus/templates/plan/app/i18n/de-DE.ts +78 -0
- package/corpus/templates/plan/app/i18n/en-US.ts +78 -0
- package/corpus/templates/plan/app/i18n/es-ES.ts +78 -0
- package/corpus/templates/plan/app/i18n/fr-FR.ts +78 -0
- package/corpus/templates/plan/app/i18n/hi-IN.ts +78 -0
- package/corpus/templates/plan/app/i18n/index.ts +31 -0
- package/corpus/templates/plan/app/i18n/ja-JP.ts +79 -0
- package/corpus/templates/plan/app/i18n/ko-KR.ts +77 -0
- package/corpus/templates/plan/app/i18n/pt-BR.ts +78 -0
- package/corpus/templates/plan/app/i18n/zh-CN.ts +74 -0
- package/corpus/templates/plan/app/root.tsx +45 -8
- package/corpus/templates/plan/app/routes/settings.tsx +86 -0
- package/corpus/templates/plan/changelog/2026-06-24-a-new-settings-page-gives-quick-access-to-language-workspace.md +6 -0
- package/corpus/templates/plan/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/corpus/templates/slides/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/corpus/templates/slides/app/components/layout/Header.tsx +23 -11
- package/corpus/templates/slides/app/components/layout/Layout.tsx +7 -6
- package/corpus/templates/slides/app/components/layout/Sidebar.tsx +23 -11
- package/corpus/templates/slides/app/i18n/ar-SA.ts +54 -0
- package/corpus/templates/slides/app/i18n/de-DE.ts +56 -0
- package/corpus/templates/slides/app/i18n/en-US.ts +55 -0
- package/corpus/templates/slides/app/i18n/es-ES.ts +55 -0
- package/corpus/templates/slides/app/i18n/fr-FR.ts +55 -0
- package/corpus/templates/slides/app/i18n/hi-IN.ts +55 -0
- package/corpus/templates/slides/app/i18n/index.ts +31 -0
- package/corpus/templates/slides/app/i18n/ja-JP.ts +55 -0
- package/corpus/templates/slides/app/i18n/ko-KR.ts +55 -0
- package/corpus/templates/slides/app/i18n/pt-BR.ts +55 -0
- package/corpus/templates/slides/app/i18n/zh-CN.ts +53 -0
- package/corpus/templates/slides/app/root.tsx +50 -8
- package/corpus/templates/slides/app/routes/settings.tsx +85 -0
- package/corpus/templates/slides/changelog/2026-06-24-a-new-settings-page-gives-quick-access-to-language-workspace.md +6 -0
- package/corpus/templates/slides/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/corpus/templates/videos/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/corpus/templates/videos/app/components/NewCompositionPopover.tsx +14 -9
- package/corpus/templates/videos/app/components/Sidebar.tsx +16 -9
- package/corpus/templates/videos/app/components/StudioHeader.tsx +12 -8
- package/corpus/templates/videos/app/components/layout/Header.tsx +21 -15
- package/corpus/templates/videos/app/components/layout/Layout.tsx +10 -7
- package/corpus/templates/videos/app/components/layout/NavSidebar.tsx +21 -6
- package/corpus/templates/videos/app/i18n/ar-SA.ts +73 -0
- package/corpus/templates/videos/app/i18n/de-DE.ts +75 -0
- package/corpus/templates/videos/app/i18n/en-US.ts +74 -0
- package/corpus/templates/videos/app/i18n/es-ES.ts +75 -0
- package/corpus/templates/videos/app/i18n/fr-FR.ts +75 -0
- package/corpus/templates/videos/app/i18n/hi-IN.ts +74 -0
- package/corpus/templates/videos/app/i18n/index.ts +31 -0
- package/corpus/templates/videos/app/i18n/ja-JP.ts +74 -0
- package/corpus/templates/videos/app/i18n/ko-KR.ts +74 -0
- package/corpus/templates/videos/app/i18n/pt-BR.ts +75 -0
- package/corpus/templates/videos/app/i18n/zh-CN.ts +72 -0
- package/corpus/templates/videos/app/pages/Index.tsx +11 -9
- package/corpus/templates/videos/app/root.tsx +45 -7
- package/corpus/templates/videos/app/routes/settings.tsx +85 -0
- package/corpus/templates/videos/changelog/2026-06-24-a-new-settings-page-gives-quick-access-to-language-workspace.md +6 -0
- package/corpus/templates/videos/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
- package/dist/agent/durable-background.d.ts +15 -0
- package/dist/agent/durable-background.d.ts.map +1 -1
- package/dist/agent/durable-background.js +28 -2
- package/dist/agent/durable-background.js.map +1 -1
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +34 -1
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/agent/run-manager.d.ts +8 -0
- package/dist/agent/run-manager.d.ts.map +1 -1
- package/dist/agent/run-manager.js +18 -1
- package/dist/agent/run-manager.js.map +1 -1
- package/dist/agent/run-store.d.ts +99 -0
- package/dist/agent/run-store.d.ts.map +1 -1
- package/dist/agent/run-store.js +155 -4
- package/dist/agent/run-store.js.map +1 -1
- package/dist/client/CommandMenu.d.ts +3 -0
- package/dist/client/CommandMenu.d.ts.map +1 -1
- package/dist/client/CommandMenu.js +9 -0
- package/dist/client/CommandMenu.js.map +1 -1
- package/dist/client/app-providers.d.ts +8 -1
- package/dist/client/app-providers.d.ts.map +1 -1
- package/dist/client/app-providers.js +7 -5
- package/dist/client/app-providers.js.map +1 -1
- package/dist/client/i18n.d.ts +54 -0
- package/dist/client/i18n.d.ts.map +1 -0
- package/dist/client/i18n.js +354 -0
- package/dist/client/i18n.js.map +1 -0
- package/dist/client/index.d.ts +2 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +2 -1
- package/dist/client/index.js.map +1 -1
- package/dist/index.browser.d.ts +1 -1
- package/dist/index.browser.d.ts.map +1 -1
- package/dist/index.browser.js +1 -1
- package/dist/index.browser.js.map +1 -1
- package/dist/localization/actions/get-localization-preference.d.ts +4 -0
- package/dist/localization/actions/get-localization-preference.d.ts.map +1 -0
- package/dist/localization/actions/get-localization-preference.js +16 -0
- package/dist/localization/actions/get-localization-preference.js.map +1 -0
- package/dist/localization/actions/set-localization-preference.d.ts +6 -0
- package/dist/localization/actions/set-localization-preference.d.ts.map +1 -0
- package/dist/localization/actions/set-localization-preference.js +24 -0
- package/dist/localization/actions/set-localization-preference.js.map +1 -0
- package/dist/localization/index.d.ts +3 -0
- package/dist/localization/index.d.ts.map +1 -0
- package/dist/localization/index.js +3 -0
- package/dist/localization/index.js.map +1 -0
- package/dist/localization/server.d.ts +25 -0
- package/dist/localization/server.d.ts.map +1 -0
- package/dist/localization/server.js +69 -0
- package/dist/localization/server.js.map +1 -0
- package/dist/localization/shared.d.ts +25 -0
- package/dist/localization/shared.d.ts.map +1 -0
- package/dist/localization/shared.js +134 -0
- package/dist/localization/shared.js.map +1 -0
- package/dist/server/action-discovery.d.ts.map +1 -1
- package/dist/server/action-discovery.js +8 -0
- package/dist/server/action-discovery.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +58 -1
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js +12 -0
- package/dist/server/auth.js.map +1 -1
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +1 -0
- package/dist/server/index.js.map +1 -1
- package/dist/templates/default/.agents/skills/adding-a-feature/SKILL.md +5 -0
- package/dist/templates/default/.agents/skills/internationalization/SKILL.md +77 -0
- package/dist/templates/default/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/dist/templates/default/AGENTS.md +16 -15
- package/dist/templates/default/app/i18n/en-US.ts +29 -0
- package/dist/templates/default/app/i18n/index.ts +13 -0
- package/dist/templates/default/app/root.tsx +20 -1
- package/dist/templates/default/app/routes/_index.tsx +24 -9
- package/dist/templates/default/app/routes/settings.tsx +67 -0
- package/dist/templates/workspace-core/.agents/skills/adding-a-feature/SKILL.md +5 -0
- package/dist/templates/workspace-core/.agents/skills/internationalization/SKILL.md +77 -0
- package/dist/templates/workspace-core/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/dist/vite/action-types-plugin.d.ts.map +1 -1
- package/dist/vite/action-types-plugin.js +8 -0
- package/dist/vite/action-types-plugin.js.map +1 -1
- package/docs/AGENTS.md +1 -0
- package/docs/content/client.md +15 -0
- package/docs/content/internationalization.md +145 -0
- package/docs/content/locales/ar-SA/internationalization.md +102 -0
- package/docs/content/locales/de-DE/internationalization.md +102 -0
- package/docs/content/locales/es-ES/internationalization.md +102 -0
- package/docs/content/locales/fr-FR/internationalization.md +102 -0
- package/docs/content/locales/hi-IN/internationalization.md +102 -0
- package/docs/content/locales/ja-JP/internationalization.md +114 -0
- package/docs/content/locales/ko-KR/internationalization.md +102 -0
- package/docs/content/locales/pt-BR/internationalization.md +102 -0
- package/docs/content/locales/zh-CN/internationalization.md +102 -0
- package/docs/content/skills-guide.md +19 -18
- package/package.json +7 -1
- package/src/templates/default/.agents/skills/adding-a-feature/SKILL.md +5 -0
- package/src/templates/default/.agents/skills/internationalization/SKILL.md +77 -0
- package/src/templates/default/.agents/skills/self-modifying-code/SKILL.md +6 -0
- package/src/templates/default/AGENTS.md +16 -15
- package/src/templates/default/app/i18n/en-US.ts +29 -0
- package/src/templates/default/app/i18n/index.ts +13 -0
- package/src/templates/default/app/root.tsx +20 -1
- package/src/templates/default/app/routes/_index.tsx +24 -9
- package/src/templates/default/app/routes/settings.tsx +67 -0
- package/src/templates/workspace-core/.agents/skills/adding-a-feature/SKILL.md +5 -0
- package/src/templates/workspace-core/.agents/skills/internationalization/SKILL.md +77 -0
- package/src/templates/workspace-core/.agents/skills/self-modifying-code/SKILL.md +6 -0
|
@@ -157,6 +157,14 @@ export declare function getActiveRunForThreadAsync(threadId: string): Promise<{
|
|
|
157
157
|
status: string;
|
|
158
158
|
heartbeatAt: number;
|
|
159
159
|
lastProgressAt: number | null;
|
|
160
|
+
/** How the run was dispatched (NULL/foreground, background, background-processing). */
|
|
161
|
+
dispatchMode?: string | null;
|
|
162
|
+
/**
|
|
163
|
+
* Last reached `_process-run` worker stage as a JSON string
|
|
164
|
+
* `{stage,detail?,at}`. Surfaced so a silent background-worker death is
|
|
165
|
+
* diagnosable from the client WITHOUT the unreadable bg-fn logs.
|
|
166
|
+
*/
|
|
167
|
+
diagStage?: string | null;
|
|
160
168
|
} | null>;
|
|
161
169
|
/** Get a run by ID */
|
|
162
170
|
export declare function getRun(runId: string): ActiveRun | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-manager.d.ts","sourceRoot":"","sources":["../../src/agent/run-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"run-manager.d.ts","sourceRoot":"","sources":["../../src/agent/run-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAuBtE,MAAM,WAAW,SAAS;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,6EAA6E;IAC7E,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,QAAQ,EAAE,CAAC;IACnB,MAAM,EAAE,SAAS,CAAC;IAClB,WAAW,EAAE,GAAG,CAAC,CAAC,KAAK,EAAE,QAAQ,KAAK,IAAI,CAAC,CAAC;IAC5C,KAAK,EAAE,eAAe,CAAC;IACvB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;CACnB;AAQD;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,kCAAkC,QAAS,CAAC;AAEzD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,8BAA8B,QAAS,CAAC;AAErD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,kCAAkC,QAAc,CAAC;AAE9D;;;;;GAKG;AACH,eAAO,MAAM,sCAAsC,QACf,CAAC;AAErC,qEAAqE;AACrE,eAAO,MAAM,kCAAkC,QAAsB,CAAC;AAEtE;;;;;GAKG;AACH,eAAO,MAAM,gCAAgC,QAA0B,CAAC;AAExE;;;;;GAKG;AACH,eAAO,MAAM,gCAAgC,QAAiB,CAAC;AAwC/D,MAAM,WAAW,eAAe;IAC9B;;2CAEuC;IACvC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;4DACwD;IACxD,2BAA2B,CAAC,EAAE,OAAO,CAAC;IACtC;;;+E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,CAAC;IACpB,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,uFAAuF;IACvF,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B,GAAG,IAAI,CAAC,CA8FR;AAkBD,sBAAsB;AACtB,wBAAgB,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAEtD;AAED,gDAAgD;AAChD,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,GAAE,MAAe,GAAG,OAAO,CAQxE;AAGD,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { EngineError } from "./engine/types.js";
|
|
2
2
|
import { captureError } from "../server/capture-error.js";
|
|
3
|
-
import { insertRun, insertRunEvent, updateRunStatusIfRunning, markRunAborted, getRunAbortState, getRunStatus, getRunEventsSince, getRunById, getRunByThread, cleanupOldRuns, updateRunHeartbeat, bumpRunProgress, reapIfStale, ensureTerminalRunEvent, setRunError, STALE_RUN_ERROR_EVENT, } from "./run-store.js";
|
|
3
|
+
import { insertRun, insertRunEvent, updateRunStatusIfRunning, markRunAborted, getRunAbortState, getRunStatus, getRunEventsSince, getRunById, getRunByThread, cleanupOldRuns, updateRunHeartbeat, bumpRunProgress, reapIfStale, reapUnclaimedBackgroundRun, ensureTerminalRunEvent, setRunError, STALE_RUN_ERROR_EVENT, } from "./run-store.js";
|
|
4
4
|
const activeRuns = new Map();
|
|
5
5
|
const threadToRun = new Map();
|
|
6
6
|
/** How long to keep completed runs in memory before cleanup (5 min) */
|
|
@@ -873,6 +873,19 @@ export async function getActiveRunForThreadAsync(threadId) {
|
|
|
873
873
|
if (!sqlRun)
|
|
874
874
|
return null;
|
|
875
875
|
if (sqlRun.status === "running") {
|
|
876
|
+
// FALLBACK HARDENING: a background-dispatched run that is still UNCLAIMED
|
|
877
|
+
// (dispatch_mode === 'background', never flipped to 'background-processing')
|
|
878
|
+
// past the tight grace means the bg-fn worker never started — a silent
|
|
879
|
+
// async-worker death that the 202-ack inline fallback can't catch. Reap it
|
|
880
|
+
// early and recoverably (background_worker_never_started) so the run no
|
|
881
|
+
// longer hangs for the full 90s window and the client's recoverable-error
|
|
882
|
+
// path can re-drive the turn. Only fires when there is provably no live
|
|
883
|
+
// worker; a claimed/heartbeating run is left alone by the conditional SQL.
|
|
884
|
+
if (sqlRun.dispatchMode === "background") {
|
|
885
|
+
const recovered = await reapUnclaimedBackgroundRun(sqlRun.id).catch(() => false);
|
|
886
|
+
if (recovered)
|
|
887
|
+
return null;
|
|
888
|
+
}
|
|
876
889
|
// If the producer is dead (no recent heartbeat), reap before the
|
|
877
890
|
// client can see a stale "running" status and enter a reconnect
|
|
878
891
|
// loop it can never exit.
|
|
@@ -886,6 +899,8 @@ export async function getActiveRunForThreadAsync(threadId) {
|
|
|
886
899
|
status: sqlRun.status,
|
|
887
900
|
heartbeatAt: sqlRun.heartbeatAt ?? sqlRun.startedAt,
|
|
888
901
|
lastProgressAt: sqlRun.lastProgressAt,
|
|
902
|
+
dispatchMode: sqlRun.dispatchMode,
|
|
903
|
+
diagStage: sqlRun.diagStage,
|
|
889
904
|
};
|
|
890
905
|
}
|
|
891
906
|
if (sqlRun.status === "completed" || sqlRun.status === "errored") {
|
|
@@ -911,6 +926,8 @@ export async function getActiveRunForThreadAsync(threadId) {
|
|
|
911
926
|
status: sqlRun.status,
|
|
912
927
|
heartbeatAt: sqlRun.heartbeatAt ?? sqlRun.startedAt,
|
|
913
928
|
lastProgressAt: sqlRun.lastProgressAt,
|
|
929
|
+
dispatchMode: sqlRun.dispatchMode,
|
|
930
|
+
diagStage: sqlRun.diagStage,
|
|
914
931
|
};
|
|
915
932
|
}
|
|
916
933
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-manager.js","sourceRoot":"","sources":["../../src/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AI;SACtB,CAAC,CAAC;QACH,IAAI,QAAQ,IAAI,QAAQ,CAAC,EAAE,KAAK,KAAK;YAAE,OAAO,QAAQ,CAAC,cAAc,CAAC;QACtE,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,sBAAsB;AACtB,MAAM,UAAU,MAAM,CAAC,KAAa;IAClC,OAAO,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC;AACvC,CAAC;AAED,gDAAgD;AAChD,MAAM,UAAU,QAAQ,CAAC,KAAa,EAAE,SAAiB,MAAM;IAC7D,MAAM,GAAG,GAAG,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAClC,IAAI,GAAG,EAAE,CAAC;QACR,gBAAgB,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IAChC,CAAC;IACD,mEAAmE;IACnE,cAAc,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IAC9C,OAAO,CAAC,CAAC,GAAG,CAAC;AACf,CAAC;AAED,oEAAoE;AACpE,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC","sourcesContent":["import type { AgentChatEvent, RunEvent, RunStatus } from \"./types.js\";\nimport { EngineError } from \"./engine/types.js\";\nimport { captureError } from \"../server/capture-error.js\";\nimport {\n insertRun,\n insertRunEvent,\n updateRunStatusIfRunning,\n markRunAborted,\n getRunAbortState,\n getRunStatus,\n getRunEventsSince,\n getRunById,\n getRunByThread,\n cleanupOldRuns,\n updateRunHeartbeat,\n bumpRunProgress,\n reapIfStale,\n ensureTerminalRunEvent,\n setRunError,\n STALE_RUN_ERROR_EVENT,\n} from \"./run-store.js\";\n\nexport interface ActiveRun {\n runId: string;\n threadId: string;\n /** Logical-turn identity (see StartRunOptions.turnId). Defaults to runId. */\n turnId: string;\n events: RunEvent[];\n status: RunStatus;\n subscribers: Set<(event: RunEvent) => void>;\n abort: AbortController;\n abortReason?: string;\n startedAt: number;\n}\n\nconst activeRuns = new Map<string, ActiveRun>();\nconst threadToRun = new Map<string, string>();\n\n/** How long to keep completed runs in memory before cleanup (5 min) */\nconst CLEANUP_DELAY_MS = 5 * 60 * 1000;\n\n/**\n * Default run chunk budget for hosted/serverless deploys.\n *\n * This MUST fire before the two upstream hard walls that otherwise kill a run\n * mid-turn with no chance to hand off:\n * 1. The Builder model gateway hard-caps a single model call at 45s\n * (builder-engine.ts MAX_BUILDER_GATEWAY_TIMEOUT_MS) — not raisable.\n * 2. Serverless functions are hard-killed around 60-65s (the heartbeat then\n * reaps the row as a stale_run).\n * Production data showed every cutoff landing in the 44-70s window with ZERO\n * auto_continue events ever emitted — i.e. the old 45s default raced the 45s\n * gateway and lost, and per-template overrides (e.g. 240_000) pushed it past\n * BOTH walls so it could never fire. 40s leaves ~5s of headroom under the\n * gateway wall to abort, persist the partial turn, write the terminal event,\n * and emit a clean auto_continue so the client resumes seamlessly.\n */\nexport const DEFAULT_HOSTED_RUN_SOFT_TIMEOUT_MS = 40_000;\n\n/**\n * Hard ceiling for the hosted soft timeout. On a hosted runtime the\n * auto_continue soft timeout can never usefully exceed this — the gateway\n * (45s) / function (~60s) walls kill the run first, so a larger configured or\n * env value just guarantees the cutoff is a hard error instead of a graceful\n * hand-off. Any resolved value above this is clamped down when hosted. Local\n * dev (non-hosted) is left alone so long-running local turns aren't chunked.\n *\n * IMPORTANT: this clamp is for the INTERACTIVE / foreground path and must NOT\n * be raised. The foreground POST still rides a synchronous serverless function\n * (~60-65s wall), so 40s remains correct there. The only sanctioned exception\n * is the opt-in `backgroundFunction` mode (see\n * `BACKGROUND_SOFT_TIMEOUT_CEILING_MS`), which runs inside a Netlify background\n * function (no ~60s wall, 15-min budget) and therefore can safely outlast 40s.\n */\nexport const HOSTED_SOFT_TIMEOUT_CEILING_MS = 40_000;\n\n/**\n * Hard ceiling for the soft timeout when a run executes inside a Netlify\n * background function (any deployed function whose name ends in `-background`).\n * Background functions return 202 immediately and run detached for up to 15\n * minutes, so the ~60s synchronous function wall that 40s defends against does\n * NOT apply. 13 minutes leaves ~2 min of headroom under Netlify's 15-min hard\n * kill to abort, persist the partial turn, write the terminal event, and (for\n * the rare >13-min turn) self-fire another background continuation.\n *\n * This ceiling is used ONLY when a caller explicitly opts in with\n * `backgroundFunction: true`. It does not change the foreground/interactive\n * ceiling and does not fire unless the durable-background path dispatched the\n * run into a background function. Per the design doc Guardrail, the 40s\n * interactive clamp stays correct for every non-background run.\n */\nexport const BACKGROUND_SOFT_TIMEOUT_CEILING_MS = 13 * 60_000; // 780_000\n\n/**\n * Default soft-timeout budget for a background-function run when the caller\n * does not pass an explicit `softTimeoutMs`. Same value as the ceiling — we\n * want a background turn to use nearly its whole 15-min budget before handing\n * off to a chained background continuation.\n */\nexport const DEFAULT_BACKGROUND_RUN_SOFT_TIMEOUT_MS =\n BACKGROUND_SOFT_TIMEOUT_CEILING_MS;\n\n/** Default SQL retention for completed run event logs (24 hours). */\nexport const DEFAULT_COMPLETED_RUN_RETENTION_MS = 24 * 60 * 60 * 1000;\n\n/**\n * Default SQL retention for errored/aborted run event logs (7 days). Kept\n * longer than completed runs so cut-off / failed chats survive for pattern\n * analysis (listErroredRuns) — these are rare and small, and they are exactly\n * the runs we need to study to keep hardening reliability.\n */\nexport const DEFAULT_ERRORED_RUN_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;\n\n/**\n * How recently a terminal run must have started for `/runs/active` to surface\n * it. Reconnect after this window won't replay the run — typical real-world\n * disconnects resolve in seconds, so 10 minutes is generous while keeping us\n * from resurrecting ancient turns when the user reopens an old thread.\n */\nexport const TERMINAL_RUN_RECONNECT_WINDOW_MS = 10 * 60 * 1000;\n\nconst PROVIDER_RATE_LIMITED_ERROR_CODE = \"provider_rate_limited\";\n\nfunction getRunErrorMessage(err: unknown): string {\n if (\n typeof err === \"object\" &&\n err !== null &&\n \"message\" in err &&\n typeof err.message === \"string\" &&\n err.message.trim().length > 0\n ) {\n return err.message;\n }\n return \"Unknown error\";\n}\n\nfunction getEngineRunErrorCode(err: EngineError): string | undefined {\n if (err.errorCode) return err.errorCode;\n if (err.statusCode === 429) return PROVIDER_RATE_LIMITED_ERROR_CODE;\n return undefined;\n}\n\nfunction getEngineRunErrorDetails(err: EngineError): string | undefined {\n if (err.statusCode === 429) return err.message;\n return undefined;\n}\n\nfunction shouldCaptureRunError(err: unknown): boolean {\n if (!(err instanceof EngineError)) return true;\n const errorCode = getEngineRunErrorCode(err);\n if (!errorCode) return true;\n const normalizedCode = errorCode.toLowerCase();\n return (\n !normalizedCode.startsWith(\"credits-limit\") &&\n normalizedCode !== \"provider_rate_limited\" &&\n normalizedCode !== \"rate_limit_exceeded\"\n );\n}\n\nexport interface StartRunOptions {\n /** Optional internal run chunk budget. When reached, the framework emits an\n * auto-continuation signal instead of a user-facing timeout. Leave unset for\n * no framework-imposed run timeout. */\n softTimeoutMs?: number;\n /** Opt into the hosted/serverless default chunk budget. Only callers with\n * automatic continuation support should enable this. */\n useHostedSoftTimeoutDefault?: boolean;\n /** Stable identity for the logical assistant turn this run belongs to. A\n * turn may span several continuation runs (each chunk is its own run); they\n * share one `turnId` so the durable assistant message can be folded across\n * them instead of dropped per-run. Defaults to the runId (turn == run). */\n turnId?: string;\n /**\n * Opt into the durable-background-function soft-timeout regime for THIS run\n * only. When true, `resolveRunSoftTimeoutMs` lifts the hosted ceiling from\n * 40s to ~13min (`BACKGROUND_SOFT_TIMEOUT_CEILING_MS`) because the run is\n * executing inside a Netlify background function (no ~60s wall). Off by\n * default — the foreground/interactive path never sets this, so its 40s\n * clamp is unchanged. See the design doc + the durable-background dispatch\n * decision in production-agent.ts.\n */\n backgroundFunction?: boolean;\n}\n\nexport interface ResolveRunSoftTimeoutOptions {\n useHostedDefault?: boolean;\n /**\n * Resolve the soft timeout for a run executing inside a Netlify background\n * function. Lifts the hosted clamp to `BACKGROUND_SOFT_TIMEOUT_CEILING_MS`\n * (~13min) for this invocation only and, when no override/env is supplied,\n * defaults to `DEFAULT_BACKGROUND_RUN_SOFT_TIMEOUT_MS`. Does NOT change the\n * foreground ceiling. Off by default.\n */\n backgroundFunction?: boolean;\n}\n\nfunction isHostedRuntime(): 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\nexport function resolveRunSoftTimeoutMs(\n overrideMs?: number,\n options?: ResolveRunSoftTimeoutOptions,\n): number {\n const hosted = isHostedRuntime();\n const background = options?.backgroundFunction === true;\n // The interactive/foreground ceiling is 40s — the synchronous serverless\n // function wall. A background-function run (opt-in only) has no ~60s wall, so\n // it is allowed to outlast that and is clamped to the larger 13-min ceiling\n // instead. The 40s clamp for non-background hosted runs is unchanged.\n const ceiling = background\n ? BACKGROUND_SOFT_TIMEOUT_CEILING_MS\n : HOSTED_SOFT_TIMEOUT_CEILING_MS;\n // A configured/env soft timeout that exceeds the upstream walls can never\n // actually fire (the gateway/function kills the run first), so clamp it down\n // on hosted runtimes. This is what makes auto_continue reach the client\n // instead of the run dying as builder_gateway_timeout / stale_run. `0` means\n // \"disabled\" and is never clamped up.\n const clampHosted = (ms: number): number =>\n hosted && ms > ceiling ? ceiling : ms;\n\n if (typeof overrideMs === \"number\" && Number.isFinite(overrideMs)) {\n return clampHosted(Math.max(0, overrideMs));\n }\n const envValue = process.env.AGENT_RUN_SOFT_TIMEOUT_MS;\n if (envValue !== undefined) {\n const raw = Number(envValue);\n if (Number.isFinite(raw) && raw >= 0) return clampHosted(raw);\n }\n // A background-function run uses the full background budget by default; the\n // foreground default (40s) is unchanged.\n if (background) {\n return hosted ? DEFAULT_BACKGROUND_RUN_SOFT_TIMEOUT_MS : 0;\n }\n return options?.useHostedDefault && hosted\n ? DEFAULT_HOSTED_RUN_SOFT_TIMEOUT_MS\n : 0;\n}\n\nexport function resolveCompletedRunRetentionMs(): number {\n const envValue = process.env.AGENT_RUN_RETENTION_MS;\n if (envValue !== undefined) {\n const raw = Number(envValue);\n if (Number.isFinite(raw) && raw >= 0) return raw;\n }\n return DEFAULT_COMPLETED_RUN_RETENTION_MS;\n}\n\nexport function resolveErroredRunRetentionMs(): number {\n const envValue = process.env.AGENT_ERRORED_RUN_RETENTION_MS;\n if (envValue !== undefined) {\n const raw = Number(envValue);\n if (Number.isFinite(raw) && raw >= 0) return raw;\n }\n return DEFAULT_ERRORED_RUN_RETENTION_MS;\n}\n\nfunction isTerminalRunEvent(event: AgentChatEvent): boolean {\n return (\n event.type === \"done\" ||\n event.type === \"error\" ||\n event.type === \"missing_api_key\" ||\n event.type === \"loop_limit\" ||\n event.type === \"auto_continue\"\n );\n}\n\nfunction abortInMemoryRun(run: ActiveRun, reason: string = \"user\") {\n run.abortReason = reason;\n run.status = \"aborted\";\n if (threadToRun.get(run.threadId) === run.runId) {\n threadToRun.delete(run.threadId);\n }\n run.abort.abort(reason);\n for (const subscriber of run.subscribers) {\n try {\n subscriber({ seq: run.events.length, event: { type: \"done\" } });\n } catch {\n // ignore — subscriber is being removed below\n }\n }\n run.subscribers.clear();\n}\n\n/**\n * Start a new agent run in the background.\n * `runFn` receives a `send` callback and an `AbortSignal`.\n * The run continues even if all SSE subscribers disconnect.\n *\n * Events are persisted to SQL for cross-isolate access (Cloudflare Workers).\n */\nexport function startRun(\n runId: string,\n threadId: string,\n runFn: (\n send: (event: AgentChatEvent) => void,\n signal: AbortSignal,\n ) => Promise<void>,\n onComplete?: (run: ActiveRun) => void | Promise<void>,\n options?: StartRunOptions,\n): ActiveRun {\n // If there's already a run for this thread, abort it\n const existingRunId = threadToRun.get(threadId);\n if (existingRunId) {\n abortRun(existingRunId);\n }\n\n const abort = new AbortController();\n let softTimedOut = false;\n const run: ActiveRun = {\n runId,\n threadId,\n turnId: options?.turnId ?? runId,\n events: [],\n status: \"running\",\n subscribers: new Set(),\n abort,\n startedAt: Date.now(),\n };\n\n activeRuns.set(runId, run);\n threadToRun.set(threadId, runId);\n\n // Persist run to SQL without blocking the response. Keep the promise so\n // final status cannot race ahead of a slow initial INSERT and then get\n // overwritten by a late row stuck at status='running'.\n const insertRunPromise = insertRun(runId, threadId, options?.turnId).catch(\n () => {},\n );\n\n // Per-run event persistence chain: events are chained so SQL inserts commit\n // in seq order. Without this, a fast seq=5 commit before a slow seq=4 means\n // the SQL poller advances its cursor past seq=4 (lastSeq = 5+1 = 6) and\n // reconnecting clients permanently miss that event (silent gap). Chaining\n // per run ensures order without blocking the fast in-memory SSE path.\n let persistenceChain: Promise<void> = Promise.resolve();\n\n // Throttle the durable progress timestamp to at most once per second so\n // a chatty token-by-token stream doesn't translate into one DB write per\n // chunk. The stuck-detector threshold is on the order of tens of seconds,\n // so 1s resolution is plenty.\n let lastProgressBumpAt = 0;\n const bumpProgressIfDue = () => {\n const now = Date.now();\n if (now - lastProgressBumpAt < 1000) return;\n lastProgressBumpAt = now;\n bumpRunProgress(runId).catch(() => {});\n };\n\n // Periodic SQL abort check interval (for cross-isolate abort on Workers).\n // Also self-aborts when our row is no longer status='running' — catches the\n // false-stale-reap zombie scenario where the reaper flipped the row while\n // this isolate was briefly unable to heartbeat (DB latency / GC pause).\n let lastAbortCheck = Date.now() - 3000;\n const checkSqlAbort = () => {\n const now = Date.now();\n if (now - lastAbortCheck < 3000) return;\n lastAbortCheck = now;\n getRunAbortState(runId)\n .then(async (state) => {\n if (state.aborted && !abort.signal.aborted) {\n abortInMemoryRun(run, state.reason ?? \"user\");\n return;\n }\n // If the row is no longer 'running' (reaped / replaced) and we're\n // still executing, self-abort so we stop executing and don't overwrite\n // the newer state with our terminal write.\n if (!abort.signal.aborted) {\n const status = await getRunStatus(runId);\n if (status !== null && status !== \"running\") {\n abortInMemoryRun(run, \"displaced\");\n }\n }\n })\n .catch(() => {});\n };\n\n // Heartbeat: bump heartbeat_at every 1.5s so watchers can detect a dead\n // producer (process crash, HMR restart, isolate eviction) quickly and\n // reap the row. Paired with RUN_STALE_MS (6s) — 4x the interval to\n // tolerate transient DB slowness without false positives.\n const heartbeatTimer: ReturnType<typeof setInterval> = setInterval(() => {\n updateRunHeartbeat(runId).catch(() => {});\n checkSqlAbort();\n }, 1500);\n const softTimeoutMs = resolveRunSoftTimeoutMs(options?.softTimeoutMs, {\n useHostedDefault: options?.useHostedSoftTimeoutDefault === true,\n backgroundFunction: options?.backgroundFunction === true,\n });\n const softTimeoutTimer =\n softTimeoutMs > 0\n ? setTimeout(() => {\n if (run.status !== \"running\" || abort.signal.aborted) return;\n softTimedOut = true;\n send({\n type: \"auto_continue\",\n reason: \"run_timeout\",\n });\n abort.abort();\n }, softTimeoutMs)\n : null;\n let pendingTerminalEvent: RunEvent | null = null;\n\n const captureRunError = (error: unknown, phase: \"run\" | \"completion\") => {\n captureError(error, {\n route: \"/_agent-native/agent-chat\",\n tags: {\n source: \"agent-run-manager\",\n phase,\n runStatus: run.status,\n softTimedOut: softTimedOut ? \"true\" : \"false\",\n abortReason: run.abortReason,\n errorCode: error instanceof EngineError ? error.errorCode : undefined,\n },\n extra: {\n runId,\n threadId,\n eventCount: run.events.length,\n startedAt: run.startedAt,\n softTimeoutMs,\n },\n contexts: {\n agentRun: {\n runId,\n threadId,\n status: run.status,\n phase,\n eventCount: run.events.length,\n startedAt: run.startedAt,\n softTimeoutMs,\n softTimedOut,\n abortReason: run.abortReason,\n },\n },\n });\n };\n\n const emitRunEvent = (\n runEvent: RunEvent,\n options?: { surfacePersistenceError?: boolean },\n ): Promise<void> => {\n run.events.push(runEvent);\n\n // Notify in-memory subscribers (same isolate, fast path)\n for (const subscriber of run.subscribers) {\n try {\n subscriber(runEvent);\n } catch {\n run.subscribers.delete(subscriber);\n }\n }\n\n // Bump the durable progress timestamp. Distinct from the heartbeat:\n // heartbeat = \"process is up\", progress = \"real work is happening.\" The\n // gap between them is what the client-side stuck-detector reads to tell\n // a hung run from a healthy one.\n bumpProgressIfDue();\n\n // Persist event to SQL. Events are chained through persistenceChain so\n // inserts commit in seq order — an out-of-order commit would advance the\n // SQL poller's cursor past the slow row, permanently dropping it for\n // reconnecting clients. Terminal events surface persistence errors so the\n // caller can decide how to handle a failed final write.\n const thisInsert = persistenceChain.then(() =>\n insertRunEvent(runId, runEvent.seq, JSON.stringify(runEvent.event)),\n );\n persistenceChain = thisInsert.catch(() => {});\n const persistence = thisInsert;\n if (!options?.surfacePersistenceError) {\n persistence.catch(() => {});\n }\n\n checkSqlAbort();\n return persistence;\n };\n\n const send = (event: AgentChatEvent) => {\n if (run.status === \"aborted\" && abort.signal.aborted) return;\n\n const runEvent: RunEvent = { seq: run.events.length, event };\n if (isTerminalRunEvent(event)) {\n pendingTerminalEvent = runEvent;\n return;\n }\n\n emitRunEvent(runEvent);\n };\n\n // Run in background — intentionally detached from any HTTP connection\n const runPromise = runFn(send, abort.signal)\n .then(() => {\n if (abort.signal.aborted) {\n run.status = softTimedOut ? \"completed\" : \"aborted\";\n return;\n }\n run.status = \"completed\";\n })\n .catch((err) => {\n // Don't surface abort errors — the run was intentionally stopped\n if (abort.signal.aborted) {\n run.status = softTimedOut ? \"completed\" : \"aborted\";\n return;\n }\n run.status = \"errored\";\n if (shouldCaptureRunError(err)) {\n captureRunError(err, \"run\");\n }\n const errorMessage = getRunErrorMessage(err);\n const errorCode =\n err instanceof EngineError ? getEngineRunErrorCode(err) : undefined;\n const details =\n err instanceof EngineError ? getEngineRunErrorDetails(err) : undefined;\n send({\n type: \"error\",\n error: errorMessage,\n ...(errorCode ? { errorCode } : {}),\n ...(details ? { details } : {}),\n ...(err instanceof EngineError && err.upgradeUrl\n ? { upgradeUrl: err.upgradeUrl }\n : {}),\n });\n })\n .finally(async () => {\n // Ordering matters here — this is the atomic-complete boundary.\n // Invariant: once agent_runs.status flips to \"completed\"/\"errored\"\n // in SQL, thread_data for this turn is already durable. This lets\n // reconnecting clients trust the simple rule \"status != running →\n // fetch thread_data\" without polling/retrying for a race window\n // where onComplete was still pending.\n\n // 1. Await the completion callback (thread_data save). Heartbeat is\n // still ticking so the run doesn't look stale to any concurrent\n // /runs/active check while we wait for SQL writes to land.\n let completionError: unknown = null;\n let terminalPersistenceError: unknown = null;\n if (\n onComplete &&\n !(run.status === \"aborted\" && run.abortReason === \"no_progress\")\n ) {\n try {\n const completionRun: ActiveRun = pendingTerminalEvent\n ? { ...run, events: [...run.events, pendingTerminalEvent] }\n : run;\n await onComplete(completionRun);\n } catch (err) {\n completionError = err;\n captureRunError(err, \"completion\");\n console.error(\n \"[run-manager] onComplete callback error:\",\n err instanceof Error ? err.message : err,\n );\n }\n }\n\n // 2. Compute final status. If the completion callback threw, we'd\n // rather mark the run errored than claim success with incomplete\n // thread_data.\n const finalStatus =\n run.status === \"aborted\"\n ? \"aborted\"\n : run.status === \"errored\" || completionError\n ? \"errored\"\n : \"completed\";\n\n // 3. Emit the terminal event only after thread_data is durable. Live\n // SSE clients close on this event and usually fetch thread_data\n // immediately, so emitting it earlier recreates the final-message\n // race this manager is meant to avoid.\n if (finalStatus === \"completed\" || finalStatus === \"errored\") {\n // Choose the terminal event payload (done / the stashed terminal /\n // a synthesized error). NOTE: the `seq` carried by\n // `pendingTerminalEvent` was captured by `send()` at stash time as\n // `run.events.length` and is NOT authoritative — if the runFn emitted\n // any more events before it actually stopped on the abort signal,\n // those events were pushed and reused that same seq. Persisting the\n // terminal event with the stale seq would collide with an\n // already-persisted streaming event and get silently dropped by\n // insertRunEvent's `ON CONFLICT (run_id, seq) DO NOTHING`, so the\n // client would never see the terminal/continuation signal. We always\n // re-stamp the seq at emit time (max-seq+1) just below.\n const terminalEvent: AgentChatEvent =\n finalStatus === \"completed\"\n ? (pendingTerminalEvent?.event ?? { type: \"done\" })\n : pendingTerminalEvent?.event.type === \"error\"\n ? pendingTerminalEvent.event\n : pendingTerminalEvent?.event.type === \"auto_continue\"\n ? // The run was checkpointed at a soft-timeout/loop boundary and\n // is recoverable: the partial turn is in agent_run_events and\n // the continuation run will re-attempt the thread_data save.\n // Even though the completion save failed (finalStatus stays\n // \"errored\" for SQL/diagnostics), re-emit the auto_continue so\n // the client resumes instead of seeing a dead chat.\n pendingTerminalEvent.event\n : {\n type: \"error\",\n error: completionError\n ? \"Agent response could not be saved.\"\n : \"Agent run ended unexpectedly\",\n };\n const last = run.events[run.events.length - 1];\n if (!last || !isTerminalRunEvent(last.event)) {\n // Assign the seq at EMIT time, not at stash time. `run.events` is a\n // contiguous 0-based log, so `run.events.length` is the next free\n // seq and can never collide with an event that was pushed after the\n // terminal event was stashed.\n const terminal: RunEvent = {\n seq: run.events.length,\n event: terminalEvent,\n };\n try {\n await emitRunEvent(terminal, { surfacePersistenceError: true });\n } catch (err) {\n terminalPersistenceError = err;\n captureRunError(err, \"completion\");\n console.error(\n \"[run-manager] terminal event persistence error:\",\n err instanceof Error ? err.message : err,\n );\n }\n }\n }\n for (const subscriber of run.subscribers) {\n run.subscribers.delete(subscriber);\n }\n\n // 4. Stop the heartbeat — all liveness writes are done.\n clearInterval(heartbeatTimer);\n if (softTimeoutTimer) clearTimeout(softTimeoutTimer);\n\n // 5. Persist final status to SQL. Use the conditional write so a zombie\n // run (reaped or displaced while executing) cannot clobber the newer\n // status written by the reaper or a replacement run.\n try {\n await insertRunPromise;\n if (!terminalPersistenceError) {\n await updateRunStatusIfRunning(runId, finalStatus);\n }\n } catch {\n // Best-effort — reapIfStale will eventually clean this up via\n // the heartbeat-stale path.\n }\n\n // 5b. Record terminal failure classification for errored runs so\n // cut-off / failed chats are queryable for pattern analysis. Read\n // the actual error event the run emitted (errorCode + message) so\n // diagnostics reflect the real cause (builder_gateway_timeout,\n // stale_run, context_length_exceeded, completion_error, …).\n if (finalStatus === \"errored\") {\n let errorCode: string | undefined;\n let errorDetail: string | undefined;\n for (let i = run.events.length - 1; i >= 0; i--) {\n const ev = run.events[i].event as {\n type: string;\n error?: string;\n errorCode?: string;\n details?: string;\n };\n if (ev.type === \"error\") {\n errorCode = ev.errorCode;\n errorDetail = ev.error ?? ev.details;\n break;\n }\n }\n if (completionError && !errorCode) {\n errorCode = \"completion_error\";\n errorDetail =\n errorDetail ??\n (completionError instanceof Error\n ? completionError.message\n : String(completionError));\n }\n await setRunError(runId, errorCode ?? \"unknown\", errorDetail);\n }\n\n // 6. Schedule in-memory cleanup + opportunistic old-run pruning.\n setTimeout(() => {\n activeRuns.delete(runId);\n if (threadToRun.get(threadId) === runId) {\n threadToRun.delete(threadId);\n }\n }, CLEANUP_DELAY_MS);\n cleanupOldRuns(\n resolveCompletedRunRetentionMs(),\n resolveErroredRunRetentionMs(),\n ).catch(() => {});\n });\n\n // On Cloudflare Workers, keep the isolate alive for this run\n try {\n const cfCtx = globalThis.__cf_ctx;\n if (cfCtx?.waitUntil) {\n cfCtx.waitUntil(runPromise);\n }\n } catch {\n // Not on Workers — ignore\n }\n\n return run;\n}\n\n/**\n * Subscribe to a run's events starting from `fromSeq`.\n * Returns a ReadableStream that replays buffered events then live-tails.\n * Cancelling the stream only unsubscribes — does NOT abort the agent.\n *\n * Falls back to SQL polling when the run is not in local memory\n * (cross-isolate reconnection on Workers).\n */\nexport function subscribeToRun(\n runId: string,\n fromSeq: number,\n): ReadableStream<Uint8Array> | null {\n const run = activeRuns.get(runId);\n if (run) {\n return subscribeInMemory(run, fromSeq);\n }\n // Not in local memory — try SQL (cross-isolate path)\n return subscribeFromSQL(runId, fromSeq);\n}\n\n/** In-memory subscription (same isolate, fast path) */\nfunction subscribeInMemory(\n run: ActiveRun,\n fromSeq: number,\n): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n let subscriberRef: ((event: RunEvent) => void) | null = null;\n let pingTimer: ReturnType<typeof setInterval> | null = null;\n\n return new ReadableStream({\n start(controller) {\n const ping = () => {\n try {\n controller.enqueue(encoder.encode(`: ping ${Date.now()}\\n\\n`));\n } catch {\n if (subscriberRef) run.subscribers.delete(subscriberRef);\n if (pingTimer) clearInterval(pingTimer);\n }\n };\n ping();\n pingTimer = setInterval(ping, 10_000);\n\n // Replay buffered events from fromSeq\n for (let i = fromSeq; i < run.events.length; i++) {\n try {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ ...run.events[i].event, seq: run.events[i].seq })}\\n\\n`,\n ),\n );\n } catch {\n return;\n }\n }\n\n // If run is already done, close immediately\n if (run.status !== \"running\") {\n if (pingTimer) clearInterval(pingTimer);\n controller.close();\n return;\n }\n\n // Subscribe to live events\n subscriberRef = (event: RunEvent) => {\n try {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ ...event.event, seq: event.seq })}\\n\\n`,\n ),\n );\n // Close stream after terminal events\n if (isTerminalRunEvent(event.event)) {\n run.subscribers.delete(subscriberRef!);\n if (pingTimer) clearInterval(pingTimer);\n controller.close();\n }\n } catch {\n run.subscribers.delete(subscriberRef!);\n }\n };\n\n run.subscribers.add(subscriberRef);\n },\n cancel() {\n // Only unsubscribe — do NOT abort the agent run\n if (subscriberRef) run.subscribers.delete(subscriberRef);\n if (pingTimer) clearInterval(pingTimer);\n },\n });\n}\n\n/** SQL-based subscription (cross-isolate, polling) */\nfunction subscribeFromSQL(\n runId: string,\n fromSeq: number,\n): ReadableStream<Uint8Array> | null {\n const encoder = new TextEncoder();\n let cancelled = false;\n let pollTimer: ReturnType<typeof setTimeout> | null = null;\n let pingTimer: ReturnType<typeof setInterval> | null = null;\n\n return new ReadableStream({\n async start(controller) {\n let lastSeq = fromSeq;\n const ping = () => {\n try {\n controller.enqueue(encoder.encode(`: ping ${Date.now()}\\n\\n`));\n } catch {\n cancelled = true;\n if (pingTimer) clearInterval(pingTimer);\n }\n };\n ping();\n pingTimer = setInterval(ping, 10_000);\n\n const poll = async () => {\n if (cancelled) return;\n try {\n // Read new events from SQL\n const events = await getRunEventsSince(runId, lastSeq);\n for (const { seq, eventData } of events) {\n // Advance the cursor first, before any parse/enqueue branch can\n // `continue`/`return`. Otherwise a single corrupt (unparseable)\n // event row is re-fetched on every poll tick forever, wedging the\n // SSE stream open and never delivering a terminal event.\n lastSeq = seq + 1;\n let parsed: any;\n try {\n parsed = JSON.parse(eventData);\n } catch {\n continue;\n }\n try {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ ...parsed, seq })}\\n\\n`,\n ),\n );\n } catch {\n cancelled = true;\n return;\n }\n\n // Close on terminal events\n if (isTerminalRunEvent(parsed)) {\n if (pingTimer) clearInterval(pingTimer);\n controller.close();\n return;\n }\n }\n\n // Check if run completed (no terminal event but status changed)\n if (events.length === 0) {\n // Opportunistically reap a stale producer before trusting SQL's\n // \"running\" status — otherwise a crashed server leaves us polling\n // forever.\n await reapIfStale(runId).catch(() => {});\n const run = await getRunById(runId);\n if (!run || run.status !== \"running\") {\n // Run ended — do one final event read, then close\n const finalEvents = await getRunEventsSince(runId, lastSeq);\n for (const { seq, eventData } of finalEvents) {\n // Advance first — see the main poll loop above for why.\n lastSeq = seq + 1;\n let parsed: any;\n try {\n parsed = JSON.parse(eventData);\n } catch {\n continue;\n }\n try {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ ...parsed, seq })}\\n\\n`,\n ),\n );\n } catch {\n cancelled = true;\n return;\n }\n if (isTerminalRunEvent(parsed)) {\n if (pingTimer) clearInterval(pingTimer);\n controller.close();\n return;\n }\n }\n if (run?.status === \"aborted\") {\n try {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ type: \"done\", seq: lastSeq })}\\n\\n`,\n ),\n );\n } catch {\n cancelled = true;\n return;\n }\n } else if (run?.status === \"completed\") {\n try {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ type: \"done\", seq: lastSeq })}\\n\\n`,\n ),\n );\n } catch {\n cancelled = true;\n return;\n }\n } else if (run?.status === \"errored\") {\n // The run row was flipped to `errored` but no terminal event\n // was ever persisted — almost always means a reaper's silent\n // `appendTerminalRunEvent(...).catch(() => {})` swallowed a\n // transient DB error, so the user-facing situation is the\n // same as a stale-run reap. Send the friendly event AND try\n // to persist it so future reconnects replay it from SQL\n // rather than regenerating it (the user used to see a bare\n // \"run_terminal_event_missing\" debug string here).\n await ensureTerminalRunEvent(\n runId,\n STALE_RUN_ERROR_EVENT,\n ).catch(() => {});\n try {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({\n ...STALE_RUN_ERROR_EVENT,\n seq: lastSeq,\n })}\\n\\n`,\n ),\n );\n } catch {\n cancelled = true;\n return;\n }\n }\n if (pingTimer) clearInterval(pingTimer);\n controller.close();\n return;\n }\n }\n\n // Schedule next poll\n if (!cancelled) {\n pollTimer = setTimeout(poll, 500);\n }\n } catch {\n // SQL error — close stream\n try {\n if (pingTimer) clearInterval(pingTimer);\n controller.close();\n } catch {}\n }\n };\n\n // Verify run exists before starting poll\n try {\n const run = await getRunById(runId);\n if (!run) {\n if (pingTimer) clearInterval(pingTimer);\n controller.close();\n return;\n }\n } catch {\n controller.close();\n return;\n }\n\n await poll();\n },\n cancel() {\n cancelled = true;\n if (pollTimer) clearTimeout(pollTimer);\n if (pingTimer) clearInterval(pingTimer);\n },\n });\n}\n\n/** Get the active run for a thread (if any) — checks memory then SQL */\nexport function getActiveRunForThread(threadId: string): ActiveRun | null {\n const runId = threadToRun.get(threadId);\n if (runId) {\n const run = activeRuns.get(runId);\n if (run) return run;\n }\n return null;\n}\n\n/**\n * Async version that also checks SQL — for cross-isolate access.\n * Used by the /runs/active endpoint.\n *\n * Returns `heartbeatAt` so the client can independently decide a run is\n * dead even before the server-side stale reap has fired. Returns\n * `lastProgressAt` so the client-side stuck-detector can show a\n * user-visible \"this chat looks stuck\" affordance when a run is alive\n * (heartbeating) but not actually emitting events.\n */\nexport async function getActiveRunForThreadAsync(threadId: string): Promise<{\n runId: string;\n threadId: string;\n turnId: string;\n status: string;\n heartbeatAt: number;\n lastProgressAt: number | null;\n} | null> {\n // Check memory first — return both running AND recently-completed runs\n // that still have events in memory. This allows sub-agent tabs to replay\n // the full conversation from completed runs via SSE.\n const memRun = getActiveRunForThread(threadId);\n if (memRun && (memRun.status === \"running\" || memRun.events.length > 0)) {\n return {\n runId: memRun.runId,\n threadId: memRun.threadId,\n turnId: memRun.turnId,\n status: memRun.status,\n // In-memory means this isolate is the producer. By definition, the\n // heartbeat is fresh as of \"now\" — the client can trust this.\n heartbeatAt: Date.now(),\n // For an in-memory run we don't have a separate \"last event emit\"\n // timestamp tracked in JS — the SQL bump is throttled per-second.\n // Read it back from SQL on demand. For the common case the SQL row\n // is well under 1s old; if it isn't, the stuck-detector will pick\n // it up on the next poll cycle.\n lastProgressAt: await fetchLastProgressAt(memRun.runId),\n };\n }\n // Fall back to SQL — also surface recently terminated runs so the client\n // can reconnect and replay synthesized done/error events instead of\n // retrying the original POST. Without this, a POST that fails after the\n // server already accepted (and finished) the run would re-execute the\n // turn and double-apply mutations: the in-memory branch above already\n // returns terminal runs whose events are still buffered, but the SQL\n // path is the only authority once memory has been evicted.\n try {\n const sqlRun = await getRunByThread(threadId, { includeTerminal: true });\n if (!sqlRun) return null;\n if (sqlRun.status === \"running\") {\n // If the producer is dead (no recent heartbeat), reap before the\n // client can see a stale \"running\" status and enter a reconnect\n // loop it can never exit.\n const reaped = await reapIfStale(sqlRun.id).catch(() => false);\n if (reaped) return null;\n return {\n runId: sqlRun.id,\n threadId: sqlRun.threadId,\n turnId: sqlRun.turnId ?? sqlRun.id,\n status: sqlRun.status,\n heartbeatAt: sqlRun.heartbeatAt ?? sqlRun.startedAt,\n lastProgressAt: sqlRun.lastProgressAt,\n };\n }\n if (sqlRun.status === \"completed\" || sqlRun.status === \"errored\") {\n // Cap how far back we'll surface terminal runs as \"active\". The goal\n // is to catch the recently-completed-but-reconnecting case, not to\n // resurrect ancient turns when the user reopens an old thread.\n //\n // Measure age from the run's terminal timestamp, not its start. A\n // long-running task that ran 11 minutes and completed five seconds\n // ago should still be reachable — the client's disconnect happened\n // around completion, so completion time is what matters for the\n // \"is the user still here waiting?\" question. Fall back to the last\n // heartbeat (older deployments may have unset completed_at) and\n // finally to startedAt for ancient rows.\n const referenceAt =\n sqlRun.completedAt ?? sqlRun.heartbeatAt ?? sqlRun.startedAt;\n const terminalAge = Date.now() - referenceAt;\n if (terminalAge > TERMINAL_RUN_RECONNECT_WINDOW_MS) return null;\n return {\n runId: sqlRun.id,\n threadId: sqlRun.threadId,\n turnId: sqlRun.turnId ?? sqlRun.id,\n status: sqlRun.status,\n heartbeatAt: sqlRun.heartbeatAt ?? sqlRun.startedAt,\n lastProgressAt: sqlRun.lastProgressAt,\n };\n }\n } catch {\n // SQL error — fall through\n }\n return null;\n}\n\nasync function fetchLastProgressAt(runId: string): Promise<number | null> {\n try {\n const run = await getRunById(runId);\n if (!run) return null;\n // `getRunById` returns a narrow projection today; ask for the row via\n // the thread lookup which carries last_progress_at.\n const byThread = await getRunByThread(run.threadId, {\n includeTerminal: true,\n });\n if (byThread && byThread.id === runId) return byThread.lastProgressAt;\n return null;\n } catch {\n return null;\n }\n}\n\n/** Get a run by ID */\nexport function getRun(runId: string): ActiveRun | null {\n return activeRuns.get(runId) ?? null;\n}\n\n/** Explicitly abort a run (e.g. Stop button) */\nexport function abortRun(runId: string, reason: string = \"user\"): boolean {\n const run = activeRuns.get(runId);\n if (run) {\n abortInMemoryRun(run, reason);\n }\n // Also mark as aborted in SQL (for cross-isolate abort on Workers)\n markRunAborted(runId, reason).catch(() => {});\n return !!run;\n}\n\n// Re-export so callers can avoid importing from run-store directly.\nexport { tryClaimRunSlot } from \"./run-store.js\";\n"]}
|
|
1
|
+
{"version":3,"file":"run-manager.js","sourceRoot":"","sources":["../../src/agent/run-manager.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,E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\"./engine/types.js\";\nimport { captureError } from \"../server/capture-error.js\";\nimport {\n insertRun,\n insertRunEvent,\n updateRunStatusIfRunning,\n markRunAborted,\n getRunAbortState,\n getRunStatus,\n getRunEventsSince,\n getRunById,\n getRunByThread,\n cleanupOldRuns,\n updateRunHeartbeat,\n bumpRunProgress,\n reapIfStale,\n reapUnclaimedBackgroundRun,\n ensureTerminalRunEvent,\n setRunError,\n STALE_RUN_ERROR_EVENT,\n} from \"./run-store.js\";\n\nexport interface ActiveRun {\n runId: string;\n threadId: string;\n /** Logical-turn identity (see StartRunOptions.turnId). Defaults to runId. */\n turnId: string;\n events: RunEvent[];\n status: RunStatus;\n subscribers: Set<(event: RunEvent) => void>;\n abort: AbortController;\n abortReason?: string;\n startedAt: number;\n}\n\nconst activeRuns = new Map<string, ActiveRun>();\nconst threadToRun = new Map<string, string>();\n\n/** How long to keep completed runs in memory before cleanup (5 min) */\nconst CLEANUP_DELAY_MS = 5 * 60 * 1000;\n\n/**\n * Default run chunk budget for hosted/serverless deploys.\n *\n * This MUST fire before the two upstream hard walls that otherwise kill a run\n * mid-turn with no chance to hand off:\n * 1. The Builder model gateway hard-caps a single model call at 45s\n * (builder-engine.ts MAX_BUILDER_GATEWAY_TIMEOUT_MS) — not raisable.\n * 2. Serverless functions are hard-killed around 60-65s (the heartbeat then\n * reaps the row as a stale_run).\n * Production data showed every cutoff landing in the 44-70s window with ZERO\n * auto_continue events ever emitted — i.e. the old 45s default raced the 45s\n * gateway and lost, and per-template overrides (e.g. 240_000) pushed it past\n * BOTH walls so it could never fire. 40s leaves ~5s of headroom under the\n * gateway wall to abort, persist the partial turn, write the terminal event,\n * and emit a clean auto_continue so the client resumes seamlessly.\n */\nexport const DEFAULT_HOSTED_RUN_SOFT_TIMEOUT_MS = 40_000;\n\n/**\n * Hard ceiling for the hosted soft timeout. On a hosted runtime the\n * auto_continue soft timeout can never usefully exceed this — the gateway\n * (45s) / function (~60s) walls kill the run first, so a larger configured or\n * env value just guarantees the cutoff is a hard error instead of a graceful\n * hand-off. Any resolved value above this is clamped down when hosted. Local\n * dev (non-hosted) is left alone so long-running local turns aren't chunked.\n *\n * IMPORTANT: this clamp is for the INTERACTIVE / foreground path and must NOT\n * be raised. The foreground POST still rides a synchronous serverless function\n * (~60-65s wall), so 40s remains correct there. The only sanctioned exception\n * is the opt-in `backgroundFunction` mode (see\n * `BACKGROUND_SOFT_TIMEOUT_CEILING_MS`), which runs inside a Netlify background\n * function (no ~60s wall, 15-min budget) and therefore can safely outlast 40s.\n */\nexport const HOSTED_SOFT_TIMEOUT_CEILING_MS = 40_000;\n\n/**\n * Hard ceiling for the soft timeout when a run executes inside a Netlify\n * background function (any deployed function whose name ends in `-background`).\n * Background functions return 202 immediately and run detached for up to 15\n * minutes, so the ~60s synchronous function wall that 40s defends against does\n * NOT apply. 13 minutes leaves ~2 min of headroom under Netlify's 15-min hard\n * kill to abort, persist the partial turn, write the terminal event, and (for\n * the rare >13-min turn) self-fire another background continuation.\n *\n * This ceiling is used ONLY when a caller explicitly opts in with\n * `backgroundFunction: true`. It does not change the foreground/interactive\n * ceiling and does not fire unless the durable-background path dispatched the\n * run into a background function. Per the design doc Guardrail, the 40s\n * interactive clamp stays correct for every non-background run.\n */\nexport const BACKGROUND_SOFT_TIMEOUT_CEILING_MS = 13 * 60_000; // 780_000\n\n/**\n * Default soft-timeout budget for a background-function run when the caller\n * does not pass an explicit `softTimeoutMs`. Same value as the ceiling — we\n * want a background turn to use nearly its whole 15-min budget before handing\n * off to a chained background continuation.\n */\nexport const DEFAULT_BACKGROUND_RUN_SOFT_TIMEOUT_MS =\n BACKGROUND_SOFT_TIMEOUT_CEILING_MS;\n\n/** Default SQL retention for completed run event logs (24 hours). */\nexport const DEFAULT_COMPLETED_RUN_RETENTION_MS = 24 * 60 * 60 * 1000;\n\n/**\n * Default SQL retention for errored/aborted run event logs (7 days). Kept\n * longer than completed runs so cut-off / failed chats survive for pattern\n * analysis (listErroredRuns) — these are rare and small, and they are exactly\n * the runs we need to study to keep hardening reliability.\n */\nexport const DEFAULT_ERRORED_RUN_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;\n\n/**\n * How recently a terminal run must have started for `/runs/active` to surface\n * it. Reconnect after this window won't replay the run — typical real-world\n * disconnects resolve in seconds, so 10 minutes is generous while keeping us\n * from resurrecting ancient turns when the user reopens an old thread.\n */\nexport const TERMINAL_RUN_RECONNECT_WINDOW_MS = 10 * 60 * 1000;\n\nconst PROVIDER_RATE_LIMITED_ERROR_CODE = \"provider_rate_limited\";\n\nfunction getRunErrorMessage(err: unknown): string {\n if (\n typeof err === \"object\" &&\n err !== null &&\n \"message\" in err &&\n typeof err.message === \"string\" &&\n err.message.trim().length > 0\n ) {\n return err.message;\n }\n return \"Unknown error\";\n}\n\nfunction getEngineRunErrorCode(err: EngineError): string | undefined {\n if (err.errorCode) return err.errorCode;\n if (err.statusCode === 429) return PROVIDER_RATE_LIMITED_ERROR_CODE;\n return undefined;\n}\n\nfunction getEngineRunErrorDetails(err: EngineError): string | undefined {\n if (err.statusCode === 429) return err.message;\n return undefined;\n}\n\nfunction shouldCaptureRunError(err: unknown): boolean {\n if (!(err instanceof EngineError)) return true;\n const errorCode = getEngineRunErrorCode(err);\n if (!errorCode) return true;\n const normalizedCode = errorCode.toLowerCase();\n return (\n !normalizedCode.startsWith(\"credits-limit\") &&\n normalizedCode !== \"provider_rate_limited\" &&\n normalizedCode !== \"rate_limit_exceeded\"\n );\n}\n\nexport interface StartRunOptions {\n /** Optional internal run chunk budget. When reached, the framework emits an\n * auto-continuation signal instead of a user-facing timeout. Leave unset for\n * no framework-imposed run timeout. */\n softTimeoutMs?: number;\n /** Opt into the hosted/serverless default chunk budget. Only callers with\n * automatic continuation support should enable this. */\n useHostedSoftTimeoutDefault?: boolean;\n /** Stable identity for the logical assistant turn this run belongs to. A\n * turn may span several continuation runs (each chunk is its own run); they\n * share one `turnId` so the durable assistant message can be folded across\n * them instead of dropped per-run. Defaults to the runId (turn == run). */\n turnId?: string;\n /**\n * Opt into the durable-background-function soft-timeout regime for THIS run\n * only. When true, `resolveRunSoftTimeoutMs` lifts the hosted ceiling from\n * 40s to ~13min (`BACKGROUND_SOFT_TIMEOUT_CEILING_MS`) because the run is\n * executing inside a Netlify background function (no ~60s wall). Off by\n * default — the foreground/interactive path never sets this, so its 40s\n * clamp is unchanged. See the design doc + the durable-background dispatch\n * decision in production-agent.ts.\n */\n backgroundFunction?: boolean;\n}\n\nexport interface ResolveRunSoftTimeoutOptions {\n useHostedDefault?: boolean;\n /**\n * Resolve the soft timeout for a run executing inside a Netlify background\n * function. Lifts the hosted clamp to `BACKGROUND_SOFT_TIMEOUT_CEILING_MS`\n * (~13min) for this invocation only and, when no override/env is supplied,\n * defaults to `DEFAULT_BACKGROUND_RUN_SOFT_TIMEOUT_MS`. Does NOT change the\n * foreground ceiling. Off by default.\n */\n backgroundFunction?: boolean;\n}\n\nfunction isHostedRuntime(): 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\nexport function resolveRunSoftTimeoutMs(\n overrideMs?: number,\n options?: ResolveRunSoftTimeoutOptions,\n): number {\n const hosted = isHostedRuntime();\n const background = options?.backgroundFunction === true;\n // The interactive/foreground ceiling is 40s — the synchronous serverless\n // function wall. A background-function run (opt-in only) has no ~60s wall, so\n // it is allowed to outlast that and is clamped to the larger 13-min ceiling\n // instead. The 40s clamp for non-background hosted runs is unchanged.\n const ceiling = background\n ? BACKGROUND_SOFT_TIMEOUT_CEILING_MS\n : HOSTED_SOFT_TIMEOUT_CEILING_MS;\n // A configured/env soft timeout that exceeds the upstream walls can never\n // actually fire (the gateway/function kills the run first), so clamp it down\n // on hosted runtimes. This is what makes auto_continue reach the client\n // instead of the run dying as builder_gateway_timeout / stale_run. `0` means\n // \"disabled\" and is never clamped up.\n const clampHosted = (ms: number): number =>\n hosted && ms > ceiling ? ceiling : ms;\n\n if (typeof overrideMs === \"number\" && Number.isFinite(overrideMs)) {\n return clampHosted(Math.max(0, overrideMs));\n }\n const envValue = process.env.AGENT_RUN_SOFT_TIMEOUT_MS;\n if (envValue !== undefined) {\n const raw = Number(envValue);\n if (Number.isFinite(raw) && raw >= 0) return clampHosted(raw);\n }\n // A background-function run uses the full background budget by default; the\n // foreground default (40s) is unchanged.\n if (background) {\n return hosted ? DEFAULT_BACKGROUND_RUN_SOFT_TIMEOUT_MS : 0;\n }\n return options?.useHostedDefault && hosted\n ? DEFAULT_HOSTED_RUN_SOFT_TIMEOUT_MS\n : 0;\n}\n\nexport function resolveCompletedRunRetentionMs(): number {\n const envValue = process.env.AGENT_RUN_RETENTION_MS;\n if (envValue !== undefined) {\n const raw = Number(envValue);\n if (Number.isFinite(raw) && raw >= 0) return raw;\n }\n return DEFAULT_COMPLETED_RUN_RETENTION_MS;\n}\n\nexport function resolveErroredRunRetentionMs(): number {\n const envValue = process.env.AGENT_ERRORED_RUN_RETENTION_MS;\n if (envValue !== undefined) {\n const raw = Number(envValue);\n if (Number.isFinite(raw) && raw >= 0) return raw;\n }\n return DEFAULT_ERRORED_RUN_RETENTION_MS;\n}\n\nfunction isTerminalRunEvent(event: AgentChatEvent): boolean {\n return (\n event.type === \"done\" ||\n event.type === \"error\" ||\n event.type === \"missing_api_key\" ||\n event.type === \"loop_limit\" ||\n event.type === \"auto_continue\"\n );\n}\n\nfunction abortInMemoryRun(run: ActiveRun, reason: string = \"user\") {\n run.abortReason = reason;\n run.status = \"aborted\";\n if (threadToRun.get(run.threadId) === run.runId) {\n threadToRun.delete(run.threadId);\n }\n run.abort.abort(reason);\n for (const subscriber of run.subscribers) {\n try {\n subscriber({ seq: run.events.length, event: { type: \"done\" } });\n } catch {\n // ignore — subscriber is being removed below\n }\n }\n run.subscribers.clear();\n}\n\n/**\n * Start a new agent run in the background.\n * `runFn` receives a `send` callback and an `AbortSignal`.\n * The run continues even if all SSE subscribers disconnect.\n *\n * Events are persisted to SQL for cross-isolate access (Cloudflare Workers).\n */\nexport function startRun(\n runId: string,\n threadId: string,\n runFn: (\n send: (event: AgentChatEvent) => void,\n signal: AbortSignal,\n ) => Promise<void>,\n onComplete?: (run: ActiveRun) => void | Promise<void>,\n options?: StartRunOptions,\n): ActiveRun {\n // If there's already a run for this thread, abort it\n const existingRunId = threadToRun.get(threadId);\n if (existingRunId) {\n abortRun(existingRunId);\n }\n\n const abort = new AbortController();\n let softTimedOut = false;\n const run: ActiveRun = {\n runId,\n threadId,\n turnId: options?.turnId ?? runId,\n events: [],\n status: \"running\",\n subscribers: new Set(),\n abort,\n startedAt: Date.now(),\n };\n\n activeRuns.set(runId, run);\n threadToRun.set(threadId, runId);\n\n // Persist run to SQL without blocking the response. Keep the promise so\n // final status cannot race ahead of a slow initial INSERT and then get\n // overwritten by a late row stuck at status='running'.\n const insertRunPromise = insertRun(runId, threadId, options?.turnId).catch(\n () => {},\n );\n\n // Per-run event persistence chain: events are chained so SQL inserts commit\n // in seq order. Without this, a fast seq=5 commit before a slow seq=4 means\n // the SQL poller advances its cursor past seq=4 (lastSeq = 5+1 = 6) and\n // reconnecting clients permanently miss that event (silent gap). Chaining\n // per run ensures order without blocking the fast in-memory SSE path.\n let persistenceChain: Promise<void> = Promise.resolve();\n\n // Throttle the durable progress timestamp to at most once per second so\n // a chatty token-by-token stream doesn't translate into one DB write per\n // chunk. The stuck-detector threshold is on the order of tens of seconds,\n // so 1s resolution is plenty.\n let lastProgressBumpAt = 0;\n const bumpProgressIfDue = () => {\n const now = Date.now();\n if (now - lastProgressBumpAt < 1000) return;\n lastProgressBumpAt = now;\n bumpRunProgress(runId).catch(() => {});\n };\n\n // Periodic SQL abort check interval (for cross-isolate abort on Workers).\n // Also self-aborts when our row is no longer status='running' — catches the\n // false-stale-reap zombie scenario where the reaper flipped the row while\n // this isolate was briefly unable to heartbeat (DB latency / GC pause).\n let lastAbortCheck = Date.now() - 3000;\n const checkSqlAbort = () => {\n const now = Date.now();\n if (now - lastAbortCheck < 3000) return;\n lastAbortCheck = now;\n getRunAbortState(runId)\n .then(async (state) => {\n if (state.aborted && !abort.signal.aborted) {\n abortInMemoryRun(run, state.reason ?? \"user\");\n return;\n }\n // If the row is no longer 'running' (reaped / replaced) and we're\n // still executing, self-abort so we stop executing and don't overwrite\n // the newer state with our terminal write.\n if (!abort.signal.aborted) {\n const status = await getRunStatus(runId);\n if (status !== null && status !== \"running\") {\n abortInMemoryRun(run, \"displaced\");\n }\n }\n })\n .catch(() => {});\n };\n\n // Heartbeat: bump heartbeat_at every 1.5s so watchers can detect a dead\n // producer (process crash, HMR restart, isolate eviction) quickly and\n // reap the row. Paired with RUN_STALE_MS (6s) — 4x the interval to\n // tolerate transient DB slowness without false positives.\n const heartbeatTimer: ReturnType<typeof setInterval> = setInterval(() => {\n updateRunHeartbeat(runId).catch(() => {});\n checkSqlAbort();\n }, 1500);\n const softTimeoutMs = resolveRunSoftTimeoutMs(options?.softTimeoutMs, {\n useHostedDefault: options?.useHostedSoftTimeoutDefault === true,\n backgroundFunction: options?.backgroundFunction === true,\n });\n const softTimeoutTimer =\n softTimeoutMs > 0\n ? setTimeout(() => {\n if (run.status !== \"running\" || abort.signal.aborted) return;\n softTimedOut = true;\n send({\n type: \"auto_continue\",\n reason: \"run_timeout\",\n });\n abort.abort();\n }, softTimeoutMs)\n : null;\n let pendingTerminalEvent: RunEvent | null = null;\n\n const captureRunError = (error: unknown, phase: \"run\" | \"completion\") => {\n captureError(error, {\n route: \"/_agent-native/agent-chat\",\n tags: {\n source: \"agent-run-manager\",\n phase,\n runStatus: run.status,\n softTimedOut: softTimedOut ? \"true\" : \"false\",\n abortReason: run.abortReason,\n errorCode: error instanceof EngineError ? error.errorCode : undefined,\n },\n extra: {\n runId,\n threadId,\n eventCount: run.events.length,\n startedAt: run.startedAt,\n softTimeoutMs,\n },\n contexts: {\n agentRun: {\n runId,\n threadId,\n status: run.status,\n phase,\n eventCount: run.events.length,\n startedAt: run.startedAt,\n softTimeoutMs,\n softTimedOut,\n abortReason: run.abortReason,\n },\n },\n });\n };\n\n const emitRunEvent = (\n runEvent: RunEvent,\n options?: { surfacePersistenceError?: boolean },\n ): Promise<void> => {\n run.events.push(runEvent);\n\n // Notify in-memory subscribers (same isolate, fast path)\n for (const subscriber of run.subscribers) {\n try {\n subscriber(runEvent);\n } catch {\n run.subscribers.delete(subscriber);\n }\n }\n\n // Bump the durable progress timestamp. Distinct from the heartbeat:\n // heartbeat = \"process is up\", progress = \"real work is happening.\" The\n // gap between them is what the client-side stuck-detector reads to tell\n // a hung run from a healthy one.\n bumpProgressIfDue();\n\n // Persist event to SQL. Events are chained through persistenceChain so\n // inserts commit in seq order — an out-of-order commit would advance the\n // SQL poller's cursor past the slow row, permanently dropping it for\n // reconnecting clients. Terminal events surface persistence errors so the\n // caller can decide how to handle a failed final write.\n const thisInsert = persistenceChain.then(() =>\n insertRunEvent(runId, runEvent.seq, JSON.stringify(runEvent.event)),\n );\n persistenceChain = thisInsert.catch(() => {});\n const persistence = thisInsert;\n if (!options?.surfacePersistenceError) {\n persistence.catch(() => {});\n }\n\n checkSqlAbort();\n return persistence;\n };\n\n const send = (event: AgentChatEvent) => {\n if (run.status === \"aborted\" && abort.signal.aborted) return;\n\n const runEvent: RunEvent = { seq: run.events.length, event };\n if (isTerminalRunEvent(event)) {\n pendingTerminalEvent = runEvent;\n return;\n }\n\n emitRunEvent(runEvent);\n };\n\n // Run in background — intentionally detached from any HTTP connection\n const runPromise = runFn(send, abort.signal)\n .then(() => {\n if (abort.signal.aborted) {\n run.status = softTimedOut ? \"completed\" : \"aborted\";\n return;\n }\n run.status = \"completed\";\n })\n .catch((err) => {\n // Don't surface abort errors — the run was intentionally stopped\n if (abort.signal.aborted) {\n run.status = softTimedOut ? \"completed\" : \"aborted\";\n return;\n }\n run.status = \"errored\";\n if (shouldCaptureRunError(err)) {\n captureRunError(err, \"run\");\n }\n const errorMessage = getRunErrorMessage(err);\n const errorCode =\n err instanceof EngineError ? getEngineRunErrorCode(err) : undefined;\n const details =\n err instanceof EngineError ? getEngineRunErrorDetails(err) : undefined;\n send({\n type: \"error\",\n error: errorMessage,\n ...(errorCode ? { errorCode } : {}),\n ...(details ? { details } : {}),\n ...(err instanceof EngineError && err.upgradeUrl\n ? { upgradeUrl: err.upgradeUrl }\n : {}),\n });\n })\n .finally(async () => {\n // Ordering matters here — this is the atomic-complete boundary.\n // Invariant: once agent_runs.status flips to \"completed\"/\"errored\"\n // in SQL, thread_data for this turn is already durable. This lets\n // reconnecting clients trust the simple rule \"status != running →\n // fetch thread_data\" without polling/retrying for a race window\n // where onComplete was still pending.\n\n // 1. Await the completion callback (thread_data save). Heartbeat is\n // still ticking so the run doesn't look stale to any concurrent\n // /runs/active check while we wait for SQL writes to land.\n let completionError: unknown = null;\n let terminalPersistenceError: unknown = null;\n if (\n onComplete &&\n !(run.status === \"aborted\" && run.abortReason === \"no_progress\")\n ) {\n try {\n const completionRun: ActiveRun = pendingTerminalEvent\n ? { ...run, events: [...run.events, pendingTerminalEvent] }\n : run;\n await onComplete(completionRun);\n } catch (err) {\n completionError = err;\n captureRunError(err, \"completion\");\n console.error(\n \"[run-manager] onComplete callback error:\",\n err instanceof Error ? err.message : err,\n );\n }\n }\n\n // 2. Compute final status. If the completion callback threw, we'd\n // rather mark the run errored than claim success with incomplete\n // thread_data.\n const finalStatus =\n run.status === \"aborted\"\n ? \"aborted\"\n : run.status === \"errored\" || completionError\n ? \"errored\"\n : \"completed\";\n\n // 3. Emit the terminal event only after thread_data is durable. Live\n // SSE clients close on this event and usually fetch thread_data\n // immediately, so emitting it earlier recreates the final-message\n // race this manager is meant to avoid.\n if (finalStatus === \"completed\" || finalStatus === \"errored\") {\n // Choose the terminal event payload (done / the stashed terminal /\n // a synthesized error). NOTE: the `seq` carried by\n // `pendingTerminalEvent` was captured by `send()` at stash time as\n // `run.events.length` and is NOT authoritative — if the runFn emitted\n // any more events before it actually stopped on the abort signal,\n // those events were pushed and reused that same seq. Persisting the\n // terminal event with the stale seq would collide with an\n // already-persisted streaming event and get silently dropped by\n // insertRunEvent's `ON CONFLICT (run_id, seq) DO NOTHING`, so the\n // client would never see the terminal/continuation signal. We always\n // re-stamp the seq at emit time (max-seq+1) just below.\n const terminalEvent: AgentChatEvent =\n finalStatus === \"completed\"\n ? (pendingTerminalEvent?.event ?? { type: \"done\" })\n : pendingTerminalEvent?.event.type === \"error\"\n ? pendingTerminalEvent.event\n : pendingTerminalEvent?.event.type === \"auto_continue\"\n ? // The run was checkpointed at a soft-timeout/loop boundary and\n // is recoverable: the partial turn is in agent_run_events and\n // the continuation run will re-attempt the thread_data save.\n // Even though the completion save failed (finalStatus stays\n // \"errored\" for SQL/diagnostics), re-emit the auto_continue so\n // the client resumes instead of seeing a dead chat.\n pendingTerminalEvent.event\n : {\n type: \"error\",\n error: completionError\n ? \"Agent response could not be saved.\"\n : \"Agent run ended unexpectedly\",\n };\n const last = run.events[run.events.length - 1];\n if (!last || !isTerminalRunEvent(last.event)) {\n // Assign the seq at EMIT time, not at stash time. `run.events` is a\n // contiguous 0-based log, so `run.events.length` is the next free\n // seq and can never collide with an event that was pushed after the\n // terminal event was stashed.\n const terminal: RunEvent = {\n seq: run.events.length,\n event: terminalEvent,\n };\n try {\n await emitRunEvent(terminal, { surfacePersistenceError: true });\n } catch (err) {\n terminalPersistenceError = err;\n captureRunError(err, \"completion\");\n console.error(\n \"[run-manager] terminal event persistence error:\",\n err instanceof Error ? err.message : err,\n );\n }\n }\n }\n for (const subscriber of run.subscribers) {\n run.subscribers.delete(subscriber);\n }\n\n // 4. Stop the heartbeat — all liveness writes are done.\n clearInterval(heartbeatTimer);\n if (softTimeoutTimer) clearTimeout(softTimeoutTimer);\n\n // 5. Persist final status to SQL. Use the conditional write so a zombie\n // run (reaped or displaced while executing) cannot clobber the newer\n // status written by the reaper or a replacement run.\n try {\n await insertRunPromise;\n if (!terminalPersistenceError) {\n await updateRunStatusIfRunning(runId, finalStatus);\n }\n } catch {\n // Best-effort — reapIfStale will eventually clean this up via\n // the heartbeat-stale path.\n }\n\n // 5b. Record terminal failure classification for errored runs so\n // cut-off / failed chats are queryable for pattern analysis. Read\n // the actual error event the run emitted (errorCode + message) so\n // diagnostics reflect the real cause (builder_gateway_timeout,\n // stale_run, context_length_exceeded, completion_error, …).\n if (finalStatus === \"errored\") {\n let errorCode: string | undefined;\n let errorDetail: string | undefined;\n for (let i = run.events.length - 1; i >= 0; i--) {\n const ev = run.events[i].event as {\n type: string;\n error?: string;\n errorCode?: string;\n details?: string;\n };\n if (ev.type === \"error\") {\n errorCode = ev.errorCode;\n errorDetail = ev.error ?? ev.details;\n break;\n }\n }\n if (completionError && !errorCode) {\n errorCode = \"completion_error\";\n errorDetail =\n errorDetail ??\n (completionError instanceof Error\n ? completionError.message\n : String(completionError));\n }\n await setRunError(runId, errorCode ?? \"unknown\", errorDetail);\n }\n\n // 6. Schedule in-memory cleanup + opportunistic old-run pruning.\n setTimeout(() => {\n activeRuns.delete(runId);\n if (threadToRun.get(threadId) === runId) {\n threadToRun.delete(threadId);\n }\n }, CLEANUP_DELAY_MS);\n cleanupOldRuns(\n resolveCompletedRunRetentionMs(),\n resolveErroredRunRetentionMs(),\n ).catch(() => {});\n });\n\n // On Cloudflare Workers, keep the isolate alive for this run\n try {\n const cfCtx = globalThis.__cf_ctx;\n if (cfCtx?.waitUntil) {\n cfCtx.waitUntil(runPromise);\n }\n } catch {\n // Not on Workers — ignore\n }\n\n return run;\n}\n\n/**\n * Subscribe to a run's events starting from `fromSeq`.\n * Returns a ReadableStream that replays buffered events then live-tails.\n * Cancelling the stream only unsubscribes — does NOT abort the agent.\n *\n * Falls back to SQL polling when the run is not in local memory\n * (cross-isolate reconnection on Workers).\n */\nexport function subscribeToRun(\n runId: string,\n fromSeq: number,\n): ReadableStream<Uint8Array> | null {\n const run = activeRuns.get(runId);\n if (run) {\n return subscribeInMemory(run, fromSeq);\n }\n // Not in local memory — try SQL (cross-isolate path)\n return subscribeFromSQL(runId, fromSeq);\n}\n\n/** In-memory subscription (same isolate, fast path) */\nfunction subscribeInMemory(\n run: ActiveRun,\n fromSeq: number,\n): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n let subscriberRef: ((event: RunEvent) => void) | null = null;\n let pingTimer: ReturnType<typeof setInterval> | null = null;\n\n return new ReadableStream({\n start(controller) {\n const ping = () => {\n try {\n controller.enqueue(encoder.encode(`: ping ${Date.now()}\\n\\n`));\n } catch {\n if (subscriberRef) run.subscribers.delete(subscriberRef);\n if (pingTimer) clearInterval(pingTimer);\n }\n };\n ping();\n pingTimer = setInterval(ping, 10_000);\n\n // Replay buffered events from fromSeq\n for (let i = fromSeq; i < run.events.length; i++) {\n try {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ ...run.events[i].event, seq: run.events[i].seq })}\\n\\n`,\n ),\n );\n } catch {\n return;\n }\n }\n\n // If run is already done, close immediately\n if (run.status !== \"running\") {\n if (pingTimer) clearInterval(pingTimer);\n controller.close();\n return;\n }\n\n // Subscribe to live events\n subscriberRef = (event: RunEvent) => {\n try {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ ...event.event, seq: event.seq })}\\n\\n`,\n ),\n );\n // Close stream after terminal events\n if (isTerminalRunEvent(event.event)) {\n run.subscribers.delete(subscriberRef!);\n if (pingTimer) clearInterval(pingTimer);\n controller.close();\n }\n } catch {\n run.subscribers.delete(subscriberRef!);\n }\n };\n\n run.subscribers.add(subscriberRef);\n },\n cancel() {\n // Only unsubscribe — do NOT abort the agent run\n if (subscriberRef) run.subscribers.delete(subscriberRef);\n if (pingTimer) clearInterval(pingTimer);\n },\n });\n}\n\n/** SQL-based subscription (cross-isolate, polling) */\nfunction subscribeFromSQL(\n runId: string,\n fromSeq: number,\n): ReadableStream<Uint8Array> | null {\n const encoder = new TextEncoder();\n let cancelled = false;\n let pollTimer: ReturnType<typeof setTimeout> | null = null;\n let pingTimer: ReturnType<typeof setInterval> | null = null;\n\n return new ReadableStream({\n async start(controller) {\n let lastSeq = fromSeq;\n const ping = () => {\n try {\n controller.enqueue(encoder.encode(`: ping ${Date.now()}\\n\\n`));\n } catch {\n cancelled = true;\n if (pingTimer) clearInterval(pingTimer);\n }\n };\n ping();\n pingTimer = setInterval(ping, 10_000);\n\n const poll = async () => {\n if (cancelled) return;\n try {\n // Read new events from SQL\n const events = await getRunEventsSince(runId, lastSeq);\n for (const { seq, eventData } of events) {\n // Advance the cursor first, before any parse/enqueue branch can\n // `continue`/`return`. Otherwise a single corrupt (unparseable)\n // event row is re-fetched on every poll tick forever, wedging the\n // SSE stream open and never delivering a terminal event.\n lastSeq = seq + 1;\n let parsed: any;\n try {\n parsed = JSON.parse(eventData);\n } catch {\n continue;\n }\n try {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ ...parsed, seq })}\\n\\n`,\n ),\n );\n } catch {\n cancelled = true;\n return;\n }\n\n // Close on terminal events\n if (isTerminalRunEvent(parsed)) {\n if (pingTimer) clearInterval(pingTimer);\n controller.close();\n return;\n }\n }\n\n // Check if run completed (no terminal event but status changed)\n if (events.length === 0) {\n // Opportunistically reap a stale producer before trusting SQL's\n // \"running\" status — otherwise a crashed server leaves us polling\n // forever.\n await reapIfStale(runId).catch(() => {});\n const run = await getRunById(runId);\n if (!run || run.status !== \"running\") {\n // Run ended — do one final event read, then close\n const finalEvents = await getRunEventsSince(runId, lastSeq);\n for (const { seq, eventData } of finalEvents) {\n // Advance first — see the main poll loop above for why.\n lastSeq = seq + 1;\n let parsed: any;\n try {\n parsed = JSON.parse(eventData);\n } catch {\n continue;\n }\n try {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ ...parsed, seq })}\\n\\n`,\n ),\n );\n } catch {\n cancelled = true;\n return;\n }\n if (isTerminalRunEvent(parsed)) {\n if (pingTimer) clearInterval(pingTimer);\n controller.close();\n return;\n }\n }\n if (run?.status === \"aborted\") {\n try {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ type: \"done\", seq: lastSeq })}\\n\\n`,\n ),\n );\n } catch {\n cancelled = true;\n return;\n }\n } else if (run?.status === \"completed\") {\n try {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({ type: \"done\", seq: lastSeq })}\\n\\n`,\n ),\n );\n } catch {\n cancelled = true;\n return;\n }\n } else if (run?.status === \"errored\") {\n // The run row was flipped to `errored` but no terminal event\n // was ever persisted — almost always means a reaper's silent\n // `appendTerminalRunEvent(...).catch(() => {})` swallowed a\n // transient DB error, so the user-facing situation is the\n // same as a stale-run reap. Send the friendly event AND try\n // to persist it so future reconnects replay it from SQL\n // rather than regenerating it (the user used to see a bare\n // \"run_terminal_event_missing\" debug string here).\n await ensureTerminalRunEvent(\n runId,\n STALE_RUN_ERROR_EVENT,\n ).catch(() => {});\n try {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({\n ...STALE_RUN_ERROR_EVENT,\n seq: lastSeq,\n })}\\n\\n`,\n ),\n );\n } catch {\n cancelled = true;\n return;\n }\n }\n if (pingTimer) clearInterval(pingTimer);\n controller.close();\n return;\n }\n }\n\n // Schedule next poll\n if (!cancelled) {\n pollTimer = setTimeout(poll, 500);\n }\n } catch {\n // SQL error — close stream\n try {\n if (pingTimer) clearInterval(pingTimer);\n controller.close();\n } catch {}\n }\n };\n\n // Verify run exists before starting poll\n try {\n const run = await getRunById(runId);\n if (!run) {\n if (pingTimer) clearInterval(pingTimer);\n controller.close();\n return;\n }\n } catch {\n controller.close();\n return;\n }\n\n await poll();\n },\n cancel() {\n cancelled = true;\n if (pollTimer) clearTimeout(pollTimer);\n if (pingTimer) clearInterval(pingTimer);\n },\n });\n}\n\n/** Get the active run for a thread (if any) — checks memory then SQL */\nexport function getActiveRunForThread(threadId: string): ActiveRun | null {\n const runId = threadToRun.get(threadId);\n if (runId) {\n const run = activeRuns.get(runId);\n if (run) return run;\n }\n return null;\n}\n\n/**\n * Async version that also checks SQL — for cross-isolate access.\n * Used by the /runs/active endpoint.\n *\n * Returns `heartbeatAt` so the client can independently decide a run is\n * dead even before the server-side stale reap has fired. Returns\n * `lastProgressAt` so the client-side stuck-detector can show a\n * user-visible \"this chat looks stuck\" affordance when a run is alive\n * (heartbeating) but not actually emitting events.\n */\nexport async function getActiveRunForThreadAsync(threadId: string): Promise<{\n runId: string;\n threadId: string;\n turnId: string;\n status: string;\n heartbeatAt: number;\n lastProgressAt: number | null;\n /** How the run was dispatched (NULL/foreground, background, background-processing). */\n dispatchMode?: string | null;\n /**\n * Last reached `_process-run` worker stage as a JSON string\n * `{stage,detail?,at}`. Surfaced so a silent background-worker death is\n * diagnosable from the client WITHOUT the unreadable bg-fn logs.\n */\n diagStage?: string | null;\n} | null> {\n // Check memory first — return both running AND recently-completed runs\n // that still have events in memory. This allows sub-agent tabs to replay\n // the full conversation from completed runs via SSE.\n const memRun = getActiveRunForThread(threadId);\n if (memRun && (memRun.status === \"running\" || memRun.events.length > 0)) {\n return {\n runId: memRun.runId,\n threadId: memRun.threadId,\n turnId: memRun.turnId,\n status: memRun.status,\n // In-memory means this isolate is the producer. By definition, the\n // heartbeat is fresh as of \"now\" — the client can trust this.\n heartbeatAt: Date.now(),\n // For an in-memory run we don't have a separate \"last event emit\"\n // timestamp tracked in JS — the SQL bump is throttled per-second.\n // Read it back from SQL on demand. For the common case the SQL row\n // is well under 1s old; if it isn't, the stuck-detector will pick\n // it up on the next poll cycle.\n lastProgressAt: await fetchLastProgressAt(memRun.runId),\n };\n }\n // Fall back to SQL — also surface recently terminated runs so the client\n // can reconnect and replay synthesized done/error events instead of\n // retrying the original POST. Without this, a POST that fails after the\n // server already accepted (and finished) the run would re-execute the\n // turn and double-apply mutations: the in-memory branch above already\n // returns terminal runs whose events are still buffered, but the SQL\n // path is the only authority once memory has been evicted.\n try {\n const sqlRun = await getRunByThread(threadId, { includeTerminal: true });\n if (!sqlRun) return null;\n if (sqlRun.status === \"running\") {\n // FALLBACK HARDENING: a background-dispatched run that is still UNCLAIMED\n // (dispatch_mode === 'background', never flipped to 'background-processing')\n // past the tight grace means the bg-fn worker never started — a silent\n // async-worker death that the 202-ack inline fallback can't catch. Reap it\n // early and recoverably (background_worker_never_started) so the run no\n // longer hangs for the full 90s window and the client's recoverable-error\n // path can re-drive the turn. Only fires when there is provably no live\n // worker; a claimed/heartbeating run is left alone by the conditional SQL.\n if (sqlRun.dispatchMode === \"background\") {\n const recovered = await reapUnclaimedBackgroundRun(sqlRun.id).catch(\n () => false,\n );\n if (recovered) return null;\n }\n // If the producer is dead (no recent heartbeat), reap before the\n // client can see a stale \"running\" status and enter a reconnect\n // loop it can never exit.\n const reaped = await reapIfStale(sqlRun.id).catch(() => false);\n if (reaped) return null;\n return {\n runId: sqlRun.id,\n threadId: sqlRun.threadId,\n turnId: sqlRun.turnId ?? sqlRun.id,\n status: sqlRun.status,\n heartbeatAt: sqlRun.heartbeatAt ?? sqlRun.startedAt,\n lastProgressAt: sqlRun.lastProgressAt,\n dispatchMode: sqlRun.dispatchMode,\n diagStage: sqlRun.diagStage,\n };\n }\n if (sqlRun.status === \"completed\" || sqlRun.status === \"errored\") {\n // Cap how far back we'll surface terminal runs as \"active\". The goal\n // is to catch the recently-completed-but-reconnecting case, not to\n // resurrect ancient turns when the user reopens an old thread.\n //\n // Measure age from the run's terminal timestamp, not its start. A\n // long-running task that ran 11 minutes and completed five seconds\n // ago should still be reachable — the client's disconnect happened\n // around completion, so completion time is what matters for the\n // \"is the user still here waiting?\" question. Fall back to the last\n // heartbeat (older deployments may have unset completed_at) and\n // finally to startedAt for ancient rows.\n const referenceAt =\n sqlRun.completedAt ?? sqlRun.heartbeatAt ?? sqlRun.startedAt;\n const terminalAge = Date.now() - referenceAt;\n if (terminalAge > TERMINAL_RUN_RECONNECT_WINDOW_MS) return null;\n return {\n runId: sqlRun.id,\n threadId: sqlRun.threadId,\n turnId: sqlRun.turnId ?? sqlRun.id,\n status: sqlRun.status,\n heartbeatAt: sqlRun.heartbeatAt ?? sqlRun.startedAt,\n lastProgressAt: sqlRun.lastProgressAt,\n dispatchMode: sqlRun.dispatchMode,\n diagStage: sqlRun.diagStage,\n };\n }\n } catch {\n // SQL error — fall through\n }\n return null;\n}\n\nasync function fetchLastProgressAt(runId: string): Promise<number | null> {\n try {\n const run = await getRunById(runId);\n if (!run) return null;\n // `getRunById` returns a narrow projection today; ask for the row via\n // the thread lookup which carries last_progress_at.\n const byThread = await getRunByThread(run.threadId, {\n includeTerminal: true,\n });\n if (byThread && byThread.id === runId) return byThread.lastProgressAt;\n return null;\n } catch {\n return null;\n }\n}\n\n/** Get a run by ID */\nexport function getRun(runId: string): ActiveRun | null {\n return activeRuns.get(runId) ?? null;\n}\n\n/** Explicitly abort a run (e.g. Stop button) */\nexport function abortRun(runId: string, reason: string = \"user\"): boolean {\n const run = activeRuns.get(runId);\n if (run) {\n abortInMemoryRun(run, reason);\n }\n // Also mark as aborted in SQL (for cross-isolate abort on Workers)\n markRunAborted(runId, reason).catch(() => {});\n return !!run;\n}\n\n// Re-export so callers can avoid importing from run-store directly.\nexport { tryClaimRunSlot } from \"./run-store.js\";\n"]}
|
|
@@ -28,6 +28,36 @@ export declare const STALE_RUN_ERROR_EVENT: {
|
|
|
28
28
|
readonly recoverable: true;
|
|
29
29
|
readonly details: "The run heartbeat stopped while the run was still marked running. Partial output and tool calls were preserved when available.";
|
|
30
30
|
};
|
|
31
|
+
/**
|
|
32
|
+
* Terminal error for a background-dispatched run whose worker NEVER claimed it
|
|
33
|
+
* (the foreground fired the self-dispatch, Netlify acked it async with a 202,
|
|
34
|
+
* but the `_process-run` worker never ran far enough to flip
|
|
35
|
+
* `dispatch_mode background → background-processing`). Distinct errorCode so the
|
|
36
|
+
* client (and prod triage) can tell "the worker died silently" apart from "a
|
|
37
|
+
* claimed worker's heartbeat went stale". Recoverable so the client surfaces a
|
|
38
|
+
* retry affordance and re-drives the turn. See `reapUnclaimedBackgroundRun`.
|
|
39
|
+
*/
|
|
40
|
+
export declare const UNCLAIMED_BACKGROUND_RUN_ERROR_EVENT: {
|
|
41
|
+
readonly type: "error";
|
|
42
|
+
readonly error: "The agent run was handed off to a background worker that never started. It was recovered so you can try again.";
|
|
43
|
+
readonly errorCode: "background_worker_never_started";
|
|
44
|
+
readonly recoverable: true;
|
|
45
|
+
readonly details: "A background-dispatched run was acknowledged (HTTP 202) but its worker never claimed the run, so no progress was produced. The run was reaped early (it had no live worker to protect) so the turn can be retried.";
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Grace period before a never-claimed background run (dispatch_mode still
|
|
49
|
+
* 'background', no worker claim) is treated as a dead handoff and reaped.
|
|
50
|
+
*
|
|
51
|
+
* This is intentionally MUCH tighter than `BACKGROUND_RUN_STALE_MS` (90s). The
|
|
52
|
+
* wide 90s window exists ONLY to protect a CLAIMED worker whose heartbeat lags
|
|
53
|
+
* during a slow cold start. A run that is still `dispatch_mode = 'background'`
|
|
54
|
+
* has, by definition, NO worker — nothing to protect — so once a Netlify
|
|
55
|
+
* background function has had a reasonable cold-start window to claim it and
|
|
56
|
+
* hasn't, the handoff is dead and should surface promptly instead of leaving
|
|
57
|
+
* the user staring at a spinner for 90s. 25s comfortably exceeds a normal
|
|
58
|
+
* Netlify Lambda cold start while still failing fast on a silent worker death.
|
|
59
|
+
*/
|
|
60
|
+
export declare const UNCLAIMED_BACKGROUND_RUN_GRACE_MS = 25000;
|
|
31
61
|
/**
|
|
32
62
|
* Persist a zombie tool-call completion to the ledger. Called by the detached
|
|
33
63
|
* promise continuation after `Promise.race` abandons it. Best-effort — never
|
|
@@ -81,6 +111,48 @@ export declare function tryClaimRunSlot(threadId: string, maxStaleMs?: number):
|
|
|
81
111
|
* never throws, since it runs on the completion path that must not fail the run.
|
|
82
112
|
*/
|
|
83
113
|
export declare function setRunError(runId: string, errorCode: string | undefined, errorDetail: string | undefined): Promise<void>;
|
|
114
|
+
/**
|
|
115
|
+
* Diagnostic stage names recorded onto a background run as it moves through the
|
|
116
|
+
* `_process-run` worker pipeline. Each value is the LAST stage successfully
|
|
117
|
+
* reached, so a stuck run's `diag_stage` reveals exactly where it died. Ordered
|
|
118
|
+
* roughly by execution; the literal strings are the client-readable contract.
|
|
119
|
+
*/
|
|
120
|
+
export declare const RUN_DIAG_STAGE: {
|
|
121
|
+
/** The `_process-run` route handler was entered (the request reached Nitro). */
|
|
122
|
+
readonly routeEntered: "route_entered";
|
|
123
|
+
/** HMAC auth + body validation in prepareProcessRunRequest FAILED. */
|
|
124
|
+
readonly authFailed: "auth_failed";
|
|
125
|
+
/** HMAC auth + body validation PASSED; about to invoke the worker handler. */
|
|
126
|
+
readonly authPassed: "auth_passed";
|
|
127
|
+
/** The re-entered agent-chat handler recognized itself as the bg worker. */
|
|
128
|
+
readonly workerEntered: "worker_entered";
|
|
129
|
+
/** The worker won the atomic claim (it owns the run). */
|
|
130
|
+
readonly workerClaimed: "worker_claimed";
|
|
131
|
+
/** The worker LOST the claim (a duplicate delivery already owns the run). */
|
|
132
|
+
readonly workerClaimLost: "worker_claim_lost";
|
|
133
|
+
/** The agent loop started (startRun fired). */
|
|
134
|
+
readonly workerStarted: "worker_started";
|
|
135
|
+
/** The worker threw before/while running the loop (message carried in detail). */
|
|
136
|
+
readonly workerThrew: "worker_threw";
|
|
137
|
+
/** The route handler caught an error from the worker invocation. */
|
|
138
|
+
readonly routeThrew: "route_threw";
|
|
139
|
+
};
|
|
140
|
+
export type RunDiagStage = (typeof RUN_DIAG_STAGE)[keyof typeof RUN_DIAG_STAGE];
|
|
141
|
+
/**
|
|
142
|
+
* Record the last reached pipeline stage (+ optional short detail) for a run.
|
|
143
|
+
*
|
|
144
|
+
* PURPOSE: a Netlify background function's logs are not readable from the build
|
|
145
|
+
* tooling, so when its worker dies silently the run just times out with no clue
|
|
146
|
+
* WHY. This writes the failure stage straight onto the `agent_runs` row, which
|
|
147
|
+
* `/runs/active` and `listRunsForThread` surface to the client — so the next
|
|
148
|
+
* prod run's death cause is readable WITHOUT bg-fn logs. Cheap, additive, and
|
|
149
|
+
* best-effort: it must never throw or perturb the run (it is called on the auth
|
|
150
|
+
* path BEFORE a 401 is returned, and around the worker body).
|
|
151
|
+
*
|
|
152
|
+
* The stored value is a compact JSON `{ stage, detail?, at }` capped to 2 KB so
|
|
153
|
+
* a long stack can't bloat the row.
|
|
154
|
+
*/
|
|
155
|
+
export declare function recordRunDiagnostic(runId: string, stage: RunDiagStage, detail?: string): Promise<void>;
|
|
84
156
|
/** Update the run's liveness heartbeat. Called periodically by run-manager. */
|
|
85
157
|
export declare function updateRunHeartbeat(runId: string): Promise<void>;
|
|
86
158
|
/**
|
|
@@ -96,6 +168,28 @@ export declare function bumpRunProgress(runId: string): Promise<void>;
|
|
|
96
168
|
* Returns true if the row was reaped.
|
|
97
169
|
*/
|
|
98
170
|
export declare function reapIfStale(runId: string, maxStaleMs?: number): Promise<boolean>;
|
|
171
|
+
/**
|
|
172
|
+
* FALLBACK HARDENING for the "dispatched with 202 but the worker never started"
|
|
173
|
+
* case. A background-dispatched run sits in `dispatch_mode = 'background'` until
|
|
174
|
+
* the worker wins `claimBackgroundRun` (which flips it to
|
|
175
|
+
* `background-processing`). If the worker silently dies (e.g. the bg-fn 401s
|
|
176
|
+
* before it can claim), the row stays `background`, never heartbeats again, and
|
|
177
|
+
* — because dispatch returned 202 — the foreground already returned the SSE
|
|
178
|
+
* stream, so the existing fast-fail inline fallback never engaged. The run would
|
|
179
|
+
* otherwise hang for the full 90s background window and then error opaquely.
|
|
180
|
+
*
|
|
181
|
+
* This reaps such a run EARLY and DISTINCTLY: a row that is still unclaimed
|
|
182
|
+
* (`dispatch_mode = 'background'`) past the tight `UNCLAIMED_BACKGROUND_RUN_GRACE_MS`
|
|
183
|
+
* grace is a dead handoff — there is no live worker to protect with the wide
|
|
184
|
+
* window — so we flip it to `errored` with the recoverable
|
|
185
|
+
* `background_worker_never_started` code. The client's existing recoverable-error
|
|
186
|
+
* path then lets the user (or auto-recovery) re-drive the turn. Idempotent and
|
|
187
|
+
* conditional: only an unclaimed, still-running, grace-exceeded row matches, so a
|
|
188
|
+
* claimed worker, a fresh dispatch, or a terminal row is never touched.
|
|
189
|
+
*
|
|
190
|
+
* Returns true when this call reaped the run.
|
|
191
|
+
*/
|
|
192
|
+
export declare function reapUnclaimedBackgroundRun(runId: string): Promise<boolean>;
|
|
99
193
|
export declare function updateRunStatus(runId: string, status: "completed" | "errored" | "aborted"): Promise<void>;
|
|
100
194
|
/**
|
|
101
195
|
* Conditional terminal status write: only updates if the row still belongs to
|
|
@@ -136,6 +230,8 @@ export declare function getRunByThread(threadId: string, options?: {
|
|
|
136
230
|
heartbeatAt: number | null;
|
|
137
231
|
completedAt: number | null;
|
|
138
232
|
lastProgressAt: number | null;
|
|
233
|
+
dispatchMode: string | null;
|
|
234
|
+
diagStage: string | null;
|
|
139
235
|
} | null>;
|
|
140
236
|
export interface AgentRunSummary {
|
|
141
237
|
id: string;
|
|
@@ -148,6 +244,9 @@ export interface AgentRunSummary {
|
|
|
148
244
|
lastProgressAt: number | null;
|
|
149
245
|
errorCode: string | null;
|
|
150
246
|
abortReason: string | null;
|
|
247
|
+
dispatchMode: string | null;
|
|
248
|
+
/** Last reached `_process-run` worker stage (JSON `{stage,detail?,at}`). */
|
|
249
|
+
diagStage: string | null;
|
|
151
250
|
}
|
|
152
251
|
export declare function listRunsForThread(threadId: string, options?: {
|
|
153
252
|
limit?: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-store.d.ts","sourceRoot":"","sources":["../../src/agent/run-store.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAIjD;;;;;;GAMG;AACH,eAAO,MAAM,YAAY,QAAS,CAAC;AAEnC;;;;;;;;;;;;GA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