@agent-native/core 0.124.2 → 0.124.4

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 (267) hide show
  1. package/README.md +1 -1
  2. package/corpus/README.md +2 -2
  3. package/corpus/core/CHANGELOG.md +16 -0
  4. package/corpus/core/docs/content/cloneable-saas.mdx +9 -9
  5. package/corpus/core/docs/content/creating-templates.mdx +2 -2
  6. package/corpus/core/docs/content/deployment.mdx +23 -0
  7. package/corpus/core/docs/content/faq.mdx +4 -4
  8. package/corpus/core/docs/content/key-concepts.mdx +1 -1
  9. package/corpus/core/docs/content/multi-app-workspace.mdx +1 -1
  10. package/corpus/core/docs/content/syncing-template-changes.mdx +1 -1
  11. package/corpus/core/docs/content/template-analytics-developers.mdx +2 -2
  12. package/corpus/core/docs/content/template-analytics.mdx +2 -2
  13. package/corpus/core/docs/content/template-assets-developers.mdx +3 -3
  14. package/corpus/core/docs/content/template-assets.mdx +2 -2
  15. package/corpus/core/docs/content/template-brain-developers.mdx +2 -2
  16. package/corpus/core/docs/content/template-brain.mdx +1 -1
  17. package/corpus/core/docs/content/template-calendar-developers.mdx +1 -1
  18. package/corpus/core/docs/content/template-calendar.mdx +1 -1
  19. package/corpus/core/docs/content/template-chat.mdx +1 -1
  20. package/corpus/core/docs/content/template-clips-developers.mdx +4 -4
  21. package/corpus/core/docs/content/template-clips.mdx +2 -2
  22. package/corpus/core/docs/content/template-content-developers.mdx +2 -2
  23. package/corpus/core/docs/content/template-content.mdx +1 -1
  24. package/corpus/core/docs/content/template-design-brand-and-figma.mdx +1 -1
  25. package/corpus/core/docs/content/template-design-developers.mdx +2 -2
  26. package/corpus/core/docs/content/template-design.mdx +2 -2
  27. package/corpus/core/docs/content/template-dispatch-developers.mdx +5 -5
  28. package/corpus/core/docs/content/template-forms-developers.mdx +1 -1
  29. package/corpus/core/docs/content/template-forms.mdx +1 -1
  30. package/corpus/core/docs/content/template-mail-developers.mdx +2 -2
  31. package/corpus/core/docs/content/template-mail.mdx +2 -2
  32. package/corpus/core/docs/content/template-plan-developers.mdx +3 -3
  33. package/corpus/core/docs/content/template-plan.mdx +3 -3
  34. package/corpus/core/docs/content/template-slides-developers.mdx +4 -4
  35. package/corpus/core/docs/content/template-slides.mdx +1 -1
  36. package/corpus/core/docs/content/what-is-agent-native.mdx +5 -5
  37. package/corpus/core/package.json +1 -1
  38. package/corpus/core/src/a2a/auth-policy.ts +1 -1
  39. package/corpus/core/src/agent/production-agent.ts +14 -1
  40. package/corpus/core/src/agent/run-manager.ts +6 -13
  41. package/corpus/core/src/cli/index.ts +11 -1
  42. package/corpus/core/src/client/route-chunk-recovery.ts +18 -7
  43. package/corpus/core/src/db/client.ts +7 -6
  44. package/corpus/core/src/db/migrations.ts +2 -1
  45. package/corpus/core/src/deploy/build.ts +290 -4
  46. package/corpus/core/src/deploy/nitro-preset.ts +50 -0
  47. package/corpus/core/src/integrations/pending-tasks-retry-job.ts +2 -1
  48. package/corpus/core/src/scripts/call-agent.ts +4 -2
  49. package/corpus/core/src/server/agent-discovery.ts +1 -0
  50. package/corpus/core/src/server/agent-run-context.ts +13 -3
  51. package/corpus/core/src/server/request-context.ts +2 -0
  52. package/corpus/core/src/shared/cloudflare-globals.d.ts +2 -1
  53. package/corpus/core/src/shared/runtime.ts +2 -0
  54. package/corpus/core/src/shared/streaming-text-smoothing.ts +15 -14
  55. package/corpus/core/src/templates/default/.agents/skills/secrets/SKILL.md +29 -0
  56. package/corpus/core/src/templates/default/app/i18n/ar-SA.ts +6 -6
  57. package/corpus/core/src/templates/default/app/i18n/de-DE.ts +6 -6
  58. package/corpus/core/src/templates/default/app/i18n/en-US.ts +6 -6
  59. package/corpus/core/src/templates/default/app/i18n/es-ES.ts +6 -6
  60. package/corpus/core/src/templates/default/app/i18n/fr-FR.ts +6 -6
  61. package/corpus/core/src/templates/default/app/i18n/hi-IN.ts +6 -6
  62. package/corpus/core/src/templates/default/app/i18n/ja-JP.ts +6 -6
  63. package/corpus/core/src/templates/default/app/i18n/ko-KR.ts +6 -6
  64. package/corpus/core/src/templates/default/app/i18n/pt-BR.ts +6 -6
  65. package/corpus/core/src/templates/default/app/i18n/zh-CN.ts +6 -6
  66. package/corpus/core/src/templates/default/app/i18n/zh-TW.ts +6 -6
  67. package/corpus/core/src/templates/headless/.agents/skills/secrets/SKILL.md +29 -0
  68. package/corpus/core/src/templates/workspace-core/.agents/skills/secrets/SKILL.md +29 -0
  69. package/corpus/core/src/vite/client.ts +20 -1
  70. package/corpus/templates/analytics/actions/restore-dashboard-revision.ts +9 -2
  71. package/corpus/templates/analytics/app/components/dashboard/DashboardHistoryPanel.tsx +3 -0
  72. package/corpus/templates/analytics/app/components/dashboard/DashboardPanelSkeleton.tsx +1 -1
  73. package/corpus/templates/analytics/app/global.css +10 -9
  74. package/corpus/templates/analytics/app/hooks/use-chart-tooltip-portal.ts +59 -18
  75. package/corpus/templates/analytics/app/hooks/use-dashboard-revisions.ts +14 -2
  76. package/corpus/templates/analytics/app/i18n-data.ts +102 -0
  77. package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/index.tsx +232 -2
  78. package/corpus/templates/analytics/changelog/2026-07-27-chart-tooltips-stay-beside-the-cursor-when-they-extend-beyon.md +6 -0
  79. package/corpus/templates/analytics/changelog/2026-07-27-chat-no-longer-claims-a-data-source-is-disconnected-when-it-.md +6 -0
  80. package/corpus/templates/analytics/changelog/2026-07-27-dashboard-changes-can-be-undone-with-cmd-z-and-actions-menu.md +6 -0
  81. package/corpus/templates/analytics/changelog/2026-07-27-dashboard-redo-with-cmd-shift-z-and-actions-menu.md +6 -0
  82. package/corpus/templates/analytics/changelog/2026-07-27-dashboard-skeletons-are-subtler-and-smoother.md +6 -0
  83. package/corpus/templates/analytics/server/lib/dashboards-store.ts +61 -20
  84. package/corpus/templates/analytics/server/lib/real-data-actions.ts +1 -0
  85. package/corpus/templates/analytics/server/plugins/agent-chat.ts +7 -3
  86. package/corpus/templates/calendar/app/components/layout/Sidebar.tsx +7 -32
  87. package/corpus/templates/calendar/changelog/2026-07-27-calendar-s-sidebar-now-uses-a-cleaner-layout-with-fewer-util.md +6 -0
  88. package/corpus/templates/content/app/components/editor/database/sidebar.tsx +14 -6
  89. package/corpus/templates/content/app/components/sidebar/DocumentSidebar.tsx +32 -37
  90. package/corpus/templates/content/changelog/2026-07-27-content-sidebar-page-lists-now-load-with-quiet-skeletons-and.md +6 -0
  91. package/corpus/templates/design/.agents/skills/design-generation/SKILL.md +34 -11
  92. package/corpus/templates/design/.agents/skills/responsive-breakpoints/SKILL.md +8 -0
  93. package/corpus/templates/design/actions/generate-design.ts +259 -36
  94. package/corpus/templates/design/actions/generate-screens.ts +51 -14
  95. package/corpus/templates/design/actions/present-design-variants.ts +6 -3
  96. package/corpus/templates/design/app/components/design/DesignCanvas.tsx +8 -0
  97. package/corpus/templates/design/app/components/design/MultiScreenCanvas.tsx +158 -9
  98. package/corpus/templates/design/app/components/design/design-canvas/content-size-report.ts +124 -0
  99. package/corpus/templates/design/app/components/design/multi-screen/frame-geometry.ts +61 -9
  100. package/corpus/templates/design/app/components/layout/Sidebar.tsx +16 -18
  101. package/corpus/templates/design/changelog/2026-07-24-ai-designs-now-default-to-a-full-size-desktop-mobile-pair-fr.md +6 -0
  102. package/corpus/templates/design/changelog/2026-07-24-design-frames-now-fill-the-viewport-height-and-grow-to-fit-t.md +6 -0
  103. package/corpus/templates/design/changelog/2026-07-24-generating-an-additional-screen-now-places-it-beside-the-exi.md +6 -0
  104. package/corpus/templates/design/changelog/2026-07-27-collapsed-sidebar-keeps-the-agent-native-logo.md +6 -0
  105. package/corpus/templates/dispatch/AGENTS.md +7 -2
  106. package/corpus/templates/dispatch/actions/view-screen.ts +3 -2
  107. package/corpus/templates/dispatch/changelog/2026-07-17-curated-template-remixes.md +1 -1
  108. package/corpus/templates/dispatch/changelog/2026-07-27-creating-an-app-from-a-curated-template-now-uses-clearer-mor.md +6 -0
  109. package/corpus/templates/dispatch/changelog/2026-07-27-thread-debug-accepts-request-run-ids.md +6 -0
  110. package/corpus/templates/slides/actions/create-design-system.ts +10 -2
  111. package/corpus/templates/slides/actions/import-file.ts +173 -1
  112. package/corpus/templates/slides/actions/list-slide-comments.ts +16 -1
  113. package/corpus/templates/slides/actions/update-design-system.ts +13 -2
  114. package/corpus/templates/slides/app/components/editor/AssetLibraryPanel.tsx +35 -12
  115. package/corpus/templates/slides/app/components/editor/EditorToolbar.tsx +36 -0
  116. package/corpus/templates/slides/app/i18n/en-US.ts +3 -0
  117. package/corpus/templates/slides/app/lib/dynamic-import.ts +63 -0
  118. package/corpus/templates/slides/app/lib/export-pdf-client.ts +3 -2
  119. package/corpus/templates/slides/app/lib/export-pptx-client.ts +5 -2
  120. package/corpus/templates/slides/app/pages/DesignSystems.tsx +9 -1
  121. package/corpus/templates/slides/server/db/schema.ts +11 -0
  122. package/corpus/templates/slides/server/handlers/assets.ts +64 -19
  123. package/corpus/templates/slides/server/handlers/import/html-converter.ts +38 -0
  124. package/corpus/templates/slides/server/plugins/db.ts +20 -0
  125. package/corpus/templates/slides/shared/design-system-validation.ts +62 -0
  126. package/dist/a2a/auth-policy.js +1 -1
  127. package/dist/a2a/auth-policy.js.map +1 -1
  128. package/dist/agent/production-agent.d.ts +1 -0
  129. package/dist/agent/production-agent.d.ts.map +1 -1
  130. package/dist/agent/production-agent.js +12 -1
  131. package/dist/agent/production-agent.js.map +1 -1
  132. package/dist/agent/run-manager.d.ts +2 -0
  133. package/dist/agent/run-manager.d.ts.map +1 -1
  134. package/dist/agent/run-manager.js +4 -10
  135. package/dist/agent/run-manager.js.map +1 -1
  136. package/dist/cli/index.js +8 -1
  137. package/dist/cli/index.js.map +1 -1
  138. package/dist/client/route-chunk-recovery.d.ts.map +1 -1
  139. package/dist/client/route-chunk-recovery.js +16 -7
  140. package/dist/client/route-chunk-recovery.js.map +1 -1
  141. package/dist/db/client.d.ts.map +1 -1
  142. package/dist/db/client.js +4 -2
  143. package/dist/db/client.js.map +1 -1
  144. package/dist/db/migrations.d.ts.map +1 -1
  145. package/dist/db/migrations.js +2 -1
  146. package/dist/db/migrations.js.map +1 -1
  147. package/dist/deploy/build.d.ts +25 -0
  148. package/dist/deploy/build.d.ts.map +1 -1
  149. package/dist/deploy/build.js +227 -4
  150. package/dist/deploy/build.js.map +1 -1
  151. package/dist/deploy/nitro-preset.d.ts +8 -0
  152. package/dist/deploy/nitro-preset.d.ts.map +1 -0
  153. package/dist/deploy/nitro-preset.js +36 -0
  154. package/dist/deploy/nitro-preset.js.map +1 -0
  155. package/dist/integrations/pending-tasks-retry-job.d.ts.map +1 -1
  156. package/dist/integrations/pending-tasks-retry-job.js +2 -1
  157. package/dist/integrations/pending-tasks-retry-job.js.map +1 -1
  158. package/dist/notifications/routes.d.ts +3 -3
  159. package/dist/observability/routes.d.ts +3 -3
  160. package/dist/progress/routes.d.ts +1 -1
  161. package/dist/provider-api/actions/custom-provider-registration.d.ts +11 -11
  162. package/dist/provider-api/actions/provider-api.d.ts +11 -11
  163. package/dist/resources/handlers.d.ts +1 -1
  164. package/dist/scripts/call-agent.d.ts.map +1 -1
  165. package/dist/scripts/call-agent.js +4 -2
  166. package/dist/scripts/call-agent.js.map +1 -1
  167. package/dist/server/agent-discovery.d.ts.map +1 -1
  168. package/dist/server/agent-discovery.js +1 -0
  169. package/dist/server/agent-discovery.js.map +1 -1
  170. package/dist/server/agent-run-context.d.ts.map +1 -1
  171. package/dist/server/agent-run-context.js +10 -3
  172. package/dist/server/agent-run-context.js.map +1 -1
  173. package/dist/server/request-context.d.ts +2 -0
  174. package/dist/server/request-context.d.ts.map +1 -1
  175. package/dist/server/request-context.js.map +1 -1
  176. package/dist/server/transcribe-voice.d.ts +1 -1
  177. package/dist/shared/runtime.d.ts.map +1 -1
  178. package/dist/shared/runtime.js +2 -0
  179. package/dist/shared/runtime.js.map +1 -1
  180. package/dist/shared/streaming-text-smoothing.d.ts.map +1 -1
  181. package/dist/shared/streaming-text-smoothing.js +15 -8
  182. package/dist/shared/streaming-text-smoothing.js.map +1 -1
  183. package/dist/templates/default/.agents/skills/secrets/SKILL.md +29 -0
  184. package/dist/templates/default/app/i18n/ar-SA.ts +6 -6
  185. package/dist/templates/default/app/i18n/de-DE.ts +6 -6
  186. package/dist/templates/default/app/i18n/en-US.ts +6 -6
  187. package/dist/templates/default/app/i18n/es-ES.ts +6 -6
  188. package/dist/templates/default/app/i18n/fr-FR.ts +6 -6
  189. package/dist/templates/default/app/i18n/hi-IN.ts +6 -6
  190. package/dist/templates/default/app/i18n/ja-JP.ts +6 -6
  191. package/dist/templates/default/app/i18n/ko-KR.ts +6 -6
  192. package/dist/templates/default/app/i18n/pt-BR.ts +6 -6
  193. package/dist/templates/default/app/i18n/zh-CN.ts +6 -6
  194. package/dist/templates/default/app/i18n/zh-TW.ts +6 -6
  195. package/dist/templates/headless/.agents/skills/secrets/SKILL.md +29 -0
  196. package/dist/templates/workspace-core/.agents/skills/secrets/SKILL.md +29 -0
  197. package/dist/vite/client.d.ts +1 -1
  198. package/dist/vite/client.d.ts.map +1 -1
  199. package/dist/vite/client.js +16 -0
  200. package/dist/vite/client.js.map +1 -1
  201. package/docs/content/cloneable-saas.mdx +9 -9
  202. package/docs/content/creating-templates.mdx +2 -2
  203. package/docs/content/deployment.mdx +23 -0
  204. package/docs/content/faq.mdx +4 -4
  205. package/docs/content/key-concepts.mdx +1 -1
  206. package/docs/content/multi-app-workspace.mdx +1 -1
  207. package/docs/content/syncing-template-changes.mdx +1 -1
  208. package/docs/content/template-analytics-developers.mdx +2 -2
  209. package/docs/content/template-analytics.mdx +2 -2
  210. package/docs/content/template-assets-developers.mdx +3 -3
  211. package/docs/content/template-assets.mdx +2 -2
  212. package/docs/content/template-brain-developers.mdx +2 -2
  213. package/docs/content/template-brain.mdx +1 -1
  214. package/docs/content/template-calendar-developers.mdx +1 -1
  215. package/docs/content/template-calendar.mdx +1 -1
  216. package/docs/content/template-chat.mdx +1 -1
  217. package/docs/content/template-clips-developers.mdx +4 -4
  218. package/docs/content/template-clips.mdx +2 -2
  219. package/docs/content/template-content-developers.mdx +2 -2
  220. package/docs/content/template-content.mdx +1 -1
  221. package/docs/content/template-design-brand-and-figma.mdx +1 -1
  222. package/docs/content/template-design-developers.mdx +2 -2
  223. package/docs/content/template-design.mdx +2 -2
  224. package/docs/content/template-dispatch-developers.mdx +5 -5
  225. package/docs/content/template-forms-developers.mdx +1 -1
  226. package/docs/content/template-forms.mdx +1 -1
  227. package/docs/content/template-mail-developers.mdx +2 -2
  228. package/docs/content/template-mail.mdx +2 -2
  229. package/docs/content/template-plan-developers.mdx +3 -3
  230. package/docs/content/template-plan.mdx +3 -3
  231. package/docs/content/template-slides-developers.mdx +4 -4
  232. package/docs/content/template-slides.mdx +1 -1
  233. package/docs/content/what-is-agent-native.mdx +5 -5
  234. package/package.json +1 -1
  235. package/src/a2a/auth-policy.ts +1 -1
  236. package/src/agent/production-agent.ts +14 -1
  237. package/src/agent/run-manager.ts +6 -13
  238. package/src/cli/index.ts +11 -1
  239. package/src/client/route-chunk-recovery.ts +18 -7
  240. package/src/db/client.ts +7 -6
  241. package/src/db/migrations.ts +2 -1
  242. package/src/deploy/build.ts +290 -4
  243. package/src/deploy/nitro-preset.ts +50 -0
  244. package/src/integrations/pending-tasks-retry-job.ts +2 -1
  245. package/src/scripts/call-agent.ts +4 -2
  246. package/src/server/agent-discovery.ts +1 -0
  247. package/src/server/agent-run-context.ts +13 -3
  248. package/src/server/request-context.ts +2 -0
  249. package/src/shared/cloudflare-globals.d.ts +2 -1
  250. package/src/shared/runtime.ts +2 -0
  251. package/src/shared/streaming-text-smoothing.ts +15 -14
  252. package/src/templates/default/.agents/skills/secrets/SKILL.md +29 -0
  253. package/src/templates/default/app/i18n/ar-SA.ts +6 -6
  254. package/src/templates/default/app/i18n/de-DE.ts +6 -6
  255. package/src/templates/default/app/i18n/en-US.ts +6 -6
  256. package/src/templates/default/app/i18n/es-ES.ts +6 -6
  257. package/src/templates/default/app/i18n/fr-FR.ts +6 -6
  258. package/src/templates/default/app/i18n/hi-IN.ts +6 -6
  259. package/src/templates/default/app/i18n/ja-JP.ts +6 -6
  260. package/src/templates/default/app/i18n/ko-KR.ts +6 -6
  261. package/src/templates/default/app/i18n/pt-BR.ts +6 -6
  262. package/src/templates/default/app/i18n/zh-CN.ts +6 -6
  263. package/src/templates/default/app/i18n/zh-TW.ts +6 -6
  264. package/src/templates/headless/.agents/skills/secrets/SKILL.md +29 -0
  265. package/src/templates/workspace-core/.agents/skills/secrets/SKILL.md +29 -0
  266. package/src/vite/client.ts +20 -1
  267. /package/corpus/templates/slides/server/routes/api/assets/{[filename].delete.ts → [id].delete.ts} +0 -0
@@ -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,SAAS,EACT,2BAA2B,EAC3B,YAAY,GACb,MAAM,kBAAkB,CAAC;AAC1B,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,YAAY,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EACL,mBAAmB,EACnB,eAAe,EACf,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,8BAA8B,CAAC;AAEtC,MAAM,6CAA6C,GAAG,MAAM,CAAC;AAC7D,MAAM,kCAAkC,GAAG,KAAK,CAAC;AACjD,MAAM,yBAAyB,GAAG,KAAK,CAAC;AAExC,SAAS,0BAA0B,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,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 callAgent,\n shouldPreferGlobalA2ASecret,\n signA2AToken,\n} from \"../a2a/client.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 { 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\";\n\nconst DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;\nconst NETLIFY_INTEGRATION_A2A_TIMEOUT_MS = 2_000;\nconst INTEGRATION_A2A_TOKEN_TTL = \"30m\";\n\nfunction buildDelegationCorrelation(\n context: ActionRunContext | undefined,\n selfAppId: string | undefined,\n invocationId?: string,\n): A2ACorrelationMetadata {\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 };\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` global injected by workerd.\n return (\n !!process.env.NETLIFY ||\n !!process.env.AWS_LAMBDA_FUNCTION_NAME ||\n !!process.env.VERCEL ||\n \"__cf_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 \"Call a DIFFERENT, separately-deployed app over A2A. When you know the exact exposed read-only action, pass action + input and omit message; this invokes it directly without starting the other app's model and is the fastest path for bounded data reads. Use message only for natural-language investigation, synthesis, mutations, or multi-step work that needs the other agent. 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 \"Exact read-only action exposed by the target app. Use with input and omit message/taskId to skip the downstream agent loop.\",\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 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 const correlation = buildDelegationCorrelation(context, selfAppId);\n const idempotencyKey =\n message && !taskId\n ? buildMessageIdempotencyKey(context?.turnId, agent.url, message)\n : undefined;\n\n if (action) {\n const agentCallId = randomUUID();\n const startedAt = Date.now();\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 (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 } finally {\n if (context?.send) {\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"done\",\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 `[Note: 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 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 const existingContinuationText = taskId\n ? null\n : await formatExistingIntegrationContinuationIfRetry(agent, message);\n if (existingContinuationText) return existingContinuationText;\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 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 {\n const reason = pollErr?.message ?? \"unknown error\";\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, pollErr) ??\n `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;\n }\n }\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"done\",\n agentCallId,\n durationMs: Date.now() - callStartedAt,\n });\n\n return responseText || \"(empty response)\";\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 return expandRelativeUrls(sanitized, agent.url) || \"(empty response)\";\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 timeoutTaskId = getA2ATaskTimeoutTaskId(err);\n if (timeoutTaskId) {\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 return `The ${agent.name} agent is taking longer than expected. Please try again, ask a simpler question, or open the ${agent.name} app directly.`;\n }\n return `Error calling ${agent.name}: ${msg}`;\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\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,SAAS,EACT,2BAA2B,EAC3B,YAAY,GACb,MAAM,kBAAkB,CAAC;AAC1B,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,YAAY,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,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AY,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 callAgent,\n shouldPreferGlobalA2ASecret,\n signA2AToken,\n} from \"../a2a/client.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 { 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\";\n\nconst DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;\nconst NETLIFY_INTEGRATION_A2A_TIMEOUT_MS = 2_000;\nconst INTEGRATION_A2A_TOKEN_TTL = \"30m\";\n\nfunction buildDelegationCorrelation(\n context: ActionRunContext | undefined,\n selfAppId: string | undefined,\n invocationId?: string,\n): A2ACorrelationMetadata {\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 };\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 \"Call a DIFFERENT, separately-deployed app over A2A. When you know the exact exposed read-only action, pass action + input and omit message; this invokes it directly without starting the other app's model and is the fastest path for bounded data reads. Use message only for natural-language investigation, synthesis, mutations, or multi-step work that needs the other agent. 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 \"Exact read-only action exposed by the target app. Use with input and omit message/taskId to skip the downstream agent loop.\",\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 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 const correlation = buildDelegationCorrelation(context, selfAppId);\n const idempotencyKey =\n message && !taskId\n ? buildMessageIdempotencyKey(context?.turnId, agent.url, message)\n : undefined;\n\n if (action) {\n const agentCallId = randomUUID();\n const startedAt = Date.now();\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 (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 } finally {\n if (context?.send) {\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"done\",\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 `[Note: 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 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 const existingContinuationText = taskId\n ? null\n : await formatExistingIntegrationContinuationIfRetry(agent, message);\n if (existingContinuationText) return existingContinuationText;\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 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 {\n const reason = pollErr?.message ?? \"unknown error\";\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, pollErr) ??\n `The ${agent.name} agent is taking longer than expected and didn't reply in time. (${reason})`;\n }\n }\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"done\",\n agentCallId,\n durationMs: Date.now() - callStartedAt,\n });\n\n return responseText || \"(empty response)\";\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 return expandRelativeUrls(sanitized, agent.url) || \"(empty response)\";\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 timeoutTaskId = getA2ATaskTimeoutTaskId(err);\n if (timeoutTaskId) {\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 return `The ${agent.name} agent is taking longer than expected. Please try again, ask a simpler question, or open the ${agent.name} app directly.`;\n }\n return `Error calling ${agent.name}: ${msg}`;\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\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-discovery.d.ts","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAKA,OAAO,EAML,KAAK,oBAAoB,EAC1B,MAAM,qCAAqC,CAAC;AAG7C,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC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C;AAiSD,+EAA+E;AAC/E,wBAAgB,0BAA0B,IAAI,eAAe,GAAG,SAAS,CAmBxE;AAED;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,EAAE,eAAe,EAOnD,CAAC"}
@@ -341,6 +341,7 @@ function isHostedRuntime() {
341
341
  !!process.env.AWS_LAMBDA_FUNCTION_NAME ||
342
342
  !!process.env.VERCEL ||
343
343
  "__cf_env" in globalThis ||
344
+ "__env__" in globalThis ||
344
345
  hasPublicRuntimeUrl());
345
346
  }
346
347
  function shouldUseLocalAgentUrls() {
@@ -1 +1 @@
1
- {"version":3,"file":"agent-discovery.js","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACrD,OAAO,EACL,8BAA8B,EAC9B,6BAA6B,EAC7B,6BAA6B,EAC7B,mCAAmC,EACnC,sCAAsC,GAEvC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAiC5E;;;;GAIG;AACH,MAAM,cAAc,GAAiB,SAAS,CAAC,MAAM,CACnD,CAAC,QAAQ,EAAE,EAAE,CACX,CAAC,CAAC,QAAQ,CAAC,MAAM,IAAI,QAAQ,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,OAAO,CACpE,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IACnB,EAAE,EAAE,QAAQ,CAAC,IAAI;IACjB,IAAI,EAAE,QAAQ,CAAC,KAAK;IACpB,WAAW,EAAE,QAAQ,CAAC,WAAW,IAAI,QAAQ,CAAC,IAAI;IAClD,GAAG,EAAE,QAAQ,CAAC,OAAQ;IACtB,M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AC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,UAAU,CAAC,CAAC;IACxE,MAAM,GAAG,GAAG,eAAe,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,CAAC,CAAC;IAC/C,IAAI,CAAC,GAAG;QAAE,OAAO,SAAS,CAAC;IAC3B,OAAO;QACL,EAAE,EAAE,GAAG,CAAC,EAAE;QACV,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,WAAW,EACT,GAAG,CAAC,WAAW;YACf,OAAO,EAAE,WAAW;YACpB,4BAA4B,GAAG,CAAC,IAAI,EAAE;QACxC,GAAG;QACH,KAAK,EAAE,OAAO,EAAE,KAAK,IAAI,SAAS;KACnC,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,0BAA0B,GACrC,cAAc,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACpD,EAAE,EAAE,GAAG,CAAC,EAAE;IACV,IAAI,EAAE,GAAG,CAAC,IAAI;IACd,WAAW,EAAE,GAAG,CAAC,WAAW;IAC5B,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,cAAc;IAC5B,KAAK,EAAE,GAAG,CAAC,KAAK;CACjB,CAAC,CAAC,CAAC","sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { TEMPLATES } from \"../cli/templates-meta.js\";\nimport {\n DEFAULT_WORKSPACE_APP_AUDIENCE,\n normalizeWorkspaceAppAudience,\n normalizeWorkspaceAppPathList,\n workspaceAppAudienceFromPackageJson,\n workspaceAppRouteAccessFromPackageJson,\n type WorkspaceAppAudience,\n} from \"../shared/workspace-app-audience.js\";\nimport { getRequestOrgId, getRequestUserEmail } from \"./request-context.js\";\n\nexport interface DiscoveredAgent {\n id: string;\n name: string;\n description: string;\n url: string;\n color: string;\n}\n\nexport interface WorkspaceAppMetadataOverride {\n name?: string;\n description?: string;\n generated?: boolean;\n sourcePrompt?: string;\n updatedAt?: string;\n updatedBy?: string;\n}\n\nexport interface WorkspaceAppMetadataSettings {\n apps: Record<string, WorkspaceAppMetadataOverride>;\n}\n\ninterface AgentEntry {\n id: string;\n name: string;\n description: string;\n url: string;\n devUrl?: string;\n devPort: number;\n color: string;\n}\n\n/**\n * Built-in agent registry. Derive this from the published CLI metadata so\n * connected-agent discovery stays aligned with first-party template metadata\n * without depending on @agent-native/shared-app-config at runtime.\n */\nconst BUILTIN_AGENTS: AgentEntry[] = TEMPLATES.filter(\n (template) =>\n (!template.hidden || template.defaultAgent) && !!template.prodUrl,\n).map((template) => ({\n id: template.name,\n name: template.label,\n description: template.description ?? template.hint,\n url: template.prodUrl!,\n devUrl: `http://localhost:${template.devPort}`,\n devPort: template.devPort,\n color: template.color,\n}));\n\nconst HIDDEN_FIRST_PARTY_AGENT_IDS = new Set([\n ...TEMPLATES.filter(\n (template) => template.hidden && !template.defaultAgent && template.prodUrl,\n ).map((template) => template.name),\n // Stale resources for removed first-party apps should not reappear as\n // custom remote agents just because the template metadata entry is gone.\n \"calls\",\n \"code\",\n \"issues\",\n \"meeting-notes\",\n \"migration\",\n \"recruiting\",\n \"scheduling\",\n \"voice\",\n \"workbench\",\n]);\n\nfunction normalizeAgentId(id: string): string {\n const normalized = id.trim().toLowerCase();\n if (\n normalized === \"image\" ||\n normalized === \"images\" ||\n normalized === \"asset\"\n ) {\n return \"assets\";\n }\n return normalized;\n}\n\nconst WORKSPACE_APPS_ENV_KEY = \"AGENT_NATIVE_WORKSPACE_APPS_JSON\";\nconst WORKSPACE_APPS_MANIFEST_FILE = \"workspace-apps.json\";\nexport const WORKSPACE_APP_METADATA_SETTINGS_KEY = \"workspace-app-metadata\";\n\nexport interface WorkspaceAppManifestEntry {\n id: string;\n name: string;\n description: string;\n path: string;\n url?: string | null;\n isDispatch?: boolean;\n audience?: WorkspaceAppAudience;\n publicPaths?: string[];\n protectedPaths?: string[];\n}\n\nexport function workspaceAppMetadataSettingsKey(input?: {\n orgId?: string | null;\n userEmail?: string | null;\n}): string | null {\n const orgId = input?.orgId ?? getRequestOrgId() ?? null;\n if (orgId) return `${WORKSPACE_APP_METADATA_SETTINGS_KEY}:org:${orgId}`;\n\n const userEmail = input?.userEmail ?? getRequestUserEmail() ?? null;\n if (userEmail)\n return `${WORKSPACE_APP_METADATA_SETTINGS_KEY}:user:${userEmail}`;\n\n return null;\n}\n\nfunction cleanOptionalText(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nexport function parseWorkspaceAppMetadataSettings(\n raw: unknown,\n): WorkspaceAppMetadataSettings {\n const record =\n raw && typeof raw === \"object\" && !Array.isArray(raw)\n ? (raw as Record<string, unknown>)\n : {};\n const rawApps =\n record.apps &&\n typeof record.apps === \"object\" &&\n !Array.isArray(record.apps)\n ? (record.apps as Record<string, unknown>)\n : {};\n const apps: Record<string, WorkspaceAppMetadataOverride> = {};\n\n for (const [id, value] of Object.entries(rawApps)) {\n if (!id.trim() || !value || typeof value !== \"object\") continue;\n const item = value as Record<string, unknown>;\n const override: WorkspaceAppMetadataOverride = {};\n const name = cleanOptionalText(item.name);\n const description = cleanOptionalText(item.description);\n const sourcePrompt = cleanOptionalText(item.sourcePrompt);\n const updatedAt = cleanOptionalText(item.updatedAt);\n const updatedBy = cleanOptionalText(item.updatedBy);\n\n if (name) override.name = name;\n if (description) override.description = description;\n if (item.generated === true) override.generated = true;\n if (sourcePrompt) override.sourcePrompt = sourcePrompt;\n if (updatedAt) override.updatedAt = updatedAt;\n if (updatedBy) override.updatedBy = updatedBy;\n\n if (Object.keys(override).length > 0) apps[id.trim()] = override;\n }\n\n return { apps };\n}\n\nexport async function readWorkspaceAppMetadataSettings(): Promise<WorkspaceAppMetadataSettings> {\n const key = workspaceAppMetadataSettingsKey();\n if (!key) return { apps: {} };\n\n try {\n const { getSetting } = await import(\"../settings/index.js\");\n return parseWorkspaceAppMetadataSettings(await getSetting(key));\n } catch {\n return { apps: {} };\n }\n}\n\nexport async function writeWorkspaceAppMetadataOverride(input: {\n appId: string;\n name?: string | null;\n description?: string | null;\n generated?: boolean;\n sourcePrompt?: string | null;\n updatedBy?: string | null;\n}): Promise<WorkspaceAppMetadataSettings> {\n const key = workspaceAppMetadataSettingsKey();\n if (!key) throw new Error(\"no authenticated user\");\n\n const appId = input.appId.trim();\n if (!appId) throw new Error(\"appId is required\");\n\n const { getSetting, putSetting } = await import(\"../settings/index.js\");\n const current = parseWorkspaceAppMetadataSettings(await getSetting(key));\n const existing = current.apps[appId] ?? {};\n const next: WorkspaceAppMetadataOverride = {\n ...existing,\n updatedAt: new Date().toISOString(),\n };\n\n const name = cleanOptionalText(input.name);\n const description = cleanOptionalText(input.description);\n const sourcePrompt = cleanOptionalText(input.sourcePrompt);\n const updatedBy = cleanOptionalText(input.updatedBy);\n\n if (name) next.name = name;\n else delete next.name;\n if (description) next.description = description;\n else delete next.description;\n if (input.generated === true) next.generated = true;\n else if (input.generated === false) delete next.generated;\n if (sourcePrompt) next.sourcePrompt = sourcePrompt;\n if (updatedBy) next.updatedBy = updatedBy;\n\n current.apps[appId] = next;\n await putSetting(key, current as unknown as Record<string, unknown>);\n return current;\n}\n\nexport function applyWorkspaceAppMetadataOverride<\n T extends {\n id: string;\n name: string;\n description?: string | null;\n },\n>(app: T, settings: WorkspaceAppMetadataSettings): T {\n const override = settings.apps[app.id];\n if (!override) return app;\n\n const name = cleanOptionalText(override.name);\n const description = cleanOptionalText(override.description);\n const generated = override.generated === true;\n const shouldApplyName = !!name && !generated;\n const shouldApplyDescription =\n !!description && (!generated || !cleanOptionalText(app.description));\n if (!shouldApplyName && !shouldApplyDescription) return app;\n\n return {\n ...app,\n ...(shouldApplyName ? { name } : {}),\n ...(shouldApplyDescription ? { description } : {}),\n };\n}\n\n/**\n * Resolve the workspace app manifest from the same fallback chain that\n * `discoverWorkspaceAgents` uses: `AGENT_NATIVE_WORKSPACE_APPS_JSON` env →\n * `.agent-native/workspace-apps.json` (or sibling) on disk → live filesystem\n * scan of `apps/<id>/package.json` under the workspace root.\n *\n * Callers (e.g. the dispatch `/dispatch/<appId>` catch-all loader) need this\n * to behave the same in production deploys (which write the manifest file)\n * and during local dev (where new apps appear under `apps/` without an env\n * restart). Reading only the env var would silently downgrade the behavior\n * in both cases.\n */\nexport function loadWorkspaceAppsManifest():\n | WorkspaceAppManifestEntry[]\n | null {\n return (\n readWorkspaceAppsFromEnv() ??\n readWorkspaceAppsFromManifestFile() ??\n readWorkspaceAppsFromFilesystem()\n );\n}\n\nexport function shouldIncludeRemoteAgentManifest(\n manifest: { id?: string | null },\n selfAppId?: string,\n): boolean {\n const id = manifest.id?.trim();\n if (!id) return false;\n const normalizedId = normalizeAgentId(id);\n const normalizedSelfAppId = selfAppId ? normalizeAgentId(selfAppId) : \"\";\n if (normalizedSelfAppId && normalizedId === normalizedSelfAppId) {\n return false;\n }\n return !HIDDEN_FIRST_PARTY_AGENT_IDS.has(normalizedId);\n}\n\n/**\n * Get built-in agents (static, no DB). Used as fallback and for seeding.\n */\nexport function getBuiltinAgents(selfAppId?: string): DiscoveredAgent[] {\n const normalizedSelfAppId = selfAppId ? normalizeAgentId(selfAppId) : \"\";\n return BUILTIN_AGENTS.filter(\n (app) => app.id !== normalizedSelfAppId && app.url,\n ).map((app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: resolveAgentUrl(app),\n color: app.color,\n }));\n}\n\n/**\n * Discover all agents: built-in + custom agents stored as resources.\n * Custom agents override built-in agents with the same ID.\n */\nexport async function discoverAgents(\n selfAppId?: string,\n): Promise<DiscoveredAgent[]> {\n const builtins = getBuiltinAgents(selfAppId);\n const agentsById = new Map<string, DiscoveredAgent>();\n\n // Start with built-ins\n for (const agent of builtins) {\n agentsById.set(agent.id, agent);\n }\n\n // Overlay custom agents from resources\n try {\n const { resourceList, resourceGet, SHARED_OWNER } =\n await import(\"../resources/store.js\");\n\n const { parseRemoteAgentManifest, REMOTE_AGENT_RESOURCE_PREFIXES } =\n await import(\"../resources/metadata.js\");\n\n const resources: Array<{ id: string; path: string }> = [];\n for (const prefix of [...REMOTE_AGENT_RESOURCE_PREFIXES].reverse()) {\n resources.push(...(await resourceList(SHARED_OWNER, prefix)));\n }\n\n for (const r of resources) {\n if (!r.path.endsWith(\".json\")) continue;\n try {\n const full = await resourceGet(r.id);\n if (!full) continue;\n const manifest = parseRemoteAgentManifest(full.content, r.path);\n if (!manifest || !shouldIncludeRemoteAgentManifest(manifest, selfAppId))\n continue;\n const manifestId = normalizeAgentId(manifest.id);\n\n // If the resource override carries a localhost URL but we're running\n // in production (e.g. a stale dev-time seed got promoted to the prod\n // DB), fall back to the matching built-in's prod URL instead of\n // letting the override win — otherwise outbound `call-agent` fetches\n // from a serverless function would target localhost and fail with\n // \"fetch failed\" instantly. The override still wins for non-localhost\n // URLs (the supported case for self-hosted custom agents).\n let url = manifest.url;\n const isProduction =\n typeof process !== \"undefined\" &&\n process.env?.NODE_ENV === \"production\";\n if (\n isProduction &&\n typeof url === \"string\" &&\n /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0)(:|\\/|$)/.test(url)\n ) {\n const builtin = agentsById.get(manifestId);\n if (builtin?.url) url = builtin.url;\n }\n\n const builtin = agentsById.get(manifestId);\n const isLegacyAssetsManifest =\n manifest.id.trim().toLowerCase() !== manifestId;\n if (isLegacyAssetsManifest && builtin?.url) {\n try {\n if (new URL(url).hostname === \"images.agent-native.com\") {\n url = builtin.url;\n }\n } catch {\n url = builtin.url;\n }\n }\n\n agentsById.set(manifestId, {\n id: manifestId,\n name:\n isLegacyAssetsManifest && builtin?.name\n ? builtin.name\n : manifest.name,\n description: manifest.description || \"\",\n url,\n color: manifest.color || builtin?.color || \"#6B7280\",\n });\n } catch {\n // Skip unreadable resources\n }\n }\n } catch {\n // Resources not available — use built-ins only\n }\n\n // Overlay sibling workspace apps last so same-origin workspaces prefer the\n // app mounted in this workspace over the public template with the same id.\n for (const agent of await discoverWorkspaceAgents(selfAppId)) {\n agentsById.set(agent.id, agent);\n }\n\n return Array.from(agentsById.values());\n}\n\n/**\n * Look up a single agent by ID or name (case-insensitive).\n */\nexport async function findAgent(\n idOrName: string,\n selfAppId?: string,\n): Promise<DiscoveredAgent | undefined> {\n const lower = normalizeAgentId(idOrName);\n const agents = await discoverAgents(selfAppId);\n return agents.find((a) => a.id === lower || a.name.toLowerCase() === lower);\n}\n\nfunction hostnameFromUrlLike(value: string | undefined): string | null {\n if (!value) return null;\n try {\n return new URL(value).hostname.toLowerCase();\n } catch {\n try {\n return new URL(`http://${value}`).hostname.toLowerCase();\n } catch {\n return null;\n }\n }\n}\n\nfunction isLoopbackUrl(value: string | undefined): boolean {\n const hostname = hostnameFromUrlLike(value);\n return (\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"0.0.0.0\" ||\n hostname === \"::1\"\n );\n}\n\nfunction hasPublicRuntimeUrl(): boolean {\n // Intentionally omit generic `URL` / `DEPLOY_URL` here. Platforms that set\n // those also expose a stronger hosted signal (for example `NETLIFY`), while\n // local shells and unrelated tools can use generic URL vars for other work.\n const keys = [\n \"WORKSPACE_GATEWAY_URL\",\n \"VITE_WORKSPACE_GATEWAY_URL\",\n \"APP_URL\",\n \"WORKSPACE_OAUTH_ORIGIN\",\n \"VITE_WORKSPACE_OAUTH_ORIGIN\",\n \"BETTER_AUTH_URL\",\n \"VITE_BETTER_AUTH_URL\",\n \"VERCEL_URL\",\n \"VERCEL_PROJECT_PRODUCTION_URL\",\n ];\n\n return keys.some((key) => {\n const value = process.env[key];\n return !!value && !isLoopbackUrl(value);\n });\n}\n\nfunction isHostedRuntime(): boolean {\n return (\n process.env.NODE_ENV === \"production\" ||\n !!process.env.NETLIFY ||\n !!process.env.AWS_LAMBDA_FUNCTION_NAME ||\n !!process.env.VERCEL ||\n \"__cf_env\" in globalThis ||\n hasPublicRuntimeUrl()\n );\n}\n\nfunction shouldUseLocalAgentUrls(): boolean {\n return !isHostedRuntime();\n}\n\nfunction resolveAgentUrl(app: AgentEntry): string {\n if (shouldUseLocalAgentUrls()) {\n return app.devUrl || `http://localhost:${app.devPort}`;\n }\n return app.url;\n}\n\nfunction readJson(file: string): any {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction findWorkspaceRoot(startDir = process.cwd()): string | null {\n let dir = path.resolve(startDir);\n for (let i = 0; i < 20; i++) {\n const pkg = readJson(path.join(dir, \"package.json\"));\n if (typeof pkg?.[\"agent-native\"]?.workspaceCore === \"string\") {\n return dir;\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nfunction titleCase(value: string): string {\n return value\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction parseWorkspaceAppsManifest(\n parsed: any,\n): WorkspaceAppManifestEntry[] | null {\n const rawApps = Array.isArray(parsed?.apps)\n ? parsed.apps\n : Array.isArray(parsed)\n ? parsed\n : null;\n if (!rawApps) return null;\n\n const apps = (rawApps as unknown[])\n .map((entry): WorkspaceAppManifestEntry | null => {\n if (!entry || typeof entry !== \"object\") return null;\n const e = entry as Record<string, unknown>;\n const id = typeof e.id === \"string\" ? e.id.trim() : \"\";\n const pathValue = typeof e.path === \"string\" ? e.path.trim() : \"\";\n if (!id || !pathValue.startsWith(\"/\")) return null;\n return {\n id,\n name:\n typeof e.name === \"string\" && e.name.trim()\n ? e.name.trim()\n : titleCase(id),\n description: typeof e.description === \"string\" ? e.description : \"\",\n path: pathValue,\n url: typeof e.url === \"string\" && e.url.trim() ? e.url.trim() : null,\n isDispatch:\n typeof e.isDispatch === \"boolean\" ? e.isDispatch : id === \"dispatch\",\n audience:\n e.audience === undefined\n ? DEFAULT_WORKSPACE_APP_AUDIENCE\n : normalizeWorkspaceAppAudience(e.audience),\n publicPaths: normalizeWorkspaceAppPathList(e.publicPaths),\n protectedPaths: normalizeWorkspaceAppPathList(e.protectedPaths),\n };\n })\n .filter((app): app is WorkspaceAppManifestEntry => app !== null)\n .sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.name.localeCompare(b.name);\n });\n\n return apps.length ? apps : null;\n}\n\nfunction readWorkspaceAppsFromEnv(): WorkspaceAppManifestEntry[] | null {\n const raw = process.env[WORKSPACE_APPS_ENV_KEY];\n if (!raw) return null;\n try {\n return parseWorkspaceAppsManifest(JSON.parse(raw));\n } catch {\n return null;\n }\n}\n\nfunction workspaceAppsManifestCandidates(): string[] {\n const candidates: string[] = [];\n try {\n candidates.push(\n path.join(process.cwd(), \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(process.cwd(), WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes do not expose process.cwd().\n }\n try {\n const moduleDir = path.dirname(fileURLToPath(import.meta.url));\n candidates.push(\n path.join(moduleDir, \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(moduleDir, WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes expose non-file module URLs. The env manifest still\n // works there, so skip file-relative candidates.\n }\n return candidates;\n}\n\nfunction readWorkspaceAppsFromManifestFile():\n | WorkspaceAppManifestEntry[]\n | null {\n for (const file of workspaceAppsManifestCandidates()) {\n if (!fs.existsSync(file)) continue;\n const apps = parseWorkspaceAppsManifest(readJson(file));\n if (apps) return apps;\n }\n return null;\n}\n\nfunction readWorkspaceAppsFromFilesystem(): WorkspaceAppManifestEntry[] | null {\n const workspaceRoot = findWorkspaceRoot();\n if (!workspaceRoot) return null;\n const appsDir = path.join(workspaceRoot, \"apps\");\n if (!fs.existsSync(appsDir)) return null;\n\n const apps = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry): WorkspaceAppManifestEntry | null => {\n const appDir = path.join(appsDir, entry.name);\n const pkg = readJson(path.join(appDir, \"package.json\"));\n if (!pkg) return null;\n const routeAccess = workspaceAppRouteAccessFromPackageJson(pkg);\n return {\n id: entry.name,\n name: pkg.displayName || titleCase(entry.name),\n description: pkg.description || \"\",\n path: `/${entry.name}`,\n isDispatch: entry.name === \"dispatch\",\n audience:\n workspaceAppAudienceFromPackageJson(pkg) ??\n DEFAULT_WORKSPACE_APP_AUDIENCE,\n publicPaths: routeAccess.publicPaths ?? [],\n protectedPaths: routeAccess.protectedPaths ?? [],\n } satisfies WorkspaceAppManifestEntry;\n })\n .filter((app): app is WorkspaceAppManifestEntry => !!app)\n .sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.name.localeCompare(b.name);\n });\n\n return apps.length ? apps : null;\n}\n\nfunction workspaceBaseUrl(): string | null {\n return (\n process.env.WORKSPACE_GATEWAY_URL ||\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL ||\n null\n );\n}\n\nfunction workspaceAppUrl(\n app: WorkspaceAppManifestEntry,\n hostedLoopbackFallbackUrl?: string,\n): string | null {\n if (app.url) {\n if (!isHostedRuntime() || !isLoopbackUrl(app.url)) return app.url;\n if (hostedLoopbackFallbackUrl) return hostedLoopbackFallbackUrl;\n }\n const base = workspaceBaseUrl();\n if (!base) return null;\n try {\n return new URL(app.path, `${base.replace(/\\/$/, \"\")}/`).toString();\n } catch {\n return null;\n }\n}\n\nasync function discoverWorkspaceAgents(\n selfAppId?: string,\n): Promise<DiscoveredAgent[]> {\n const workspaceApps = loadWorkspaceAppsManifest();\n if (!workspaceApps) return [];\n\n const metadataSettings = await readWorkspaceAppMetadataSettings();\n\n return workspaceApps\n .filter((app) => app.id !== selfAppId)\n .map((app) => {\n const withOverride = applyWorkspaceAppMetadataOverride(\n app,\n metadataSettings,\n );\n const builtin = BUILTIN_AGENTS.find(\n (agent) => agent.id === withOverride.id,\n );\n const url = workspaceAppUrl(withOverride, builtin?.url);\n if (!url) return null;\n return {\n id: withOverride.id,\n name: withOverride.name,\n description:\n withOverride.description ||\n builtin?.description ||\n `Workspace app mounted at ${withOverride.path}`,\n url,\n color: builtin?.color || \"#6B7280\",\n } satisfies DiscoveredAgent;\n })\n .filter((agent): agent is DiscoveredAgent => !!agent);\n}\n\n/** Resolve only the Dispatch app designated by the receiver's own manifest. */\nexport function findWorkspaceDispatchAgent(): DiscoveredAgent | undefined {\n const app = loadWorkspaceAppsManifest()?.find(\n (candidate) => candidate.isDispatch === true,\n );\n if (!app) return undefined;\n\n const builtin = BUILTIN_AGENTS.find((agent) => agent.id === \"dispatch\");\n const url = workspaceAppUrl(app, builtin?.url);\n if (!url) return undefined;\n return {\n id: app.id,\n name: app.name,\n description:\n app.description ||\n builtin?.description ||\n `Workspace app mounted at ${app.path}`,\n url,\n color: builtin?.color || \"#6B7280\",\n };\n}\n\n/**\n * Like `getBuiltinAgents`, but always returns the production URL — never the\n * env-resolved devUrl. Used by the resource seeder so that a one-time seed\n * (`ON CONFLICT DO NOTHING`) can't permanently bake a localhost URL into the\n * DB, which would override the built-in's prod URL for every later\n * production deploy.\n */\nexport const BUILTIN_AGENTS_FOR_SEEDING: DiscoveredAgent[] =\n BUILTIN_AGENTS.filter((app) => app.url).map((app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: app.url, // ALWAYS prod\n color: app.color,\n }));\n"]}
1
+ {"version":3,"file":"agent-discovery.js","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACrD,OAAO,EACL,8BAA8B,EAC9B,6BAA6B,EAC7B,6BAA6B,EAC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AC;IACpD,EAAE,EAAE,GAAG,CAAC,EAAE;IACV,IAAI,EAAE,GAAG,CAAC,IAAI;IACd,WAAW,EAAE,GAAG,CAAC,WAAW;IAC5B,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,cAAc;IAC5B,KAAK,EAAE,GAAG,CAAC,KAAK;CACjB,CAAC,CAAC,CAAC","sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { TEMPLATES } from \"../cli/templates-meta.js\";\nimport {\n DEFAULT_WORKSPACE_APP_AUDIENCE,\n normalizeWorkspaceAppAudience,\n normalizeWorkspaceAppPathList,\n workspaceAppAudienceFromPackageJson,\n workspaceAppRouteAccessFromPackageJson,\n type WorkspaceAppAudience,\n} from \"../shared/workspace-app-audience.js\";\nimport { getRequestOrgId, getRequestUserEmail } from \"./request-context.js\";\n\nexport interface DiscoveredAgent {\n id: string;\n name: string;\n description: string;\n url: string;\n color: string;\n}\n\nexport interface WorkspaceAppMetadataOverride {\n name?: string;\n description?: string;\n generated?: boolean;\n sourcePrompt?: string;\n updatedAt?: string;\n updatedBy?: string;\n}\n\nexport interface WorkspaceAppMetadataSettings {\n apps: Record<string, WorkspaceAppMetadataOverride>;\n}\n\ninterface AgentEntry {\n id: string;\n name: string;\n description: string;\n url: string;\n devUrl?: string;\n devPort: number;\n color: string;\n}\n\n/**\n * Built-in agent registry. Derive this from the published CLI metadata so\n * connected-agent discovery stays aligned with first-party template metadata\n * without depending on @agent-native/shared-app-config at runtime.\n */\nconst BUILTIN_AGENTS: AgentEntry[] = TEMPLATES.filter(\n (template) =>\n (!template.hidden || template.defaultAgent) && !!template.prodUrl,\n).map((template) => ({\n id: template.name,\n name: template.label,\n description: template.description ?? template.hint,\n url: template.prodUrl!,\n devUrl: `http://localhost:${template.devPort}`,\n devPort: template.devPort,\n color: template.color,\n}));\n\nconst HIDDEN_FIRST_PARTY_AGENT_IDS = new Set([\n ...TEMPLATES.filter(\n (template) => template.hidden && !template.defaultAgent && template.prodUrl,\n ).map((template) => template.name),\n // Stale resources for removed first-party apps should not reappear as\n // custom remote agents just because the template metadata entry is gone.\n \"calls\",\n \"code\",\n \"issues\",\n \"meeting-notes\",\n \"migration\",\n \"recruiting\",\n \"scheduling\",\n \"voice\",\n \"workbench\",\n]);\n\nfunction normalizeAgentId(id: string): string {\n const normalized = id.trim().toLowerCase();\n if (\n normalized === \"image\" ||\n normalized === \"images\" ||\n normalized === \"asset\"\n ) {\n return \"assets\";\n }\n return normalized;\n}\n\nconst WORKSPACE_APPS_ENV_KEY = \"AGENT_NATIVE_WORKSPACE_APPS_JSON\";\nconst WORKSPACE_APPS_MANIFEST_FILE = \"workspace-apps.json\";\nexport const WORKSPACE_APP_METADATA_SETTINGS_KEY = \"workspace-app-metadata\";\n\nexport interface WorkspaceAppManifestEntry {\n id: string;\n name: string;\n description: string;\n path: string;\n url?: string | null;\n isDispatch?: boolean;\n audience?: WorkspaceAppAudience;\n publicPaths?: string[];\n protectedPaths?: string[];\n}\n\nexport function workspaceAppMetadataSettingsKey(input?: {\n orgId?: string | null;\n userEmail?: string | null;\n}): string | null {\n const orgId = input?.orgId ?? getRequestOrgId() ?? null;\n if (orgId) return `${WORKSPACE_APP_METADATA_SETTINGS_KEY}:org:${orgId}`;\n\n const userEmail = input?.userEmail ?? getRequestUserEmail() ?? null;\n if (userEmail)\n return `${WORKSPACE_APP_METADATA_SETTINGS_KEY}:user:${userEmail}`;\n\n return null;\n}\n\nfunction cleanOptionalText(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nexport function parseWorkspaceAppMetadataSettings(\n raw: unknown,\n): WorkspaceAppMetadataSettings {\n const record =\n raw && typeof raw === \"object\" && !Array.isArray(raw)\n ? (raw as Record<string, unknown>)\n : {};\n const rawApps =\n record.apps &&\n typeof record.apps === \"object\" &&\n !Array.isArray(record.apps)\n ? (record.apps as Record<string, unknown>)\n : {};\n const apps: Record<string, WorkspaceAppMetadataOverride> = {};\n\n for (const [id, value] of Object.entries(rawApps)) {\n if (!id.trim() || !value || typeof value !== \"object\") continue;\n const item = value as Record<string, unknown>;\n const override: WorkspaceAppMetadataOverride = {};\n const name = cleanOptionalText(item.name);\n const description = cleanOptionalText(item.description);\n const sourcePrompt = cleanOptionalText(item.sourcePrompt);\n const updatedAt = cleanOptionalText(item.updatedAt);\n const updatedBy = cleanOptionalText(item.updatedBy);\n\n if (name) override.name = name;\n if (description) override.description = description;\n if (item.generated === true) override.generated = true;\n if (sourcePrompt) override.sourcePrompt = sourcePrompt;\n if (updatedAt) override.updatedAt = updatedAt;\n if (updatedBy) override.updatedBy = updatedBy;\n\n if (Object.keys(override).length > 0) apps[id.trim()] = override;\n }\n\n return { apps };\n}\n\nexport async function readWorkspaceAppMetadataSettings(): Promise<WorkspaceAppMetadataSettings> {\n const key = workspaceAppMetadataSettingsKey();\n if (!key) return { apps: {} };\n\n try {\n const { getSetting } = await import(\"../settings/index.js\");\n return parseWorkspaceAppMetadataSettings(await getSetting(key));\n } catch {\n return { apps: {} };\n }\n}\n\nexport async function writeWorkspaceAppMetadataOverride(input: {\n appId: string;\n name?: string | null;\n description?: string | null;\n generated?: boolean;\n sourcePrompt?: string | null;\n updatedBy?: string | null;\n}): Promise<WorkspaceAppMetadataSettings> {\n const key = workspaceAppMetadataSettingsKey();\n if (!key) throw new Error(\"no authenticated user\");\n\n const appId = input.appId.trim();\n if (!appId) throw new Error(\"appId is required\");\n\n const { getSetting, putSetting } = await import(\"../settings/index.js\");\n const current = parseWorkspaceAppMetadataSettings(await getSetting(key));\n const existing = current.apps[appId] ?? {};\n const next: WorkspaceAppMetadataOverride = {\n ...existing,\n updatedAt: new Date().toISOString(),\n };\n\n const name = cleanOptionalText(input.name);\n const description = cleanOptionalText(input.description);\n const sourcePrompt = cleanOptionalText(input.sourcePrompt);\n const updatedBy = cleanOptionalText(input.updatedBy);\n\n if (name) next.name = name;\n else delete next.name;\n if (description) next.description = description;\n else delete next.description;\n if (input.generated === true) next.generated = true;\n else if (input.generated === false) delete next.generated;\n if (sourcePrompt) next.sourcePrompt = sourcePrompt;\n if (updatedBy) next.updatedBy = updatedBy;\n\n current.apps[appId] = next;\n await putSetting(key, current as unknown as Record<string, unknown>);\n return current;\n}\n\nexport function applyWorkspaceAppMetadataOverride<\n T extends {\n id: string;\n name: string;\n description?: string | null;\n },\n>(app: T, settings: WorkspaceAppMetadataSettings): T {\n const override = settings.apps[app.id];\n if (!override) return app;\n\n const name = cleanOptionalText(override.name);\n const description = cleanOptionalText(override.description);\n const generated = override.generated === true;\n const shouldApplyName = !!name && !generated;\n const shouldApplyDescription =\n !!description && (!generated || !cleanOptionalText(app.description));\n if (!shouldApplyName && !shouldApplyDescription) return app;\n\n return {\n ...app,\n ...(shouldApplyName ? { name } : {}),\n ...(shouldApplyDescription ? { description } : {}),\n };\n}\n\n/**\n * Resolve the workspace app manifest from the same fallback chain that\n * `discoverWorkspaceAgents` uses: `AGENT_NATIVE_WORKSPACE_APPS_JSON` env →\n * `.agent-native/workspace-apps.json` (or sibling) on disk → live filesystem\n * scan of `apps/<id>/package.json` under the workspace root.\n *\n * Callers (e.g. the dispatch `/dispatch/<appId>` catch-all loader) need this\n * to behave the same in production deploys (which write the manifest file)\n * and during local dev (where new apps appear under `apps/` without an env\n * restart). Reading only the env var would silently downgrade the behavior\n * in both cases.\n */\nexport function loadWorkspaceAppsManifest():\n | WorkspaceAppManifestEntry[]\n | null {\n return (\n readWorkspaceAppsFromEnv() ??\n readWorkspaceAppsFromManifestFile() ??\n readWorkspaceAppsFromFilesystem()\n );\n}\n\nexport function shouldIncludeRemoteAgentManifest(\n manifest: { id?: string | null },\n selfAppId?: string,\n): boolean {\n const id = manifest.id?.trim();\n if (!id) return false;\n const normalizedId = normalizeAgentId(id);\n const normalizedSelfAppId = selfAppId ? normalizeAgentId(selfAppId) : \"\";\n if (normalizedSelfAppId && normalizedId === normalizedSelfAppId) {\n return false;\n }\n return !HIDDEN_FIRST_PARTY_AGENT_IDS.has(normalizedId);\n}\n\n/**\n * Get built-in agents (static, no DB). Used as fallback and for seeding.\n */\nexport function getBuiltinAgents(selfAppId?: string): DiscoveredAgent[] {\n const normalizedSelfAppId = selfAppId ? normalizeAgentId(selfAppId) : \"\";\n return BUILTIN_AGENTS.filter(\n (app) => app.id !== normalizedSelfAppId && app.url,\n ).map((app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: resolveAgentUrl(app),\n color: app.color,\n }));\n}\n\n/**\n * Discover all agents: built-in + custom agents stored as resources.\n * Custom agents override built-in agents with the same ID.\n */\nexport async function discoverAgents(\n selfAppId?: string,\n): Promise<DiscoveredAgent[]> {\n const builtins = getBuiltinAgents(selfAppId);\n const agentsById = new Map<string, DiscoveredAgent>();\n\n // Start with built-ins\n for (const agent of builtins) {\n agentsById.set(agent.id, agent);\n }\n\n // Overlay custom agents from resources\n try {\n const { resourceList, resourceGet, SHARED_OWNER } =\n await import(\"../resources/store.js\");\n\n const { parseRemoteAgentManifest, REMOTE_AGENT_RESOURCE_PREFIXES } =\n await import(\"../resources/metadata.js\");\n\n const resources: Array<{ id: string; path: string }> = [];\n for (const prefix of [...REMOTE_AGENT_RESOURCE_PREFIXES].reverse()) {\n resources.push(...(await resourceList(SHARED_OWNER, prefix)));\n }\n\n for (const r of resources) {\n if (!r.path.endsWith(\".json\")) continue;\n try {\n const full = await resourceGet(r.id);\n if (!full) continue;\n const manifest = parseRemoteAgentManifest(full.content, r.path);\n if (!manifest || !shouldIncludeRemoteAgentManifest(manifest, selfAppId))\n continue;\n const manifestId = normalizeAgentId(manifest.id);\n\n // If the resource override carries a localhost URL but we're running\n // in production (e.g. a stale dev-time seed got promoted to the prod\n // DB), fall back to the matching built-in's prod URL instead of\n // letting the override win — otherwise outbound `call-agent` fetches\n // from a serverless function would target localhost and fail with\n // \"fetch failed\" instantly. The override still wins for non-localhost\n // URLs (the supported case for self-hosted custom agents).\n let url = manifest.url;\n const isProduction =\n typeof process !== \"undefined\" &&\n process.env?.NODE_ENV === \"production\";\n if (\n isProduction &&\n typeof url === \"string\" &&\n /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0)(:|\\/|$)/.test(url)\n ) {\n const builtin = agentsById.get(manifestId);\n if (builtin?.url) url = builtin.url;\n }\n\n const builtin = agentsById.get(manifestId);\n const isLegacyAssetsManifest =\n manifest.id.trim().toLowerCase() !== manifestId;\n if (isLegacyAssetsManifest && builtin?.url) {\n try {\n if (new URL(url).hostname === \"images.agent-native.com\") {\n url = builtin.url;\n }\n } catch {\n url = builtin.url;\n }\n }\n\n agentsById.set(manifestId, {\n id: manifestId,\n name:\n isLegacyAssetsManifest && builtin?.name\n ? builtin.name\n : manifest.name,\n description: manifest.description || \"\",\n url,\n color: manifest.color || builtin?.color || \"#6B7280\",\n });\n } catch {\n // Skip unreadable resources\n }\n }\n } catch {\n // Resources not available — use built-ins only\n }\n\n // Overlay sibling workspace apps last so same-origin workspaces prefer the\n // app mounted in this workspace over the public template with the same id.\n for (const agent of await discoverWorkspaceAgents(selfAppId)) {\n agentsById.set(agent.id, agent);\n }\n\n return Array.from(agentsById.values());\n}\n\n/**\n * Look up a single agent by ID or name (case-insensitive).\n */\nexport async function findAgent(\n idOrName: string,\n selfAppId?: string,\n): Promise<DiscoveredAgent | undefined> {\n const lower = normalizeAgentId(idOrName);\n const agents = await discoverAgents(selfAppId);\n return agents.find((a) => a.id === lower || a.name.toLowerCase() === lower);\n}\n\nfunction hostnameFromUrlLike(value: string | undefined): string | null {\n if (!value) return null;\n try {\n return new URL(value).hostname.toLowerCase();\n } catch {\n try {\n return new URL(`http://${value}`).hostname.toLowerCase();\n } catch {\n return null;\n }\n }\n}\n\nfunction isLoopbackUrl(value: string | undefined): boolean {\n const hostname = hostnameFromUrlLike(value);\n return (\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"0.0.0.0\" ||\n hostname === \"::1\"\n );\n}\n\nfunction hasPublicRuntimeUrl(): boolean {\n // Intentionally omit generic `URL` / `DEPLOY_URL` here. Platforms that set\n // those also expose a stronger hosted signal (for example `NETLIFY`), while\n // local shells and unrelated tools can use generic URL vars for other work.\n const keys = [\n \"WORKSPACE_GATEWAY_URL\",\n \"VITE_WORKSPACE_GATEWAY_URL\",\n \"APP_URL\",\n \"WORKSPACE_OAUTH_ORIGIN\",\n \"VITE_WORKSPACE_OAUTH_ORIGIN\",\n \"BETTER_AUTH_URL\",\n \"VITE_BETTER_AUTH_URL\",\n \"VERCEL_URL\",\n \"VERCEL_PROJECT_PRODUCTION_URL\",\n ];\n\n return keys.some((key) => {\n const value = process.env[key];\n return !!value && !isLoopbackUrl(value);\n });\n}\n\nfunction isHostedRuntime(): boolean {\n return (\n process.env.NODE_ENV === \"production\" ||\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 hasPublicRuntimeUrl()\n );\n}\n\nfunction shouldUseLocalAgentUrls(): boolean {\n return !isHostedRuntime();\n}\n\nfunction resolveAgentUrl(app: AgentEntry): string {\n if (shouldUseLocalAgentUrls()) {\n return app.devUrl || `http://localhost:${app.devPort}`;\n }\n return app.url;\n}\n\nfunction readJson(file: string): any {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch {\n return null;\n }\n}\n\nfunction findWorkspaceRoot(startDir = process.cwd()): string | null {\n let dir = path.resolve(startDir);\n for (let i = 0; i < 20; i++) {\n const pkg = readJson(path.join(dir, \"package.json\"));\n if (typeof pkg?.[\"agent-native\"]?.workspaceCore === \"string\") {\n return dir;\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nfunction titleCase(value: string): string {\n return value\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction parseWorkspaceAppsManifest(\n parsed: any,\n): WorkspaceAppManifestEntry[] | null {\n const rawApps = Array.isArray(parsed?.apps)\n ? parsed.apps\n : Array.isArray(parsed)\n ? parsed\n : null;\n if (!rawApps) return null;\n\n const apps = (rawApps as unknown[])\n .map((entry): WorkspaceAppManifestEntry | null => {\n if (!entry || typeof entry !== \"object\") return null;\n const e = entry as Record<string, unknown>;\n const id = typeof e.id === \"string\" ? e.id.trim() : \"\";\n const pathValue = typeof e.path === \"string\" ? e.path.trim() : \"\";\n if (!id || !pathValue.startsWith(\"/\")) return null;\n return {\n id,\n name:\n typeof e.name === \"string\" && e.name.trim()\n ? e.name.trim()\n : titleCase(id),\n description: typeof e.description === \"string\" ? e.description : \"\",\n path: pathValue,\n url: typeof e.url === \"string\" && e.url.trim() ? e.url.trim() : null,\n isDispatch:\n typeof e.isDispatch === \"boolean\" ? e.isDispatch : id === \"dispatch\",\n audience:\n e.audience === undefined\n ? DEFAULT_WORKSPACE_APP_AUDIENCE\n : normalizeWorkspaceAppAudience(e.audience),\n publicPaths: normalizeWorkspaceAppPathList(e.publicPaths),\n protectedPaths: normalizeWorkspaceAppPathList(e.protectedPaths),\n };\n })\n .filter((app): app is WorkspaceAppManifestEntry => app !== null)\n .sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.name.localeCompare(b.name);\n });\n\n return apps.length ? apps : null;\n}\n\nfunction readWorkspaceAppsFromEnv(): WorkspaceAppManifestEntry[] | null {\n const raw = process.env[WORKSPACE_APPS_ENV_KEY];\n if (!raw) return null;\n try {\n return parseWorkspaceAppsManifest(JSON.parse(raw));\n } catch {\n return null;\n }\n}\n\nfunction workspaceAppsManifestCandidates(): string[] {\n const candidates: string[] = [];\n try {\n candidates.push(\n path.join(process.cwd(), \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(process.cwd(), WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes do not expose process.cwd().\n }\n try {\n const moduleDir = path.dirname(fileURLToPath(import.meta.url));\n candidates.push(\n path.join(moduleDir, \".agent-native\", WORKSPACE_APPS_MANIFEST_FILE),\n path.join(moduleDir, WORKSPACE_APPS_MANIFEST_FILE),\n );\n } catch {\n // Some edge runtimes expose non-file module URLs. The env manifest still\n // works there, so skip file-relative candidates.\n }\n return candidates;\n}\n\nfunction readWorkspaceAppsFromManifestFile():\n | WorkspaceAppManifestEntry[]\n | null {\n for (const file of workspaceAppsManifestCandidates()) {\n if (!fs.existsSync(file)) continue;\n const apps = parseWorkspaceAppsManifest(readJson(file));\n if (apps) return apps;\n }\n return null;\n}\n\nfunction readWorkspaceAppsFromFilesystem(): WorkspaceAppManifestEntry[] | null {\n const workspaceRoot = findWorkspaceRoot();\n if (!workspaceRoot) return null;\n const appsDir = path.join(workspaceRoot, \"apps\");\n if (!fs.existsSync(appsDir)) return null;\n\n const apps = fs\n .readdirSync(appsDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry): WorkspaceAppManifestEntry | null => {\n const appDir = path.join(appsDir, entry.name);\n const pkg = readJson(path.join(appDir, \"package.json\"));\n if (!pkg) return null;\n const routeAccess = workspaceAppRouteAccessFromPackageJson(pkg);\n return {\n id: entry.name,\n name: pkg.displayName || titleCase(entry.name),\n description: pkg.description || \"\",\n path: `/${entry.name}`,\n isDispatch: entry.name === \"dispatch\",\n audience:\n workspaceAppAudienceFromPackageJson(pkg) ??\n DEFAULT_WORKSPACE_APP_AUDIENCE,\n publicPaths: routeAccess.publicPaths ?? [],\n protectedPaths: routeAccess.protectedPaths ?? [],\n } satisfies WorkspaceAppManifestEntry;\n })\n .filter((app): app is WorkspaceAppManifestEntry => !!app)\n .sort((a, b) => {\n if (a.id === \"dispatch\") return -1;\n if (b.id === \"dispatch\") return 1;\n return a.name.localeCompare(b.name);\n });\n\n return apps.length ? apps : null;\n}\n\nfunction workspaceBaseUrl(): string | null {\n return (\n process.env.WORKSPACE_GATEWAY_URL ||\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL ||\n null\n );\n}\n\nfunction workspaceAppUrl(\n app: WorkspaceAppManifestEntry,\n hostedLoopbackFallbackUrl?: string,\n): string | null {\n if (app.url) {\n if (!isHostedRuntime() || !isLoopbackUrl(app.url)) return app.url;\n if (hostedLoopbackFallbackUrl) return hostedLoopbackFallbackUrl;\n }\n const base = workspaceBaseUrl();\n if (!base) return null;\n try {\n return new URL(app.path, `${base.replace(/\\/$/, \"\")}/`).toString();\n } catch {\n return null;\n }\n}\n\nasync function discoverWorkspaceAgents(\n selfAppId?: string,\n): Promise<DiscoveredAgent[]> {\n const workspaceApps = loadWorkspaceAppsManifest();\n if (!workspaceApps) return [];\n\n const metadataSettings = await readWorkspaceAppMetadataSettings();\n\n return workspaceApps\n .filter((app) => app.id !== selfAppId)\n .map((app) => {\n const withOverride = applyWorkspaceAppMetadataOverride(\n app,\n metadataSettings,\n );\n const builtin = BUILTIN_AGENTS.find(\n (agent) => agent.id === withOverride.id,\n );\n const url = workspaceAppUrl(withOverride, builtin?.url);\n if (!url) return null;\n return {\n id: withOverride.id,\n name: withOverride.name,\n description:\n withOverride.description ||\n builtin?.description ||\n `Workspace app mounted at ${withOverride.path}`,\n url,\n color: builtin?.color || \"#6B7280\",\n } satisfies DiscoveredAgent;\n })\n .filter((agent): agent is DiscoveredAgent => !!agent);\n}\n\n/** Resolve only the Dispatch app designated by the receiver's own manifest. */\nexport function findWorkspaceDispatchAgent(): DiscoveredAgent | undefined {\n const app = loadWorkspaceAppsManifest()?.find(\n (candidate) => candidate.isDispatch === true,\n );\n if (!app) return undefined;\n\n const builtin = BUILTIN_AGENTS.find((agent) => agent.id === \"dispatch\");\n const url = workspaceAppUrl(app, builtin?.url);\n if (!url) return undefined;\n return {\n id: app.id,\n name: app.name,\n description:\n app.description ||\n builtin?.description ||\n `Workspace app mounted at ${app.path}`,\n url,\n color: builtin?.color || \"#6B7280\",\n };\n}\n\n/**\n * Like `getBuiltinAgents`, but always returns the production URL — never the\n * env-resolved devUrl. Used by the resource seeder so that a one-time seed\n * (`ON CONFLICT DO NOTHING`) can't permanently bake a localhost URL into the\n * DB, which would override the built-in's prod URL for every later\n * production deploy.\n */\nexport const BUILTIN_AGENTS_FOR_SEEDING: DiscoveredAgent[] =\n BUILTIN_AGENTS.filter((app) => app.url).map((app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: app.url, // ALWAYS prod\n color: app.color,\n }));\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-run-context.d.ts","sourceRoot":"","sources":["../../src/server/agent-run-context.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0B,KAAK,OAAO,EAAE,MAAM,IAAI,CAAC;AAI1D,OAAO,EAEL,KAAK,cAAc,EACpB,MAAM,sBAAsB,CAAC;AAE9B,MAAM,MAAM,oBAAoB,GAAG;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,OAAO,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,eAAO,MAAM,2BAA2B,8BAA8B,CAAC;AAMvE,KAAK,sBAAsB,GAAG,CAC5B,KAAK,EAAE,OAAO,KACX,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;AAE5C,KAAK,aAAa,GAAG,CACnB,KAAK,EAAE,OAAO,KACX,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;AAoCpE,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAQvE;AAED,wBAAgB,wBAAwB,CACtC,KAAK,EAAE,OAAO,EACd,YAAY,EAAE,oBAAoB,GACjC,oBAAoB,CAItB;AAED,wBAAsB,kCAAkC,CACtD,KAAK,EAAE,OAAO,EACd,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAA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AAE,oBAAoB,CAAC;IACnC,YAAY,CAAC,EAAE,aAAa,CAAC;IAC7B,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B,EACD,EAAE,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GACvB,OAAO,CAAC,CAAC,CAAC,CAGZ"}
@@ -7,6 +7,10 @@ function eventContext(event) {
7
7
  event.context = event.context ?? {};
8
8
  return event.context;
9
9
  }
10
+ function requestWaitUntil(event) {
11
+ const waitUntil = event.req?.waitUntil;
12
+ return typeof waitUntil === "function" ? waitUntil : undefined;
13
+ }
10
14
  function normalizeId(value) {
11
15
  return typeof value === "string" && value.trim().length > 0
12
16
  ? value.trim()
@@ -120,14 +124,17 @@ export async function resolveAgentRunOrgId(options) {
120
124
  export async function resolveAgentRunRequestContext(options) {
121
125
  const orgId = await resolveAgentRunOrgId(options);
122
126
  const timezone = readAgentRunTimezone(options.event);
127
+ const waitUntil = requestWaitUntil(options.event);
128
+ const run = {
129
+ ...(options.isBackgroundWorker ? { isBackgroundWorker: true } : {}),
130
+ ...(waitUntil ? { waitUntil } : {}),
131
+ };
123
132
  return {
124
133
  userEmail: options.ownerContext.owner,
125
134
  userName: options.ownerContext.name,
126
135
  orgId,
127
136
  timezone,
128
- ...(options.isBackgroundWorker
129
- ? { run: { isBackgroundWorker: true } }
130
- : {}),
137
+ ...(Object.keys(run).length > 0 ? { run } : {}),
131
138
  };
132
139
  }
133
140
  export async function runWithAgentRunContext(options, fn) {