@agent-native/core 0.132.1 → 0.133.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (456) hide show
  1. package/corpus/README.md +2 -2
  2. package/corpus/core/CHANGELOG.md +198 -0
  3. package/corpus/core/package.json +1 -1
  4. package/corpus/core/src/a2a/correlation.ts +11 -1
  5. package/corpus/core/src/a2a/types.ts +11 -3
  6. package/corpus/core/src/agent/engine/ai-sdk-engine.ts +33 -46
  7. package/corpus/core/src/agent/engine/builder-engine.ts +22 -10
  8. package/corpus/core/src/agent/engine/error-detail.ts +184 -3
  9. package/corpus/core/src/agent/engine/failure-taxonomy.ts +123 -0
  10. package/corpus/core/src/agent/engine/index.ts +8 -0
  11. package/corpus/core/src/agent/engine/registry.ts +92 -8
  12. package/corpus/core/src/agent/engine/translate-ai-sdk.ts +17 -2
  13. package/corpus/core/src/agent/production-agent.ts +13 -33
  14. package/corpus/core/src/agent/run-loop-with-resume.ts +1 -1
  15. package/corpus/core/src/agent/run-manager.ts +43 -14
  16. package/corpus/core/src/agent/run-store.ts +30 -3
  17. package/corpus/core/src/agent/thread-data-builder.ts +36 -4
  18. package/corpus/core/src/chat-threads/store.ts +42 -0
  19. package/corpus/core/src/cli/templates-meta.ts +13 -0
  20. package/corpus/core/src/cli/workspace-dev.ts +1 -0
  21. package/corpus/core/src/client/error-format.ts +12 -0
  22. package/corpus/core/src/client/use-chat-threads.ts +76 -16
  23. package/corpus/core/src/credentials/index.ts +51 -12
  24. package/corpus/core/src/extensions/url-safety.ts +46 -12
  25. package/corpus/core/src/integrations/adapters/slack.ts +32 -10
  26. package/corpus/core/src/integrations/google-docs-poller.ts +12 -1
  27. package/corpus/core/src/integrations/installations-store.ts +30 -0
  28. package/corpus/core/src/integrations/plugin.ts +5 -5
  29. package/corpus/core/src/integrations/types.ts +7 -0
  30. package/corpus/core/src/integrations/webhook-handler.ts +24 -1
  31. package/corpus/core/src/jobs/background-automation-runner.ts +38 -1
  32. package/corpus/core/src/provider-api/index.ts +8 -2
  33. package/corpus/core/src/scripts/call-agent.ts +6 -0
  34. package/corpus/core/src/server/agent-chat-plugin.ts +46 -10
  35. package/corpus/core/src/server/agent-discovery.ts +2 -0
  36. package/corpus/core/src/server/builder-design-systems.ts +21 -0
  37. package/corpus/core/src/server/credential-provider.ts +51 -12
  38. package/corpus/core/src/server/index.ts +1 -0
  39. package/corpus/core/src/server/onboarding-html.ts +37 -2
  40. package/corpus/core/src/shared/reasoning-effort.ts +1 -1
  41. package/corpus/core/src/templates/workspace-core/.agents/skills/a2a-protocol/SKILL.md +11 -0
  42. package/corpus/templates/analytics/app/components/layout/Sidebar.tsx +6 -2
  43. package/corpus/templates/assets/app/components/layout/Sidebar.tsx +39 -19
  44. package/corpus/templates/assets/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
  45. package/corpus/templates/brain/app/components/layout/Sidebar.tsx +30 -3
  46. package/corpus/templates/brain/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
  47. package/corpus/templates/calendar/app/components/layout/AppLayout.tsx +1 -1
  48. package/corpus/templates/calendar/app/components/layout/Sidebar.tsx +54 -25
  49. package/corpus/templates/calendar/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
  50. package/corpus/templates/chat/app/components/layout/Sidebar.tsx +30 -3
  51. package/corpus/templates/chat/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
  52. package/corpus/templates/clips/app/components/library/library-layout.tsx +37 -21
  53. package/corpus/templates/clips/changelog/2026-07-30-meeting-microphone-transcription-works-reliably-from-the-fir.md +6 -0
  54. package/corpus/templates/clips/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
  55. package/corpus/templates/clips/desktop/src/hooks/useMediaDevices.ts +1 -1
  56. package/corpus/templates/clips/desktop/src/lib/media-capture-constraints.ts +1 -1
  57. package/corpus/templates/clips/desktop/src-tauri/src/native_screen/custom_capture.rs +13 -0
  58. package/corpus/templates/clips/desktop/src-tauri/src/native_screen.rs +2 -0
  59. package/corpus/templates/clips/desktop/src-tauri/src/system_audio.rs +25 -132
  60. package/corpus/templates/content/app/components/sidebar/DocumentSidebar.tsx +34 -17
  61. package/corpus/templates/content/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
  62. package/corpus/templates/design/.agents/skills/design-systems/SKILL.md +6 -2
  63. package/corpus/templates/design/.generated/bridge/editor-chrome.generated.ts +5 -0
  64. package/corpus/templates/design/actions/create-design-system.ts +1 -0
  65. package/corpus/templates/design/actions/set-default-design-system.ts +34 -26
  66. package/corpus/templates/design/app/components/design/KeyboardShortcutsPanel.tsx +5 -3
  67. package/corpus/templates/design/app/components/design/bridge/editor-chrome.bridge.ts +23 -0
  68. package/corpus/templates/design/app/components/design/keyboard-shortcuts.ts +3 -0
  69. package/corpus/templates/design/app/components/layout/Sidebar.tsx +21 -4
  70. package/corpus/templates/design/app/hooks/useDesignHotkeys.ts +11 -7
  71. package/corpus/templates/design/app/i18n-data.ts +39 -0
  72. package/corpus/templates/design/app/pages/DesignSystemSetup.tsx +229 -12
  73. package/corpus/templates/design/app/pages/DesignSystems.tsx +10 -4
  74. package/corpus/templates/design/changelog/2026-07-30-fixed-the-keyboard-shortcuts-panel-not-opening-with-ctrl-shi.md +6 -0
  75. package/corpus/templates/design/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
  76. package/corpus/templates/design/changelog/2026-07-31-design-system-indexing-keeps-your-chosen-name-when-you-uploa.md +6 -0
  77. package/corpus/templates/design/server/lib/builder-design-system-proxy.ts +19 -4
  78. package/corpus/templates/dispatch/AGENTS.md +4 -0
  79. package/corpus/templates/factory/.agents/skills/actions/SKILL.md +562 -0
  80. package/corpus/templates/factory/.agents/skills/adding-a-feature/SKILL.md +198 -0
  81. package/corpus/templates/factory/.agents/skills/agent-native-docs/SKILL.md +115 -0
  82. package/corpus/templates/factory/.agents/skills/agent-native-toolkit/SKILL.md +182 -0
  83. package/corpus/templates/factory/.agents/skills/capture-learnings/SKILL.md +89 -0
  84. package/corpus/templates/factory/.agents/skills/create-skill/SKILL.md +221 -0
  85. package/corpus/templates/factory/.agents/skills/customizing-agent-native/SKILL.md +220 -0
  86. package/corpus/templates/factory/.agents/skills/delegate-to-agent/SKILL.md +263 -0
  87. package/corpus/templates/factory/.agents/skills/factory-graphs/SKILL.md +52 -0
  88. package/corpus/templates/factory/.agents/skills/feature-flags/SKILL.md +169 -0
  89. package/corpus/templates/factory/.agents/skills/frontend-design/SKILL.md +174 -0
  90. package/corpus/templates/factory/.agents/skills/real-time-sync/SKILL.md +232 -0
  91. package/corpus/templates/factory/.agents/skills/security/SKILL.md +324 -0
  92. package/corpus/templates/factory/.agents/skills/self-modifying-code/SKILL.md +119 -0
  93. package/corpus/templates/factory/.agents/skills/shadcn-ui/SKILL.md +123 -0
  94. package/corpus/templates/factory/.agents/skills/sharing/SKILL.md +232 -0
  95. package/corpus/templates/factory/.agents/skills/storing-data/SKILL.md +178 -0
  96. package/corpus/templates/factory/.agents/skills/upgrade-agent-native/SKILL.md +122 -0
  97. package/corpus/templates/factory/.env.example +24 -0
  98. package/corpus/templates/factory/.ignore +0 -0
  99. package/corpus/templates/factory/.oxfmtrc.json +8 -0
  100. package/corpus/templates/factory/AGENTS.md +90 -0
  101. package/corpus/templates/factory/CHANGELOG.md +10 -0
  102. package/corpus/templates/factory/DEVELOPING.md +185 -0
  103. package/corpus/templates/factory/README.md +64 -0
  104. package/corpus/templates/factory/_gitignore +42 -0
  105. package/corpus/templates/factory/actions/add-factory-comment.ts +55 -0
  106. package/corpus/templates/factory/actions/approve-factory-item.ts +214 -0
  107. package/corpus/templates/factory/actions/babysit-pull-request.ts +126 -0
  108. package/corpus/templates/factory/actions/evaluate-triage-item.ts +172 -0
  109. package/corpus/templates/factory/actions/get-factory-graph.ts +62 -0
  110. package/corpus/templates/factory/actions/get-triage-config.ts +42 -0
  111. package/corpus/templates/factory/actions/get-triage-item.ts +74 -0
  112. package/corpus/templates/factory/actions/hello.ts +13 -0
  113. package/corpus/templates/factory/actions/ingest-github-observation.ts +100 -0
  114. package/corpus/templates/factory/actions/list-factories.ts +40 -0
  115. package/corpus/templates/factory/actions/list-factory-comments.ts +40 -0
  116. package/corpus/templates/factory/actions/list-triage-items.ts +85 -0
  117. package/corpus/templates/factory/actions/list-triage-rules.ts +44 -0
  118. package/corpus/templates/factory/actions/navigate.ts +41 -0
  119. package/corpus/templates/factory/actions/poll-slack-channel.ts +118 -0
  120. package/corpus/templates/factory/actions/reconcile-triage-run.ts +179 -0
  121. package/corpus/templates/factory/actions/record-triage-feedback.ts +58 -0
  122. package/corpus/templates/factory/actions/run.ts +2 -0
  123. package/corpus/templates/factory/actions/save-factory-graph.ts +129 -0
  124. package/corpus/templates/factory/actions/save-triage-config.ts +67 -0
  125. package/corpus/templates/factory/actions/save-triage-rule.ts +89 -0
  126. package/corpus/templates/factory/actions/suggest-factory-rules.ts +70 -0
  127. package/corpus/templates/factory/actions/view-screen.ts +73 -0
  128. package/corpus/templates/factory/app/components/factory/FactoryCanvas.tsx +441 -0
  129. package/corpus/templates/factory/app/components/factory/FactoryInspector.tsx +388 -0
  130. package/corpus/templates/factory/app/components/layout/Header.tsx +60 -0
  131. package/corpus/templates/factory/app/components/layout/Layout.tsx +190 -0
  132. package/corpus/templates/factory/app/components/layout/Sidebar.tsx +538 -0
  133. package/corpus/templates/factory/app/components/triage/triage-status-pill.tsx +28 -0
  134. package/corpus/templates/factory/app/components/ui/button.tsx +1 -0
  135. package/corpus/templates/factory/app/components/ui/card.tsx +1 -0
  136. package/corpus/templates/factory/app/components/ui/dropdown-menu.tsx +1 -0
  137. package/corpus/templates/factory/app/components/ui/input.tsx +1 -0
  138. package/corpus/templates/factory/app/components/ui/label.tsx +1 -0
  139. package/corpus/templates/factory/app/components/ui/sheet.tsx +1 -0
  140. package/corpus/templates/factory/app/components/ui/textarea.tsx +1 -0
  141. package/corpus/templates/factory/app/components/ui/toolkit-provider.tsx +17 -0
  142. package/corpus/templates/factory/app/components/ui/tooltip.tsx +1 -0
  143. package/corpus/templates/factory/app/design-system.ts +3 -0
  144. package/corpus/templates/factory/app/entry.client.tsx +22 -0
  145. package/corpus/templates/factory/app/entry.server.tsx +10 -0
  146. package/corpus/templates/factory/app/global.css +93 -0
  147. package/corpus/templates/factory/app/hooks/use-navigation-state.ts +113 -0
  148. package/corpus/templates/factory/app/i18n/en-US.ts +211 -0
  149. package/corpus/templates/factory/app/i18n/index.ts +34 -0
  150. package/corpus/templates/factory/app/i18n-data.ts +556 -0
  151. package/corpus/templates/factory/app/lib/agent-page.tsx +49 -0
  152. package/corpus/templates/factory/app/lib/app-config.ts +11 -0
  153. package/corpus/templates/factory/app/lib/tab-id.ts +1 -0
  154. package/corpus/templates/factory/app/lib/utils.ts +1 -0
  155. package/corpus/templates/factory/app/root.tsx +175 -0
  156. package/corpus/templates/factory/app/routes/_index.tsx +94 -0
  157. package/corpus/templates/factory/app/routes/agent.tsx +24 -0
  158. package/corpus/templates/factory/app/routes/chat.$threadId.tsx +1 -0
  159. package/corpus/templates/factory/app/routes/database.tsx +17 -0
  160. package/corpus/templates/factory/app/routes/extensions.$id.$slug.tsx +2 -0
  161. package/corpus/templates/factory/app/routes/extensions.$id.tsx +11 -0
  162. package/corpus/templates/factory/app/routes/extensions._index.tsx +11 -0
  163. package/corpus/templates/factory/app/routes/extensions.tsx +5 -0
  164. package/corpus/templates/factory/app/routes/factory.tsx +1003 -0
  165. package/corpus/templates/factory/app/routes/observability.tsx +19 -0
  166. package/corpus/templates/factory/app/routes/settings.tsx +89 -0
  167. package/corpus/templates/factory/app/routes/team.tsx +11 -0
  168. package/corpus/templates/factory/app/routes.ts +4 -0
  169. package/corpus/templates/factory/app/vite-env.d.ts +6 -0
  170. package/corpus/templates/factory/changelog/2026-06-24-a-new-settings-page-gives-quick-access-to-language-workspace.md +6 -0
  171. package/corpus/templates/factory/changelog/2026-06-24-added-a-language-picker-and-localized-app-chrome-for-support.md +6 -0
  172. package/corpus/templates/factory/changelog/2026-06-27-traditional-chinese-copy-uses-taiwan-terminology.md +6 -0
  173. package/corpus/templates/factory/changelog/2026-06-28-left-sidebar-collapse-motion-and-footer-chrome-are-quieter.md +6 -0
  174. package/corpus/templates/factory/changelog/2026-06-29-chat-layouts-adapt-when-the-agent-sidebar-is-open.md +6 -0
  175. package/corpus/templates/factory/changelog/2026-07-08-settings-are-cleaner-and-searchable.md +5 -0
  176. package/corpus/templates/factory/changelog/2026-07-10-chat-now-makes-ai-connection-setup-clear-without-shifting-th.md +6 -0
  177. package/corpus/templates/factory/changelog/2026-07-13-a-full-agent-page-now-brings-context-files-connections-jobs-.md +6 -0
  178. package/corpus/templates/factory/changelog/2026-07-14-chat-opens-reliably-on-hosted-deployments-instead-of-failing.md +6 -0
  179. package/corpus/templates/factory/changelog/2026-07-14-fixed-chat-template-startup-with-older-core-versions.md +6 -0
  180. package/corpus/templates/factory/changelog/2026-07-15-chat-navigation-focuses-on-chat-and-agent.md +6 -0
  181. package/corpus/templates/factory/changelog/2026-07-17-the-agent-chat-sidebar-stays-closed-until-you-open-it-or-sta.md +6 -0
  182. package/corpus/templates/factory/changelog/2026-07-22-compact-sidebar-footer.md +6 -0
  183. package/corpus/templates/factory/changelog/2026-07-22-full-page-chat-keeps-the-active-conversation-when-moving-to-.md +6 -0
  184. package/corpus/templates/factory/changelog/2026-07-22-manage-agent-navigation-now-uses-the-connected-nodes-icon.md +6 -0
  185. package/corpus/templates/factory/changelog/2026-07-22-recent-chats-are-easier-to-scan-and-expand.md +6 -0
  186. package/corpus/templates/factory/changelog/2026-07-23-full-page-chat-is-better-centered-with-quieter-chat-history-.md +6 -0
  187. package/corpus/templates/factory/changelog/2026-07-24-borderless-secondary-surfaces.md +6 -0
  188. package/corpus/templates/factory/changelog/2026-07-24-sidebar-footer-controls-follow-a-consistent-order.md +6 -0
  189. package/corpus/templates/factory/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  190. package/corpus/templates/factory/changelog/2026-07-29-sidebar-footers-now-keep-feedback-search-and-collapse-togeth.md +6 -0
  191. package/corpus/templates/factory/changelog/2026-07-31-added-an-inspectable-observe-only-factory-queue-for-slack-.md +6 -0
  192. package/corpus/templates/factory/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
  193. package/corpus/templates/factory/components.json +20 -0
  194. package/corpus/templates/factory/data/sync-config.json +1 -0
  195. package/corpus/templates/factory/learnings.defaults.md +5 -0
  196. package/corpus/templates/factory/netlify.toml +10 -0
  197. package/corpus/templates/factory/package.json +105 -0
  198. package/corpus/templates/factory/public/agent-native-icon-dark.svg +10 -0
  199. package/corpus/templates/factory/public/agent-native-icon-light.svg +10 -0
  200. package/corpus/templates/factory/public/agent-native-logo-dark.svg +21 -0
  201. package/corpus/templates/factory/public/agent-native-logo-light.svg +21 -0
  202. package/corpus/templates/factory/public/favicon.svg +1 -0
  203. package/corpus/templates/factory/public/icon-180.svg +1 -0
  204. package/corpus/templates/factory/public/icon-192.svg +1 -0
  205. package/corpus/templates/factory/public/icon-512.svg +1 -0
  206. package/corpus/templates/factory/public/manifest.json +21 -0
  207. package/corpus/templates/factory/react-router.config.ts +7 -0
  208. package/corpus/templates/factory/server/connectors/credentials.ts +129 -0
  209. package/corpus/templates/factory/server/connectors/slack.ts +129 -0
  210. package/corpus/templates/factory/server/db/index.ts +6 -0
  211. package/corpus/templates/factory/server/db/schema.ts +193 -0
  212. package/corpus/templates/factory/server/factory-graph/contracts.ts +212 -0
  213. package/corpus/templates/factory/server/factory-graph/store.ts +121 -0
  214. package/corpus/templates/factory/server/lib/require-workspace-member.ts +55 -0
  215. package/corpus/templates/factory/server/middleware/auth.ts +15 -0
  216. package/corpus/templates/factory/server/plugins/agent-chat.ts +58 -0
  217. package/corpus/templates/factory/server/plugins/auth.ts +14 -0
  218. package/corpus/templates/factory/server/plugins/factory-migrations.ts +247 -0
  219. package/corpus/templates/factory/server/plugins/factory-scheduler-job.ts +116 -0
  220. package/corpus/templates/factory/server/plugins/integrations.ts +46 -0
  221. package/corpus/templates/factory/server/routes/[...page].get.ts +5 -0
  222. package/corpus/templates/factory/server/routes/_agent-native/factory/builder-callback.post.ts +116 -0
  223. package/corpus/templates/factory/server/triage/ai-services-git.ts +197 -0
  224. package/corpus/templates/factory/server/triage/builder-executor.ts +118 -0
  225. package/corpus/templates/factory/server/triage/contracts.ts +164 -0
  226. package/corpus/templates/factory/server/triage/github-ingestion.ts +35 -0
  227. package/corpus/templates/factory/server/triage/guards.ts +121 -0
  228. package/corpus/templates/factory/server/triage/ids.ts +27 -0
  229. package/corpus/templates/factory/server/triage/pr-babysit.ts +100 -0
  230. package/corpus/templates/factory/server/triage/pr-monitor.ts +220 -0
  231. package/corpus/templates/factory/server/triage/slack-client.ts +55 -0
  232. package/corpus/templates/factory/server/triage/slack-poller.ts +152 -0
  233. package/corpus/templates/factory/ssr-entry.ts +15 -0
  234. package/corpus/templates/factory/tsconfig.json +21 -0
  235. package/corpus/templates/factory/vite.config.ts +19 -0
  236. package/corpus/templates/forms/app/components/layout/Sidebar.tsx +55 -5
  237. package/corpus/templates/forms/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
  238. package/corpus/templates/macros/app/components/layout/AppLayout.tsx +6 -2
  239. package/corpus/templates/plan/app/components/layout/Sidebar.tsx +21 -6
  240. package/corpus/templates/plan/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
  241. package/corpus/templates/slides/.agents/skills/create-deck/SKILL.md +12 -0
  242. package/corpus/templates/slides/.agents/skills/design-systems/SKILL.md +9 -0
  243. package/corpus/templates/slides/.agents/skills/slide-editing/SKILL.md +11 -0
  244. package/corpus/templates/slides/AGENTS.md +5 -6
  245. package/corpus/templates/slides/actions/_await-fit-check.ts +20 -10
  246. package/corpus/templates/slides/actions/add-slide.ts +17 -4
  247. package/corpus/templates/slides/actions/create-design-system.ts +16 -4
  248. package/corpus/templates/slides/actions/delete-design-system.ts +18 -2
  249. package/corpus/templates/slides/actions/get-layout-overflows.ts +88 -0
  250. package/corpus/templates/slides/actions/import-file.ts +1 -0
  251. package/corpus/templates/slides/actions/index-design-system-with-builder.ts +8 -0
  252. package/corpus/templates/slides/actions/patch-deck.ts +48 -16
  253. package/corpus/templates/slides/actions/set-default-design-system.ts +49 -19
  254. package/corpus/templates/slides/actions/update-slide.ts +13 -3
  255. package/corpus/templates/slides/actions/view-screen.ts +87 -10
  256. package/corpus/templates/slides/app/components/deck/SlideRenderer.tsx +155 -28
  257. package/corpus/templates/slides/app/components/design-system/DesignSystemCard.tsx +21 -17
  258. package/corpus/templates/slides/app/components/design-system/DesignSystemSetup.tsx +849 -341
  259. package/corpus/templates/slides/app/components/editor/EditorSidebar.tsx +102 -2
  260. package/corpus/templates/slides/app/components/editor/PromptDialog.tsx +13 -16
  261. package/corpus/templates/slides/app/components/editor/SlideEditor.tsx +60 -12
  262. package/corpus/templates/slides/app/components/editor/SlideOverflowWarning.tsx +11 -1
  263. package/corpus/templates/slides/app/components/layout/Sidebar.tsx +66 -19
  264. package/corpus/templates/slides/app/i18n/en-US.ts +23 -0
  265. package/corpus/templates/slides/app/lib/normalize-slide-padding.ts +8 -15
  266. package/corpus/templates/slides/app/pages/DeckEditor.tsx +4 -3
  267. package/corpus/templates/slides/app/pages/DesignSystems.tsx +4 -3
  268. package/corpus/templates/slides/app/pages/Index.tsx +1 -1
  269. package/corpus/templates/slides/changelog/2026-07-31-design-system-details-now-show-their-source-and-indexing-sta.md +6 -0
  270. package/corpus/templates/slides/changelog/2026-07-31-design-system-indexing-keeps-your-chosen-name-when-you-uploa.md +6 -0
  271. package/corpus/templates/slides/changelog/2026-07-31-design-system-setup-keeps-focus-rings-visible-and-uses-a-sim.md +6 -0
  272. package/corpus/templates/slides/changelog/2026-07-31-skip-prompt-is-now-available-in-the-new-deck-prompt-header.md +6 -0
  273. package/corpus/templates/slides/changelog/2026-07-31-slides-now-detect-real-text-and-box-overflow-across-the-deck.md +6 -0
  274. package/corpus/templates/slides/changelog/2026-07-31-the-agent-native-logo-stays-visible-when-the-sidebar-is-coll.md +6 -0
  275. package/corpus/templates/slides/server/handlers/design-systems.ts +1 -0
  276. package/corpus/templates/slides/server/handlers/index-design-system-sources.ts +1 -0
  277. package/corpus/templates/slides/server/lib/builder-design-system-proxy.ts +23 -4
  278. package/corpus/templates/slides/server/plugins/agent-chat.ts +5 -0
  279. package/corpus/templates/slides/server/plugins/creative-context.ts +16 -3
  280. package/corpus/templates/slides/server/workspace-defaults.ts +5 -1
  281. package/corpus/templates/slides/shared/slide-fit.ts +26 -0
  282. package/corpus/templates/tasks/app/components/layout/Sidebar.tsx +30 -3
  283. package/corpus/templates/tasks/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
  284. package/dist/a2a/correlation.d.ts +4 -1
  285. package/dist/a2a/correlation.d.ts.map +1 -1
  286. package/dist/a2a/correlation.js +8 -1
  287. package/dist/a2a/correlation.js.map +1 -1
  288. package/dist/a2a/types.d.ts +11 -3
  289. package/dist/a2a/types.d.ts.map +1 -1
  290. package/dist/a2a/types.js.map +1 -1
  291. package/dist/agent/engine/ai-sdk-engine.d.ts.map +1 -1
  292. package/dist/agent/engine/ai-sdk-engine.js +27 -41
  293. package/dist/agent/engine/ai-sdk-engine.js.map +1 -1
  294. package/dist/agent/engine/builder-engine.d.ts.map +1 -1
  295. package/dist/agent/engine/builder-engine.js +18 -8
  296. package/dist/agent/engine/builder-engine.js.map +1 -1
  297. package/dist/agent/engine/error-detail.d.ts +61 -0
  298. package/dist/agent/engine/error-detail.d.ts.map +1 -1
  299. package/dist/agent/engine/error-detail.js +145 -3
  300. package/dist/agent/engine/error-detail.js.map +1 -1
  301. package/dist/agent/engine/failure-taxonomy.d.ts +24 -0
  302. package/dist/agent/engine/failure-taxonomy.d.ts.map +1 -0
  303. package/dist/agent/engine/failure-taxonomy.js +88 -0
  304. package/dist/agent/engine/failure-taxonomy.js.map +1 -0
  305. package/dist/agent/engine/index.d.ts +2 -1
  306. package/dist/agent/engine/index.d.ts.map +1 -1
  307. package/dist/agent/engine/index.js +2 -1
  308. package/dist/agent/engine/index.js.map +1 -1
  309. package/dist/agent/engine/registry.d.ts +16 -0
  310. package/dist/agent/engine/registry.d.ts.map +1 -1
  311. package/dist/agent/engine/registry.js +71 -6
  312. package/dist/agent/engine/registry.js.map +1 -1
  313. package/dist/agent/engine/translate-ai-sdk.d.ts.map +1 -1
  314. package/dist/agent/engine/translate-ai-sdk.js +14 -2
  315. package/dist/agent/engine/translate-ai-sdk.js.map +1 -1
  316. package/dist/agent/production-agent.d.ts.map +1 -1
  317. package/dist/agent/production-agent.js +13 -24
  318. package/dist/agent/production-agent.js.map +1 -1
  319. package/dist/agent/run-loop-with-resume.js +1 -1
  320. package/dist/agent/run-loop-with-resume.js.map +1 -1
  321. package/dist/agent/run-manager.d.ts.map +1 -1
  322. package/dist/agent/run-manager.js +39 -10
  323. package/dist/agent/run-manager.js.map +1 -1
  324. package/dist/agent/run-store.d.ts +10 -0
  325. package/dist/agent/run-store.d.ts.map +1 -1
  326. package/dist/agent/run-store.js +20 -3
  327. package/dist/agent/run-store.js.map +1 -1
  328. package/dist/agent/thread-data-builder.d.ts.map +1 -1
  329. package/dist/agent/thread-data-builder.js +28 -4
  330. package/dist/agent/thread-data-builder.js.map +1 -1
  331. package/dist/chat-threads/store.d.ts +13 -0
  332. package/dist/chat-threads/store.d.ts.map +1 -1
  333. package/dist/chat-threads/store.js +35 -0
  334. package/dist/chat-threads/store.js.map +1 -1
  335. package/dist/cli/templates-meta.d.ts.map +1 -1
  336. package/dist/cli/templates-meta.js +13 -0
  337. package/dist/cli/templates-meta.js.map +1 -1
  338. package/dist/cli/workspace-dev.d.ts.map +1 -1
  339. package/dist/cli/workspace-dev.js +1 -0
  340. package/dist/cli/workspace-dev.js.map +1 -1
  341. package/dist/client/error-format.d.ts.map +1 -1
  342. package/dist/client/error-format.js +10 -0
  343. package/dist/client/error-format.js.map +1 -1
  344. package/dist/client/use-chat-threads.d.ts.map +1 -1
  345. package/dist/client/use-chat-threads.js +66 -16
  346. package/dist/client/use-chat-threads.js.map +1 -1
  347. package/dist/collab/awareness.d.ts +2 -2
  348. package/dist/collab/awareness.d.ts.map +1 -1
  349. package/dist/collab/struct-routes.d.ts +1 -1
  350. package/dist/credentials/index.d.ts +9 -2
  351. package/dist/credentials/index.d.ts.map +1 -1
  352. package/dist/credentials/index.js +50 -8
  353. package/dist/credentials/index.js.map +1 -1
  354. package/dist/extensions/url-safety.d.ts.map +1 -1
  355. package/dist/extensions/url-safety.js +38 -12
  356. package/dist/extensions/url-safety.js.map +1 -1
  357. package/dist/integrations/adapters/slack.d.ts.map +1 -1
  358. package/dist/integrations/adapters/slack.js +25 -8
  359. package/dist/integrations/adapters/slack.js.map +1 -1
  360. package/dist/integrations/google-docs-poller.d.ts.map +1 -1
  361. package/dist/integrations/google-docs-poller.js +13 -1
  362. package/dist/integrations/google-docs-poller.js.map +1 -1
  363. package/dist/integrations/installations-store.d.ts +10 -0
  364. package/dist/integrations/installations-store.d.ts.map +1 -1
  365. package/dist/integrations/installations-store.js +24 -0
  366. package/dist/integrations/installations-store.js.map +1 -1
  367. package/dist/integrations/plugin.d.ts.map +1 -1
  368. package/dist/integrations/plugin.js +6 -5
  369. package/dist/integrations/plugin.js.map +1 -1
  370. package/dist/integrations/types.d.ts +7 -0
  371. package/dist/integrations/types.d.ts.map +1 -1
  372. package/dist/integrations/types.js.map +1 -1
  373. package/dist/integrations/webhook-handler.d.ts.map +1 -1
  374. package/dist/integrations/webhook-handler.js +16 -1
  375. package/dist/integrations/webhook-handler.js.map +1 -1
  376. package/dist/jobs/background-automation-runner.d.ts.map +1 -1
  377. package/dist/jobs/background-automation-runner.js +35 -2
  378. package/dist/jobs/background-automation-runner.js.map +1 -1
  379. package/dist/notifications/routes.d.ts +6 -6
  380. package/dist/observability/routes.d.ts +3 -3
  381. package/dist/provider-api/actions/custom-provider-registration.d.ts +14 -14
  382. package/dist/provider-api/actions/provider-api.d.ts +8 -8
  383. package/dist/provider-api/index.js +7 -3
  384. package/dist/provider-api/index.js.map +1 -1
  385. package/dist/scripts/call-agent.d.ts.map +1 -1
  386. package/dist/scripts/call-agent.js +6 -1
  387. package/dist/scripts/call-agent.js.map +1 -1
  388. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  389. package/dist/server/agent-chat-plugin.js +38 -9
  390. package/dist/server/agent-chat-plugin.js.map +1 -1
  391. package/dist/server/agent-discovery.d.ts +2 -0
  392. package/dist/server/agent-discovery.d.ts.map +1 -1
  393. package/dist/server/agent-discovery.js.map +1 -1
  394. package/dist/server/builder-design-systems.d.ts +4 -1
  395. package/dist/server/builder-design-systems.d.ts.map +1 -1
  396. package/dist/server/builder-design-systems.js +11 -1
  397. package/dist/server/builder-design-systems.js.map +1 -1
  398. package/dist/server/credential-provider.d.ts.map +1 -1
  399. package/dist/server/credential-provider.js +49 -12
  400. package/dist/server/credential-provider.js.map +1 -1
  401. package/dist/server/index.d.ts +1 -1
  402. package/dist/server/index.d.ts.map +1 -1
  403. package/dist/server/index.js.map +1 -1
  404. package/dist/server/onboarding-html.d.ts.map +1 -1
  405. package/dist/server/onboarding-html.js +37 -2
  406. package/dist/server/onboarding-html.js.map +1 -1
  407. package/dist/server/transcribe-voice.d.ts +1 -1
  408. package/dist/shared/reasoning-effort.d.ts +1 -0
  409. package/dist/shared/reasoning-effort.d.ts.map +1 -1
  410. package/dist/shared/reasoning-effort.js +1 -1
  411. package/dist/shared/reasoning-effort.js.map +1 -1
  412. package/dist/templates/chat/app/components/layout/Sidebar.tsx +30 -3
  413. package/dist/templates/chat/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
  414. package/dist/templates/workspace-core/.agents/skills/a2a-protocol/SKILL.md +11 -0
  415. package/package.json +1 -1
  416. package/src/a2a/correlation.ts +11 -1
  417. package/src/a2a/types.ts +11 -3
  418. package/src/agent/engine/ai-sdk-engine.ts +33 -46
  419. package/src/agent/engine/builder-engine.ts +22 -10
  420. package/src/agent/engine/error-detail.ts +184 -3
  421. package/src/agent/engine/failure-taxonomy.ts +123 -0
  422. package/src/agent/engine/index.ts +8 -0
  423. package/src/agent/engine/registry.ts +92 -8
  424. package/src/agent/engine/translate-ai-sdk.ts +17 -2
  425. package/src/agent/production-agent.ts +13 -33
  426. package/src/agent/run-loop-with-resume.ts +1 -1
  427. package/src/agent/run-manager.ts +43 -14
  428. package/src/agent/run-store.ts +30 -3
  429. package/src/agent/thread-data-builder.ts +36 -4
  430. package/src/chat-threads/store.ts +42 -0
  431. package/src/cli/templates-meta.ts +13 -0
  432. package/src/cli/workspace-dev.ts +1 -0
  433. package/src/client/error-format.ts +12 -0
  434. package/src/client/use-chat-threads.ts +76 -16
  435. package/src/credentials/index.ts +51 -12
  436. package/src/extensions/url-safety.ts +46 -12
  437. package/src/integrations/adapters/slack.ts +32 -10
  438. package/src/integrations/google-docs-poller.ts +12 -1
  439. package/src/integrations/installations-store.ts +30 -0
  440. package/src/integrations/plugin.ts +5 -5
  441. package/src/integrations/types.ts +7 -0
  442. package/src/integrations/webhook-handler.ts +24 -1
  443. package/src/jobs/background-automation-runner.ts +38 -1
  444. package/src/provider-api/index.ts +8 -2
  445. package/src/scripts/call-agent.ts +6 -0
  446. package/src/server/agent-chat-plugin.ts +46 -10
  447. package/src/server/agent-discovery.ts +2 -0
  448. package/src/server/builder-design-systems.ts +21 -0
  449. package/src/server/credential-provider.ts +51 -12
  450. package/src/server/index.ts +1 -0
  451. package/src/server/onboarding-html.ts +37 -2
  452. package/src/shared/reasoning-effort.ts +1 -1
  453. package/src/templates/chat/app/components/layout/Sidebar.tsx +30 -3
  454. package/src/templates/chat/changelog/2026-07-31-clicking-the-agent-native-logo-now-toggles-the-app-sidebar.md +6 -0
  455. package/src/templates/workspace-core/.agents/skills/a2a-protocol/SKILL.md +11 -0
  456. package/corpus/templates/clips/desktop/src/lib/media-device-selection.ts +0 -157
@@ -1 +1 @@
1
- {"version":3,"file":"call-agent.d.ts","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AA8OpD,eAAO,MAAM,IAAI,EAAE,UAsDlB,CAAC;AAEF,wBAAsB,GAAG,CACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,OAAO,CAAC,EAAE,gBAAgB,EAC1B,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CA+kBjB;AAqPD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CASzE"}
1
+ {"version":3,"file":"call-agent.d.ts","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAoPpD,eAAO,MAAM,IAAI,EAAE,UAsDlB,CAAC;AAEF,wBAAsB,GAAG,CACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,OAAO,CAAC,EAAE,gBAAgB,EAC1B,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CA+kBjB;AAqPD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CASzE"}
@@ -8,7 +8,7 @@ import { A2A_CONTINUATION_QUEUED_MARKER } from "../integrations/a2a-continuation
8
8
  import { trackingIdentityProperties } from "../observability/tracking-identity.js";
9
9
  import { getOrgDomain, getOrgA2ASecret } from "../org/context.js";
10
10
  import { findAgent, discoverAgents } from "../server/agent-discovery.js";
11
- import { getRequestUserEmail, getRequestOrgId, isIntegrationCallerRequest, getIntegrationRequestContext, } from "../server/request-context.js";
11
+ import { getRequestUserEmail, getRequestOrgId, getRequestRunContext, isIntegrationCallerRequest, getIntegrationRequestContext, } from "../server/request-context.js";
12
12
  import { track } from "../tracking/registry.js";
13
13
  const DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;
14
14
  const NETLIFY_INTEGRATION_A2A_TIMEOUT_MS = 2_000;
@@ -47,8 +47,13 @@ function buildDelegationCorrelation(context, selfAppId, invocationId) {
47
47
  const inheritedDepth = Number.isInteger(context?.delegationDepth)
48
48
  ? Math.max(0, Number(context?.delegationDepth))
49
49
  : 0;
50
+ // The model this turn is actually running on, so a receiver with no model of
51
+ // its own can match the user's selection instead of its own default. A
52
+ // preference only — the receiver bounds it to its own engine's catalog.
53
+ const callerModel = getRequestRunContext()?.model?.trim();
50
54
  return {
51
55
  ...(selfAppId?.trim() ? { callerApp: selfAppId.trim() } : {}),
56
+ ...(callerModel ? { callerModel } : {}),
52
57
  ...(context?.threadId ? { callerThreadId: context.threadId } : {}),
53
58
  ...(context?.runId ? { parentRunId: context.runId } : {}),
54
59
  ...(context?.turnId ? { parentTurnId: context.turnId } : {}),
@@ -1 +1 @@
1
- {"version":3,"file":"call-agent.js","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAErD,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EACL,mBAAmB,EACnB,6BAA6B,EAC7B,SAAS,EACT,2BAA2B,EAC3B,YAAY,GACb,MAAM,kBAAkB,CAAC;AAC1B,OAAO,E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AAI,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IACpC,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACzC,4EAA4E;IAC5E,8EAA8E;IAC9E,OAAO,IAAI,CAAC,OAAO,CACjB,oDAAoD,EACpD,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE,CAChD,CAAC;AACJ,CAAC","sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\n\nimport { parseA2AAgentActivityPart } from \"../a2a/activity.js\";\nimport {\n A2ATaskTimeoutError,\n MAX_A2A_CALLER_RESPONSE_CHARS,\n callAgent,\n shouldPreferGlobalA2ASecret,\n signA2AToken,\n} from \"../a2a/client.js\";\nimport { MAX_A2A_DELEGATION_HOPS } from \"../a2a/correlation.js\";\nimport { invokeAgentAction } from \"../a2a/invoke.js\";\nimport type {\n A2AApprovedAction,\n A2ACorrelationMetadata,\n A2ASourceContext,\n A2ASourceContextReference,\n Task,\n} from \"../a2a/types.js\";\nimport {\n formatLlmCredentialErrorMessage,\n isLlmCredentialError,\n} from \"../agent/engine/credential-errors.js\";\nimport type { ActionRunContext } from \"../agent/production-agent.js\";\nimport type { ActionTool } from \"../agent/types.js\";\nimport { A2A_CONTINUATION_QUEUED_MARKER } from \"../integrations/a2a-continuation-marker.js\";\nimport { trackingIdentityProperties } from \"../observability/tracking-identity.js\";\nimport { getOrgDomain, getOrgA2ASecret } from \"../org/context.js\";\nimport { findAgent, discoverAgents } from \"../server/agent-discovery.js\";\nimport {\n getRequestUserEmail,\n getRequestOrgId,\n isIntegrationCallerRequest,\n getIntegrationRequestContext,\n} from \"../server/request-context.js\";\nimport { track } from \"../tracking/registry.js\";\n\nconst DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;\nconst NETLIFY_INTEGRATION_A2A_TIMEOUT_MS = 2_000;\nconst INTEGRATION_A2A_TOKEN_TTL = \"30m\";\nconst A2A_INVOCATION_EVENT = \"$a2a_invocation\";\n\ntype A2AInvocationStatus = \"success\" | \"pending\" | \"error\";\n\nfunction trackA2AInvocation(args: {\n invocationId: string;\n callerApp?: string;\n targetApp: string;\n mode: \"message\" | \"task_poll\" | \"direct_action\";\n status: A2AInvocationStatus;\n startedAt: number;\n taskId?: string;\n terminalCode?: string;\n correlation: A2ACorrelationMetadata;\n}): void {\n try {\n track(\n A2A_INVOCATION_EVENT,\n {\n ...trackingIdentityProperties(),\n source: \"a2a_delegation\",\n invocation_id: args.invocationId,\n caller_app: args.callerApp ?? \"unknown\",\n target_app: args.targetApp,\n mode: args.mode,\n status: args.status,\n duration_ms: Math.max(0, Date.now() - args.startedAt),\n task_id: args.taskId,\n terminal_code: args.terminalCode,\n delegation_depth: args.correlation.delegationDepth,\n parent_run_id: args.correlation.parentRunId,\n parent_turn_id: args.correlation.parentTurnId,\n },\n { userId: getRequestUserEmail() },\n );\n } catch {\n // Tracking must never affect delegation.\n }\n}\n\nfunction buildDelegationCorrelation(\n context: ActionRunContext | undefined,\n selfAppId: string | undefined,\n invocationId?: string,\n): A2ACorrelationMetadata {\n const self = normalizeAppHandle(selfAppId);\n const inheritedVisited = Array.isArray(context?.visitedApps)\n ? context.visitedApps.map(normalizeAppHandle).filter(Boolean)\n : [];\n const visitedApps = self\n ? [...new Set([...inheritedVisited, self])]\n : [...new Set(inheritedVisited)];\n const inheritedDepth = Number.isInteger(context?.delegationDepth)\n ? Math.max(0, Number(context?.delegationDepth))\n : 0;\n return {\n ...(selfAppId?.trim() ? { callerApp: selfAppId.trim() } : {}),\n ...(context?.threadId ? { callerThreadId: context.threadId } : {}),\n ...(context?.runId ? { parentRunId: context.runId } : {}),\n ...(context?.turnId ? { parentTurnId: context.turnId } : {}),\n ...(invocationId ? { invocationId } : {}),\n delegationDepth: Math.min(MAX_A2A_DELEGATION_HOPS, inheritedDepth + 1),\n ...(visitedApps.length > 0 ? { visitedApps } : {}),\n };\n}\n\nfunction normalizeAppHandle(value: unknown): string {\n return typeof value === \"string\"\n ? value\n .trim()\n .toLowerCase()\n .replace(/^agent-native-/, \"\")\n : \"\";\n}\n\nfunction terminalTaskError(value: unknown): {\n state: string;\n taskId?: string;\n responseText?: string;\n errorCode?: string;\n} | null {\n if (!value || typeof value !== \"object\") return null;\n const candidate = value as Record<string, unknown>;\n if (candidate.name !== \"A2ATaskTerminalError\") return null;\n return {\n state: String(candidate.state ?? \"failed\"),\n ...(typeof candidate.taskId === \"string\"\n ? { taskId: candidate.taskId }\n : {}),\n ...(typeof candidate.responseText === \"string\"\n ? { responseText: candidate.responseText }\n : {}),\n ...(typeof candidate.errorCode === \"string\"\n ? { errorCode: candidate.errorCode }\n : {}),\n };\n}\n\nfunction buildMessageIdempotencyKey(\n originatingTurnId: string | undefined,\n target: string,\n exactMessage: string,\n): string | undefined {\n if (!originatingTurnId) return undefined;\n const digest = createHash(\"sha256\")\n .update(\n JSON.stringify({\n originatingTurnId,\n target,\n message: exactMessage,\n }),\n )\n .digest(\"hex\");\n return `v1:${digest}`;\n}\n\nfunction parseTimeoutMs(value: string | undefined): number | undefined {\n if (!value) return undefined;\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) return undefined;\n return Math.floor(parsed);\n}\n\nfunction isServerlessHost(): boolean {\n // Detection mirrors db/migrations.ts:297-301. On Cloudflare Workers/Pages,\n // `process.env` is shimmed and CF_PAGES isn't reliably populated at runtime —\n // the canonical signal is the `__cf_env`/`__env__` global injected by the\n // Cloudflare runtime adapter.\n return (\n !!process.env.NETLIFY ||\n !!process.env.AWS_LAMBDA_FUNCTION_NAME ||\n !!process.env.VERCEL ||\n \"__cf_env\" in globalThis ||\n \"__env__\" in globalThis\n );\n}\n\nfunction getIntegrationCallTimeoutMs(): number | undefined {\n if (!isServerlessHost() || !isIntegrationCallerRequest()) return undefined;\n\n const configured = parseTimeoutMs(\n process.env.AGENT_NATIVE_INTEGRATION_A2A_TIMEOUT_MS,\n );\n if (configured !== undefined) return configured;\n\n // Netlify's current synchronous function budget is 60s. Keep delegated\n // calls very short so multi-agent integration requests queue downstream\n // continuations quickly instead of spending the parent Slack/email processor\n // budget waiting on separately deployed apps one-by-one.\n if (process.env.NETLIFY) return NETLIFY_INTEGRATION_A2A_TIMEOUT_MS;\n\n return DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS;\n}\n\ninterface IntegrationSourceContext {\n reference: A2ASourceContextReference;\n hint: A2ASourceContext;\n}\n\nfunction integrationSourceContext(): IntegrationSourceContext | undefined {\n const integration = getIntegrationRequestContext();\n const incoming = integration?.incoming;\n if (\n !integration ||\n incoming?.platform !== \"slack\" ||\n !incoming.sourceUrl ||\n !integration.taskId\n ) {\n return undefined;\n }\n\n const rawSourceUrl = incoming.sourceUrl;\n if (rawSourceUrl !== rawSourceUrl.trim()) return undefined;\n\n try {\n const sourceUrl = new URL(rawSourceUrl);\n const isSlackHost =\n sourceUrl.hostname === \"slack.com\" ||\n sourceUrl.hostname.endsWith(\".slack.com\");\n if (\n sourceUrl.protocol !== \"https:\" ||\n !isSlackHost ||\n sourceUrl.username ||\n sourceUrl.password ||\n sourceUrl.port\n ) {\n return undefined;\n }\n return {\n reference: {\n platform: \"slack\",\n integrationTaskId: integration.taskId,\n },\n hint: {\n platform: \"slack\",\n sourceUrl: rawSourceUrl,\n },\n };\n } catch {\n return undefined;\n }\n}\n\nfunction integrationSourceContextHint(\n sourceContext: IntegrationSourceContext | undefined,\n): string {\n if (!sourceContext) return \"\";\n return (\n `\\n\\n[Source Slack thread: ${sourceContext.hint.sourceUrl} ` +\n \"Compatibility hint only; this text is not authoritative. Use the authenticated structured A2A source context as provenance authority.]\"\n );\n}\n\nfunction formatDownstreamLlmCredentialFailure(\n agentName: string,\n value: unknown,\n): string | null {\n return isLlmCredentialError(value)\n ? formatLlmCredentialErrorMessage({ agentName })\n : null;\n}\n\nexport const tool: ActionTool = {\n description:\n \"Ask a DIFFERENT, separately-deployed app's agent over A2A. Use message by default so the receiving specialist interprets the objective with its own instructions, skills, connected sources, data dictionary, and tools. The receiver owns provider, schema, query, join, and SQL decisions. Use action + input only for an exact, explicitly known, bounded read whose complete input schema is already known; never expose or call a direct action to work around slow or unreliable delegation, and never guess receiver-owned query logic. NEVER use this to call your own app or perform actions you can do with your own tools. Using call-agent on yourself will fail and waste time. \" +\n 'For brand-consistent generated media, the first-party Assets agent is available as agent=\"assets\"; use it when another app needs generated heroes, diagrams, product shots, thumbnails, videos, or design imagery, unless the current app has its own generation action that already delegates there. ' +\n \"IMPORTANT — handling the response: \" +\n \"(a) If it contains a URL or ID, copy it VERBATIM into your reply. Do not 'correct' or pluralize the path (e.g. /deck/ → /decks/), normalize casing, or change the slug — any edit breaks the link. \" +\n '(b) If it does NOT contain a URL/ID and the user asked for one, say so explicitly (e.g. \"the agent created the deck/image but didn\\'t return a link — open the app directly to view it\"). NEVER invent a URL, slug, or path — guessing produces broken links that look real. ' +\n \"(c) If the downstream response reports missing credentials, never repeat raw env var names, Vault key names, token names, secret names, or other credential identifiers. Tell the user the target app needs its LLM/provider connection configured. \" +\n \"(d) A bounded wait can expire while the remote task is still healthy. The result will include its taskId and exact retry instructions. Continue polling that SAME task with taskId; NEVER send a new check-in/follow-up message, because that starts duplicate downstream work.\",\n parameters: {\n type: \"object\",\n properties: {\n agent: {\n type: \"string\",\n description:\n \"Name or URL of a DIFFERENT deployed agent app (e.g. 'mail', 'calendar', 'analytics'). Must not be the current app's own name.\",\n },\n message: {\n type: \"string\",\n description:\n \"The message/question to send when starting a new task. Omit when taskId is provided.\",\n },\n taskId: {\n type: \"string\",\n description:\n \"Existing A2A task ID returned by a timed-out call. Polls that exact task without sending a new message. Never create a fresh check-in message for work that already has a taskId.\",\n },\n action: {\n type: \"string\",\n description:\n \"Optional exact read-only action for an explicitly known bounded operation. Prefer message when the target agent must interpret data, choose sources or tools, synthesize, mutate, or do multi-step work. Never guess the action schema or send receiver-owned SQL.\",\n },\n input: {\n type: \"object\",\n description:\n \"Complete input object for action. The target app validates it and refuses actions that are not explicitly exposed read-only operations.\",\n additionalProperties: true,\n },\n approvedActions: {\n type: \"array\",\n description:\n \"Exact downstream tool calls the current user explicitly authorized in this chat. Never infer authorization or include a broader/different action.\",\n items: {\n type: \"object\",\n properties: {\n tool: { type: \"string\" },\n input: { type: \"object\", additionalProperties: true },\n },\n required: [\"tool\", \"input\"],\n },\n },\n },\n required: [\"agent\"],\n },\n};\n\nexport async function run(\n args: Record<string, unknown>,\n context?: ActionRunContext,\n selfAppId?: string,\n): Promise<string> {\n const agentIdOrName = String(args.agent ?? \"\");\n const message = String(args.message ?? \"\");\n const taskId = String(args.taskId ?? \"\").trim();\n const action = String(args.action ?? \"\").trim();\n const input = args.input ?? {};\n const approvedActions = Array.isArray(args.approvedActions)\n ? (args.approvedActions as A2AApprovedAction[])\n : undefined;\n\n if (!agentIdOrName) return \"Error: --agent is required\";\n if (!message && !taskId && !action) {\n return \"Error: --message, --taskId, or --action is required\";\n }\n if (action && (message || taskId)) {\n return \"Error: --action direct-invoke mode cannot be combined with --message or --taskId\";\n }\n if (action && (!input || typeof input !== \"object\" || Array.isArray(input))) {\n return \"Error: --input must be an object when --action is provided\";\n }\n\n // Prevent self-calls — the agent must use its own registered tools instead\n if (selfAppId && agentIdOrName.toLowerCase() === selfAppId.toLowerCase()) {\n return `Error: You cannot use call-agent to call yourself (${selfAppId}). Use your own registered actions/tools instead. call-agent is only for communicating with OTHER separately-deployed apps.`;\n }\n\n const inheritedDepth = Number.isInteger(context?.delegationDepth)\n ? Math.max(0, Number(context?.delegationDepth))\n : 0;\n if (!taskId && inheritedDepth >= MAX_A2A_DELEGATION_HOPS) {\n return (\n `Error: Cross-app delegation stopped at the ${MAX_A2A_DELEGATION_HOPS}-hop limit. ` +\n \"Finish with the results already collected instead of starting another agent.\"\n );\n }\n\n const agent = await findAgent(agentIdOrName, selfAppId);\n if (!agent) {\n const available = (await discoverAgents(selfAppId))\n .map((a) => a.name)\n .join(\", \");\n return `Error: Agent \"${agentIdOrName}\" not found. Available agents: ${available || \"(none)\"}`;\n }\n\n if (!taskId) {\n const visited = new Set(\n (context?.visitedApps ?? []).map(normalizeAppHandle).filter(Boolean),\n );\n const self = normalizeAppHandle(selfAppId);\n if (self) visited.add(self);\n const targetHandles = [\n normalizeAppHandle((agent as { id?: string }).id),\n normalizeAppHandle(agent.name),\n normalizeAppHandle(agentIdOrName),\n ].filter(Boolean);\n const repeated = targetHandles.find((handle) => visited.has(handle));\n if (repeated) {\n return (\n `Error: Cross-app delegation cycle blocked before calling ${agent.name}. ` +\n `The request already visited ${[...visited].join(\" -> \")}.`\n );\n }\n }\n\n const correlation = buildDelegationCorrelation(context, selfAppId);\n const idempotencyKey =\n message && !taskId\n ? buildMessageIdempotencyKey(context?.turnId, agent.url, message)\n : undefined;\n const targetApp =\n normalizeAppHandle((agent as { id?: string }).id) ||\n normalizeAppHandle(agent.name) ||\n normalizeAppHandle(agentIdOrName) ||\n \"unknown\";\n\n if (action) {\n const agentCallId = randomUUID();\n const startedAt = Date.now();\n let terminalStatus: \"done\" | \"error\" = \"done\";\n let terminalCode: string | undefined;\n if (context?.send) {\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"start\",\n agentCallId,\n });\n }\n try {\n const output = await invokeReadOnlyAppAction(\n agent,\n action,\n input as Record<string, unknown>,\n buildDelegationCorrelation(context, selfAppId, randomUUID()),\n );\n if (/^Error\\b/i.test(output)) {\n terminalStatus = \"error\";\n terminalCode = \"direct_action_failed\";\n }\n if (context?.send && output) {\n context.send({\n type: \"agent_call_text\",\n agent: agent.name,\n text: output,\n agentCallId,\n });\n }\n return output;\n } catch (error) {\n terminalStatus = \"error\";\n terminalCode = \"direct_action_failed\";\n throw error;\n } finally {\n trackA2AInvocation({\n invocationId: agentCallId,\n callerApp: selfAppId,\n targetApp,\n mode: \"direct_action\",\n status: terminalStatus === \"done\" ? \"success\" : \"error\",\n startedAt,\n terminalCode,\n correlation,\n });\n if (context?.send) {\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: terminalStatus,\n agentCallId,\n durationMs: Date.now() - startedAt,\n });\n }\n }\n }\n\n // Append a small cross-app hint to the outgoing message so the receiving\n // agent (which may be on an older deploy without the receiver-side hint\n // in handlers.ts) still emits fully-qualified URLs. This is belt-and-\n // suspenders with the receiver hint — but it works against any current\n // deployment, no redeploy required.\n const sourceContext = integrationSourceContext();\n const messageWithHint = taskId\n ? \"\"\n : `${message}${integrationSourceContextHint(sourceContext)}\\n\\n` +\n `<a2a-caller-hint>\\n` +\n `This request comes from another app via A2A. The caller cannot see your local UI, deck list, or navigation — only the literal text you put in your reply. ` +\n `If you create or reference a deck/document/design/dashboard, include its FULLY-QUALIFIED URL (e.g. ${agent.url}/deck/<id>) in your reply, not a relative path. ` +\n `Use only artifact IDs and URL paths returned by successful actions — never invent slugs, IDs, or hosts. ` +\n `Return a concise caller-ready synthesis rather than raw tool output or full transcripts; preserve source counts, IDs, short supporting quotes, and URLs needed to substantiate the answer.\\n` +\n `</a2a-caller-hint>`;\n\n const invocationId = randomUUID();\n const invocationStartedAt = Date.now();\n let invocationStatus: A2AInvocationStatus = \"error\";\n let invocationTaskId = taskId || undefined;\n let invocationTerminalCode: string | undefined;\n\n try {\n // If we have a send context, use streaming so the UI shows progressive text\n if (context?.send) {\n const callerEmail = getRequestUserEmail();\n\n // Build metadata with identity\n const a2aMetadata: Record<string, unknown> = {};\n if (callerEmail) a2aMetadata.userEmail = callerEmail;\n\n // Include org domain for cross-app org resolution\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n const domain = await getOrgDomain(orgId);\n if (domain) {\n callerOrgDomain = domain;\n a2aMetadata.orgDomain = domain;\n }\n } catch {}\n try {\n const secret = await getOrgA2ASecret(orgId);\n if (secret) callerOrgSecret = secret;\n } catch {}\n }\n\n // Sign JWT with identity + org domain for the streaming client\n let apiKey: string | undefined;\n if (callerEmail && (callerOrgSecret || process.env.A2A_SECRET)) {\n try {\n apiKey = await signA2AToken(\n callerEmail,\n callerOrgDomain,\n callerOrgSecret,\n {\n expiresIn: INTEGRATION_A2A_TOKEN_TTL,\n preferGlobalSecret: shouldPreferGlobalA2ASecret(callerOrgSecret),\n },\n );\n } catch {}\n }\n\n if (process.env.NODE_ENV === \"production\" && callerEmail) {\n try {\n const { listOAuthAccountsByOwner } =\n await import(\"../oauth-tokens/store.js\");\n const accounts = await listOAuthAccountsByOwner(\n \"google\",\n callerEmail,\n );\n const tokens = accounts[0]?.tokens;\n if (tokens?.access_token) {\n a2aMetadata.googleToken = tokens.access_token;\n }\n } catch {}\n }\n\n let responseText = \"\";\n let lastSentLength = 0;\n const agentCallId = randomUUID();\n let terminalStatus: \"done\" | \"pending\" | \"error\" = \"done\";\n const existingContinuationText = taskId\n ? null\n : await formatExistingIntegrationContinuationIfRetry(agent, message);\n if (existingContinuationText) {\n invocationStatus = \"pending\";\n invocationTerminalCode = \"existing_continuation\";\n return existingContinuationText;\n }\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"start\",\n agentCallId,\n });\n\n const emitNewText = (newText: string) => {\n if (newText.length > lastSentLength) {\n context.send!({\n type: \"agent_call_text\",\n agent: agent.name,\n text: newText.slice(lastSentLength),\n agentCallId,\n });\n lastSentLength = newText.length;\n }\n responseText = newText;\n };\n\n // Skip the SSE streaming attempt and go straight to async + poll.\n // Why: on Netlify (Lambda), the receiving server has no streaming\n // response support, so message/stream returns a single JSON-RPC error\n // body in a 200 response that our SSE parser silently consumes — the\n // `for await` loop yields nothing AND keeps the connection open until\n // the function timeout, eating the current serverless budget. By the\n // time we get to the sync fallback, Lambda is dead and the second fetch\n // errors out as \"fetch failed\". Async+poll has its own short fetches\n // with their own budgets, so it works reliably across hosts. The\n // trade-off is that cross-app activity arrives at the poll cadence rather\n // than token-by-token. Agent Native peers attach their current reasoning,\n // tool status, and response preview to each task checkpoint, and the\n // receiver's full response still surfaces below.\n //\n // That trade-off has a second-order cost: callAgent()'s poll (see\n // A2AClient.sendAndWait in a2a/client.ts) can legitimately run for\n // minutes with nothing emitted to the parent between the \"start\" event\n // above and \"done\" below. On the parent run, that silence freezes\n // `last_progress_at` — shouldBumpProgressForEvent in\n // agent/run-manager.ts treats a stream of literally nothing as no\n // progress — which trips the client's stuck-detector\n // (DEFAULT_STUCK_THRESHOLD_MS = 90_000 in\n // client/use-run-stuck-detection.ts) and the server's stale-run sweep\n // (BACKGROUND_RUN_STALE_MS = 90_000 in agent/run-store.ts). In\n // production this handed users a \"still working, no progress\" Retry\n // button that aborted a perfectly healthy call and re-ran the sub-agent\n // from scratch.\n //\n // Fix: surface the REAL remote liveness the poll already gathers. The\n // A2A poll round-trips to the remote agent every ~2s and gets back a\n // task with `status.state` (see A2AClient.sendAndWait / `onUpdate`). We\n // emit an `agent_call_progress` event ONLY from that callback, and ONLY\n // when a poll actually succeeds AND reports an actively-working state.\n // Crucially this is NOT a timer: if the remote hangs or dies, the poll\n // fetch throws, `onUpdate` stops firing, we emit nothing, and the\n // stuck-detector correctly surfaces its banner. A wall-clock heartbeat\n // would instead keep a dead sub-agent looking alive forever — trading a\n // false stuck-positive for a worse false stuck-negative.\n //\n // Throttle: the poll runs every ~2s but both thresholds above are 90s,\n // so emitting per-poll would be ~45 events per stuck-window. We coalesce\n // to at most one emission per 30s — a 3x margin under 90s, so at least\n // two land inside either window even with jitter, without flooding.\n //\n // Shape: a dedicated `agent_call_progress` event type (see\n // agent/types.ts), not an extra `agent_call` status. `agent_call`\n // consumers (production-agent.ts's step summarizer, slack.ts's task\n // cards) render any status that isn't \"start\"/\"done\" as a failure, so a\n // \"progress\" status would surface an in-flight tick as an error. A\n // distinct type is instead ignored gracefully everywhere: the run-event\n // switches fall to their `default`, the client if-chains fall through,\n // and sse-event-processor returns `{action:\"continue\"}`. It still counts\n // as real progress in shouldBumpProgressForEvent (any non-special event\n // type does), which is the whole point.\n const PROGRESS_MIN_INTERVAL_MS = 30_000;\n // Terminal states resolve the poll; \"input-required\" means the remote is\n // blocked waiting on us, not making progress. Only actively-working\n // states count as liveness worth surfacing.\n const ACTIVELY_WORKING_STATES = new Set([\n \"working\",\n \"submitted\",\n \"processing\",\n ]);\n const callStartedAt = Date.now();\n let lastProgressEmitAt = callStartedAt;\n let lastActivitySequence = -1;\n const onRemotePollUpdate = (task: Task) => {\n const state = task?.status?.state;\n const parts = task.status?.message?.parts;\n const snapshot = Array.isArray(parts)\n ? parts.map(parseA2AAgentActivityPart).find((value) => value !== null)\n : undefined;\n if (snapshot && snapshot.sequence > lastActivitySequence) {\n lastActivitySequence = snapshot.sequence;\n context.send!({\n type: \"agent_call_activity\",\n agent: agent.name,\n agentCallId,\n snapshot,\n });\n }\n if (!state || !ACTIVELY_WORKING_STATES.has(state)) return;\n const now = Date.now();\n if (now - lastProgressEmitAt < PROGRESS_MIN_INTERVAL_MS) return;\n lastProgressEmitAt = now;\n const detail = extractRemoteProgressDetail(task);\n context.send!({\n type: \"agent_call_progress\",\n agent: agent.name,\n state,\n elapsedSeconds: Math.round((now - callStartedAt) / 1000),\n agentCallId,\n ...(detail ? { detail } : {}),\n });\n };\n\n try {\n // Apply a polling cap ONLY for integration-platform callers on\n // serverless hosts. Normal chat, local Node, self-hosted Node, and\n // Docker can wait for slow-but-valid answers; integration processors\n // still need to finish before their current function execution dies.\n const callTimeoutMs = getIntegrationCallTimeoutMs();\n responseText = await callAgent(agent.url, messageWithHint, {\n apiKey,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n approvedActions,\n ...(sourceContext ? { sourceContext: sourceContext.reference } : {}),\n contextId: context.threadId,\n correlation,\n idempotencyKey,\n ...(taskId ? { taskId } : {}),\n onUpdate: onRemotePollUpdate,\n returnRecoverableArtifactsOnTimeout: false,\n ...(callTimeoutMs\n ? {\n timeoutMs: callTimeoutMs,\n }\n : {}),\n });\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, responseText) ??\n responseText;\n // Some agents reply with relative paths (e.g. slides emits\n // \"/deck/abc\"). Those resolve against the caller's host, not the\n // receiver's, so they're broken for the user. Expand any leading-slash\n // URL into a fully-qualified one rooted at the receiving agent's host.\n responseText = expandRelativeUrls(responseText, agent.url);\n // Mirror the response into the streaming UI so the user sees it.\n if (responseText) emitNewText(responseText);\n } catch (pollErr: any) {\n const timeoutTaskId = getA2ATaskTimeoutTaskId(pollErr);\n if (timeoutTaskId) {\n terminalStatus = \"pending\";\n invocationTaskId = timeoutTaskId;\n invocationTerminalCode = \"timeout_pending\";\n const queued = await enqueueIntegrationContinuationIfPossible(\n timeoutTaskId,\n agent,\n message,\n callerEmail,\n );\n if (queued) {\n responseText =\n `${A2A_CONTINUATION_QUEUED_MARKER}\\n` +\n `The ${agent.name} agent accepted this delegated subtask and will post its own final result to the originating integration thread automatically. ` +\n `Do not call ${agent.name} again for this same subtask. Continue any other requested work, then answer with the completed results you have; if needed, mention that ${agent.name} is posting its result separately.`;\n } else {\n // The normal integration path must preserve the timeout task id so\n // it can enqueue a durable continuation. If that enqueue fails,\n // do not hide receiver-verified artifacts that were already\n // returned with the last poll; this mirrors callAgent's default\n // timeout behavior without treating arbitrary remote status text\n // as a completed response.\n const recoverableArtifactText =\n extractRecoverableTimeoutArtifactText(pollErr);\n if (recoverableArtifactText) {\n responseText = expandRelativeUrls(\n recoverableArtifactText,\n agent.url,\n );\n } else {\n responseText = formatExistingTaskWaitInstruction(\n agent.name,\n timeoutTaskId,\n agentIdOrName,\n );\n }\n }\n } else if (terminalTaskError(pollErr)?.state === \"input-required\") {\n terminalStatus = \"pending\";\n const terminal = terminalTaskError(pollErr)!;\n invocationTaskId = terminal.taskId;\n invocationTerminalCode = terminal.errorCode ?? \"input_required\";\n responseText = formatInputRequiredWaitInstruction(\n agent.name,\n terminal,\n agentIdOrName,\n );\n } else if (terminalTaskError(pollErr)) {\n terminalStatus = \"error\";\n const terminal = terminalTaskError(pollErr)!;\n invocationTaskId = terminal.taskId;\n invocationTerminalCode = terminal.errorCode ?? terminal.state;\n const detail = expandRelativeUrls(\n terminal.responseText ?? pollErr?.message ?? \"unknown failure\",\n agent.url,\n );\n responseText =\n `Error: The ${agent.name} agent ended ${terminal.state}` +\n (terminal.errorCode ? ` (${terminal.errorCode})` : \"\") +\n (terminal.taskId ? ` [taskId: ${terminal.taskId}]` : \"\") +\n (detail ? `: ${detail}` : \"\");\n } else {\n terminalStatus = \"error\";\n invocationTerminalCode = \"call_failed\";\n const reason = pollErr?.message ?? \"unknown error\";\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, pollErr) ??\n `Error: The ${agent.name} agent call failed. (${reason})`;\n }\n }\n\n if (!responseText && terminalStatus === \"done\") {\n terminalStatus = \"error\";\n invocationTerminalCode = \"empty_agent_response\";\n }\n if (responseText.length > MAX_A2A_CALLER_RESPONSE_CHARS) {\n terminalStatus = \"error\";\n invocationTerminalCode = \"a2a_response_too_large\";\n responseText =\n `Error: The ${agent.name} agent returned more data than the caller can safely consume. ` +\n \"Ask it for a concise synthesis or a retrievable artifact instead.\";\n }\n invocationStatus =\n terminalStatus === \"done\"\n ? \"success\"\n : terminalStatus === \"pending\"\n ? \"pending\"\n : \"error\";\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: terminalStatus,\n agentCallId,\n ...(invocationTaskId ? { taskId: invocationTaskId } : {}),\n durationMs: Date.now() - callStartedAt,\n });\n\n return (\n responseText || `Error: The ${agent.name} agent returned no result.`\n );\n }\n\n // No context — use the async + poll call so we don't get cut off at the\n // serverless gateway's ~30s timeout. callAgent defaults to async:true.\n const email = getRequestUserEmail();\n let domain: string | undefined;\n let orgSecret: string | undefined;\n const currentOrgId = getRequestOrgId();\n if (currentOrgId) {\n try {\n domain = (await getOrgDomain(currentOrgId)) ?? undefined;\n } catch {}\n try {\n orgSecret = (await getOrgA2ASecret(currentOrgId)) ?? undefined;\n } catch {}\n }\n const response = await callAgent(agent.url, messageWithHint, {\n userEmail: email,\n orgDomain: domain,\n orgSecret,\n approvedActions,\n ...(sourceContext ? { sourceContext: sourceContext.reference } : {}),\n contextId: context?.threadId,\n correlation,\n idempotencyKey,\n ...(taskId ? { taskId } : {}),\n returnRecoverableArtifactsOnTimeout: false,\n });\n const sanitized =\n formatDownstreamLlmCredentialFailure(agent.name, response) ?? response;\n const expanded = expandRelativeUrls(sanitized, agent.url);\n if (!expanded) {\n invocationStatus = \"error\";\n invocationTerminalCode = \"empty_agent_response\";\n return \"Error: The remote agent returned no result.\";\n }\n if (expanded.length > MAX_A2A_CALLER_RESPONSE_CHARS) {\n invocationStatus = \"error\";\n invocationTerminalCode = \"a2a_response_too_large\";\n return (\n `Error: The ${agent.name} agent returned more data than the caller can safely consume. ` +\n \"Ask it for a concise synthesis or a retrievable artifact instead.\"\n );\n }\n invocationStatus = \"success\";\n return expanded;\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n const credentialMessage = formatDownstreamLlmCredentialFailure(\n agent.name,\n err,\n );\n if (credentialMessage) return credentialMessage;\n const terminal = terminalTaskError(err);\n if (terminal?.state === \"input-required\") {\n invocationStatus = \"pending\";\n invocationTaskId = terminal.taskId;\n invocationTerminalCode = terminal.errorCode ?? \"input_required\";\n return formatInputRequiredWaitInstruction(\n agent.name,\n terminal,\n agentIdOrName,\n );\n }\n if (terminal) {\n invocationStatus = \"error\";\n invocationTaskId = terminal.taskId;\n invocationTerminalCode = terminal.errorCode ?? terminal.state;\n return (\n `Error calling ${agent.name}: remote task ${terminal.state}` +\n (terminal.errorCode ? ` (${terminal.errorCode})` : \"\") +\n (terminal.taskId ? ` [taskId: ${terminal.taskId}]` : \"\") +\n (terminal.responseText ? `: ${terminal.responseText}` : \"\")\n );\n }\n const timeoutTaskId = getA2ATaskTimeoutTaskId(err);\n if (timeoutTaskId) {\n invocationStatus = \"pending\";\n invocationTaskId = timeoutTaskId;\n invocationTerminalCode = \"timeout_pending\";\n return formatExistingTaskWaitInstruction(\n agent.name,\n timeoutTaskId,\n agentIdOrName,\n );\n }\n // Friendlier message for the common timeout case so the calling agent can\n // decide whether to give up or retry.\n if (/timeout|did not complete|Inactivity|504/i.test(msg)) {\n invocationStatus = \"error\";\n invocationTerminalCode = \"timeout_without_task\";\n return `Error calling ${agent.name}: the remote request timed out before a task id could be recovered.`;\n }\n invocationStatus = \"error\";\n invocationTerminalCode = \"call_failed\";\n return `Error calling ${agent.name}: ${msg}`;\n } finally {\n trackA2AInvocation({\n invocationId,\n callerApp: selfAppId,\n targetApp,\n mode: taskId ? \"task_poll\" : \"message\",\n status: invocationStatus,\n startedAt: invocationStartedAt,\n taskId: invocationTaskId,\n terminalCode: invocationTerminalCode,\n correlation,\n });\n }\n}\n\nasync function invokeReadOnlyAppAction(\n agent: { name: string; url: string },\n action: string,\n input: Record<string, unknown>,\n correlation: A2ACorrelationMetadata,\n): Promise<string> {\n const callerEmail = getRequestUserEmail();\n if (!callerEmail) {\n return `Error calling ${agent.name} action ${action}: a signed-in user identity is required`;\n }\n\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n callerOrgDomain = (await getOrgDomain(orgId)) ?? undefined;\n } catch {}\n try {\n callerOrgSecret = (await getOrgA2ASecret(orgId)) ?? undefined;\n } catch {}\n }\n\n if (!callerOrgSecret && !process.env.A2A_SECRET) {\n return `Error calling ${agent.name} action ${action}: direct cross-app reads require A2A identity verification`;\n }\n\n try {\n const invocation = await invokeAgentAction({\n target: agent.url,\n action,\n input,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n correlation,\n });\n return invocation.result.status === \"completed\"\n ? invocation.result.output\n : `Error calling ${agent.name} action ${action}: ${invocation.result.output}`;\n } catch (error) {\n return `Error calling ${agent.name} action ${action}: ${\n error instanceof Error ? error.message : String(error)\n }`;\n }\n}\n\nfunction formatExistingTaskWaitInstruction(\n agentName: string,\n taskId: string,\n agentIdOrName: string,\n): string {\n return (\n `The ${agentName} task is still running under taskId \"${taskId}\". ` +\n `Do not send ${agentName} a new check-in or follow-up message; that would start duplicate work. ` +\n `Call call-agent again with agent=\"${agentIdOrName}\" and taskId=\"${taskId}\" (omit message) to continue waiting for this same task.`\n );\n}\n\nfunction formatInputRequiredWaitInstruction(\n agentName: string,\n terminal: {\n taskId?: string;\n responseText?: string;\n },\n agentIdOrName: string,\n): string {\n const detail = terminal.responseText?.trim();\n if (!terminal.taskId) {\n return (\n (detail ? `${detail}\\n\\n` : \"\") +\n `Pending: The ${agentName} agent needs input before it can continue.`\n );\n }\n return (\n (detail ? `${detail}\\n\\n` : \"\") +\n `The ${agentName} agent is waiting for input under taskId \"${terminal.taskId}\". ` +\n `After providing or approving the requested input, call call-agent with agent=\"${agentIdOrName}\" and taskId=\"${terminal.taskId}\" (omit message) to continue this same task. Do not start a new message for this work.`\n );\n}\n\nasync function enqueueIntegrationContinuationIfPossible(\n taskId: string,\n agent: { name: string; url: string },\n message: string,\n ownerEmail: string | undefined,\n): Promise<boolean> {\n const integration = getIntegrationRequestContext();\n if (!integration || !ownerEmail) return false;\n\n try {\n const [{ insertA2AContinuation }, { dispatchA2AContinuation }] =\n await Promise.all([\n import(\"../integrations/a2a-continuations-store.js\"),\n import(\"../integrations/a2a-continuation-processor.js\"),\n ]);\n const continuation = await insertA2AContinuation({\n integrationTaskId: integration.taskId,\n platform: integration.incoming.platform,\n externalThreadId: integration.incoming.externalThreadId,\n incoming: integration.incoming,\n placeholderRef: integration.placeholderRef,\n progressRef: integration.progressRef,\n ownerEmail,\n orgId: getRequestOrgId() ?? null,\n agentName: agent.name,\n agentUrl: agent.url,\n dedupeKey: getIntegrationContinuationDedupeKey(message),\n a2aTaskId: taskId,\n // Do not persist the short-lived JWT used for the initial send. The\n // continuation processor can mint a fresh token for each poll.\n a2aAuthToken: null,\n });\n await dispatchA2AContinuation(continuation.id).catch((err) => {\n console.error(\n `[call-agent] Failed to dispatch A2A continuation ${continuation.id}:`,\n err,\n );\n });\n return true;\n } catch (err) {\n console.error(\"[call-agent] Failed to enqueue A2A continuation:\", err);\n return false;\n }\n}\n\n// Pull a short human-readable detail from a polled A2A task's status message,\n// when the remote includes one, so the progress event can surface a real\n// signal (e.g. \"Generating hero image…\") instead of a bare elapsed counter.\n// Bounded so a chatty remote can't push a large payload through the event.\nconst MAX_PROGRESS_DETAIL_CHARS = 200;\nfunction extractRemoteProgressDetail(task: Task): string | undefined {\n const parts = task.status?.message?.parts;\n if (!Array.isArray(parts)) return undefined;\n const text = parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text)\n .join(\" \")\n .replace(/\\s+/g, \" \")\n .trim();\n if (!text) return undefined;\n return text.length > MAX_PROGRESS_DETAIL_CHARS\n ? `${text.slice(0, MAX_PROGRESS_DETAIL_CHARS - 1)}…`\n : text;\n}\n\nfunction getA2ATaskTimeoutTaskId(err: unknown): string | null {\n if (err instanceof A2ATaskTimeoutError) return err.taskId;\n\n const candidate = err as\n | { name?: unknown; taskId?: unknown; message?: unknown }\n | null\n | undefined;\n const message = String(candidate?.message ?? \"\");\n if (\n candidate?.name === \"A2ATaskTimeoutError\" &&\n typeof candidate.taskId === \"string\"\n ) {\n return candidate.taskId;\n }\n\n const match = message.match(/^A2A task ([^\\s]+) did not complete\\b/);\n return match?.[1] ?? null;\n}\n\n/**\n * Mirrors the A2A client's default timeout recovery for the exceptional case\n * where an integration cannot enqueue a durable continuation. Only an\n * explicitly receiver-marked task message is safe to surface as a completed\n * partial result; ordinary working-state text remains a timeout failure.\n */\nfunction extractRecoverableTimeoutArtifactText(err: unknown): string {\n const candidate = err as\n | { lastTask?: Task | unknown; name?: unknown }\n | null\n | undefined;\n const lastTask =\n err instanceof A2ATaskTimeoutError\n ? err.lastTask\n : candidate?.name === \"A2ATaskTimeoutError\"\n ? (candidate.lastTask as Task | undefined)\n : undefined;\n const message = lastTask?.status?.message;\n if (!message?.metadata?.agentNativeRecoverableArtifacts) return \"\";\n\n return message.parts\n .filter(\n (part): part is { type: \"text\"; text: string } => part.type === \"text\",\n )\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\nasync function formatExistingIntegrationContinuationIfRetry(\n agent: {\n name: string;\n url: string;\n },\n message: string,\n): Promise<string | null> {\n const integration = getIntegrationRequestContext();\n if (!integration || (integration.attempts ?? 1) <= 1) return null;\n\n try {\n const { getA2AContinuationsForIntegrationTaskAgent } =\n await import(\"../integrations/a2a-continuations-store.js\");\n const continuations = await getA2AContinuationsForIntegrationTaskAgent(\n integration.taskId,\n agent.url,\n getIntegrationContinuationDedupeKey(message),\n );\n const active = continuations.find((continuation) =>\n [\"pending\", \"processing\", \"delivering\", \"completed\"].includes(\n continuation.status,\n ),\n );\n if (!active) return null;\n\n const state =\n active.status === \"completed\"\n ? \"already completed this delegated subtask and posted its result to the originating integration thread\"\n : \"already accepted this delegated subtask and is still working on it for the originating integration thread\";\n return (\n `${A2A_CONTINUATION_QUEUED_MARKER}\\n` +\n `The ${agent.name} agent ${state}. Do not call ${agent.name} again for this same subtask. Continue any other requested work, then answer with the completed results you have; if needed, mention that ${agent.name} is posting or has posted its result separately.`\n );\n } catch (err) {\n console.error(\"[call-agent] Failed to inspect existing continuation:\", err);\n return null;\n }\n}\n\nfunction getIntegrationContinuationDedupeKey(message: string): string {\n const normalized = message.trim().replace(/\\s+/g, \" \");\n return createHash(\"sha256\").update(normalized).digest(\"hex\");\n}\n\n// Expand bare leading-slash paths (e.g. \"/deck/abc\") into fully-qualified URLs\n// rooted at the receiving agent's host. The receiver doesn't always know it's\n// being called cross-app, so it may emit relative paths that resolve against\n// the caller's host (broken). Match a path that starts at a word boundary,\n// begins with `/`, and has at least one path segment after that. Skip if it\n// already looks like a fully-qualified URL.\nexport function expandRelativeUrls(text: string, agentUrl: string): string {\n if (!text || !agentUrl) return text;\n const base = agentUrl.replace(/\\/$/, \"\");\n // Path must start at boundary (start, whitespace, or punctuation that isn't\n // ':' — to avoid mangling `https://example.com/foo` or markdown link bodies).\n return text.replace(\n /(^|[\\s([<\"'`])(\\/[a-z0-9_-][a-z0-9_/?&=%#.,:-]*)/gi,\n (_match, lead, path) => `${lead}${base}${path}`,\n );\n}\n"]}
1
+ {"version":3,"file":"call-agent.js","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAErD,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EACL,mBAAmB,EACnB,6BAA6B,EAC7B,SAAS,EACT,2BAA2B,EAC3B,YAAY,GACb,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAQrD,OAAO,EACL,+BAA+B,EAC/B,oBAAoB,GACrB,MAAM,sCAAsC,CAAC;AAG9C,OAAO,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AAC5F,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EACL,mBAAmB,EACnB,eAAe,EACf,oBAAoB,EACpB,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,KAAK,EAAE,MAAM,yBAAyB,CAAC;AAEhD,MAAM,6CAA6C,GAAG,MAAM,CAAC;AAC7D,MAAM,kCAAkC,GAAG,KAAK,CAAC;AACjD,MAAM,yBAAyB,GAAG,KAAK,CAAC;AACxC,MAAM,oBAAoB,GAAG,iBAAiB,CAAC;AAI/C,SAAS,kBAAkB,CAAC,IAU3B;IACC,IAAI,CAAC;QACH,KAAK,CACH,oBAAoB,EACpB;YACE,GAAG,0BAA0B,EA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KAAK,iBAAiB,KAAK,CAAC,IAAI,6IAA6I,KAAK,CAAC,IAAI,kDAAkD,CACrQ,CAAC;IACJ,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,uDAAuD,EAAE,GAAG,CAAC,CAAC;QAC5E,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,SAAS,mCAAmC,CAAC,OAAe;IAC1D,MAAM,UAAU,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACvD,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC/D,CAAC;AAED,+EAA+E;AAC/E,8EAA8E;AAC9E,6EAA6E;AAC7E,2EAA2E;AAC3E,4EAA4E;AAC5E,4CAA4C;AAC5C,MAAM,UAAU,kBAAkB,CAAC,IAAY,EAAE,QAAgB;IAC/D,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IACpC,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACzC,4EAA4E;IAC5E,8EAA8E;IAC9E,OAAO,IAAI,CAAC,OAAO,CACjB,oDAAoD,EACpD,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE,CAChD,CAAC;AACJ,CAAC","sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\n\nimport { parseA2AAgentActivityPart } from \"../a2a/activity.js\";\nimport {\n A2ATaskTimeoutError,\n MAX_A2A_CALLER_RESPONSE_CHARS,\n callAgent,\n shouldPreferGlobalA2ASecret,\n signA2AToken,\n} from \"../a2a/client.js\";\nimport { MAX_A2A_DELEGATION_HOPS } from \"../a2a/correlation.js\";\nimport { invokeAgentAction } from \"../a2a/invoke.js\";\nimport type {\n A2AApprovedAction,\n A2ACorrelationMetadata,\n A2ASourceContext,\n A2ASourceContextReference,\n Task,\n} from \"../a2a/types.js\";\nimport {\n formatLlmCredentialErrorMessage,\n isLlmCredentialError,\n} from \"../agent/engine/credential-errors.js\";\nimport type { ActionRunContext } from \"../agent/production-agent.js\";\nimport type { ActionTool } from \"../agent/types.js\";\nimport { A2A_CONTINUATION_QUEUED_MARKER } from \"../integrations/a2a-continuation-marker.js\";\nimport { trackingIdentityProperties } from \"../observability/tracking-identity.js\";\nimport { getOrgDomain, getOrgA2ASecret } from \"../org/context.js\";\nimport { findAgent, discoverAgents } from \"../server/agent-discovery.js\";\nimport {\n getRequestUserEmail,\n getRequestOrgId,\n getRequestRunContext,\n isIntegrationCallerRequest,\n getIntegrationRequestContext,\n} from \"../server/request-context.js\";\nimport { track } from \"../tracking/registry.js\";\n\nconst DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;\nconst NETLIFY_INTEGRATION_A2A_TIMEOUT_MS = 2_000;\nconst INTEGRATION_A2A_TOKEN_TTL = \"30m\";\nconst A2A_INVOCATION_EVENT = \"$a2a_invocation\";\n\ntype A2AInvocationStatus = \"success\" | \"pending\" | \"error\";\n\nfunction trackA2AInvocation(args: {\n invocationId: string;\n callerApp?: string;\n targetApp: string;\n mode: \"message\" | \"task_poll\" | \"direct_action\";\n status: A2AInvocationStatus;\n startedAt: number;\n taskId?: string;\n terminalCode?: string;\n correlation: A2ACorrelationMetadata;\n}): void {\n try {\n track(\n A2A_INVOCATION_EVENT,\n {\n ...trackingIdentityProperties(),\n source: \"a2a_delegation\",\n invocation_id: args.invocationId,\n caller_app: args.callerApp ?? \"unknown\",\n target_app: args.targetApp,\n mode: args.mode,\n status: args.status,\n duration_ms: Math.max(0, Date.now() - args.startedAt),\n task_id: args.taskId,\n terminal_code: args.terminalCode,\n delegation_depth: args.correlation.delegationDepth,\n parent_run_id: args.correlation.parentRunId,\n parent_turn_id: args.correlation.parentTurnId,\n },\n { userId: getRequestUserEmail() },\n );\n } catch {\n // Tracking must never affect delegation.\n }\n}\n\nfunction buildDelegationCorrelation(\n context: ActionRunContext | undefined,\n selfAppId: string | undefined,\n invocationId?: string,\n): A2ACorrelationMetadata {\n const self = normalizeAppHandle(selfAppId);\n const inheritedVisited = Array.isArray(context?.visitedApps)\n ? context.visitedApps.map(normalizeAppHandle).filter(Boolean)\n : [];\n const visitedApps = self\n ? [...new Set([...inheritedVisited, self])]\n : [...new Set(inheritedVisited)];\n const inheritedDepth = Number.isInteger(context?.delegationDepth)\n ? Math.max(0, Number(context?.delegationDepth))\n : 0;\n // The model this turn is actually running on, so a receiver with no model of\n // its own can match the user's selection instead of its own default. A\n // preference only — the receiver bounds it to its own engine's catalog.\n const callerModel = getRequestRunContext()?.model?.trim();\n return {\n ...(selfAppId?.trim() ? { callerApp: selfAppId.trim() } : {}),\n ...(callerModel ? { callerModel } : {}),\n ...(context?.threadId ? { callerThreadId: context.threadId } : {}),\n ...(context?.runId ? { parentRunId: context.runId } : {}),\n ...(context?.turnId ? { parentTurnId: context.turnId } : {}),\n ...(invocationId ? { invocationId } : {}),\n delegationDepth: Math.min(MAX_A2A_DELEGATION_HOPS, inheritedDepth + 1),\n ...(visitedApps.length > 0 ? { visitedApps } : {}),\n };\n}\n\nfunction normalizeAppHandle(value: unknown): string {\n return typeof value === \"string\"\n ? value\n .trim()\n .toLowerCase()\n .replace(/^agent-native-/, \"\")\n : \"\";\n}\n\nfunction terminalTaskError(value: unknown): {\n state: string;\n taskId?: string;\n responseText?: string;\n errorCode?: string;\n} | null {\n if (!value || typeof value !== \"object\") return null;\n const candidate = value as Record<string, unknown>;\n if (candidate.name !== \"A2ATaskTerminalError\") return null;\n return {\n state: String(candidate.state ?? \"failed\"),\n ...(typeof candidate.taskId === \"string\"\n ? { taskId: candidate.taskId }\n : {}),\n ...(typeof candidate.responseText === \"string\"\n ? { responseText: candidate.responseText }\n : {}),\n ...(typeof candidate.errorCode === \"string\"\n ? { errorCode: candidate.errorCode }\n : {}),\n };\n}\n\nfunction buildMessageIdempotencyKey(\n originatingTurnId: string | undefined,\n target: string,\n exactMessage: string,\n): string | undefined {\n if (!originatingTurnId) return undefined;\n const digest = createHash(\"sha256\")\n .update(\n JSON.stringify({\n originatingTurnId,\n target,\n message: exactMessage,\n }),\n )\n .digest(\"hex\");\n return `v1:${digest}`;\n}\n\nfunction parseTimeoutMs(value: string | undefined): number | undefined {\n if (!value) return undefined;\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) return undefined;\n return Math.floor(parsed);\n}\n\nfunction isServerlessHost(): boolean {\n // Detection mirrors db/migrations.ts:297-301. On Cloudflare Workers/Pages,\n // `process.env` is shimmed and CF_PAGES isn't reliably populated at runtime —\n // the canonical signal is the `__cf_env`/`__env__` global injected by the\n // Cloudflare runtime adapter.\n return (\n !!process.env.NETLIFY ||\n !!process.env.AWS_LAMBDA_FUNCTION_NAME ||\n !!process.env.VERCEL ||\n \"__cf_env\" in globalThis ||\n \"__env__\" in globalThis\n );\n}\n\nfunction getIntegrationCallTimeoutMs(): number | undefined {\n if (!isServerlessHost() || !isIntegrationCallerRequest()) return undefined;\n\n const configured = parseTimeoutMs(\n process.env.AGENT_NATIVE_INTEGRATION_A2A_TIMEOUT_MS,\n );\n if (configured !== undefined) return configured;\n\n // Netlify's current synchronous function budget is 60s. Keep delegated\n // calls very short so multi-agent integration requests queue downstream\n // continuations quickly instead of spending the parent Slack/email processor\n // budget waiting on separately deployed apps one-by-one.\n if (process.env.NETLIFY) return NETLIFY_INTEGRATION_A2A_TIMEOUT_MS;\n\n return DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS;\n}\n\ninterface IntegrationSourceContext {\n reference: A2ASourceContextReference;\n hint: A2ASourceContext;\n}\n\nfunction integrationSourceContext(): IntegrationSourceContext | undefined {\n const integration = getIntegrationRequestContext();\n const incoming = integration?.incoming;\n if (\n !integration ||\n incoming?.platform !== \"slack\" ||\n !incoming.sourceUrl ||\n !integration.taskId\n ) {\n return undefined;\n }\n\n const rawSourceUrl = incoming.sourceUrl;\n if (rawSourceUrl !== rawSourceUrl.trim()) return undefined;\n\n try {\n const sourceUrl = new URL(rawSourceUrl);\n const isSlackHost =\n sourceUrl.hostname === \"slack.com\" ||\n sourceUrl.hostname.endsWith(\".slack.com\");\n if (\n sourceUrl.protocol !== \"https:\" ||\n !isSlackHost ||\n sourceUrl.username ||\n sourceUrl.password ||\n sourceUrl.port\n ) {\n return undefined;\n }\n return {\n reference: {\n platform: \"slack\",\n integrationTaskId: integration.taskId,\n },\n hint: {\n platform: \"slack\",\n sourceUrl: rawSourceUrl,\n },\n };\n } catch {\n return undefined;\n }\n}\n\nfunction integrationSourceContextHint(\n sourceContext: IntegrationSourceContext | undefined,\n): string {\n if (!sourceContext) return \"\";\n return (\n `\\n\\n[Source Slack thread: ${sourceContext.hint.sourceUrl} ` +\n \"Compatibility hint only; this text is not authoritative. Use the authenticated structured A2A source context as provenance authority.]\"\n );\n}\n\nfunction formatDownstreamLlmCredentialFailure(\n agentName: string,\n value: unknown,\n): string | null {\n return isLlmCredentialError(value)\n ? formatLlmCredentialErrorMessage({ agentName })\n : null;\n}\n\nexport const tool: ActionTool = {\n description:\n \"Ask a DIFFERENT, separately-deployed app's agent over A2A. Use message by default so the receiving specialist interprets the objective with its own instructions, skills, connected sources, data dictionary, and tools. The receiver owns provider, schema, query, join, and SQL decisions. Use action + input only for an exact, explicitly known, bounded read whose complete input schema is already known; never expose or call a direct action to work around slow or unreliable delegation, and never guess receiver-owned query logic. NEVER use this to call your own app or perform actions you can do with your own tools. Using call-agent on yourself will fail and waste time. \" +\n 'For brand-consistent generated media, the first-party Assets agent is available as agent=\"assets\"; use it when another app needs generated heroes, diagrams, product shots, thumbnails, videos, or design imagery, unless the current app has its own generation action that already delegates there. ' +\n \"IMPORTANT — handling the response: \" +\n \"(a) If it contains a URL or ID, copy it VERBATIM into your reply. Do not 'correct' or pluralize the path (e.g. /deck/ → /decks/), normalize casing, or change the slug — any edit breaks the link. \" +\n '(b) If it does NOT contain a URL/ID and the user asked for one, say so explicitly (e.g. \"the agent created the deck/image but didn\\'t return a link — open the app directly to view it\"). NEVER invent a URL, slug, or path — guessing produces broken links that look real. ' +\n \"(c) If the downstream response reports missing credentials, never repeat raw env var names, Vault key names, token names, secret names, or other credential identifiers. Tell the user the target app needs its LLM/provider connection configured. \" +\n \"(d) A bounded wait can expire while the remote task is still healthy. The result will include its taskId and exact retry instructions. Continue polling that SAME task with taskId; NEVER send a new check-in/follow-up message, because that starts duplicate downstream work.\",\n parameters: {\n type: \"object\",\n properties: {\n agent: {\n type: \"string\",\n description:\n \"Name or URL of a DIFFERENT deployed agent app (e.g. 'mail', 'calendar', 'analytics'). Must not be the current app's own name.\",\n },\n message: {\n type: \"string\",\n description:\n \"The message/question to send when starting a new task. Omit when taskId is provided.\",\n },\n taskId: {\n type: \"string\",\n description:\n \"Existing A2A task ID returned by a timed-out call. Polls that exact task without sending a new message. Never create a fresh check-in message for work that already has a taskId.\",\n },\n action: {\n type: \"string\",\n description:\n \"Optional exact read-only action for an explicitly known bounded operation. Prefer message when the target agent must interpret data, choose sources or tools, synthesize, mutate, or do multi-step work. Never guess the action schema or send receiver-owned SQL.\",\n },\n input: {\n type: \"object\",\n description:\n \"Complete input object for action. The target app validates it and refuses actions that are not explicitly exposed read-only operations.\",\n additionalProperties: true,\n },\n approvedActions: {\n type: \"array\",\n description:\n \"Exact downstream tool calls the current user explicitly authorized in this chat. Never infer authorization or include a broader/different action.\",\n items: {\n type: \"object\",\n properties: {\n tool: { type: \"string\" },\n input: { type: \"object\", additionalProperties: true },\n },\n required: [\"tool\", \"input\"],\n },\n },\n },\n required: [\"agent\"],\n },\n};\n\nexport async function run(\n args: Record<string, unknown>,\n context?: ActionRunContext,\n selfAppId?: string,\n): Promise<string> {\n const agentIdOrName = String(args.agent ?? \"\");\n const message = String(args.message ?? \"\");\n const taskId = String(args.taskId ?? \"\").trim();\n const action = String(args.action ?? \"\").trim();\n const input = args.input ?? {};\n const approvedActions = Array.isArray(args.approvedActions)\n ? (args.approvedActions as A2AApprovedAction[])\n : undefined;\n\n if (!agentIdOrName) return \"Error: --agent is required\";\n if (!message && !taskId && !action) {\n return \"Error: --message, --taskId, or --action is required\";\n }\n if (action && (message || taskId)) {\n return \"Error: --action direct-invoke mode cannot be combined with --message or --taskId\";\n }\n if (action && (!input || typeof input !== \"object\" || Array.isArray(input))) {\n return \"Error: --input must be an object when --action is provided\";\n }\n\n // Prevent self-calls — the agent must use its own registered tools instead\n if (selfAppId && agentIdOrName.toLowerCase() === selfAppId.toLowerCase()) {\n return `Error: You cannot use call-agent to call yourself (${selfAppId}). Use your own registered actions/tools instead. call-agent is only for communicating with OTHER separately-deployed apps.`;\n }\n\n const inheritedDepth = Number.isInteger(context?.delegationDepth)\n ? Math.max(0, Number(context?.delegationDepth))\n : 0;\n if (!taskId && inheritedDepth >= MAX_A2A_DELEGATION_HOPS) {\n return (\n `Error: Cross-app delegation stopped at the ${MAX_A2A_DELEGATION_HOPS}-hop limit. ` +\n \"Finish with the results already collected instead of starting another agent.\"\n );\n }\n\n const agent = await findAgent(agentIdOrName, selfAppId);\n if (!agent) {\n const available = (await discoverAgents(selfAppId))\n .map((a) => a.name)\n .join(\", \");\n return `Error: Agent \"${agentIdOrName}\" not found. Available agents: ${available || \"(none)\"}`;\n }\n\n if (!taskId) {\n const visited = new Set(\n (context?.visitedApps ?? []).map(normalizeAppHandle).filter(Boolean),\n );\n const self = normalizeAppHandle(selfAppId);\n if (self) visited.add(self);\n const targetHandles = [\n normalizeAppHandle((agent as { id?: string }).id),\n normalizeAppHandle(agent.name),\n normalizeAppHandle(agentIdOrName),\n ].filter(Boolean);\n const repeated = targetHandles.find((handle) => visited.has(handle));\n if (repeated) {\n return (\n `Error: Cross-app delegation cycle blocked before calling ${agent.name}. ` +\n `The request already visited ${[...visited].join(\" -> \")}.`\n );\n }\n }\n\n const correlation = buildDelegationCorrelation(context, selfAppId);\n const idempotencyKey =\n message && !taskId\n ? buildMessageIdempotencyKey(context?.turnId, agent.url, message)\n : undefined;\n const targetApp =\n normalizeAppHandle((agent as { id?: string }).id) ||\n normalizeAppHandle(agent.name) ||\n normalizeAppHandle(agentIdOrName) ||\n \"unknown\";\n\n if (action) {\n const agentCallId = randomUUID();\n const startedAt = Date.now();\n let terminalStatus: \"done\" | \"error\" = \"done\";\n let terminalCode: string | undefined;\n if (context?.send) {\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"start\",\n agentCallId,\n });\n }\n try {\n const output = await invokeReadOnlyAppAction(\n agent,\n action,\n input as Record<string, unknown>,\n buildDelegationCorrelation(context, selfAppId, randomUUID()),\n );\n if (/^Error\\b/i.test(output)) {\n terminalStatus = \"error\";\n terminalCode = \"direct_action_failed\";\n }\n if (context?.send && output) {\n context.send({\n type: \"agent_call_text\",\n agent: agent.name,\n text: output,\n agentCallId,\n });\n }\n return output;\n } catch (error) {\n terminalStatus = \"error\";\n terminalCode = \"direct_action_failed\";\n throw error;\n } finally {\n trackA2AInvocation({\n invocationId: agentCallId,\n callerApp: selfAppId,\n targetApp,\n mode: \"direct_action\",\n status: terminalStatus === \"done\" ? \"success\" : \"error\",\n startedAt,\n terminalCode,\n correlation,\n });\n if (context?.send) {\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: terminalStatus,\n agentCallId,\n durationMs: Date.now() - startedAt,\n });\n }\n }\n }\n\n // Append a small cross-app hint to the outgoing message so the receiving\n // agent (which may be on an older deploy without the receiver-side hint\n // in handlers.ts) still emits fully-qualified URLs. This is belt-and-\n // suspenders with the receiver hint — but it works against any current\n // deployment, no redeploy required.\n const sourceContext = integrationSourceContext();\n const messageWithHint = taskId\n ? \"\"\n : `${message}${integrationSourceContextHint(sourceContext)}\\n\\n` +\n `<a2a-caller-hint>\\n` +\n `This request comes from another app via A2A. The caller cannot see your local UI, deck list, or navigation — only the literal text you put in your reply. ` +\n `If you create or reference a deck/document/design/dashboard, include its FULLY-QUALIFIED URL (e.g. ${agent.url}/deck/<id>) in your reply, not a relative path. ` +\n `Use only artifact IDs and URL paths returned by successful actions — never invent slugs, IDs, or hosts. ` +\n `Return a concise caller-ready synthesis rather than raw tool output or full transcripts; preserve source counts, IDs, short supporting quotes, and URLs needed to substantiate the answer.\\n` +\n `</a2a-caller-hint>`;\n\n const invocationId = randomUUID();\n const invocationStartedAt = Date.now();\n let invocationStatus: A2AInvocationStatus = \"error\";\n let invocationTaskId = taskId || undefined;\n let invocationTerminalCode: string | undefined;\n\n try {\n // If we have a send context, use streaming so the UI shows progressive text\n if (context?.send) {\n const callerEmail = getRequestUserEmail();\n\n // Build metadata with identity\n const a2aMetadata: Record<string, unknown> = {};\n if (callerEmail) a2aMetadata.userEmail = callerEmail;\n\n // Include org domain for cross-app org resolution\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n const domain = await getOrgDomain(orgId);\n if (domain) {\n callerOrgDomain = domain;\n a2aMetadata.orgDomain = domain;\n }\n } catch {}\n try {\n const secret = await getOrgA2ASecret(orgId);\n if (secret) callerOrgSecret = secret;\n } catch {}\n }\n\n // Sign JWT with identity + org domain for the streaming client\n let apiKey: string | undefined;\n if (callerEmail && (callerOrgSecret || process.env.A2A_SECRET)) {\n try {\n apiKey = await signA2AToken(\n callerEmail,\n callerOrgDomain,\n callerOrgSecret,\n {\n expiresIn: INTEGRATION_A2A_TOKEN_TTL,\n preferGlobalSecret: shouldPreferGlobalA2ASecret(callerOrgSecret),\n },\n );\n } catch {}\n }\n\n if (process.env.NODE_ENV === \"production\" && callerEmail) {\n try {\n const { listOAuthAccountsByOwner } =\n await import(\"../oauth-tokens/store.js\");\n const accounts = await listOAuthAccountsByOwner(\n \"google\",\n callerEmail,\n );\n const tokens = accounts[0]?.tokens;\n if (tokens?.access_token) {\n a2aMetadata.googleToken = tokens.access_token;\n }\n } catch {}\n }\n\n let responseText = \"\";\n let lastSentLength = 0;\n const agentCallId = randomUUID();\n let terminalStatus: \"done\" | \"pending\" | \"error\" = \"done\";\n const existingContinuationText = taskId\n ? null\n : await formatExistingIntegrationContinuationIfRetry(agent, message);\n if (existingContinuationText) {\n invocationStatus = \"pending\";\n invocationTerminalCode = \"existing_continuation\";\n return existingContinuationText;\n }\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"start\",\n agentCallId,\n });\n\n const emitNewText = (newText: string) => {\n if (newText.length > lastSentLength) {\n context.send!({\n type: \"agent_call_text\",\n agent: agent.name,\n text: newText.slice(lastSentLength),\n agentCallId,\n });\n lastSentLength = newText.length;\n }\n responseText = newText;\n };\n\n // Skip the SSE streaming attempt and go straight to async + poll.\n // Why: on Netlify (Lambda), the receiving server has no streaming\n // response support, so message/stream returns a single JSON-RPC error\n // body in a 200 response that our SSE parser silently consumes — the\n // `for await` loop yields nothing AND keeps the connection open until\n // the function timeout, eating the current serverless budget. By the\n // time we get to the sync fallback, Lambda is dead and the second fetch\n // errors out as \"fetch failed\". Async+poll has its own short fetches\n // with their own budgets, so it works reliably across hosts. The\n // trade-off is that cross-app activity arrives at the poll cadence rather\n // than token-by-token. Agent Native peers attach their current reasoning,\n // tool status, and response preview to each task checkpoint, and the\n // receiver's full response still surfaces below.\n //\n // That trade-off has a second-order cost: callAgent()'s poll (see\n // A2AClient.sendAndWait in a2a/client.ts) can legitimately run for\n // minutes with nothing emitted to the parent between the \"start\" event\n // above and \"done\" below. On the parent run, that silence freezes\n // `last_progress_at` — shouldBumpProgressForEvent in\n // agent/run-manager.ts treats a stream of literally nothing as no\n // progress — which trips the client's stuck-detector\n // (DEFAULT_STUCK_THRESHOLD_MS = 90_000 in\n // client/use-run-stuck-detection.ts) and the server's stale-run sweep\n // (BACKGROUND_RUN_STALE_MS = 90_000 in agent/run-store.ts). In\n // production this handed users a \"still working, no progress\" Retry\n // button that aborted a perfectly healthy call and re-ran the sub-agent\n // from scratch.\n //\n // Fix: surface the REAL remote liveness the poll already gathers. The\n // A2A poll round-trips to the remote agent every ~2s and gets back a\n // task with `status.state` (see A2AClient.sendAndWait / `onUpdate`). We\n // emit an `agent_call_progress` event ONLY from that callback, and ONLY\n // when a poll actually succeeds AND reports an actively-working state.\n // Crucially this is NOT a timer: if the remote hangs or dies, the poll\n // fetch throws, `onUpdate` stops firing, we emit nothing, and the\n // stuck-detector correctly surfaces its banner. A wall-clock heartbeat\n // would instead keep a dead sub-agent looking alive forever — trading a\n // false stuck-positive for a worse false stuck-negative.\n //\n // Throttle: the poll runs every ~2s but both thresholds above are 90s,\n // so emitting per-poll would be ~45 events per stuck-window. We coalesce\n // to at most one emission per 30s — a 3x margin under 90s, so at least\n // two land inside either window even with jitter, without flooding.\n //\n // Shape: a dedicated `agent_call_progress` event type (see\n // agent/types.ts), not an extra `agent_call` status. `agent_call`\n // consumers (production-agent.ts's step summarizer, slack.ts's task\n // cards) render any status that isn't \"start\"/\"done\" as a failure, so a\n // \"progress\" status would surface an in-flight tick as an error. A\n // distinct type is instead ignored gracefully everywhere: the run-event\n // switches fall to their `default`, the client if-chains fall through,\n // and sse-event-processor returns `{action:\"continue\"}`. It still counts\n // as real progress in shouldBumpProgressForEvent (any non-special event\n // type does), which is the whole point.\n const PROGRESS_MIN_INTERVAL_MS = 30_000;\n // Terminal states resolve the poll; \"input-required\" means the remote is\n // blocked waiting on us, not making progress. Only actively-working\n // states count as liveness worth surfacing.\n const ACTIVELY_WORKING_STATES = new Set([\n \"working\",\n \"submitted\",\n \"processing\",\n ]);\n const callStartedAt = Date.now();\n let lastProgressEmitAt = callStartedAt;\n let lastActivitySequence = -1;\n const onRemotePollUpdate = (task: Task) => {\n const state = task?.status?.state;\n const parts = task.status?.message?.parts;\n const snapshot = Array.isArray(parts)\n ? parts.map(parseA2AAgentActivityPart).find((value) => value !== null)\n : undefined;\n if (snapshot && snapshot.sequence > lastActivitySequence) {\n lastActivitySequence = snapshot.sequence;\n context.send!({\n type: \"agent_call_activity\",\n agent: agent.name,\n agentCallId,\n snapshot,\n });\n }\n if (!state || !ACTIVELY_WORKING_STATES.has(state)) return;\n const now = Date.now();\n if (now - lastProgressEmitAt < PROGRESS_MIN_INTERVAL_MS) return;\n lastProgressEmitAt = now;\n const detail = extractRemoteProgressDetail(task);\n context.send!({\n type: \"agent_call_progress\",\n agent: agent.name,\n state,\n elapsedSeconds: Math.round((now - callStartedAt) / 1000),\n agentCallId,\n ...(detail ? { detail } : {}),\n });\n };\n\n try {\n // Apply a polling cap ONLY for integration-platform callers on\n // serverless hosts. Normal chat, local Node, self-hosted Node, and\n // Docker can wait for slow-but-valid answers; integration processors\n // still need to finish before their current function execution dies.\n const callTimeoutMs = getIntegrationCallTimeoutMs();\n responseText = await callAgent(agent.url, messageWithHint, {\n apiKey,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n approvedActions,\n ...(sourceContext ? { sourceContext: sourceContext.reference } : {}),\n contextId: context.threadId,\n correlation,\n idempotencyKey,\n ...(taskId ? { taskId } : {}),\n onUpdate: onRemotePollUpdate,\n returnRecoverableArtifactsOnTimeout: false,\n ...(callTimeoutMs\n ? {\n timeoutMs: callTimeoutMs,\n }\n : {}),\n });\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, responseText) ??\n responseText;\n // Some agents reply with relative paths (e.g. slides emits\n // \"/deck/abc\"). Those resolve against the caller's host, not the\n // receiver's, so they're broken for the user. Expand any leading-slash\n // URL into a fully-qualified one rooted at the receiving agent's host.\n responseText = expandRelativeUrls(responseText, agent.url);\n // Mirror the response into the streaming UI so the user sees it.\n if (responseText) emitNewText(responseText);\n } catch (pollErr: any) {\n const timeoutTaskId = getA2ATaskTimeoutTaskId(pollErr);\n if (timeoutTaskId) {\n terminalStatus = \"pending\";\n invocationTaskId = timeoutTaskId;\n invocationTerminalCode = \"timeout_pending\";\n const queued = await enqueueIntegrationContinuationIfPossible(\n timeoutTaskId,\n agent,\n message,\n callerEmail,\n );\n if (queued) {\n responseText =\n `${A2A_CONTINUATION_QUEUED_MARKER}\\n` +\n `The ${agent.name} agent accepted this delegated subtask and will post its own final result to the originating integration thread automatically. ` +\n `Do not call ${agent.name} again for this same subtask. Continue any other requested work, then answer with the completed results you have; if needed, mention that ${agent.name} is posting its result separately.`;\n } else {\n // The normal integration path must preserve the timeout task id so\n // it can enqueue a durable continuation. If that enqueue fails,\n // do not hide receiver-verified artifacts that were already\n // returned with the last poll; this mirrors callAgent's default\n // timeout behavior without treating arbitrary remote status text\n // as a completed response.\n const recoverableArtifactText =\n extractRecoverableTimeoutArtifactText(pollErr);\n if (recoverableArtifactText) {\n responseText = expandRelativeUrls(\n recoverableArtifactText,\n agent.url,\n );\n } else {\n responseText = formatExistingTaskWaitInstruction(\n agent.name,\n timeoutTaskId,\n agentIdOrName,\n );\n }\n }\n } else if (terminalTaskError(pollErr)?.state === \"input-required\") {\n terminalStatus = \"pending\";\n const terminal = terminalTaskError(pollErr)!;\n invocationTaskId = terminal.taskId;\n invocationTerminalCode = terminal.errorCode ?? \"input_required\";\n responseText = formatInputRequiredWaitInstruction(\n agent.name,\n terminal,\n agentIdOrName,\n );\n } else if (terminalTaskError(pollErr)) {\n terminalStatus = \"error\";\n const terminal = terminalTaskError(pollErr)!;\n invocationTaskId = terminal.taskId;\n invocationTerminalCode = terminal.errorCode ?? terminal.state;\n const detail = expandRelativeUrls(\n terminal.responseText ?? pollErr?.message ?? \"unknown failure\",\n agent.url,\n );\n responseText =\n `Error: The ${agent.name} agent ended ${terminal.state}` +\n (terminal.errorCode ? ` (${terminal.errorCode})` : \"\") +\n (terminal.taskId ? ` [taskId: ${terminal.taskId}]` : \"\") +\n (detail ? `: ${detail}` : \"\");\n } else {\n terminalStatus = \"error\";\n invocationTerminalCode = \"call_failed\";\n const reason = pollErr?.message ?? \"unknown error\";\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, pollErr) ??\n `Error: The ${agent.name} agent call failed. (${reason})`;\n }\n }\n\n if (!responseText && terminalStatus === \"done\") {\n terminalStatus = \"error\";\n invocationTerminalCode = \"empty_agent_response\";\n }\n if (responseText.length > MAX_A2A_CALLER_RESPONSE_CHARS) {\n terminalStatus = \"error\";\n invocationTerminalCode = \"a2a_response_too_large\";\n responseText =\n `Error: The ${agent.name} agent returned more data than the caller can safely consume. ` +\n \"Ask it for a concise synthesis or a retrievable artifact instead.\";\n }\n invocationStatus =\n terminalStatus === \"done\"\n ? \"success\"\n : terminalStatus === \"pending\"\n ? \"pending\"\n : \"error\";\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: terminalStatus,\n agentCallId,\n ...(invocationTaskId ? { taskId: invocationTaskId } : {}),\n durationMs: Date.now() - callStartedAt,\n });\n\n return (\n responseText || `Error: The ${agent.name} agent returned no result.`\n );\n }\n\n // No context — use the async + poll call so we don't get cut off at the\n // serverless gateway's ~30s timeout. callAgent defaults to async:true.\n const email = getRequestUserEmail();\n let domain: string | undefined;\n let orgSecret: string | undefined;\n const currentOrgId = getRequestOrgId();\n if (currentOrgId) {\n try {\n domain = (await getOrgDomain(currentOrgId)) ?? undefined;\n } catch {}\n try {\n orgSecret = (await getOrgA2ASecret(currentOrgId)) ?? undefined;\n } catch {}\n }\n const response = await callAgent(agent.url, messageWithHint, {\n userEmail: email,\n orgDomain: domain,\n orgSecret,\n approvedActions,\n ...(sourceContext ? { sourceContext: sourceContext.reference } : {}),\n contextId: context?.threadId,\n correlation,\n idempotencyKey,\n ...(taskId ? { taskId } : {}),\n returnRecoverableArtifactsOnTimeout: false,\n });\n const sanitized =\n formatDownstreamLlmCredentialFailure(agent.name, response) ?? response;\n const expanded = expandRelativeUrls(sanitized, agent.url);\n if (!expanded) {\n invocationStatus = \"error\";\n invocationTerminalCode = \"empty_agent_response\";\n return \"Error: The remote agent returned no result.\";\n }\n if (expanded.length > MAX_A2A_CALLER_RESPONSE_CHARS) {\n invocationStatus = \"error\";\n invocationTerminalCode = \"a2a_response_too_large\";\n return (\n `Error: The ${agent.name} agent returned more data than the caller can safely consume. ` +\n \"Ask it for a concise synthesis or a retrievable artifact instead.\"\n );\n }\n invocationStatus = \"success\";\n return expanded;\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n const credentialMessage = formatDownstreamLlmCredentialFailure(\n agent.name,\n err,\n );\n if (credentialMessage) return credentialMessage;\n const terminal = terminalTaskError(err);\n if (terminal?.state === \"input-required\") {\n invocationStatus = \"pending\";\n invocationTaskId = terminal.taskId;\n invocationTerminalCode = terminal.errorCode ?? \"input_required\";\n return formatInputRequiredWaitInstruction(\n agent.name,\n terminal,\n agentIdOrName,\n );\n }\n if (terminal) {\n invocationStatus = \"error\";\n invocationTaskId = terminal.taskId;\n invocationTerminalCode = terminal.errorCode ?? terminal.state;\n return (\n `Error calling ${agent.name}: remote task ${terminal.state}` +\n (terminal.errorCode ? ` (${terminal.errorCode})` : \"\") +\n (terminal.taskId ? ` [taskId: ${terminal.taskId}]` : \"\") +\n (terminal.responseText ? `: ${terminal.responseText}` : \"\")\n );\n }\n const timeoutTaskId = getA2ATaskTimeoutTaskId(err);\n if (timeoutTaskId) {\n invocationStatus = \"pending\";\n invocationTaskId = timeoutTaskId;\n invocationTerminalCode = \"timeout_pending\";\n return formatExistingTaskWaitInstruction(\n agent.name,\n timeoutTaskId,\n agentIdOrName,\n );\n }\n // Friendlier message for the common timeout case so the calling agent can\n // decide whether to give up or retry.\n if (/timeout|did not complete|Inactivity|504/i.test(msg)) {\n invocationStatus = \"error\";\n invocationTerminalCode = \"timeout_without_task\";\n return `Error calling ${agent.name}: the remote request timed out before a task id could be recovered.`;\n }\n invocationStatus = \"error\";\n invocationTerminalCode = \"call_failed\";\n return `Error calling ${agent.name}: ${msg}`;\n } finally {\n trackA2AInvocation({\n invocationId,\n callerApp: selfAppId,\n targetApp,\n mode: taskId ? \"task_poll\" : \"message\",\n status: invocationStatus,\n startedAt: invocationStartedAt,\n taskId: invocationTaskId,\n terminalCode: invocationTerminalCode,\n correlation,\n });\n }\n}\n\nasync function invokeReadOnlyAppAction(\n agent: { name: string; url: string },\n action: string,\n input: Record<string, unknown>,\n correlation: A2ACorrelationMetadata,\n): Promise<string> {\n const callerEmail = getRequestUserEmail();\n if (!callerEmail) {\n return `Error calling ${agent.name} action ${action}: a signed-in user identity is required`;\n }\n\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n callerOrgDomain = (await getOrgDomain(orgId)) ?? undefined;\n } catch {}\n try {\n callerOrgSecret = (await getOrgA2ASecret(orgId)) ?? undefined;\n } catch {}\n }\n\n if (!callerOrgSecret && !process.env.A2A_SECRET) {\n return `Error calling ${agent.name} action ${action}: direct cross-app reads require A2A identity verification`;\n }\n\n try {\n const invocation = await invokeAgentAction({\n target: agent.url,\n action,\n input,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n correlation,\n });\n return invocation.result.status === \"completed\"\n ? invocation.result.output\n : `Error calling ${agent.name} action ${action}: ${invocation.result.output}`;\n } catch (error) {\n return `Error calling ${agent.name} action ${action}: ${\n error instanceof Error ? error.message : String(error)\n }`;\n }\n}\n\nfunction formatExistingTaskWaitInstruction(\n agentName: string,\n taskId: string,\n agentIdOrName: string,\n): string {\n return (\n `The ${agentName} task is still running under taskId \"${taskId}\". ` +\n `Do not send ${agentName} a new check-in or follow-up message; that would start duplicate work. ` +\n `Call call-agent again with agent=\"${agentIdOrName}\" and taskId=\"${taskId}\" (omit message) to continue waiting for this same task.`\n );\n}\n\nfunction formatInputRequiredWaitInstruction(\n agentName: string,\n terminal: {\n taskId?: string;\n responseText?: string;\n },\n agentIdOrName: string,\n): string {\n const detail = terminal.responseText?.trim();\n if (!terminal.taskId) {\n return (\n (detail ? `${detail}\\n\\n` : \"\") +\n `Pending: The ${agentName} agent needs input before it can continue.`\n );\n }\n return (\n (detail ? `${detail}\\n\\n` : \"\") +\n `The ${agentName} agent is waiting for input under taskId \"${terminal.taskId}\". ` +\n `After providing or approving the requested input, call call-agent with agent=\"${agentIdOrName}\" and taskId=\"${terminal.taskId}\" (omit message) to continue this same task. Do not start a new message for this work.`\n );\n}\n\nasync function enqueueIntegrationContinuationIfPossible(\n taskId: string,\n agent: { name: string; url: string },\n message: string,\n ownerEmail: string | undefined,\n): Promise<boolean> {\n const integration = getIntegrationRequestContext();\n if (!integration || !ownerEmail) return false;\n\n try {\n const [{ insertA2AContinuation }, { dispatchA2AContinuation }] =\n await Promise.all([\n import(\"../integrations/a2a-continuations-store.js\"),\n import(\"../integrations/a2a-continuation-processor.js\"),\n ]);\n const continuation = await insertA2AContinuation({\n integrationTaskId: integration.taskId,\n platform: integration.incoming.platform,\n externalThreadId: integration.incoming.externalThreadId,\n incoming: integration.incoming,\n placeholderRef: integration.placeholderRef,\n progressRef: integration.progressRef,\n ownerEmail,\n orgId: getRequestOrgId() ?? null,\n agentName: agent.name,\n agentUrl: agent.url,\n dedupeKey: getIntegrationContinuationDedupeKey(message),\n a2aTaskId: taskId,\n // Do not persist the short-lived JWT used for the initial send. The\n // continuation processor can mint a fresh token for each poll.\n a2aAuthToken: null,\n });\n await dispatchA2AContinuation(continuation.id).catch((err) => {\n console.error(\n `[call-agent] Failed to dispatch A2A continuation ${continuation.id}:`,\n err,\n );\n });\n return true;\n } catch (err) {\n console.error(\"[call-agent] Failed to enqueue A2A continuation:\", err);\n return false;\n }\n}\n\n// Pull a short human-readable detail from a polled A2A task's status message,\n// when the remote includes one, so the progress event can surface a real\n// signal (e.g. \"Generating hero image…\") instead of a bare elapsed counter.\n// Bounded so a chatty remote can't push a large payload through the event.\nconst MAX_PROGRESS_DETAIL_CHARS = 200;\nfunction extractRemoteProgressDetail(task: Task): string | undefined {\n const parts = task.status?.message?.parts;\n if (!Array.isArray(parts)) return undefined;\n const text = parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text)\n .join(\" \")\n .replace(/\\s+/g, \" \")\n .trim();\n if (!text) return undefined;\n return text.length > MAX_PROGRESS_DETAIL_CHARS\n ? `${text.slice(0, MAX_PROGRESS_DETAIL_CHARS - 1)}…`\n : text;\n}\n\nfunction getA2ATaskTimeoutTaskId(err: unknown): string | null {\n if (err instanceof A2ATaskTimeoutError) return err.taskId;\n\n const candidate = err as\n | { name?: unknown; taskId?: unknown; message?: unknown }\n | null\n | undefined;\n const message = String(candidate?.message ?? \"\");\n if (\n candidate?.name === \"A2ATaskTimeoutError\" &&\n typeof candidate.taskId === \"string\"\n ) {\n return candidate.taskId;\n }\n\n const match = message.match(/^A2A task ([^\\s]+) did not complete\\b/);\n return match?.[1] ?? null;\n}\n\n/**\n * Mirrors the A2A client's default timeout recovery for the exceptional case\n * where an integration cannot enqueue a durable continuation. Only an\n * explicitly receiver-marked task message is safe to surface as a completed\n * partial result; ordinary working-state text remains a timeout failure.\n */\nfunction extractRecoverableTimeoutArtifactText(err: unknown): string {\n const candidate = err as\n | { lastTask?: Task | unknown; name?: unknown }\n | null\n | undefined;\n const lastTask =\n err instanceof A2ATaskTimeoutError\n ? err.lastTask\n : candidate?.name === \"A2ATaskTimeoutError\"\n ? (candidate.lastTask as Task | undefined)\n : undefined;\n const message = lastTask?.status?.message;\n if (!message?.metadata?.agentNativeRecoverableArtifacts) return \"\";\n\n return message.parts\n .filter(\n (part): part is { type: \"text\"; text: string } => part.type === \"text\",\n )\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\nasync function formatExistingIntegrationContinuationIfRetry(\n agent: {\n name: string;\n url: string;\n },\n message: string,\n): Promise<string | null> {\n const integration = getIntegrationRequestContext();\n if (!integration || (integration.attempts ?? 1) <= 1) return null;\n\n try {\n const { getA2AContinuationsForIntegrationTaskAgent } =\n await import(\"../integrations/a2a-continuations-store.js\");\n const continuations = await getA2AContinuationsForIntegrationTaskAgent(\n integration.taskId,\n agent.url,\n getIntegrationContinuationDedupeKey(message),\n );\n const active = continuations.find((continuation) =>\n [\"pending\", \"processing\", \"delivering\", \"completed\"].includes(\n continuation.status,\n ),\n );\n if (!active) return null;\n\n const state =\n active.status === \"completed\"\n ? \"already completed this delegated subtask and posted its result to the originating integration thread\"\n : \"already accepted this delegated subtask and is still working on it for the originating integration thread\";\n return (\n `${A2A_CONTINUATION_QUEUED_MARKER}\\n` +\n `The ${agent.name} agent ${state}. Do not call ${agent.name} again for this same subtask. Continue any other requested work, then answer with the completed results you have; if needed, mention that ${agent.name} is posting or has posted its result separately.`\n );\n } catch (err) {\n console.error(\"[call-agent] Failed to inspect existing continuation:\", err);\n return null;\n }\n}\n\nfunction getIntegrationContinuationDedupeKey(message: string): string {\n const normalized = message.trim().replace(/\\s+/g, \" \");\n return createHash(\"sha256\").update(normalized).digest(\"hex\");\n}\n\n// Expand bare leading-slash paths (e.g. \"/deck/abc\") into fully-qualified URLs\n// rooted at the receiving agent's host. The receiver doesn't always know it's\n// being called cross-app, so it may emit relative paths that resolve against\n// the caller's host (broken). Match a path that starts at a word boundary,\n// begins with `/`, and has at least one path segment after that. Skip if it\n// already looks like a fully-qualified URL.\nexport function expandRelativeUrls(text: string, agentUrl: string): string {\n if (!text || !agentUrl) return text;\n const base = agentUrl.replace(/\\/$/, \"\");\n // Path must start at boundary (start, whitespace, or punctuation that isn't\n // ':' — to avoid mangling `https://example.com/foo` or markdown link bodies).\n return text.replace(\n /(^|[\\s([<\"'`])(\\/[a-z0-9_-][a-z0-9_/?&=%#.,:-]*)/gi,\n (_match, lead, path) => `${lead}${base}${path}`,\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-chat-plugin.d.ts","sourceRoot":"","sources":["../../src/server/agent-chat-plugin.ts"],"names":[],"mappings":"AAsCA,OAAO,KAAK,EAAE,OAAO,IAAI,UAAU,EAAE,MAAM,iBAAiB,CAAC;AA6H7D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAEvE,OAAO,EACL,yBAAyB,EACzB,KAAK,6BAA6B,EACnC,MAAM,+BAA+B,CAAC;AAkCvC,OAAO,EAAE,yBAAy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E,MAAM,EACf,YAAY,EAAE,oBAAoB,EAAE,GAAG,SAAS,EAChD,KAAK,EAAE,MAAM,EACb,IAAI,EAAE;IACJ,eAAe,EAAE,CACf,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,MAAM,KACZ,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,CAAC;IAC9B,uBAAuB,EAAE,CACvB,GAAG,EAAE,oBAAoB,KACtB,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,CAAC;CAC/B,GACA,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,CAI1B;AAED,wBAAgB,qBAAqB,CACnC,OAAO,CAAC,EAAE,sBAAsB,GAC/B,cAAc,CA8hLhB;AAED;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,EAAE,cAAwC,CAAC;AAE9E,OAAO,EAEL,mBAAmB,EACnB,uBAAuB,EAGxB,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,mBAAmB,EAAE,CAAC;AAC/B,OAAO,EAAE,uBAAuB,EAAE,CAAC"}
@@ -9,7 +9,7 @@ import { createA2AApproval, updateTaskStatusMessage, } from "../a2a/task-store.j
9
9
  import { canUpdateAgentAppModelDefaultSettings, normalizeAgentAppModelDefaultAppId, readAgentAppModelDefaultSettings, resetAgentAppModelDefaultSettings, writeAgentAppModelDefaultSettings, } from "../agent/app-model-defaults.js";
10
10
  import { DEFAULT_ANTHROPIC_MODEL } from "../agent/default-model.js";
11
11
  import { AGENT_CHAT_BACKGROUND_RUN_FIELD, AGENT_CHAT_PROCESS_RUN_PATH, backgroundRunMarkerExpectsBackgroundRuntime, isInBackgroundFunctionRuntime, prepareProcessRunRequest, } from "../agent/durable-background.js";
12
- import { resolveEngine, createAnthropicEngine, getStoredModelForEngine, normalizeModelForEngine, getAgentEngineEntry, isAgentEnginePackageInstalled, isStoredEngineUsableForRequest, listAgentEngines, registerBuiltinEngines, } from "../agent/engine/index.js";
12
+ import { resolveEngine, createAnthropicEngine, getStoredModelForEngine, normalizeModelForEngine, resolveDelegatedRunModel, getAgentEngineEntry, isAgentEnginePackageInstalled, isStoredEngineUsableForRequest, listAgentEngines, registerBuiltinEngines, } from "../agent/engine/index.js";
13
13
  import { SYSTEM_PROMPT_CACHE_SPLIT } from "../agent/engine/prompt-cache.js";
14
14
  import { createProductionAgentHandler, actionsToEngineTools, executeAgentToolCall, toolCallCacheKey, getActiveRunForThreadAsync, abortRunDurably, abortTurnDurably, subscribeToRun, } from "../agent/production-agent.js";
15
15
  import { callerHasRunAccess, callerHasThreadAccess, } from "../agent/run-ownership.js";
@@ -20,7 +20,7 @@ import { appendThreadDebugHistory } from "../agent/thread-debug-history.js";
20
20
  import { attachToolSearch } from "../agent/tool-search.js";
21
21
  import { readAppStateForCurrentTab } from "../application-state/script-helpers.js";
22
22
  import { runChatThreadDataMigrations } from "../chat-threads/migrations.js";
23
- import { createThread, forkThread, getThread, registerChatThreadsShareable, resolveThreadAccess, listThreads, searchThreads, renameThread, createThreadShareLink, getThreadByShareToken, getThreadShareState, revokeThreadShareLink, setThreadArchived, setThreadPinned, setThreadScope, updateThreadData, withThreadDataLock, deleteThread, setThreadQueuedMessages, } from "../chat-threads/store.js";
23
+ import { adoptThreadScopeIfUnscoped, createThread, forkThread, getThread, registerChatThreadsShareable, resolveRunThreadScope, resolveThreadAccess, listThreads, searchThreads, renameThread, createThreadShareLink, getThreadByShareToken, getThreadShareState, revokeThreadShareLink, setThreadArchived, setThreadPinned, setThreadScope, updateThreadData, withThreadDataLock, deleteThread, setThreadQueuedMessages, } from "../chat-threads/store.js";
24
24
  import { isCheckpointRestorePath } from "../checkpoints/route-match.js";
25
25
  import { createDbAdminAgentTools } from "../db-admin/agent-tools.js";
26
26
  import { isTransientDatabaseError } from "../db/client.js";
@@ -1208,12 +1208,17 @@ export function createAgentChatPlugin(options) {
1208
1208
  ? ""
1209
1209
  : await buildSchemaBlock(owner, databaseToolsMode);
1210
1210
  const extra = await resolveExtraContext(context.event, owner);
1211
- const a2aModelCandidate = options?.model ??
1212
- (await getStoredModelForEngine(a2aEngine, {
1211
+ const model = resolveDelegatedRunModel(a2aEngine, {
1212
+ explicitModel: options?.model,
1213
+ storedModel: await getStoredModelForEngine(a2aEngine, {
1213
1214
  appId: options?.appId,
1214
- })) ??
1215
- a2aEngine.defaultModel;
1216
- const model = normalizeModelForEngine(a2aEngine, a2aModelCandidate);
1215
+ }),
1216
+ // Preference only, and last before the default: an app that pinned
1217
+ // a model keeps it. Read separately from the correlation sanitizer
1218
+ // below so it stays out of every identity/access path.
1219
+ callerModelHint: sanitizeA2ACorrelationMetadata(context.metadata)
1220
+ .callerModel,
1221
+ });
1217
1222
  if (a2aRunContext) {
1218
1223
  a2aRunContext.engine = a2aEngine;
1219
1224
  a2aRunContext.model = model;
@@ -1974,11 +1979,15 @@ export function createAgentChatPlugin(options) {
1974
1979
  const ownerEmail = getRequestRunContext()?.owner ?? getRequestUserEmail();
1975
1980
  if (!ownerEmail)
1976
1981
  return;
1982
+ const runScope = getRequestRunContext()?.chatScope ?? null;
1977
1983
  await withThreadDataLock(threadId, async () => {
1978
1984
  let thread = await getThread(threadId);
1979
1985
  if (!thread) {
1980
1986
  try {
1981
- thread = await createThread(ownerEmail, { id: threadId });
1987
+ thread = await createThread(ownerEmail, {
1988
+ id: threadId,
1989
+ scope: runScope,
1990
+ });
1982
1991
  }
1983
1992
  catch {
1984
1993
  thread = await getThread(threadId);
@@ -1997,6 +2006,13 @@ export function createAgentChatPlugin(options) {
1997
2006
  statusMessage: "Thread not found",
1998
2007
  });
1999
2008
  }
2009
+ const nextScope = resolveRunThreadScope(thread.scope, runScope);
2010
+ if (nextScope && nextScope !== thread.scope) {
2011
+ thread = {
2012
+ ...thread,
2013
+ scope: await adoptThreadScopeIfUnscoped(threadId, nextScope),
2014
+ };
2015
+ }
2000
2016
  let repo;
2001
2017
  try {
2002
2018
  repo = JSON.parse(thread.threadData || "{}");
@@ -4721,6 +4737,14 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
4721
4737
  // in production-agent.ts; guard + wire signal: run-manager.ts; recovery
4722
4738
  // actors: here).
4723
4739
  const attemptUnclaimedBackgroundRunRedispatch = async (row) => {
4740
+ // Eligibility for this sweep does not mean the row is redispatchable.
4741
+ // The marker below asserts `payloadRef: true`, and a worker that then
4742
+ // finds no payload fails the run as `dispatch_payload_missing` — so
4743
+ // redispatching a payload-less row does not recover it, it destroys it.
4744
+ // Leave it for the slow sweep's reap, which reports the true cause
4745
+ // (`background_worker_never_started`) and is client-recoverable.
4746
+ if (!row.hasDispatchPayload)
4747
+ return;
4724
4748
  const { updateRunHeartbeat } = await import("../agent/run-store.js");
4725
4749
  const { resolveAgentChatProcessRunDispatchPath } = await import("../agent/durable-background.js");
4726
4750
  const { fireInternalDispatch } = await import("./self-dispatch.js");
@@ -4836,7 +4860,12 @@ Non-code requests are still fine on this surface: read data, navigate the UI, su
4836
4860
  }
4837
4861
  for (const row of rows) {
4838
4862
  try {
4839
- if (shouldRedispatchUnclaimedBackgroundRun(row)) {
4863
+ // A row with no `dispatch_payload` can never be rehydrated by
4864
+ // a redispatched worker, so waiting out the redispatch bound
4865
+ // buys nothing — fall straight through to the reap below and
4866
+ // fail it loudly with its real cause.
4867
+ if (row.hasDispatchPayload &&
4868
+ shouldRedispatchUnclaimedBackgroundRun(row)) {
4840
4869
  await attemptUnclaimedBackgroundRunRedispatch(row);
4841
4870
  continue;
4842
4871
  }