@agent-native/core 0.121.2 → 0.122.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (588) hide show
  1. package/README.md +4 -12
  2. package/corpus/README.md +2 -2
  3. package/corpus/core/CHANGELOG.md +148 -0
  4. package/corpus/core/docs/content/actions.mdx +2 -2
  5. package/corpus/core/docs/content/agent-surfaces.mdx +1 -1
  6. package/corpus/core/docs/content/authentication.mdx +2 -0
  7. package/corpus/core/docs/content/deployment.mdx +36 -0
  8. package/corpus/core/docs/content/http-api.mdx +266 -0
  9. package/corpus/core/docs/content/syncing-template-changes.mdx +159 -0
  10. package/corpus/core/package.json +2 -1
  11. package/corpus/core/src/a2a/activity.ts +38 -27
  12. package/corpus/core/src/a2a/client.ts +57 -4
  13. package/corpus/core/src/agent/engine/builder-engine.ts +35 -4
  14. package/corpus/core/src/agent/run-manager.ts +20 -1
  15. package/corpus/core/src/agent/run-store.ts +4 -1
  16. package/corpus/core/src/agent/types.ts +28 -8
  17. package/corpus/core/src/chat-threads/store.ts +45 -0
  18. package/corpus/core/src/checkpoints/index.ts +2 -0
  19. package/corpus/core/src/checkpoints/route-match.ts +13 -0
  20. package/corpus/core/src/cli/create.ts +105 -17
  21. package/corpus/core/src/cli/index.ts +20 -0
  22. package/corpus/core/src/cli/template-baseline.ts +410 -0
  23. package/corpus/core/src/cli/template-sync.ts +1004 -0
  24. package/corpus/core/src/cli/templates-meta.ts +1 -0
  25. package/corpus/core/src/client/AssistantChat.tsx +38 -12
  26. package/corpus/core/src/client/NewWorkspaceAppFlow.tsx +75 -10
  27. package/corpus/core/src/client/chat/message-components.tsx +127 -66
  28. package/corpus/core/src/client/chat/tool-call-display.tsx +29 -5
  29. package/corpus/core/src/client/error-format.ts +18 -0
  30. package/corpus/core/src/client/org/OrgSwitcher.tsx +30 -8
  31. package/corpus/core/src/client/org/TeamPage.tsx +7 -6
  32. package/corpus/core/src/client/settings/SettingsPanel.tsx +9 -9
  33. package/corpus/core/src/client/settings/SettingsTabsPage.tsx +12 -2
  34. package/corpus/core/src/client/sse-event-processor.ts +3 -0
  35. package/corpus/core/src/data-widgets/index.ts +41 -0
  36. package/corpus/core/src/deploy/build.ts +11 -9
  37. package/corpus/core/src/extensions/url-safety.ts +67 -4
  38. package/corpus/core/src/integrations/webhook-handler.ts +63 -9
  39. package/corpus/core/src/org/auto-join-domain.ts +4 -3
  40. package/corpus/core/src/org/context.ts +108 -39
  41. package/corpus/core/src/org/index.ts +5 -0
  42. package/corpus/core/src/org/service-identity.ts +60 -0
  43. package/corpus/core/src/provider-api/index.ts +22 -1
  44. package/corpus/core/src/scripts/docs/search.ts +12 -1
  45. package/corpus/core/src/server/agent-chat/context-tools.ts +9 -4
  46. package/corpus/core/src/server/agent-chat/framework-prompts.ts +38 -66
  47. package/corpus/core/src/server/agent-chat-plugin.ts +17 -10
  48. package/corpus/core/src/server/agents-bundle.ts +84 -5
  49. package/corpus/core/src/server/auth.ts +4 -3
  50. package/corpus/core/src/server/builder-browser.ts +47 -19
  51. package/corpus/core/src/server/core-routes-plugin.ts +2 -2
  52. package/corpus/core/src/server/credential-provider.ts +209 -68
  53. package/corpus/core/src/server/index.ts +3 -0
  54. package/corpus/core/src/server/prompts/framework-core-compact.ts +6 -13
  55. package/corpus/core/src/server/prompts/framework-core.ts +9 -21
  56. package/corpus/core/src/server/prompts/index.ts +0 -1
  57. package/corpus/core/src/server/prompts/shared-rules.ts +19 -11
  58. package/corpus/core/src/server/ssr-handler.ts +13 -2
  59. package/corpus/core/src/settings/user-settings.ts +13 -1
  60. package/corpus/core/src/shared/cache-control.ts +141 -0
  61. package/corpus/core/src/templates/chat/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  62. package/corpus/core/src/templates/chat/_gitignore +1 -0
  63. package/corpus/core/src/templates/chat/app/components/layout/Sidebar.tsx +0 -7
  64. package/corpus/core/src/templates/default/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  65. package/corpus/core/src/templates/default/app/root.tsx +1 -1
  66. package/corpus/core/src/templates/default/public/manifest.json +2 -2
  67. package/corpus/core/src/templates/headless/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  68. package/corpus/core/src/templates/workspace-core/.agents/skills/performance/SKILL.md +19 -0
  69. package/corpus/core/src/templates/workspace-core/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  70. package/corpus/core/src/templates/workspace-core/.agents/skills/visual-answer/SKILL.md +1 -0
  71. package/corpus/core/src/vite/agents-bundle-plugin.ts +7 -6
  72. package/corpus/core/src/vite/client.ts +69 -3
  73. package/corpus/templates/analytics/.agents/skills/adhoc-analysis/SKILL.md +4 -5
  74. package/corpus/templates/analytics/.agents/skills/admin-surfaces/SKILL.md +55 -0
  75. package/corpus/templates/analytics/.agents/skills/dashboard-management/SKILL.md +10 -0
  76. package/corpus/templates/analytics/.agents/skills/dashboard-management/references/template-catalog-and-demo.md +62 -0
  77. package/corpus/templates/analytics/.agents/skills/dashboard-ops/SKILL.md +85 -0
  78. package/corpus/templates/analytics/.agents/skills/data-querying/SKILL.md +27 -2
  79. package/corpus/templates/analytics/.agents/skills/data-querying/references/inline-chart-embeds.md +139 -0
  80. package/corpus/templates/analytics/.agents/skills/monitoring/SKILL.md +77 -0
  81. package/corpus/templates/analytics/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  82. package/corpus/templates/analytics/AGENTS.md +91 -563
  83. package/corpus/templates/analytics/_gitignore +1 -0
  84. package/corpus/templates/analytics/actions/bigquery.ts +12 -4
  85. package/corpus/templates/analytics/actions/generate-chart.ts +5 -5
  86. package/corpus/templates/analytics/app/components/dashboard/SqlChart.tsx +30 -1
  87. package/corpus/templates/analytics/app/components/layout/Sidebar.tsx +1 -23
  88. package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/DashboardFilterBar.tsx +3 -0
  89. package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/SqlChartCard.tsx +1 -1
  90. package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/index.tsx +1 -0
  91. package/corpus/templates/analytics/app/routes/_index.tsx +1 -1
  92. package/corpus/templates/analytics/changelog/2026-07-24-analytics-finds-saved-dashboards-and-queries-far-more-reliab.md +6 -0
  93. package/corpus/templates/analytics/changelog/2026-07-24-notion-access-errors-now-explain-that-a-page-needs-sharing-w.md +6 -0
  94. package/corpus/templates/analytics/changelog/2026-07-25-app-branding-now-uses-the-product-name-without-the-agent-nat.md +6 -0
  95. package/corpus/templates/analytics/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  96. package/corpus/templates/analytics/package.json +1 -1
  97. package/corpus/templates/analytics/public/manifest.json +1 -1
  98. package/corpus/templates/analytics/server/lib/agent-chat-plan-mode.ts +7 -0
  99. package/corpus/templates/analytics/server/lib/analytics-query-catalog.ts +191 -30
  100. package/corpus/templates/analytics/server/lib/bigquery.ts +11 -1
  101. package/corpus/templates/analytics/server/lib/notion.ts +15 -4
  102. package/corpus/templates/analytics/server/plugins/agent-chat.ts +10 -0
  103. package/corpus/templates/analytics/server/plugins/auth.ts +1 -1
  104. package/corpus/templates/assets/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  105. package/corpus/templates/assets/app/components/layout/Sidebar.tsx +0 -2
  106. package/corpus/templates/assets/app/routes/_index.tsx +1 -1
  107. package/corpus/templates/assets/changelog/2026-07-25-app-branding-now-uses-the-product-name-without-the-agent-nat.md +6 -0
  108. package/corpus/templates/assets/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  109. package/corpus/templates/assets/server/plugins/auth.ts +1 -1
  110. package/corpus/templates/brain/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  111. package/corpus/templates/brain/_gitignore +1 -0
  112. package/corpus/templates/brain/app/lib/brain.ts +0 -7
  113. package/corpus/templates/brain/app/routes/_index.tsx +1 -2
  114. package/corpus/templates/brain/changelog/2026-07-25-app-branding-now-uses-the-product-name-without-the-agent-nat.md +6 -0
  115. package/corpus/templates/brain/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  116. package/corpus/templates/brain/package.json +1 -1
  117. package/corpus/templates/brain/public/manifest.json +1 -1
  118. package/corpus/templates/brain/server/plugins/auth.ts +1 -1
  119. package/corpus/templates/calendar/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  120. package/corpus/templates/calendar/_gitignore +1 -0
  121. package/corpus/templates/calendar/app/components/layout/Sidebar.tsx +0 -6
  122. package/corpus/templates/calendar/app/routes/_app._index.tsx +1 -1
  123. package/corpus/templates/calendar/changelog/2026-07-25-app-branding-now-uses-the-product-name-without-the-agent-nat.md +6 -0
  124. package/corpus/templates/calendar/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  125. package/corpus/templates/calendar/package.json +1 -1
  126. package/corpus/templates/calendar/public/manifest.json +1 -1
  127. package/corpus/templates/calendar/server/plugins/auth.ts +1 -1
  128. package/corpus/templates/chat/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  129. package/corpus/templates/chat/_gitignore +1 -0
  130. package/corpus/templates/chat/app/components/layout/Sidebar.tsx +0 -7
  131. package/corpus/templates/chat/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  132. package/corpus/templates/clips/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  133. package/corpus/templates/clips/.agents/skills/video-sharing/SKILL.md +34 -0
  134. package/corpus/templates/clips/AGENTS.md +5 -4
  135. package/corpus/templates/clips/_gitignore +1 -0
  136. package/corpus/templates/clips/actions/cleanup-transcript.ts +5 -0
  137. package/corpus/templates/clips/actions/get-recording-insights.ts +44 -8
  138. package/corpus/templates/clips/actions/get-recording-player-data.ts +39 -70
  139. package/corpus/templates/clips/actions/import-loom-recording.ts +53 -98
  140. package/corpus/templates/clips/actions/lib/loom-import-job.ts +260 -0
  141. package/corpus/templates/clips/actions/list-clip-views.ts +2 -4
  142. package/corpus/templates/clips/actions/list-recordings.ts +69 -19
  143. package/corpus/templates/clips/actions/list-viewers.ts +5 -2
  144. package/corpus/templates/clips/actions/regenerate-summary.ts +5 -1
  145. package/corpus/templates/clips/actions/request-transcript.ts +28 -1
  146. package/corpus/templates/clips/app/components/editor/stitch-manager.tsx +21 -1
  147. package/corpus/templates/clips/app/components/library/library-layout.tsx +0 -7
  148. package/corpus/templates/clips/app/components/meetings/quick-ask-sidebar.tsx +14 -1
  149. package/corpus/templates/clips/app/components/player/insights-panel.tsx +8 -20
  150. package/corpus/templates/clips/app/components/player/recording-views-badge.tsx +335 -0
  151. package/corpus/templates/clips/app/components/player/video-player.tsx +13 -8
  152. package/corpus/templates/clips/app/components/sharing/share-ui.tsx +2 -1
  153. package/corpus/templates/clips/app/i18n/en-US.ts +13 -2
  154. package/corpus/templates/clips/app/lib/capture-permissions.ts +110 -0
  155. package/corpus/templates/clips/app/lib/recording-link.ts +32 -0
  156. package/corpus/templates/clips/app/routes/_app.library._index.tsx +1 -1
  157. package/corpus/templates/clips/app/routes/_app.meetings.$meetingId.tsx +27 -0
  158. package/corpus/templates/clips/app/routes/_index.tsx +1 -1
  159. package/corpus/templates/clips/app/routes/r.$recordingId.tsx +52 -15
  160. package/corpus/templates/clips/app/routes/record.tsx +82 -31
  161. package/corpus/templates/clips/app/routes/share.$shareId.tsx +42 -31
  162. package/corpus/templates/clips/changelog/2026-07-24-clip-pages-now-show-a-view-count-with-viewer-avatars-next-to.md +6 -0
  163. package/corpus/templates/clips/changelog/2026-07-24-clip-summaries-read-like-a-description-you-d-write-yourself-.md +6 -0
  164. package/corpus/templates/clips/changelog/2026-07-24-clip-view-counts-now-separate-human-views-from-agent-views-s.md +6 -0
  165. package/corpus/templates/clips/changelog/2026-07-24-clips-actions-can-now-be-called-by-org-service-tokens-so-ext.md +6 -0
  166. package/corpus/templates/clips/changelog/2026-07-24-clips-no-longer-briefly-shows-a-dock-icon-while-launching.md +6 -0
  167. package/corpus/templates/clips/changelog/2026-07-24-fixed-owner-and-editor-share-links-redirecting-to-the-record.md +6 -0
  168. package/corpus/templates/clips/changelog/2026-07-24-meeting-and-note-recordings-now-start-as-a-compact-pill-on-t.md +6 -0
  169. package/corpus/templates/clips/changelog/2026-07-24-new-clips-now-copy-a-shareable-link-instead-of-the-owner-onl.md +6 -0
  170. package/corpus/templates/clips/changelog/2026-07-24-opening-a-share-link-as-the-clip-s-owner-now-goes-straight-t.md +6 -0
  171. package/corpus/templates/clips/changelog/2026-07-24-permissions-and-rewind-controls-now-use-compact-consistent-h.md +6 -0
  172. package/corpus/templates/clips/changelog/2026-07-24-quitting-the-desktop-app-no-longer-shows-a-false-macos-crash.md +6 -0
  173. package/corpus/templates/clips/changelog/2026-07-24-screen-recording-permission-errors-now-name-the-exact-app-to.md +6 -0
  174. package/corpus/templates/clips/changelog/2026-07-24-the-desktop-app-now-copies-a-new-clip-s-share-link-to-your-c.md +6 -0
  175. package/corpus/templates/clips/changelog/2026-07-24-the-recording-toolbar-now-stays-above-other-apps-including-o.md +6 -0
  176. package/corpus/templates/clips/changelog/2026-07-24-transcript-captions-now-use-real-speech-timings-instead-of-a.md +6 -0
  177. package/corpus/templates/clips/changelog/2026-07-24-video-playback-no-longer-stutters-and-replays-the-last-momen.md +6 -0
  178. package/corpus/templates/clips/changelog/2026-07-25-app-branding-now-uses-the-product-name-without-the-agent-nat.md +6 -0
  179. package/corpus/templates/clips/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  180. package/corpus/templates/clips/chrome-extension/src/background.ts +17 -1
  181. package/corpus/templates/clips/desktop/package.json +2 -0
  182. package/corpus/templates/clips/desktop/src/app.tsx +89 -0
  183. package/corpus/templates/clips/desktop/src/hooks/useMeetingTranscription.ts +9 -3
  184. package/corpus/templates/clips/desktop/src/lib/audio-meter.ts +51 -0
  185. package/corpus/templates/clips/desktop/src/lib/native-notification.ts +44 -0
  186. package/corpus/templates/clips/desktop/src/lib/recording-link.ts +67 -0
  187. package/corpus/templates/clips/desktop/src/overlays/live-audio-bars.tsx +35 -35
  188. package/corpus/templates/clips/desktop/src/overlays/live-transcript.tsx +3 -2
  189. package/corpus/templates/clips/desktop/src/overlays/recording-pill.tsx +47 -46
  190. package/corpus/templates/clips/desktop/src/styles.css +127 -78
  191. package/corpus/templates/clips/desktop/src-tauri/Cargo.toml +7 -0
  192. package/corpus/templates/clips/desktop/src-tauri/Info.plist +6 -0
  193. package/corpus/templates/clips/desktop/src-tauri/capabilities/default.json +1 -0
  194. package/corpus/templates/clips/desktop/src-tauri/src/clips/mod.rs +7 -3
  195. package/corpus/templates/clips/desktop/src-tauri/src/lib.rs +4 -1
  196. package/corpus/templates/clips/desktop/src-tauri/src/main.rs +8 -0
  197. package/corpus/templates/clips/desktop/src-tauri/src/recording_indicator.rs +21 -10
  198. package/corpus/templates/clips/desktop/src-tauri/src/util.rs +40 -0
  199. package/corpus/templates/clips/server/db/schema.ts +27 -0
  200. package/corpus/templates/clips/server/lib/agent-views.ts +145 -0
  201. package/corpus/templates/clips/server/lib/post-finalize-dispatch.ts +2 -1
  202. package/corpus/templates/clips/server/lib/public-agent-context.ts +7 -0
  203. package/corpus/templates/clips/server/lib/recording-share-grant.ts +79 -0
  204. package/corpus/templates/clips/server/lib/recordings.ts +51 -3
  205. package/corpus/templates/clips/server/plugins/auth.ts +1 -1
  206. package/corpus/templates/clips/server/plugins/db.ts +31 -0
  207. package/corpus/templates/clips/server/routes/api/_agent-native-background/post-finalize-worker.post.ts +56 -3
  208. package/corpus/templates/clips/server/routes/api/public-recording.get.ts +49 -17
  209. package/corpus/templates/clips/shared/recording-link.ts +43 -0
  210. package/corpus/templates/clips/shared/share-attribution.ts +4 -0
  211. package/corpus/templates/clips/shared/share-dashboard-redirect.ts +42 -0
  212. package/corpus/templates/clips/shared/view-analytics.ts +26 -0
  213. package/corpus/templates/content/.agents/skills/content/SKILL.md +5 -0
  214. package/corpus/templates/content/.agents/skills/content/references/local-file-mode.md +135 -0
  215. package/corpus/templates/content/.agents/skills/document-editing/SKILL.md +12 -0
  216. package/corpus/templates/content/.agents/skills/document-editing/references/databases.md +238 -0
  217. package/corpus/templates/content/.agents/skills/document-editing/references/document-behavior.md +91 -0
  218. package/corpus/templates/content/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  219. package/corpus/templates/content/AGENTS.md +62 -583
  220. package/corpus/templates/content/_gitignore +1 -0
  221. package/corpus/templates/content/app/components/sidebar/DocumentSidebar.tsx +1 -39
  222. package/corpus/templates/content/app/routes/_app._index.tsx +1 -2
  223. package/corpus/templates/content/changelog/2026-07-25-app-branding-now-uses-the-product-name-without-the-agent-nat.md +6 -0
  224. package/corpus/templates/content/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  225. package/corpus/templates/content/package.json +1 -1
  226. package/corpus/templates/content/public/manifest.json +1 -1
  227. package/corpus/templates/content/server/plugins/auth.ts +1 -1
  228. package/corpus/templates/design/.agents/skills/creative-context/SKILL.md +11 -0
  229. package/corpus/templates/design/.agents/skills/design-generation/SKILL.md +50 -8
  230. package/corpus/templates/design/.agents/skills/design-generation/references/code-layers.md +81 -0
  231. package/corpus/templates/design/.agents/skills/design-generation/references/code-workspace.md +42 -0
  232. package/corpus/templates/design/.agents/skills/design-generation/references/editor-extensions.md +34 -0
  233. package/corpus/templates/design/.agents/skills/responsive-breakpoints/SKILL.md +4 -1
  234. package/corpus/templates/design/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  235. package/corpus/templates/design/.agents/skills/visual-edit/SKILL.md +17 -0
  236. package/corpus/templates/design/.generated/bridge/editor-chrome.generated.ts +8196 -0
  237. package/corpus/templates/design/.generated/bridge/embedded-wheel.generated.ts +265 -0
  238. package/corpus/templates/design/.generated/bridge/hit-test.generated.ts +642 -0
  239. package/corpus/templates/design/.generated/bridge/motion-preview.generated.ts +571 -0
  240. package/corpus/templates/design/.generated/bridge/nav.generated.ts +91 -0
  241. package/corpus/templates/design/.generated/bridge/sample.generated.ts +23 -0
  242. package/corpus/templates/design/.generated/bridge/shader-fill-preview.generated.ts +263 -0
  243. package/corpus/templates/design/.generated/bridge/shader-runtime.generated.ts +518 -0
  244. package/corpus/templates/design/.generated/bridge/tweak.generated.ts +20 -0
  245. package/corpus/templates/design/.generated/bridge/zoom.generated.ts +32 -0
  246. package/corpus/templates/design/AGENTS.md +88 -503
  247. package/corpus/templates/design/_gitignore +1 -0
  248. package/corpus/templates/design/app/components/layout/Sidebar.tsx +0 -2
  249. package/corpus/templates/design/app/routes/_index.tsx +1 -1
  250. package/corpus/templates/design/changelog/2026-07-25-app-branding-now-uses-the-product-name-without-the-agent-nat.md +6 -0
  251. package/corpus/templates/design/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  252. package/corpus/templates/design/server/plugins/auth.ts +1 -1
  253. package/corpus/templates/dispatch/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  254. package/corpus/templates/dispatch/_gitignore +1 -0
  255. package/corpus/templates/dispatch/app/dispatch-extensions.tsx +1 -10
  256. package/corpus/templates/dispatch/app/routes/overview.tsx +1 -1
  257. package/corpus/templates/dispatch/changelog/2026-07-24-signing-in-now-puts-you-in-your-companys-workspace.md +6 -0
  258. package/corpus/templates/dispatch/changelog/2026-07-25-app-branding-now-uses-the-product-name-without-the-agent-nat.md +6 -0
  259. package/corpus/templates/dispatch/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  260. package/corpus/templates/dispatch/package.json +1 -1
  261. package/corpus/templates/dispatch/public/manifest.json +1 -1
  262. package/corpus/templates/forms/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  263. package/corpus/templates/forms/_gitignore +1 -0
  264. package/corpus/templates/forms/app/components/layout/Sidebar.tsx +0 -35
  265. package/corpus/templates/forms/changelog/2026-07-25-app-branding-now-uses-the-product-name-without-the-agent-nat.md +6 -0
  266. package/corpus/templates/forms/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  267. package/corpus/templates/forms/package.json +1 -1
  268. package/corpus/templates/forms/public/manifest.json +1 -1
  269. package/corpus/templates/forms/server/lib/public-form-ssr.ts +2 -2
  270. package/corpus/templates/forms/server/plugins/auth.ts +1 -1
  271. package/corpus/templates/macros/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  272. package/corpus/templates/macros/_gitignore +1 -0
  273. package/corpus/templates/macros/app/components/layout/AppLayout.tsx +0 -2
  274. package/corpus/templates/macros/changelog/2026-07-25-app-branding-now-uses-the-product-name-without-the-agent-nat.md +6 -0
  275. package/corpus/templates/macros/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  276. package/corpus/templates/macros/package.json +1 -1
  277. package/corpus/templates/macros/server/plugins/auth.ts +2 -2
  278. package/corpus/templates/mail/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  279. package/corpus/templates/mail/_gitignore +1 -0
  280. package/corpus/templates/mail/app/components/layout/AppLayout.tsx +0 -39
  281. package/corpus/templates/mail/app/routes/$view.$threadId.tsx +1 -1
  282. package/corpus/templates/mail/app/routes/$view.tsx +1 -1
  283. package/corpus/templates/mail/app/routes/_index.tsx +1 -1
  284. package/corpus/templates/mail/changelog/2026-07-25-app-branding-now-uses-the-product-name-without-the-agent-nat.md +6 -0
  285. package/corpus/templates/mail/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  286. package/corpus/templates/mail/package.json +1 -1
  287. package/corpus/templates/mail/public/manifest.json +1 -1
  288. package/corpus/templates/mail/server/plugins/auth.ts +1 -1
  289. package/corpus/templates/plan/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  290. package/corpus/templates/plan/_gitignore +1 -0
  291. package/corpus/templates/plan/agent-native.app-skill.json +1 -1
  292. package/corpus/templates/plan/app/components/layout/Sidebar.tsx +4 -9
  293. package/corpus/templates/plan/app/lib/app-config.ts +1 -1
  294. package/corpus/templates/plan/changelog/2026-07-25-app-branding-now-uses-the-product-name-without-the-agent-nat.md +6 -0
  295. package/corpus/templates/plan/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  296. package/corpus/templates/plan/package.json +1 -1
  297. package/corpus/templates/plan/public/manifest.json +1 -1
  298. package/corpus/templates/plan/server/plugins/auth.ts +1 -1
  299. package/corpus/templates/slides/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  300. package/corpus/templates/slides/_gitignore +1 -0
  301. package/corpus/templates/slides/app/components/layout/Sidebar.tsx +0 -2
  302. package/corpus/templates/slides/app/routes/_index.tsx +1 -1
  303. package/corpus/templates/slides/changelog/2026-07-25-app-branding-now-uses-the-product-name-without-the-agent-nat.md +6 -0
  304. package/corpus/templates/slides/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  305. package/corpus/templates/slides/package.json +1 -1
  306. package/corpus/templates/slides/public/manifest.json +1 -1
  307. package/corpus/templates/slides/server/plugins/auth.ts +1 -1
  308. package/corpus/templates/slides/server/plugins/db.ts +4 -0
  309. package/corpus/templates/tasks/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  310. package/corpus/templates/tasks/AGENTS.md +1 -1
  311. package/corpus/templates/tasks/_gitignore +1 -0
  312. package/dist/a2a/activity.d.ts +4 -1
  313. package/dist/a2a/activity.d.ts.map +1 -1
  314. package/dist/a2a/activity.js +27 -16
  315. package/dist/a2a/activity.js.map +1 -1
  316. package/dist/a2a/client.d.ts.map +1 -1
  317. package/dist/a2a/client.js +58 -4
  318. package/dist/a2a/client.js.map +1 -1
  319. package/dist/agent/engine/builder-engine.d.ts +1 -0
  320. package/dist/agent/engine/builder-engine.d.ts.map +1 -1
  321. package/dist/agent/engine/builder-engine.js +31 -4
  322. package/dist/agent/engine/builder-engine.js.map +1 -1
  323. package/dist/agent/run-manager.d.ts.map +1 -1
  324. package/dist/agent/run-manager.js +18 -1
  325. package/dist/agent/run-manager.js.map +1 -1
  326. package/dist/agent/run-store.d.ts +1 -0
  327. package/dist/agent/run-store.d.ts.map +1 -1
  328. package/dist/agent/run-store.js +2 -1
  329. package/dist/agent/run-store.js.map +1 -1
  330. package/dist/agent/types.d.ts +12 -1
  331. package/dist/agent/types.d.ts.map +1 -1
  332. package/dist/agent/types.js +21 -1
  333. package/dist/agent/types.js.map +1 -1
  334. package/dist/chat-threads/store.d.ts +10 -0
  335. package/dist/chat-threads/store.d.ts.map +1 -1
  336. package/dist/chat-threads/store.js +41 -0
  337. package/dist/chat-threads/store.js.map +1 -1
  338. package/dist/checkpoints/index.d.ts +1 -0
  339. package/dist/checkpoints/index.d.ts.map +1 -1
  340. package/dist/checkpoints/index.js +1 -0
  341. package/dist/checkpoints/index.js.map +1 -1
  342. package/dist/checkpoints/route-match.d.ts +8 -0
  343. package/dist/checkpoints/route-match.d.ts.map +1 -0
  344. package/dist/checkpoints/route-match.js +13 -0
  345. package/dist/checkpoints/route-match.js.map +1 -0
  346. package/dist/cli/create.d.ts +35 -4
  347. package/dist/cli/create.d.ts.map +1 -1
  348. package/dist/cli/create.js +69 -19
  349. package/dist/cli/create.js.map +1 -1
  350. package/dist/cli/index.js +19 -0
  351. package/dist/cli/index.js.map +1 -1
  352. package/dist/cli/template-baseline.d.ts +54 -0
  353. package/dist/cli/template-baseline.d.ts.map +1 -0
  354. package/dist/cli/template-baseline.js +334 -0
  355. package/dist/cli/template-baseline.js.map +1 -0
  356. package/dist/cli/template-sync.d.ts +57 -0
  357. package/dist/cli/template-sync.d.ts.map +1 -0
  358. package/dist/cli/template-sync.js +787 -0
  359. package/dist/cli/template-sync.js.map +1 -0
  360. package/dist/cli/templates-meta.d.ts.map +1 -1
  361. package/dist/cli/templates-meta.js +1 -0
  362. package/dist/cli/templates-meta.js.map +1 -1
  363. package/dist/client/AssistantChat.d.ts +2 -1
  364. package/dist/client/AssistantChat.d.ts.map +1 -1
  365. package/dist/client/AssistantChat.js +38 -10
  366. package/dist/client/AssistantChat.js.map +1 -1
  367. package/dist/client/NewWorkspaceAppFlow.d.ts.map +1 -1
  368. package/dist/client/NewWorkspaceAppFlow.js +32 -2
  369. package/dist/client/NewWorkspaceAppFlow.js.map +1 -1
  370. package/dist/client/chat/message-components.d.ts +20 -0
  371. package/dist/client/chat/message-components.d.ts.map +1 -1
  372. package/dist/client/chat/message-components.js +81 -46
  373. package/dist/client/chat/message-components.js.map +1 -1
  374. package/dist/client/chat/tool-call-display.d.ts.map +1 -1
  375. package/dist/client/chat/tool-call-display.js +14 -6
  376. package/dist/client/chat/tool-call-display.js.map +1 -1
  377. package/dist/client/error-format.d.ts.map +1 -1
  378. package/dist/client/error-format.js +13 -0
  379. package/dist/client/error-format.js.map +1 -1
  380. package/dist/client/org/OrgSwitcher.d.ts +8 -1
  381. package/dist/client/org/OrgSwitcher.d.ts.map +1 -1
  382. package/dist/client/org/OrgSwitcher.js +3 -2
  383. package/dist/client/org/OrgSwitcher.js.map +1 -1
  384. package/dist/client/org/TeamPage.d.ts.map +1 -1
  385. package/dist/client/org/TeamPage.js +1 -1
  386. package/dist/client/org/TeamPage.js.map +1 -1
  387. package/dist/client/settings/SettingsPanel.js +9 -9
  388. package/dist/client/settings/SettingsPanel.js.map +1 -1
  389. package/dist/client/settings/SettingsTabsPage.d.ts.map +1 -1
  390. package/dist/client/settings/SettingsTabsPage.js +7 -4
  391. package/dist/client/settings/SettingsTabsPage.js.map +1 -1
  392. package/dist/client/sse-event-processor.d.ts.map +1 -1
  393. package/dist/client/sse-event-processor.js +3 -0
  394. package/dist/client/sse-event-processor.js.map +1 -1
  395. package/dist/collab/awareness.d.ts +2 -2
  396. package/dist/collab/awareness.d.ts.map +1 -1
  397. package/dist/collab/struct-routes.d.ts +1 -1
  398. package/dist/data-widgets/index.d.ts +3 -0
  399. package/dist/data-widgets/index.d.ts.map +1 -1
  400. package/dist/data-widgets/index.js +33 -0
  401. package/dist/data-widgets/index.js.map +1 -1
  402. package/dist/deploy/build.d.ts.map +1 -1
  403. package/dist/deploy/build.js +11 -7
  404. package/dist/deploy/build.js.map +1 -1
  405. package/dist/eject/provider-api-definitions.d.ts +1 -0
  406. package/dist/eject/provider-api-definitions.d.ts.map +1 -1
  407. package/dist/extensions/url-safety.d.ts +9 -16
  408. package/dist/extensions/url-safety.d.ts.map +1 -1
  409. package/dist/extensions/url-safety.js +48 -4
  410. package/dist/extensions/url-safety.js.map +1 -1
  411. package/dist/file-upload/actions/upload-image.d.ts +1 -1
  412. package/dist/integrations/webhook-handler.d.ts.map +1 -1
  413. package/dist/integrations/webhook-handler.js +46 -9
  414. package/dist/integrations/webhook-handler.js.map +1 -1
  415. package/dist/notifications/routes.d.ts +2 -2
  416. package/dist/observability/routes.d.ts +3 -3
  417. package/dist/org/auto-join-domain.d.ts +3 -2
  418. package/dist/org/auto-join-domain.d.ts.map +1 -1
  419. package/dist/org/auto-join-domain.js +1 -1
  420. package/dist/org/auto-join-domain.js.map +1 -1
  421. package/dist/org/context.d.ts.map +1 -1
  422. package/dist/org/context.js +84 -28
  423. package/dist/org/context.js.map +1 -1
  424. package/dist/org/index.d.ts +1 -0
  425. package/dist/org/index.d.ts.map +1 -1
  426. package/dist/org/index.js +1 -0
  427. package/dist/org/index.js.map +1 -1
  428. package/dist/org/service-identity.d.ts +43 -0
  429. package/dist/org/service-identity.d.ts.map +1 -0
  430. package/dist/org/service-identity.js +34 -0
  431. package/dist/org/service-identity.js.map +1 -0
  432. package/dist/provider-api/actions/custom-provider-registration.d.ts +14 -14
  433. package/dist/provider-api/actions/provider-api.d.ts +13 -11
  434. package/dist/provider-api/actions/provider-api.d.ts.map +1 -1
  435. package/dist/provider-api/index.d.ts +4 -0
  436. package/dist/provider-api/index.d.ts.map +1 -1
  437. package/dist/provider-api/index.js +17 -1
  438. package/dist/provider-api/index.js.map +1 -1
  439. package/dist/scripts/docs/search.d.ts.map +1 -1
  440. package/dist/scripts/docs/search.js +12 -1
  441. package/dist/scripts/docs/search.js.map +1 -1
  442. package/dist/server/agent-chat/context-tools.d.ts.map +1 -1
  443. package/dist/server/agent-chat/context-tools.js +3 -3
  444. package/dist/server/agent-chat/context-tools.js.map +1 -1
  445. package/dist/server/agent-chat/framework-prompts.d.ts +8 -3
  446. package/dist/server/agent-chat/framework-prompts.d.ts.map +1 -1
  447. package/dist/server/agent-chat/framework-prompts.js +33 -62
  448. package/dist/server/agent-chat/framework-prompts.js.map +1 -1
  449. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  450. package/dist/server/agent-chat-plugin.js +16 -10
  451. package/dist/server/agent-chat-plugin.js.map +1 -1
  452. package/dist/server/agent-engine-api-key-route.d.ts +1 -1
  453. package/dist/server/agents-bundle.d.ts +18 -0
  454. package/dist/server/agents-bundle.d.ts.map +1 -1
  455. package/dist/server/agents-bundle.js +70 -4
  456. package/dist/server/agents-bundle.js.map +1 -1
  457. package/dist/server/auth.d.ts.map +1 -1
  458. package/dist/server/auth.js +4 -3
  459. package/dist/server/auth.js.map +1 -1
  460. package/dist/server/builder-browser.d.ts.map +1 -1
  461. package/dist/server/builder-browser.js +43 -19
  462. package/dist/server/builder-browser.js.map +1 -1
  463. package/dist/server/core-routes-plugin.js +2 -2
  464. package/dist/server/core-routes-plugin.js.map +1 -1
  465. package/dist/server/credential-provider.d.ts +38 -2
  466. package/dist/server/credential-provider.d.ts.map +1 -1
  467. package/dist/server/credential-provider.js +142 -64
  468. package/dist/server/credential-provider.js.map +1 -1
  469. package/dist/server/index.d.ts +1 -1
  470. package/dist/server/index.d.ts.map +1 -1
  471. package/dist/server/index.js +1 -1
  472. package/dist/server/index.js.map +1 -1
  473. package/dist/server/prompts/framework-core-compact.d.ts +1 -1
  474. package/dist/server/prompts/framework-core-compact.d.ts.map +1 -1
  475. package/dist/server/prompts/framework-core-compact.js +7 -13
  476. package/dist/server/prompts/framework-core-compact.js.map +1 -1
  477. package/dist/server/prompts/framework-core.d.ts +1 -1
  478. package/dist/server/prompts/framework-core.d.ts.map +1 -1
  479. package/dist/server/prompts/framework-core.js +10 -21
  480. package/dist/server/prompts/framework-core.js.map +1 -1
  481. package/dist/server/prompts/index.d.ts +1 -1
  482. package/dist/server/prompts/index.d.ts.map +1 -1
  483. package/dist/server/prompts/index.js +1 -1
  484. package/dist/server/prompts/index.js.map +1 -1
  485. package/dist/server/prompts/shared-rules.d.ts +16 -10
  486. package/dist/server/prompts/shared-rules.d.ts.map +1 -1
  487. package/dist/server/prompts/shared-rules.js +19 -10
  488. package/dist/server/prompts/shared-rules.js.map +1 -1
  489. package/dist/server/ssr-handler.d.ts +1 -1
  490. package/dist/server/ssr-handler.d.ts.map +1 -1
  491. package/dist/server/ssr-handler.js +10 -3
  492. package/dist/server/ssr-handler.js.map +1 -1
  493. package/dist/server/transcribe-voice.d.ts +1 -1
  494. package/dist/settings/user-settings.d.ts.map +1 -1
  495. package/dist/settings/user-settings.js +13 -1
  496. package/dist/settings/user-settings.js.map +1 -1
  497. package/dist/shared/cache-control.d.ts +52 -0
  498. package/dist/shared/cache-control.d.ts.map +1 -1
  499. package/dist/shared/cache-control.js +107 -0
  500. package/dist/shared/cache-control.js.map +1 -1
  501. package/dist/templates/chat/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  502. package/dist/templates/chat/_gitignore +1 -0
  503. package/dist/templates/chat/app/components/layout/Sidebar.tsx +0 -7
  504. package/dist/templates/chat/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  505. package/dist/templates/default/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  506. package/dist/templates/default/app/root.tsx +1 -1
  507. package/dist/templates/default/public/manifest.json +2 -2
  508. package/dist/templates/headless/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  509. package/dist/templates/workspace-core/.agents/skills/performance/SKILL.md +19 -0
  510. package/dist/templates/workspace-core/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  511. package/dist/templates/workspace-core/.agents/skills/visual-answer/SKILL.md +1 -0
  512. package/dist/vite/agents-bundle-plugin.d.ts.map +1 -1
  513. package/dist/vite/agents-bundle-plugin.js +8 -7
  514. package/dist/vite/agents-bundle-plugin.js.map +1 -1
  515. package/dist/vite/client.d.ts.map +1 -1
  516. package/dist/vite/client.js +66 -1
  517. package/dist/vite/client.js.map +1 -1
  518. package/docs/content/actions.mdx +2 -2
  519. package/docs/content/agent-surfaces.mdx +1 -1
  520. package/docs/content/authentication.mdx +2 -0
  521. package/docs/content/deployment.mdx +36 -0
  522. package/docs/content/http-api.mdx +266 -0
  523. package/docs/content/syncing-template-changes.mdx +159 -0
  524. package/package.json +4 -3
  525. package/src/a2a/activity.ts +38 -27
  526. package/src/a2a/client.ts +57 -4
  527. package/src/agent/engine/builder-engine.ts +35 -4
  528. package/src/agent/run-manager.ts +20 -1
  529. package/src/agent/run-store.ts +4 -1
  530. package/src/agent/types.ts +28 -8
  531. package/src/chat-threads/store.ts +45 -0
  532. package/src/checkpoints/index.ts +2 -0
  533. package/src/checkpoints/route-match.ts +13 -0
  534. package/src/cli/create.ts +105 -17
  535. package/src/cli/index.ts +20 -0
  536. package/src/cli/template-baseline.ts +410 -0
  537. package/src/cli/template-sync.ts +1004 -0
  538. package/src/cli/templates-meta.ts +1 -0
  539. package/src/client/AssistantChat.tsx +38 -12
  540. package/src/client/NewWorkspaceAppFlow.tsx +75 -10
  541. package/src/client/chat/message-components.tsx +127 -66
  542. package/src/client/chat/tool-call-display.tsx +29 -5
  543. package/src/client/error-format.ts +18 -0
  544. package/src/client/org/OrgSwitcher.tsx +30 -8
  545. package/src/client/org/TeamPage.tsx +7 -6
  546. package/src/client/settings/SettingsPanel.tsx +9 -9
  547. package/src/client/settings/SettingsTabsPage.tsx +12 -2
  548. package/src/client/sse-event-processor.ts +3 -0
  549. package/src/data-widgets/index.ts +41 -0
  550. package/src/deploy/build.ts +11 -9
  551. package/src/extensions/url-safety.ts +67 -4
  552. package/src/integrations/webhook-handler.ts +63 -9
  553. package/src/org/auto-join-domain.ts +4 -3
  554. package/src/org/context.ts +108 -39
  555. package/src/org/index.ts +5 -0
  556. package/src/org/service-identity.ts +60 -0
  557. package/src/provider-api/index.ts +22 -1
  558. package/src/scripts/docs/search.ts +12 -1
  559. package/src/server/__snapshots__/agent-chat-plugin.surface.spec.ts.snap +25 -36
  560. package/src/server/agent-chat/context-tools.ts +9 -4
  561. package/src/server/agent-chat/framework-prompts.ts +38 -66
  562. package/src/server/agent-chat-plugin.ts +17 -10
  563. package/src/server/agents-bundle.ts +84 -5
  564. package/src/server/auth.ts +4 -3
  565. package/src/server/builder-browser.ts +47 -19
  566. package/src/server/core-routes-plugin.ts +2 -2
  567. package/src/server/credential-provider.ts +209 -68
  568. package/src/server/index.ts +3 -0
  569. package/src/server/prompts/framework-core-compact.ts +6 -13
  570. package/src/server/prompts/framework-core.ts +9 -21
  571. package/src/server/prompts/index.ts +0 -1
  572. package/src/server/prompts/shared-rules.ts +19 -11
  573. package/src/server/ssr-handler.ts +13 -2
  574. package/src/settings/user-settings.ts +13 -1
  575. package/src/shared/cache-control.ts +141 -0
  576. package/src/templates/chat/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  577. package/src/templates/chat/_gitignore +1 -0
  578. package/src/templates/chat/app/components/layout/Sidebar.tsx +0 -7
  579. package/src/templates/chat/changelog/2026-07-25-settings-navigation-now-keeps-manage-agent-as-a-dedicated-li.md +6 -0
  580. package/src/templates/default/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  581. package/src/templates/default/app/root.tsx +1 -1
  582. package/src/templates/default/public/manifest.json +2 -2
  583. package/src/templates/headless/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  584. package/src/templates/workspace-core/.agents/skills/performance/SKILL.md +19 -0
  585. package/src/templates/workspace-core/.agents/skills/upgrade-agent-native/SKILL.md +24 -2
  586. package/src/templates/workspace-core/.agents/skills/visual-answer/SKILL.md +1 -0
  587. package/src/vite/agents-bundle-plugin.ts +7 -6
  588. package/src/vite/client.ts +69 -3
@@ -1,5 +1,49 @@
1
1
  import * as jose from "jose";
2
2
  import { ssrfSafeFetch } from "../extensions/url-safety.js";
3
+ /**
4
+ * A workspace serves every app from one gateway on loopback, so sibling A2A
5
+ * targets are private addresses by construction and the SSRF guard cannot tell
6
+ * them apart from an attack. Trust only origins this deployment configured for
7
+ * itself — never a value that arrived on a request.
8
+ */
9
+ function workspacePrivateOrigins() {
10
+ const origins = [
11
+ process.env.WORKSPACE_GATEWAY_URL,
12
+ process.env.APP_URL,
13
+ process.env.BETTER_AUTH_URL,
14
+ // Escape hatch for contexts that never receive the gateway manifest (the
15
+ // action CLI, one-off scripts). Comma-separated origins.
16
+ ...(process.env.AGENT_NATIVE_A2A_ALLOWED_ORIGINS ?? "").split(","),
17
+ ]
18
+ .map((value) => value?.trim())
19
+ .filter((value) => !!value);
20
+ // The gateway also hands each child the sibling manifest, and siblings are
21
+ // reached on their own loopback ports rather than through the gateway.
22
+ const raw = process.env.AGENT_NATIVE_WORKSPACE_APPS_JSON;
23
+ if (raw) {
24
+ try {
25
+ const parsed = JSON.parse(raw);
26
+ const apps = Array.isArray(parsed?.apps)
27
+ ? parsed.apps
28
+ : Array.isArray(parsed)
29
+ ? parsed
30
+ : [];
31
+ for (const app of apps) {
32
+ const url = app?.url ?? app?.origin ?? app?.baseUrl;
33
+ if (typeof url === "string" && url)
34
+ origins.push(url);
35
+ const port = app?.port;
36
+ if (typeof port === "number" && Number.isFinite(port)) {
37
+ origins.push(`http://127.0.0.1:${port}`);
38
+ }
39
+ }
40
+ }
41
+ catch {
42
+ // A malformed manifest must not disable the SSRF guard.
43
+ }
44
+ }
45
+ return origins;
46
+ }
3
47
  import { sanitizeA2ACorrelationMetadata } from "./correlation.js";
4
48
  const DEFAULT_A2A_POLL_REQUEST_TIMEOUT_MS = 15_000;
5
49
  export class A2ATaskTimeoutError extends Error {
@@ -87,7 +131,7 @@ export class A2AClient {
87
131
  return;
88
132
  for (const endpoint of this.endpointCandidates) {
89
133
  try {
90
- const res = await ssrfSafeFetch(endpoint, { method: "OPTIONS" }, { maxRedirects: 3 });
134
+ const res = await ssrfSafeFetch(endpoint, { method: "OPTIONS" }, { maxRedirects: 3, allowedPrivateOrigins: workspacePrivateOrigins() });
91
135
  if (res.status !== 404 && res.status !== 405) {
92
136
  this.endpointCandidates = [endpoint];
93
137
  return;
@@ -157,7 +201,7 @@ export class A2AClient {
157
201
  throw lastError ?? new Error("No A2A endpoint candidates available");
158
202
  }
159
203
  async getAgentCard() {
160
- const res = await ssrfSafeFetch(`${this.baseUrl}/.well-known/agent-card.json`, {}, { maxRedirects: 3 });
204
+ const res = await ssrfSafeFetch(`${this.baseUrl}/.well-known/agent-card.json`, {}, { maxRedirects: 3, allowedPrivateOrigins: workspacePrivateOrigins() });
161
205
  if (!res.ok) {
162
206
  throw new Error(`Failed to fetch agent card (${res.status})`);
163
207
  }
@@ -372,7 +416,7 @@ export class A2AClient {
372
416
  headers: this.headers(apiKey),
373
417
  body: JSON.stringify(body),
374
418
  signal: controller?.signal,
375
- }, { maxRedirects: 3 });
419
+ }, { maxRedirects: 3, allowedPrivateOrigins: workspacePrivateOrigins() });
376
420
  }
377
421
  finally {
378
422
  if (timer)
@@ -609,7 +653,17 @@ async function buildA2AApiKeyAttempts(opts, audience) {
609
653
  }
610
654
  function normalizeA2AAudience(url) {
611
655
  const explicit = splitExplicitA2AEndpoint(url.replace(/\/$/, ""));
612
- return (explicit?.baseUrl ?? url).replace(/\/$/, "");
656
+ const base = (explicit?.baseUrl ?? url).replace(/\/$/, "");
657
+ // Receivers derive their expected audience from APP_URL, which carries no
658
+ // app path. In a workspace every app is mounted under one gateway origin, so
659
+ // signing the path-qualified URL yields an audience the receiver can never
660
+ // match. The origin is the identifier both sides agree on.
661
+ try {
662
+ return new URL(base).origin;
663
+ }
664
+ catch {
665
+ return base;
666
+ }
613
667
  }
614
668
  function isA2AAuthRejection(err) {
615
669
  const message = err instanceof Error ? err.message : String(err ?? "");
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../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K,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC;IACvE,OAAO,iMAAiM,CAAC,IAAI,CAC3M,OAAO,CACR,CAAC;AACJ,CAAC;AAED,SAAS,8BAA8B,CAAC,IAAU;IAChD,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,QAAQ,EAAE,+BAA+B,EAAE,CAAC;QACpE,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,OAAO,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AACjD,CAAC;AAED,SAAS,kBAAkB,CAAC,OAAgB;IAC1C,OAAO,OAAO,CAAC,KAAK;SACjB,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;SACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;SAClB,IAAI,CAAC,IAAI,CAAC,CAAC;AAChB,CAAC","sourcesContent":["import * as jose from \"jose\";\n\nimport { ssrfSafeFetch } from \"../extensions/url-safety.js\";\nimport { sanitizeA2ACorrelationMetadata } from \"./correlation.js\";\nimport type {\n A2AApprovedAction,\n A2ACorrelationMetadata,\n A2ASourceContextReference,\n A2AReadOnlyActionResult,\n AgentCard,\n JsonRpcRequest,\n JsonRpcResponse,\n Message,\n Task,\n} from \"./types.js\";\n\nconst DEFAULT_A2A_POLL_REQUEST_TIMEOUT_MS = 15_000;\n\nexport class A2ATaskTimeoutError extends Error {\n readonly taskId: string;\n readonly lastTask: Task;\n readonly lastState: string;\n readonly timeoutMs: number;\n\n constructor(taskId: string, lastTask: Task, timeoutMs: number) {\n const lastState = lastTask.status.state;\n super(\n `A2A task ${taskId} did not complete within ${timeoutMs}ms (last state: ${lastState})`,\n );\n this.name = \"A2ATaskTimeoutError\";\n this.taskId = taskId;\n this.lastTask = lastTask;\n this.lastState = lastState;\n this.timeoutMs = timeoutMs;\n }\n}\n\n/**\n * Sign a JWT for A2A cross-app identity verification.\n *\n * Uses an org-level secret by default for direct org-secret workflows. Callers\n * that are doing ordinary hosted cross-app delegation can set\n * `preferGlobalSecret` so deployments with a shared A2A_SECRET don't depend on\n * every app database having an identical org row. The token contains the\n * caller's email as `sub`, so the receiving app can verify who's calling.\n */\nexport async function signA2AToken(\n email: string,\n orgDomain?: string,\n orgSecret?: string,\n options?: {\n expiresIn?: string | number;\n preferGlobalSecret?: boolean;\n audience?: string | string[];\n /**\n * Extra JWT claims to merge alongside `sub` / `org_domain`. Used by the\n * MCP connect flow to add a revocable `jti` and a `scope: \"mcp-connect\"`\n * marker. Reserved claims (`sub`, `org_domain`) cannot be overridden —\n * they are spread last so a caller can never spoof identity via this map.\n */\n extraClaims?: Record<string, unknown>;\n },\n): Promise<string> {\n const secret = options?.preferGlobalSecret\n ? process.env.A2A_SECRET || orgSecret\n : orgSecret || process.env.A2A_SECRET;\n if (!secret) {\n throw new Error(\n \"No A2A secret available. Set an org-level A2A secret in Team settings, \" +\n \"or set A2A_SECRET as an environment variable on all apps that need to verify identity.\",\n );\n }\n\n const appUrl =\n process.env.APP_URL ||\n process.env.BETTER_AUTH_URL ||\n \"http://localhost:3000\";\n\n const jwt = new jose.SignJWT({\n ...(options?.extraClaims ?? {}),\n // `sub` / `org_domain` are spread AFTER extraClaims so a caller-supplied\n // map can never override the verified identity claims.\n sub: email,\n ...(orgDomain ? { org_domain: orgDomain } : {}),\n })\n .setProtectedHeader({ alg: \"HS256\" })\n .setIssuer(appUrl)\n .setIssuedAt()\n .setExpirationTime(options?.expiresIn ?? \"15m\");\n\n if (options?.audience) jwt.setAudience(options.audience);\n\n return jwt.sign(new TextEncoder().encode(secret));\n}\n\nexport function shouldPreferGlobalA2ASecret(orgSecret?: string): boolean {\n return !!process.env.A2A_SECRET?.trim() || !orgSecret;\n}\n\nexport class A2AClient {\n private baseUrl: string;\n private apiKey?: string;\n private apiKeyAttempts: Array<string | undefined>;\n private endpointCandidates: string[] = [];\n private endpointResolved = false;\n private requestTimeoutMs?: number;\n\n constructor(\n baseUrl: string,\n apiKey?: string,\n options?: { requestTimeoutMs?: number; fallbackApiKeys?: string[] },\n ) {\n const normalized = baseUrl.replace(/\\/$/, \"\");\n const explicitEndpoint = splitExplicitA2AEndpoint(normalized);\n this.baseUrl = explicitEndpoint?.baseUrl ?? normalized;\n if (explicitEndpoint) {\n this.endpointCandidates = [explicitEndpoint.endpointUrl];\n this.endpointResolved = true;\n }\n this.apiKey = apiKey;\n this.apiKeyAttempts = uniqueAuthTokens([\n apiKey,\n ...(options?.fallbackApiKeys ?? []),\n ]);\n this.requestTimeoutMs = options?.requestTimeoutMs;\n }\n\n /**\n * Detect which A2A path the target agent uses.\n * Agent-native apps use /_agent-native/a2a, external agents may use /a2a.\n */\n async resolveEndpoint(): Promise<void> {\n await this.ensureEndpointCandidates();\n if (this.endpointCandidates.length <= 1) return;\n\n for (const endpoint of this.endpointCandidates) {\n try {\n const res = await ssrfSafeFetch(\n endpoint,\n { method: \"OPTIONS\" },\n { maxRedirects: 3 },\n );\n if (res.status !== 404 && res.status !== 405) {\n this.endpointCandidates = [endpoint];\n return;\n }\n if (res.status === 405) {\n this.endpointCandidates = [endpoint];\n return;\n }\n } catch {\n // Try the next candidate.\n }\n }\n }\n\n private headers(apiKey = this.apiKey): Record<string, string> {\n const h: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (apiKey) {\n h[\"Authorization\"] = `Bearer ${apiKey}`;\n }\n return h;\n }\n\n private markApiKeySucceeded(apiKey: string | undefined) {\n this.apiKey = apiKey;\n this.apiKeyAttempts = uniqueAuthTokens([\n apiKey,\n ...this.apiKeyAttempts.filter((token) => token !== apiKey),\n ]);\n }\n\n private async rpc(\n method: string,\n params: Record<string, unknown>,\n options?: { requestTimeoutMs?: number },\n ): Promise<JsonRpcResponse> {\n const body: JsonRpcRequest = {\n jsonrpc: \"2.0\",\n id: Date.now(),\n method,\n params,\n };\n\n await this.ensureEndpointCandidates();\n let lastError: Error | null = null;\n\n for (const url of this.endpointCandidates) {\n for (let i = 0; i < this.apiKeyAttempts.length; i++) {\n console.log(`[A2A Client] POST ${url} method=${method}`);\n const startTime = Date.now();\n const res = await this.postJson(\n url,\n body,\n this.apiKeyAttempts[i],\n options?.requestTimeoutMs,\n );\n console.log(\n `[A2A Client] Response: ${res.status} in ${Date.now() - startTime}ms`,\n );\n\n if (res.ok) {\n const text = await res.text();\n if (\n i < this.apiKeyAttempts.length - 1 &&\n isA2AAuthRejectionResponse(res.status, text)\n ) {\n lastError = new Error(\n `A2A request failed (${res.status}): ${text}`,\n );\n continue;\n }\n this.endpointCandidates = [url];\n this.markApiKeySucceeded(this.apiKeyAttempts[i]);\n return JSON.parse(text) as JsonRpcResponse;\n }\n\n const text = await res.text();\n lastError = new Error(`A2A request failed (${res.status}): ${text}`);\n if (\n i < this.apiKeyAttempts.length - 1 &&\n isA2AAuthRejectionResponse(res.status, text)\n ) {\n continue;\n }\n if (!shouldTryNextEndpoint(res.status)) {\n throw lastError;\n }\n break;\n }\n }\n\n throw lastError ?? new Error(\"No A2A endpoint candidates available\");\n }\n\n async getAgentCard(): Promise<AgentCard> {\n const res = await ssrfSafeFetch(\n `${this.baseUrl}/.well-known/agent-card.json`,\n {},\n { maxRedirects: 3 },\n );\n if (!res.ok) {\n throw new Error(`Failed to fetch agent card (${res.status})`);\n }\n return res.json() as Promise<AgentCard>;\n }\n\n async send(\n message: Message,\n opts?: {\n contextId?: string;\n metadata?: Record<string, unknown>;\n idempotencyKey?: string;\n approvedActions?: A2AApprovedAction[];\n /**\n * If true, ask the server to return the task immediately in `working`\n * state and process the handler in the background. The caller should\n * then poll `getTask(taskId)` until `completed` / `failed` / `canceled`.\n *\n * Use this when you expect the handler may exceed a synchronous\n * serverless request budget.\n */\n async?: boolean;\n },\n ): Promise<Task> {\n const response = await this.rpc(\"message/send\", {\n message,\n contextId: opts?.contextId,\n metadata: opts?.metadata,\n ...(opts?.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : {}),\n ...(opts?.approvedActions?.length\n ? { approvedActions: opts.approvedActions }\n : {}),\n ...(opts?.async ? { async: true } : {}),\n });\n\n if (response.error) {\n throw new Error(\n `A2A error (${response.error.code}): ${response.error.message}`,\n );\n }\n\n return response.result as Task;\n }\n\n /**\n * Poll for a task by id. Used in async mode after `send({ async: true })`.\n */\n async getTask(\n taskId: string,\n opts?: { requestTimeoutMs?: number },\n ): Promise<Task> {\n const response = await this.rpc(\n \"tasks/get\",\n { id: taskId },\n { requestTimeoutMs: opts?.requestTimeoutMs },\n );\n if (response.error) {\n throw new Error(\n `A2A error (${response.error.code}): ${response.error.message}`,\n );\n }\n return response.result as Task;\n }\n\n /**\n * Execute one receiver-approved read-only action without starting the\n * receiver's agent loop. The receiver still owns validation, credentials,\n * request scoping, and the explicit action exposure decision.\n */\n async invokeAction(\n action: string,\n input: Record<string, unknown> = {},\n opts?: { metadata?: A2ACorrelationMetadata },\n ): Promise<A2AReadOnlyActionResult> {\n const metadata = sanitizeA2ACorrelationMetadata(opts?.metadata);\n const response = await this.rpc(\"actions/invoke\", {\n action,\n input,\n ...(Object.keys(metadata).length > 0 ? { metadata } : {}),\n });\n if (response.error) {\n throw new Error(\n `A2A error (${response.error.code}): ${response.error.message}`,\n );\n }\n return response.result as A2AReadOnlyActionResult;\n }\n\n /**\n * Send a message in async mode and poll until the task reaches a terminal\n * state. This is the recommended path on serverless hosts with short\n * function timeouts (Netlify, Vercel) where a synchronous LLM-driven A2A\n * call can exceed the gateway limit.\n *\n * Each individual fetch returns quickly; long-running work happens on the\n * receiving side and is checked via `tasks/get`.\n */\n async sendAndWait(\n message: Message,\n opts?: {\n contextId?: string;\n metadata?: Record<string, unknown>;\n idempotencyKey?: string;\n approvedActions?: A2AApprovedAction[];\n /** Total time to wait for completion. Default 5 min. */\n timeoutMs?: number;\n /** Poll interval. Default 2s. */\n pollIntervalMs?: number;\n /** Called with each polled task — useful for surfacing progress. */\n onUpdate?: (task: Task) => void;\n },\n ): Promise<Task> {\n const submitted = await this.send(message, {\n contextId: opts?.contextId,\n metadata: opts?.metadata,\n idempotencyKey: opts?.idempotencyKey,\n ...(opts?.approvedActions?.length\n ? { approvedActions: opts.approvedActions }\n : {}),\n async: true,\n });\n\n return this.pollTask(submitted, opts);\n }\n\n /**\n * Continue waiting for an existing async task without submitting a second\n * message. Use this after a bounded caller-side wait expires but the remote\n * task is still working.\n */\n async waitForTask(\n taskId: string,\n opts?: {\n /** Total time to wait for completion. Default 5 min. */\n timeoutMs?: number;\n /** Poll interval. Default 2s. */\n pollIntervalMs?: number;\n /** Called with each successfully polled task. */\n onUpdate?: (task: Task) => void;\n },\n ): Promise<Task> {\n const current = await this.getTask(taskId);\n opts?.onUpdate?.(current);\n return this.pollTask(current, opts);\n }\n\n private async pollTask(\n submitted: Task,\n opts?: {\n timeoutMs?: number;\n pollIntervalMs?: number;\n onUpdate?: (task: Task) => void;\n },\n ): Promise<Task> {\n const terminalStates = new Set([\n \"completed\",\n \"failed\",\n \"canceled\",\n \"input-required\",\n ]);\n if (terminalStates.has(submitted.status.state)) return submitted;\n\n const timeoutMs = opts?.timeoutMs ?? 5 * 60_000;\n const pollMs = opts?.pollIntervalMs ?? 2_000;\n const deadline = Date.now() + timeoutMs;\n\n let current = submitted;\n while (Date.now() < deadline) {\n const sleepMs = Math.min(pollMs, Math.max(0, deadline - Date.now()));\n await new Promise((r) => setTimeout(r, sleepMs));\n const remainingMs = deadline - Date.now();\n if (remainingMs <= 0) break;\n try {\n current = await this.getTask(submitted.id, {\n requestTimeoutMs: Math.min(\n this.requestTimeoutMs ?? DEFAULT_A2A_POLL_REQUEST_TIMEOUT_MS,\n remainingMs,\n ),\n });\n opts?.onUpdate?.(current);\n } catch {\n // Transient fetch failure — keep polling until the deadline.\n continue;\n }\n if (terminalStates.has(current.status.state)) return current;\n }\n throw new A2ATaskTimeoutError(submitted.id, current, timeoutMs);\n }\n\n async *stream(\n message: Message,\n opts?: { contextId?: string; metadata?: Record<string, unknown> },\n ): AsyncGenerator<Task> {\n const body: JsonRpcRequest = {\n jsonrpc: \"2.0\",\n id: Date.now(),\n method: \"message/stream\",\n params: {\n message,\n contextId: opts?.contextId,\n metadata: opts?.metadata,\n },\n };\n\n await this.ensureEndpointCandidates();\n let res: Response | null = null;\n let lastError: Error | null = null;\n for (const candidate of this.endpointCandidates) {\n for (let i = 0; i < this.apiKeyAttempts.length; i++) {\n res = await this.postJson(candidate, body, this.apiKeyAttempts[i]);\n if (res.ok) {\n this.endpointCandidates = [candidate];\n this.markApiKeySucceeded(this.apiKeyAttempts[i]);\n break;\n }\n const text = await res.text();\n lastError = new Error(`A2A stream failed (${res.status}): ${text}`);\n if (\n i < this.apiKeyAttempts.length - 1 &&\n isA2AAuthRejectionResponse(res.status, text)\n ) {\n continue;\n }\n if (!shouldTryNextEndpoint(res.status)) throw lastError;\n break;\n }\n if (res?.ok) break;\n }\n if (!res?.ok) {\n throw lastError ?? new Error(\"No A2A endpoint candidates available\");\n }\n\n const reader = res.body?.getReader();\n if (!reader) throw new Error(\"No response body\");\n\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const json = line.slice(6).trim();\n if (!json) continue;\n\n const response: JsonRpcResponse = JSON.parse(json);\n if (response.error) {\n throw new Error(\n `A2A error (${response.error.code}): ${response.error.message}`,\n );\n }\n if (response.result) {\n yield response.result as Task;\n }\n }\n }\n }\n\n private async ensureEndpointCandidates(): Promise<void> {\n if (this.endpointResolved) return;\n this.endpointResolved = true;\n\n const candidates: string[] = [];\n addDefaultEndpointCandidates(candidates, this.baseUrl);\n\n try {\n const card = await this.getAgentCard();\n const cardUrl = normalizeUrl(card.url, this.baseUrl);\n if (cardUrl) {\n const explicitEndpoint = splitExplicitA2AEndpoint(cardUrl);\n if (explicitEndpoint) {\n candidates.unshift(explicitEndpoint.endpointUrl);\n } else {\n addDefaultEndpointCandidates(candidates, cardUrl);\n }\n }\n } catch {\n // Agent cards are discovery hints. Fall back to conventional endpoints.\n }\n\n this.endpointCandidates = unique(candidates);\n }\n\n private async postJson(\n url: string,\n body: JsonRpcRequest,\n apiKey = this.apiKey,\n requestTimeoutMs = this.requestTimeoutMs,\n ): Promise<Response> {\n const controller = requestTimeoutMs ? new AbortController() : undefined;\n const timer =\n controller && requestTimeoutMs\n ? setTimeout(() => controller.abort(), requestTimeoutMs)\n : undefined;\n try {\n return await ssrfSafeFetch(\n url,\n {\n method: \"POST\",\n headers: this.headers(apiKey),\n body: JSON.stringify(body),\n signal: controller?.signal,\n },\n { maxRedirects: 3 },\n );\n } finally {\n if (timer) clearTimeout(timer);\n }\n }\n}\n\nfunction splitExplicitA2AEndpoint(\n url: string,\n): { baseUrl: string; endpointUrl: string } | null {\n try {\n const parsed = new URL(url);\n const pathname = parsed.pathname.replace(/\\/$/, \"\");\n if (pathname.endsWith(\"/_agent-native/a2a\")) {\n parsed.pathname = pathname.slice(0, -\"/_agent-native/a2a\".length) || \"/\";\n parsed.search = \"\";\n parsed.hash = \"\";\n return {\n baseUrl: parsed.toString().replace(/\\/$/, \"\"),\n endpointUrl: url,\n };\n }\n if (pathname.endsWith(\"/a2a\")) {\n parsed.pathname = pathname.slice(0, -\"/a2a\".length) || \"/\";\n parsed.search = \"\";\n parsed.hash = \"\";\n return {\n baseUrl: parsed.toString().replace(/\\/$/, \"\"),\n endpointUrl: url,\n };\n }\n } catch {\n // Relative or invalid URLs are handled by the caller's normal fetch path.\n }\n return null;\n}\n\nfunction addDefaultEndpointCandidates(candidates: string[], baseUrl: string) {\n const base = baseUrl.replace(/\\/$/, \"\");\n candidates.push(`${base}/_agent-native/a2a`, `${base}/a2a`);\n}\n\nfunction normalizeUrl(\n value: string | undefined,\n baseUrl: string,\n): string | null {\n if (!value) return null;\n try {\n return new URL(value, `${baseUrl.replace(/\\/$/, \"\")}/`)\n .toString()\n .replace(/\\/$/, \"\");\n } catch {\n return null;\n }\n}\n\nfunction shouldTryNextEndpoint(status: number): boolean {\n return status === 404 || status === 405;\n}\n\nfunction unique(values: string[]): string[] {\n return Array.from(new Set(values));\n}\n\nfunction uniqueAuthTokens(\n values: Array<string | undefined>,\n): Array<string | undefined> {\n const result: Array<string | undefined> = [];\n for (const value of values) {\n if (result.includes(value)) continue;\n result.push(value);\n }\n if (result.length === 0) result.push(undefined);\n return result;\n}\n\nfunction isA2AAuthRejectionResponse(status: number, text: string): boolean {\n return (\n status === 401 ||\n /verified, audience-bound user identity/i.test(text) ||\n /A2A error \\(-32001\\): (?:Invalid or expired A2A token|Invalid API key|Authentication required)|Invalid or expired A2A token|Invalid API key|Authentication required/i.test(\n text,\n )\n );\n}\n\n/**\n * One-shot convenience function: send a text message and get a text response.\n *\n * When A2A_SECRET is set and userEmail is provided, outbound calls are signed\n * with a JWT so the receiving app can cryptographically verify the caller's\n * identity (instead of blindly trusting metadata).\n */\nexport async function callAgent(\n url: string,\n text: string,\n opts?: {\n apiKey?: string;\n /** Additional bearer tokens to try in order after apiKey during rotation. */\n apiKeyFallbacks?: string[];\n /** Additional transport metadata. Receivers must not use it as identity. */\n metadata?: Record<string, unknown>;\n contextId?: string;\n userEmail?: string;\n orgDomain?: string;\n orgSecret?: string;\n /** Origin used to build links back to the receiving app. */\n requestOrigin?: string;\n /** Exact downstream actions explicitly authorized in the caller's chat. */\n approvedActions?: A2AApprovedAction[];\n /** Opaque provenance reference resolved by the receiver through Dispatch. */\n sourceContext?: A2ASourceContextReference;\n /** Bounded telemetry-only lineage forwarded to the receiving app. */\n correlation?: A2ACorrelationMetadata;\n /** Stable caller-generated key for one message submission. */\n idempotencyKey?: string;\n /**\n * Use async/poll instead of a single blocking POST. Recommended for\n * cross-app calls that may exceed a synchronous serverless request budget.\n * Defaults to true so callers get safe behavior out of the box.\n */\n async?: boolean;\n /** Total time to wait for the polled task (default 5 min). */\n timeoutMs?: number;\n /**\n * Existing async task to keep polling. When set, no new message is sent.\n * This prevents a caller-side timeout from duplicating downstream work.\n */\n taskId?: string;\n /** Poll interval for async calls. Primarily useful for tests/retries. */\n pollIntervalMs?: number;\n /**\n * Return receiver-verified artifact text from the last polled task when\n * the call times out. Defaults to true for backwards compatibility.\n * Callers that can continue polling the remote task separately should set\n * this to false so the A2ATaskTimeoutError (and its taskId) is preserved.\n */\n returnRecoverableArtifactsOnTimeout?: boolean;\n /**\n * Called with each successfully polled task while an async call is still\n * in flight (see `A2AClient.sendAndWait`). Fires once per real poll\n * round-trip that returns a task — including the terminal poll — so\n * callers can surface genuine remote liveness/progress. Not called when a\n * poll fetch throws (remote unresponsive) or when the task completes\n * synchronously on submit. Only threaded through for async calls.\n */\n onUpdate?: (task: Task) => void;\n },\n): Promise<string> {\n const metadata: Record<string, unknown> = { ...opts?.metadata };\n if (opts?.userEmail) metadata.userEmail = opts.userEmail;\n if (opts?.orgDomain) metadata.orgDomain = opts.orgDomain;\n if (opts?.requestOrigin) metadata.requestOrigin = opts.requestOrigin;\n if (opts?.sourceContext) metadata.sourceContext = opts.sourceContext;\n Object.assign(metadata, sanitizeA2ACorrelationMetadata(opts?.correlation));\n\n // Default to async + poll. The receiving A2A server's `_process-task` route\n // runs the handler in a fresh function execution (cross-platform queue\n // pattern), so async mode now works on every host instead of relying on\n // detached promises that get killed on Netlify/Vercel. Callers that\n // explicitly want a single-shot blocking POST can pass `async: false`.\n const useAsync = opts?.async ?? true;\n const message: Message = {\n role: \"user\",\n parts: [{ type: \"text\", text }],\n };\n\n const apiKeyAttempts = await buildA2AApiKeyAttempts(opts);\n let lastAuthError: unknown;\n\n for (let i = 0; i < apiKeyAttempts.length; i++) {\n try {\n const fallbackApiKeys = apiKeyAttempts\n .slice(i + 1)\n .filter((token): token is string => token !== undefined);\n const client = new A2AClient(url, apiKeyAttempts[i], {\n fallbackApiKeys,\n });\n let task: Task;\n if (useAsync) {\n task = opts?.taskId\n ? await client.waitForTask(opts.taskId, {\n timeoutMs: opts.timeoutMs,\n pollIntervalMs: opts.pollIntervalMs,\n onUpdate: opts.onUpdate,\n })\n : await client.sendAndWait(message, {\n contextId: opts?.contextId,\n metadata,\n idempotencyKey: opts?.idempotencyKey,\n ...(opts?.approvedActions?.length\n ? { approvedActions: opts.approvedActions }\n : {}),\n timeoutMs: opts?.timeoutMs,\n pollIntervalMs: opts?.pollIntervalMs,\n onUpdate: opts?.onUpdate,\n });\n } else {\n if (opts?.taskId) {\n throw new Error(\"Polling an existing A2A task requires async mode\");\n }\n task = await client.send(message, {\n contextId: opts?.contextId,\n metadata,\n idempotencyKey: opts?.idempotencyKey,\n ...(opts?.approvedActions?.length\n ? { approvedActions: opts.approvedActions }\n : {}),\n });\n }\n\n // Extract text from the response\n const responseMessage = task.status.message;\n if (responseMessage) {\n const textParts = responseMessage.parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text);\n return textParts.join(\"\\n\");\n }\n\n return \"\";\n } catch (err) {\n if (\n opts?.returnRecoverableArtifactsOnTimeout !== false &&\n err instanceof A2ATaskTimeoutError\n ) {\n const recoverableText = extractRecoverableArtifactText(err.lastTask);\n if (recoverableText) return recoverableText;\n }\n if (i < apiKeyAttempts.length - 1 && isA2AAuthRejection(err)) {\n lastAuthError = err;\n continue;\n }\n throw err;\n }\n }\n\n if (lastAuthError) throw lastAuthError;\n return \"\";\n}\n\n/**\n * Invoke one receiver-approved read-only action with an audience-bound user\n * token. Unlike conversational delegation, this never starts the receiver's\n * model loop.\n */\nexport async function callAction(\n url: string,\n action: string,\n input: Record<string, unknown> = {},\n opts?: {\n apiKey?: string;\n userEmail?: string;\n orgDomain?: string;\n orgSecret?: string;\n requestTimeoutMs?: number;\n correlation?: A2ACorrelationMetadata;\n },\n): Promise<A2AReadOnlyActionResult> {\n const actionName = action.trim();\n if (!actionName) throw new Error(\"A2A action name is required\");\n if (!input || typeof input !== \"object\" || Array.isArray(input)) {\n throw new Error(\"A2A action input must be an object\");\n }\n\n const apiKeyAttempts = await buildA2AApiKeyAttempts(\n opts,\n normalizeA2AAudience(url),\n );\n const fallbackApiKeys = apiKeyAttempts\n .slice(1)\n .filter((token): token is string => token !== undefined);\n const client = new A2AClient(url, apiKeyAttempts[0], {\n fallbackApiKeys,\n requestTimeoutMs: opts?.requestTimeoutMs,\n });\n return client.invokeAction(actionName, input, {\n metadata: sanitizeA2ACorrelationMetadata(opts?.correlation),\n });\n}\n\nasync function buildA2AApiKeyAttempts(\n opts?: {\n apiKey?: string;\n apiKeyFallbacks?: string[];\n userEmail?: string;\n orgDomain?: string;\n orgSecret?: string;\n },\n audience?: string,\n): Promise<Array<string | undefined>> {\n const attempts: Array<string | undefined> = [];\n const add = (token: string | undefined) => {\n if (token === undefined || attempts.includes(token)) return;\n attempts.push(token);\n };\n\n add(opts?.apiKey);\n for (const fallback of opts?.apiKeyFallbacks ?? []) add(fallback);\n\n if (opts?.userEmail && (opts.orgSecret || process.env.A2A_SECRET)) {\n if (process.env.A2A_SECRET?.trim()) {\n try {\n add(\n await signA2AToken(opts.userEmail, opts.orgDomain, opts.orgSecret, {\n preferGlobalSecret: true,\n audience,\n }),\n );\n } catch {\n // Keep any explicit token attempt, then fall back below.\n }\n }\n\n if (opts.orgSecret) {\n try {\n add(\n await signA2AToken(opts.userEmail, opts.orgDomain, opts.orgSecret, {\n preferGlobalSecret: false,\n audience,\n }),\n );\n } catch {\n // Fall through to the attempts we already have.\n }\n }\n }\n\n if (attempts.length === 0) attempts.push(undefined);\n return attempts;\n}\n\nfunction normalizeA2AAudience(url: string): string {\n const explicit = splitExplicitA2AEndpoint(url.replace(/\\/$/, \"\"));\n return (explicit?.baseUrl ?? url).replace(/\\/$/, \"\");\n}\n\nfunction isA2AAuthRejection(err: unknown): boolean {\n const message = err instanceof Error ? err.message : String(err ?? \"\");\n return /A2A request failed \\(401\\)|A2A error \\(-32001\\): (?:Invalid or expired A2A token|Invalid API key|Authentication required)|Invalid or expired A2A token|Invalid API key|Authentication required/i.test(\n message,\n );\n}\n\nfunction extractRecoverableArtifactText(task: Task): string {\n if (!task.status.message?.metadata?.agentNativeRecoverableArtifacts) {\n return \"\";\n }\n return extractMessageText(task.status.message);\n}\n\nfunction extractMessageText(message: Message): string {\n return message.parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\\n\");\n}\n"]}
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/a2a/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D;;;;;GAKG;AACH,SAAS,uBAAuB;IAC9B,MAAM,OAAO,GAAG;QACd,OAAO,CAAC,GAAG,CAAC,qBAAqB;QACjC,OAAO,CAAC,GAAG,CAAC,OAAO;QACnB,OAAO,CAAC,GAAG,CAAC,eAAe;QAC3B,yEAAyE;QACzE,yDAAyD;QACzD,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,gCAAgC,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC;KACnE;SACE,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC;SAC7B,MAAM,CAAC,CAAC,KAAK,EAAmB,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;IAE/C,2EAA2E;IAC3E,uEAAuE;IACvE,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC;IACzD,IAAI,GAAG,EAAE,CAAC;QACR,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAC/B,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC;gBACtC,CAAC,CA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OAAO,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AACjD,CAAC;AAED,SAAS,kBAAkB,CAAC,OAAgB;IAC1C,OAAO,OAAO,CAAC,KAAK;SACjB,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;SACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;SAClB,IAAI,CAAC,IAAI,CAAC,CAAC;AAChB,CAAC","sourcesContent":["import * as jose from \"jose\";\n\nimport { ssrfSafeFetch } from \"../extensions/url-safety.js\";\n\n/**\n * A workspace serves every app from one gateway on loopback, so sibling A2A\n * targets are private addresses by construction and the SSRF guard cannot tell\n * them apart from an attack. Trust only origins this deployment configured for\n * itself — never a value that arrived on a request.\n */\nfunction workspacePrivateOrigins(): string[] {\n const origins = [\n process.env.WORKSPACE_GATEWAY_URL,\n process.env.APP_URL,\n process.env.BETTER_AUTH_URL,\n // Escape hatch for contexts that never receive the gateway manifest (the\n // action CLI, one-off scripts). Comma-separated origins.\n ...(process.env.AGENT_NATIVE_A2A_ALLOWED_ORIGINS ?? \"\").split(\",\"),\n ]\n .map((value) => value?.trim())\n .filter((value): value is string => !!value);\n\n // The gateway also hands each child the sibling manifest, and siblings are\n // reached on their own loopback ports rather than through the gateway.\n const raw = process.env.AGENT_NATIVE_WORKSPACE_APPS_JSON;\n if (raw) {\n try {\n const parsed = JSON.parse(raw);\n const apps = Array.isArray(parsed?.apps)\n ? parsed.apps\n : Array.isArray(parsed)\n ? parsed\n : [];\n for (const app of apps) {\n const url = app?.url ?? app?.origin ?? app?.baseUrl;\n if (typeof url === \"string\" && url) origins.push(url);\n const port = app?.port;\n if (typeof port === \"number\" && Number.isFinite(port)) {\n origins.push(`http://127.0.0.1:${port}`);\n }\n }\n } catch {\n // A malformed manifest must not disable the SSRF guard.\n }\n }\n return origins;\n}\nimport { sanitizeA2ACorrelationMetadata } from \"./correlation.js\";\nimport type {\n A2AApprovedAction,\n A2ACorrelationMetadata,\n A2ASourceContextReference,\n A2AReadOnlyActionResult,\n AgentCard,\n JsonRpcRequest,\n JsonRpcResponse,\n Message,\n Task,\n} from \"./types.js\";\n\nconst DEFAULT_A2A_POLL_REQUEST_TIMEOUT_MS = 15_000;\n\nexport class A2ATaskTimeoutError extends Error {\n readonly taskId: string;\n readonly lastTask: Task;\n readonly lastState: string;\n readonly timeoutMs: number;\n\n constructor(taskId: string, lastTask: Task, timeoutMs: number) {\n const lastState = lastTask.status.state;\n super(\n `A2A task ${taskId} did not complete within ${timeoutMs}ms (last state: ${lastState})`,\n );\n this.name = \"A2ATaskTimeoutError\";\n this.taskId = taskId;\n this.lastTask = lastTask;\n this.lastState = lastState;\n this.timeoutMs = timeoutMs;\n }\n}\n\n/**\n * Sign a JWT for A2A cross-app identity verification.\n *\n * Uses an org-level secret by default for direct org-secret workflows. Callers\n * that are doing ordinary hosted cross-app delegation can set\n * `preferGlobalSecret` so deployments with a shared A2A_SECRET don't depend on\n * every app database having an identical org row. The token contains the\n * caller's email as `sub`, so the receiving app can verify who's calling.\n */\nexport async function signA2AToken(\n email: string,\n orgDomain?: string,\n orgSecret?: string,\n options?: {\n expiresIn?: string | number;\n preferGlobalSecret?: boolean;\n audience?: string | string[];\n /**\n * Extra JWT claims to merge alongside `sub` / `org_domain`. Used by the\n * MCP connect flow to add a revocable `jti` and a `scope: \"mcp-connect\"`\n * marker. Reserved claims (`sub`, `org_domain`) cannot be overridden —\n * they are spread last so a caller can never spoof identity via this map.\n */\n extraClaims?: Record<string, unknown>;\n },\n): Promise<string> {\n const secret = options?.preferGlobalSecret\n ? process.env.A2A_SECRET || orgSecret\n : orgSecret || process.env.A2A_SECRET;\n if (!secret) {\n throw new Error(\n \"No A2A secret available. Set an org-level A2A secret in Team settings, \" +\n \"or set A2A_SECRET as an environment variable on all apps that need to verify identity.\",\n );\n }\n\n const appUrl =\n process.env.APP_URL ||\n process.env.BETTER_AUTH_URL ||\n \"http://localhost:3000\";\n\n const jwt = new jose.SignJWT({\n ...(options?.extraClaims ?? {}),\n // `sub` / `org_domain` are spread AFTER extraClaims so a caller-supplied\n // map can never override the verified identity claims.\n sub: email,\n ...(orgDomain ? { org_domain: orgDomain } : {}),\n })\n .setProtectedHeader({ alg: \"HS256\" })\n .setIssuer(appUrl)\n .setIssuedAt()\n .setExpirationTime(options?.expiresIn ?? \"15m\");\n\n if (options?.audience) jwt.setAudience(options.audience);\n\n return jwt.sign(new TextEncoder().encode(secret));\n}\n\nexport function shouldPreferGlobalA2ASecret(orgSecret?: string): boolean {\n return !!process.env.A2A_SECRET?.trim() || !orgSecret;\n}\n\nexport class A2AClient {\n private baseUrl: string;\n private apiKey?: string;\n private apiKeyAttempts: Array<string | undefined>;\n private endpointCandidates: string[] = [];\n private endpointResolved = false;\n private requestTimeoutMs?: number;\n\n constructor(\n baseUrl: string,\n apiKey?: string,\n options?: { requestTimeoutMs?: number; fallbackApiKeys?: string[] },\n ) {\n const normalized = baseUrl.replace(/\\/$/, \"\");\n const explicitEndpoint = splitExplicitA2AEndpoint(normalized);\n this.baseUrl = explicitEndpoint?.baseUrl ?? normalized;\n if (explicitEndpoint) {\n this.endpointCandidates = [explicitEndpoint.endpointUrl];\n this.endpointResolved = true;\n }\n this.apiKey = apiKey;\n this.apiKeyAttempts = uniqueAuthTokens([\n apiKey,\n ...(options?.fallbackApiKeys ?? []),\n ]);\n this.requestTimeoutMs = options?.requestTimeoutMs;\n }\n\n /**\n * Detect which A2A path the target agent uses.\n * Agent-native apps use /_agent-native/a2a, external agents may use /a2a.\n */\n async resolveEndpoint(): Promise<void> {\n await this.ensureEndpointCandidates();\n if (this.endpointCandidates.length <= 1) return;\n\n for (const endpoint of this.endpointCandidates) {\n try {\n const res = await ssrfSafeFetch(\n endpoint,\n { method: \"OPTIONS\" },\n { maxRedirects: 3, allowedPrivateOrigins: workspacePrivateOrigins() },\n );\n if (res.status !== 404 && res.status !== 405) {\n this.endpointCandidates = [endpoint];\n return;\n }\n if (res.status === 405) {\n this.endpointCandidates = [endpoint];\n return;\n }\n } catch {\n // Try the next candidate.\n }\n }\n }\n\n private headers(apiKey = this.apiKey): Record<string, string> {\n const h: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (apiKey) {\n h[\"Authorization\"] = `Bearer ${apiKey}`;\n }\n return h;\n }\n\n private markApiKeySucceeded(apiKey: string | undefined) {\n this.apiKey = apiKey;\n this.apiKeyAttempts = uniqueAuthTokens([\n apiKey,\n ...this.apiKeyAttempts.filter((token) => token !== apiKey),\n ]);\n }\n\n private async rpc(\n method: string,\n params: Record<string, unknown>,\n options?: { requestTimeoutMs?: number },\n ): Promise<JsonRpcResponse> {\n const body: JsonRpcRequest = {\n jsonrpc: \"2.0\",\n id: Date.now(),\n method,\n params,\n };\n\n await this.ensureEndpointCandidates();\n let lastError: Error | null = null;\n\n for (const url of this.endpointCandidates) {\n for (let i = 0; i < this.apiKeyAttempts.length; i++) {\n console.log(`[A2A Client] POST ${url} method=${method}`);\n const startTime = Date.now();\n const res = await this.postJson(\n url,\n body,\n this.apiKeyAttempts[i],\n options?.requestTimeoutMs,\n );\n console.log(\n `[A2A Client] Response: ${res.status} in ${Date.now() - startTime}ms`,\n );\n\n if (res.ok) {\n const text = await res.text();\n if (\n i < this.apiKeyAttempts.length - 1 &&\n isA2AAuthRejectionResponse(res.status, text)\n ) {\n lastError = new Error(\n `A2A request failed (${res.status}): ${text}`,\n );\n continue;\n }\n this.endpointCandidates = [url];\n this.markApiKeySucceeded(this.apiKeyAttempts[i]);\n return JSON.parse(text) as JsonRpcResponse;\n }\n\n const text = await res.text();\n lastError = new Error(`A2A request failed (${res.status}): ${text}`);\n if (\n i < this.apiKeyAttempts.length - 1 &&\n isA2AAuthRejectionResponse(res.status, text)\n ) {\n continue;\n }\n if (!shouldTryNextEndpoint(res.status)) {\n throw lastError;\n }\n break;\n }\n }\n\n throw lastError ?? new Error(\"No A2A endpoint candidates available\");\n }\n\n async getAgentCard(): Promise<AgentCard> {\n const res = await ssrfSafeFetch(\n `${this.baseUrl}/.well-known/agent-card.json`,\n {},\n { maxRedirects: 3, allowedPrivateOrigins: workspacePrivateOrigins() },\n );\n if (!res.ok) {\n throw new Error(`Failed to fetch agent card (${res.status})`);\n }\n return res.json() as Promise<AgentCard>;\n }\n\n async send(\n message: Message,\n opts?: {\n contextId?: string;\n metadata?: Record<string, unknown>;\n idempotencyKey?: string;\n approvedActions?: A2AApprovedAction[];\n /**\n * If true, ask the server to return the task immediately in `working`\n * state and process the handler in the background. The caller should\n * then poll `getTask(taskId)` until `completed` / `failed` / `canceled`.\n *\n * Use this when you expect the handler may exceed a synchronous\n * serverless request budget.\n */\n async?: boolean;\n },\n ): Promise<Task> {\n const response = await this.rpc(\"message/send\", {\n message,\n contextId: opts?.contextId,\n metadata: opts?.metadata,\n ...(opts?.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : {}),\n ...(opts?.approvedActions?.length\n ? { approvedActions: opts.approvedActions }\n : {}),\n ...(opts?.async ? { async: true } : {}),\n });\n\n if (response.error) {\n throw new Error(\n `A2A error (${response.error.code}): ${response.error.message}`,\n );\n }\n\n return response.result as Task;\n }\n\n /**\n * Poll for a task by id. Used in async mode after `send({ async: true })`.\n */\n async getTask(\n taskId: string,\n opts?: { requestTimeoutMs?: number },\n ): Promise<Task> {\n const response = await this.rpc(\n \"tasks/get\",\n { id: taskId },\n { requestTimeoutMs: opts?.requestTimeoutMs },\n );\n if (response.error) {\n throw new Error(\n `A2A error (${response.error.code}): ${response.error.message}`,\n );\n }\n return response.result as Task;\n }\n\n /**\n * Execute one receiver-approved read-only action without starting the\n * receiver's agent loop. The receiver still owns validation, credentials,\n * request scoping, and the explicit action exposure decision.\n */\n async invokeAction(\n action: string,\n input: Record<string, unknown> = {},\n opts?: { metadata?: A2ACorrelationMetadata },\n ): Promise<A2AReadOnlyActionResult> {\n const metadata = sanitizeA2ACorrelationMetadata(opts?.metadata);\n const response = await this.rpc(\"actions/invoke\", {\n action,\n input,\n ...(Object.keys(metadata).length > 0 ? { metadata } : {}),\n });\n if (response.error) {\n throw new Error(\n `A2A error (${response.error.code}): ${response.error.message}`,\n );\n }\n return response.result as A2AReadOnlyActionResult;\n }\n\n /**\n * Send a message in async mode and poll until the task reaches a terminal\n * state. This is the recommended path on serverless hosts with short\n * function timeouts (Netlify, Vercel) where a synchronous LLM-driven A2A\n * call can exceed the gateway limit.\n *\n * Each individual fetch returns quickly; long-running work happens on the\n * receiving side and is checked via `tasks/get`.\n */\n async sendAndWait(\n message: Message,\n opts?: {\n contextId?: string;\n metadata?: Record<string, unknown>;\n idempotencyKey?: string;\n approvedActions?: A2AApprovedAction[];\n /** Total time to wait for completion. Default 5 min. */\n timeoutMs?: number;\n /** Poll interval. Default 2s. */\n pollIntervalMs?: number;\n /** Called with each polled task — useful for surfacing progress. */\n onUpdate?: (task: Task) => void;\n },\n ): Promise<Task> {\n const submitted = await this.send(message, {\n contextId: opts?.contextId,\n metadata: opts?.metadata,\n idempotencyKey: opts?.idempotencyKey,\n ...(opts?.approvedActions?.length\n ? { approvedActions: opts.approvedActions }\n : {}),\n async: true,\n });\n\n return this.pollTask(submitted, opts);\n }\n\n /**\n * Continue waiting for an existing async task without submitting a second\n * message. Use this after a bounded caller-side wait expires but the remote\n * task is still working.\n */\n async waitForTask(\n taskId: string,\n opts?: {\n /** Total time to wait for completion. Default 5 min. */\n timeoutMs?: number;\n /** Poll interval. Default 2s. */\n pollIntervalMs?: number;\n /** Called with each successfully polled task. */\n onUpdate?: (task: Task) => void;\n },\n ): Promise<Task> {\n const current = await this.getTask(taskId);\n opts?.onUpdate?.(current);\n return this.pollTask(current, opts);\n }\n\n private async pollTask(\n submitted: Task,\n opts?: {\n timeoutMs?: number;\n pollIntervalMs?: number;\n onUpdate?: (task: Task) => void;\n },\n ): Promise<Task> {\n const terminalStates = new Set([\n \"completed\",\n \"failed\",\n \"canceled\",\n \"input-required\",\n ]);\n if (terminalStates.has(submitted.status.state)) return submitted;\n\n const timeoutMs = opts?.timeoutMs ?? 5 * 60_000;\n const pollMs = opts?.pollIntervalMs ?? 2_000;\n const deadline = Date.now() + timeoutMs;\n\n let current = submitted;\n while (Date.now() < deadline) {\n const sleepMs = Math.min(pollMs, Math.max(0, deadline - Date.now()));\n await new Promise((r) => setTimeout(r, sleepMs));\n const remainingMs = deadline - Date.now();\n if (remainingMs <= 0) break;\n try {\n current = await this.getTask(submitted.id, {\n requestTimeoutMs: Math.min(\n this.requestTimeoutMs ?? DEFAULT_A2A_POLL_REQUEST_TIMEOUT_MS,\n remainingMs,\n ),\n });\n opts?.onUpdate?.(current);\n } catch {\n // Transient fetch failure — keep polling until the deadline.\n continue;\n }\n if (terminalStates.has(current.status.state)) return current;\n }\n throw new A2ATaskTimeoutError(submitted.id, current, timeoutMs);\n }\n\n async *stream(\n message: Message,\n opts?: { contextId?: string; metadata?: Record<string, unknown> },\n ): AsyncGenerator<Task> {\n const body: JsonRpcRequest = {\n jsonrpc: \"2.0\",\n id: Date.now(),\n method: \"message/stream\",\n params: {\n message,\n contextId: opts?.contextId,\n metadata: opts?.metadata,\n },\n };\n\n await this.ensureEndpointCandidates();\n let res: Response | null = null;\n let lastError: Error | null = null;\n for (const candidate of this.endpointCandidates) {\n for (let i = 0; i < this.apiKeyAttempts.length; i++) {\n res = await this.postJson(candidate, body, this.apiKeyAttempts[i]);\n if (res.ok) {\n this.endpointCandidates = [candidate];\n this.markApiKeySucceeded(this.apiKeyAttempts[i]);\n break;\n }\n const text = await res.text();\n lastError = new Error(`A2A stream failed (${res.status}): ${text}`);\n if (\n i < this.apiKeyAttempts.length - 1 &&\n isA2AAuthRejectionResponse(res.status, text)\n ) {\n continue;\n }\n if (!shouldTryNextEndpoint(res.status)) throw lastError;\n break;\n }\n if (res?.ok) break;\n }\n if (!res?.ok) {\n throw lastError ?? new Error(\"No A2A endpoint candidates available\");\n }\n\n const reader = res.body?.getReader();\n if (!reader) throw new Error(\"No response body\");\n\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const json = line.slice(6).trim();\n if (!json) continue;\n\n const response: JsonRpcResponse = JSON.parse(json);\n if (response.error) {\n throw new Error(\n `A2A error (${response.error.code}): ${response.error.message}`,\n );\n }\n if (response.result) {\n yield response.result as Task;\n }\n }\n }\n }\n\n private async ensureEndpointCandidates(): Promise<void> {\n if (this.endpointResolved) return;\n this.endpointResolved = true;\n\n const candidates: string[] = [];\n addDefaultEndpointCandidates(candidates, this.baseUrl);\n\n try {\n const card = await this.getAgentCard();\n const cardUrl = normalizeUrl(card.url, this.baseUrl);\n if (cardUrl) {\n const explicitEndpoint = splitExplicitA2AEndpoint(cardUrl);\n if (explicitEndpoint) {\n candidates.unshift(explicitEndpoint.endpointUrl);\n } else {\n addDefaultEndpointCandidates(candidates, cardUrl);\n }\n }\n } catch {\n // Agent cards are discovery hints. Fall back to conventional endpoints.\n }\n\n this.endpointCandidates = unique(candidates);\n }\n\n private async postJson(\n url: string,\n body: JsonRpcRequest,\n apiKey = this.apiKey,\n requestTimeoutMs = this.requestTimeoutMs,\n ): Promise<Response> {\n const controller = requestTimeoutMs ? new AbortController() : undefined;\n const timer =\n controller && requestTimeoutMs\n ? setTimeout(() => controller.abort(), requestTimeoutMs)\n : undefined;\n try {\n return await ssrfSafeFetch(\n url,\n {\n method: \"POST\",\n headers: this.headers(apiKey),\n body: JSON.stringify(body),\n signal: controller?.signal,\n },\n { maxRedirects: 3, allowedPrivateOrigins: workspacePrivateOrigins() },\n );\n } finally {\n if (timer) clearTimeout(timer);\n }\n }\n}\n\nfunction splitExplicitA2AEndpoint(\n url: string,\n): { baseUrl: string; endpointUrl: string } | null {\n try {\n const parsed = new URL(url);\n const pathname = parsed.pathname.replace(/\\/$/, \"\");\n if (pathname.endsWith(\"/_agent-native/a2a\")) {\n parsed.pathname = pathname.slice(0, -\"/_agent-native/a2a\".length) || \"/\";\n parsed.search = \"\";\n parsed.hash = \"\";\n return {\n baseUrl: parsed.toString().replace(/\\/$/, \"\"),\n endpointUrl: url,\n };\n }\n if (pathname.endsWith(\"/a2a\")) {\n parsed.pathname = pathname.slice(0, -\"/a2a\".length) || \"/\";\n parsed.search = \"\";\n parsed.hash = \"\";\n return {\n baseUrl: parsed.toString().replace(/\\/$/, \"\"),\n endpointUrl: url,\n };\n }\n } catch {\n // Relative or invalid URLs are handled by the caller's normal fetch path.\n }\n return null;\n}\n\nfunction addDefaultEndpointCandidates(candidates: string[], baseUrl: string) {\n const base = baseUrl.replace(/\\/$/, \"\");\n candidates.push(`${base}/_agent-native/a2a`, `${base}/a2a`);\n}\n\nfunction normalizeUrl(\n value: string | undefined,\n baseUrl: string,\n): string | null {\n if (!value) return null;\n try {\n return new URL(value, `${baseUrl.replace(/\\/$/, \"\")}/`)\n .toString()\n .replace(/\\/$/, \"\");\n } catch {\n return null;\n }\n}\n\nfunction shouldTryNextEndpoint(status: number): boolean {\n return status === 404 || status === 405;\n}\n\nfunction unique(values: string[]): string[] {\n return Array.from(new Set(values));\n}\n\nfunction uniqueAuthTokens(\n values: Array<string | undefined>,\n): Array<string | undefined> {\n const result: Array<string | undefined> = [];\n for (const value of values) {\n if (result.includes(value)) continue;\n result.push(value);\n }\n if (result.length === 0) result.push(undefined);\n return result;\n}\n\nfunction isA2AAuthRejectionResponse(status: number, text: string): boolean {\n return (\n status === 401 ||\n /verified, audience-bound user identity/i.test(text) ||\n /A2A error \\(-32001\\): (?:Invalid or expired A2A token|Invalid API key|Authentication required)|Invalid or expired A2A token|Invalid API key|Authentication required/i.test(\n text,\n )\n );\n}\n\n/**\n * One-shot convenience function: send a text message and get a text response.\n *\n * When A2A_SECRET is set and userEmail is provided, outbound calls are signed\n * with a JWT so the receiving app can cryptographically verify the caller's\n * identity (instead of blindly trusting metadata).\n */\nexport async function callAgent(\n url: string,\n text: string,\n opts?: {\n apiKey?: string;\n /** Additional bearer tokens to try in order after apiKey during rotation. */\n apiKeyFallbacks?: string[];\n /** Additional transport metadata. Receivers must not use it as identity. */\n metadata?: Record<string, unknown>;\n contextId?: string;\n userEmail?: string;\n orgDomain?: string;\n orgSecret?: string;\n /** Origin used to build links back to the receiving app. */\n requestOrigin?: string;\n /** Exact downstream actions explicitly authorized in the caller's chat. */\n approvedActions?: A2AApprovedAction[];\n /** Opaque provenance reference resolved by the receiver through Dispatch. */\n sourceContext?: A2ASourceContextReference;\n /** Bounded telemetry-only lineage forwarded to the receiving app. */\n correlation?: A2ACorrelationMetadata;\n /** Stable caller-generated key for one message submission. */\n idempotencyKey?: string;\n /**\n * Use async/poll instead of a single blocking POST. Recommended for\n * cross-app calls that may exceed a synchronous serverless request budget.\n * Defaults to true so callers get safe behavior out of the box.\n */\n async?: boolean;\n /** Total time to wait for the polled task (default 5 min). */\n timeoutMs?: number;\n /**\n * Existing async task to keep polling. When set, no new message is sent.\n * This prevents a caller-side timeout from duplicating downstream work.\n */\n taskId?: string;\n /** Poll interval for async calls. Primarily useful for tests/retries. */\n pollIntervalMs?: number;\n /**\n * Return receiver-verified artifact text from the last polled task when\n * the call times out. Defaults to true for backwards compatibility.\n * Callers that can continue polling the remote task separately should set\n * this to false so the A2ATaskTimeoutError (and its taskId) is preserved.\n */\n returnRecoverableArtifactsOnTimeout?: boolean;\n /**\n * Called with each successfully polled task while an async call is still\n * in flight (see `A2AClient.sendAndWait`). Fires once per real poll\n * round-trip that returns a task — including the terminal poll — so\n * callers can surface genuine remote liveness/progress. Not called when a\n * poll fetch throws (remote unresponsive) or when the task completes\n * synchronously on submit. Only threaded through for async calls.\n */\n onUpdate?: (task: Task) => void;\n },\n): Promise<string> {\n const metadata: Record<string, unknown> = { ...opts?.metadata };\n if (opts?.userEmail) metadata.userEmail = opts.userEmail;\n if (opts?.orgDomain) metadata.orgDomain = opts.orgDomain;\n if (opts?.requestOrigin) metadata.requestOrigin = opts.requestOrigin;\n if (opts?.sourceContext) metadata.sourceContext = opts.sourceContext;\n Object.assign(metadata, sanitizeA2ACorrelationMetadata(opts?.correlation));\n\n // Default to async + poll. The receiving A2A server's `_process-task` route\n // runs the handler in a fresh function execution (cross-platform queue\n // pattern), so async mode now works on every host instead of relying on\n // detached promises that get killed on Netlify/Vercel. Callers that\n // explicitly want a single-shot blocking POST can pass `async: false`.\n const useAsync = opts?.async ?? true;\n const message: Message = {\n role: \"user\",\n parts: [{ type: \"text\", text }],\n };\n\n const apiKeyAttempts = await buildA2AApiKeyAttempts(opts);\n let lastAuthError: unknown;\n\n for (let i = 0; i < apiKeyAttempts.length; i++) {\n try {\n const fallbackApiKeys = apiKeyAttempts\n .slice(i + 1)\n .filter((token): token is string => token !== undefined);\n const client = new A2AClient(url, apiKeyAttempts[i], {\n fallbackApiKeys,\n });\n let task: Task;\n if (useAsync) {\n task = opts?.taskId\n ? await client.waitForTask(opts.taskId, {\n timeoutMs: opts.timeoutMs,\n pollIntervalMs: opts.pollIntervalMs,\n onUpdate: opts.onUpdate,\n })\n : await client.sendAndWait(message, {\n contextId: opts?.contextId,\n metadata,\n idempotencyKey: opts?.idempotencyKey,\n ...(opts?.approvedActions?.length\n ? { approvedActions: opts.approvedActions }\n : {}),\n timeoutMs: opts?.timeoutMs,\n pollIntervalMs: opts?.pollIntervalMs,\n onUpdate: opts?.onUpdate,\n });\n } else {\n if (opts?.taskId) {\n throw new Error(\"Polling an existing A2A task requires async mode\");\n }\n task = await client.send(message, {\n contextId: opts?.contextId,\n metadata,\n idempotencyKey: opts?.idempotencyKey,\n ...(opts?.approvedActions?.length\n ? { approvedActions: opts.approvedActions }\n : {}),\n });\n }\n\n // Extract text from the response\n const responseMessage = task.status.message;\n if (responseMessage) {\n const textParts = responseMessage.parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text);\n return textParts.join(\"\\n\");\n }\n\n return \"\";\n } catch (err) {\n if (\n opts?.returnRecoverableArtifactsOnTimeout !== false &&\n err instanceof A2ATaskTimeoutError\n ) {\n const recoverableText = extractRecoverableArtifactText(err.lastTask);\n if (recoverableText) return recoverableText;\n }\n if (i < apiKeyAttempts.length - 1 && isA2AAuthRejection(err)) {\n lastAuthError = err;\n continue;\n }\n throw err;\n }\n }\n\n if (lastAuthError) throw lastAuthError;\n return \"\";\n}\n\n/**\n * Invoke one receiver-approved read-only action with an audience-bound user\n * token. Unlike conversational delegation, this never starts the receiver's\n * model loop.\n */\nexport async function callAction(\n url: string,\n action: string,\n input: Record<string, unknown> = {},\n opts?: {\n apiKey?: string;\n userEmail?: string;\n orgDomain?: string;\n orgSecret?: string;\n requestTimeoutMs?: number;\n correlation?: A2ACorrelationMetadata;\n },\n): Promise<A2AReadOnlyActionResult> {\n const actionName = action.trim();\n if (!actionName) throw new Error(\"A2A action name is required\");\n if (!input || typeof input !== \"object\" || Array.isArray(input)) {\n throw new Error(\"A2A action input must be an object\");\n }\n\n const apiKeyAttempts = await buildA2AApiKeyAttempts(\n opts,\n normalizeA2AAudience(url),\n );\n const fallbackApiKeys = apiKeyAttempts\n .slice(1)\n .filter((token): token is string => token !== undefined);\n const client = new A2AClient(url, apiKeyAttempts[0], {\n fallbackApiKeys,\n requestTimeoutMs: opts?.requestTimeoutMs,\n });\n return client.invokeAction(actionName, input, {\n metadata: sanitizeA2ACorrelationMetadata(opts?.correlation),\n });\n}\n\nasync function buildA2AApiKeyAttempts(\n opts?: {\n apiKey?: string;\n apiKeyFallbacks?: string[];\n userEmail?: string;\n orgDomain?: string;\n orgSecret?: string;\n },\n audience?: string,\n): Promise<Array<string | undefined>> {\n const attempts: Array<string | undefined> = [];\n const add = (token: string | undefined) => {\n if (token === undefined || attempts.includes(token)) return;\n attempts.push(token);\n };\n\n add(opts?.apiKey);\n for (const fallback of opts?.apiKeyFallbacks ?? []) add(fallback);\n\n if (opts?.userEmail && (opts.orgSecret || process.env.A2A_SECRET)) {\n if (process.env.A2A_SECRET?.trim()) {\n try {\n add(\n await signA2AToken(opts.userEmail, opts.orgDomain, opts.orgSecret, {\n preferGlobalSecret: true,\n audience,\n }),\n );\n } catch {\n // Keep any explicit token attempt, then fall back below.\n }\n }\n\n if (opts.orgSecret) {\n try {\n add(\n await signA2AToken(opts.userEmail, opts.orgDomain, opts.orgSecret, {\n preferGlobalSecret: false,\n audience,\n }),\n );\n } catch {\n // Fall through to the attempts we already have.\n }\n }\n }\n\n if (attempts.length === 0) attempts.push(undefined);\n return attempts;\n}\n\nfunction normalizeA2AAudience(url: string): string {\n const explicit = splitExplicitA2AEndpoint(url.replace(/\\/$/, \"\"));\n const base = (explicit?.baseUrl ?? url).replace(/\\/$/, \"\");\n // Receivers derive their expected audience from APP_URL, which carries no\n // app path. In a workspace every app is mounted under one gateway origin, so\n // signing the path-qualified URL yields an audience the receiver can never\n // match. The origin is the identifier both sides agree on.\n try {\n return new URL(base).origin;\n } catch {\n return base;\n }\n}\n\nfunction isA2AAuthRejection(err: unknown): boolean {\n const message = err instanceof Error ? err.message : String(err ?? \"\");\n return /A2A request failed \\(401\\)|A2A error \\(-32001\\): (?:Invalid or expired A2A token|Invalid API key|Authentication required)|Invalid or expired A2A token|Invalid API key|Authentication required/i.test(\n message,\n );\n}\n\nfunction extractRecoverableArtifactText(task: Task): string {\n if (!task.status.message?.metadata?.agentNativeRecoverableArtifacts) {\n return \"\";\n }\n return extractMessageText(task.status.message);\n}\n\nfunction extractMessageText(message: Message): string {\n return message.parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\\n\");\n}\n"]}
@@ -15,6 +15,7 @@
15
15
  import type { AgentEngine, EngineCapabilities } from "./types.js";
16
16
  export declare const BUILDER_CAPABILITIES: EngineCapabilities;
17
17
  export declare const BUILDER_SUPPORTED_MODELS: readonly ["auto", string, "gpt-5-6-terra", "gpt-5-6-sol", "claude-haiku-4-5", "claude-sonnet-4-6" | "claude-sonnet-5", "claude-opus-4-8", "gemini-3-5-flash", "gemini-3-1-pro"];
18
+ export declare const BUILDER_MODEL_UNAUTHORIZED_ERROR_CODE = "builder_model_unauthorized";
18
19
  export declare const BUILDER_DEFAULT_MODEL: string;
19
20
  export declare function createBuilderEngine(_config?: Record<string, unknown>): AgentEngine;
20
21
  //# sourceMappingURL=builder-engine.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"builder-engine.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/builder-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AA2BH,OAAO,KAAK,EACV,WAAW,EACX,kBAAkB,EAInB,MAAM,YAAY,CAAC;AAEpB,eAAO,MAAM,oBAAoB,EAAE,kBAMlC,CAAC;AAEF,eAAO,MAAM,wBAAwB,iLAAuC,CAAC;AAkB7E,eAAO,MAAM,qBAAqB,QAAoC,CAAC;AA6vBvE,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GACpC,WAAW,CAEb"}
1
+ {"version":3,"file":"builder-engine.d.ts","sourceRoot":"","sources":["../../../src/agent/engine/builder-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AA2BH,OAAO,KAAK,EACV,WAAW,EACX,kBAAkB,EAInB,MAAM,YAAY,CAAC;AAEpB,eAAO,MAAM,oBAAoB,EAAE,kBAMlC,CAAC;AAEF,eAAO,MAAM,wBAAwB,iLAAuC,CAAC;AAiB7E,eAAO,MAAM,qCAAqC,+BACpB,CAAC;AAE/B,eAAO,MAAM,qBAAqB,QAAoC,CAAC;AAuwBvE,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GACpC,WAAW,CAEb"}
@@ -45,6 +45,7 @@ const MAX_BACKGROUND_BUILDER_GATEWAY_TIMEOUT_MS = 14 * 60_000;
45
45
  /** Local and non-hosted runtimes have no synchronous serverless wall. */
46
46
  const MAX_LOCAL_BUILDER_GATEWAY_TIMEOUT_MS = MAX_BACKGROUND_BUILDER_GATEWAY_TIMEOUT_MS;
47
47
  const BUILDER_GATEWAY_NETWORK_ERROR_CODE = "builder_gateway_network_error";
48
+ export const BUILDER_MODEL_UNAUTHORIZED_ERROR_CODE = "builder_model_unauthorized";
48
49
  export const BUILDER_DEFAULT_MODEL = BUILDER_MODEL_CONFIG.defaultModel;
49
50
  /**
50
51
  * Bucket an Anthropic `thinking.budgetTokens` value into the gateway's
@@ -559,7 +560,14 @@ async function* parseJsonlStream(reader, model, captureContext = {}) {
559
560
  const errMsg = explicitErrMsg ??
560
561
  `Gateway error (no detail; raw event: ${JSON.stringify(event)})`;
561
562
  const gatewayErrCode = event.errorCode ?? event.code;
563
+ // The gateway already authenticated this request before streaming,
564
+ // so a bare "Unauthorized" here means the account cannot use this
565
+ // model — not that the connection is broken. Only a message that
566
+ // names the credential may tear down the Builder connection.
562
567
  const isCredentialAuthError = Boolean(explicitErrMsg) &&
568
+ isBuilderCredentialAuthErrorInStream(String(errMsg));
569
+ const isModelAuthError = Boolean(explicitErrMsg) &&
570
+ !isCredentialAuthError &&
563
571
  isBuilderCredentialAuthError(String(errMsg));
564
572
  // Anthropic's bare "Connection error." often arrives here with no
565
573
  // gateway code. Tag it as a network error so in-run retries and
@@ -568,10 +576,12 @@ async function* parseJsonlStream(reader, model, captureContext = {}) {
568
576
  isProviderConnectionErrorMessage(String(explicitErrMsg));
569
577
  const errCode = isCredentialAuthError
570
578
  ? "builder_auth_error"
571
- : isProviderConnectionError
572
- ? BUILDER_GATEWAY_NETWORK_ERROR_CODE
573
- : (gatewayErrCode ??
574
- (!explicitErrMsg ? "builder_gateway_error" : undefined));
579
+ : isModelAuthError
580
+ ? BUILDER_MODEL_UNAUTHORIZED_ERROR_CODE
581
+ : isProviderConnectionError
582
+ ? BUILDER_GATEWAY_NETWORK_ERROR_CODE
583
+ : (gatewayErrCode ??
584
+ (!explicitErrMsg ? "builder_gateway_error" : undefined));
575
585
  console.error(`[builder-engine] stop reason=error model=${model} code=${errCode ?? "(none)"} error=${errMsg}`);
576
586
  if (isCredentialAuthError) {
577
587
  await recordBuilderCredentialAuthFailure({
@@ -826,6 +836,23 @@ function isBuilderCredentialAuthError(message) {
826
836
  lowerMessage.includes("token invalid") ||
827
837
  (referencesAccessToken && rejectedToken));
828
838
  }
839
+ /**
840
+ * Stricter than {@link isBuilderCredentialAuthError} for errors that arrive
841
+ * inside an already-authenticated stream, where a bare "unauthorized" is far
842
+ * more likely to be a per-model entitlement rejection than a bad credential.
843
+ * Misreading one there disconnects Builder for every model, including the ones
844
+ * that still work.
845
+ */
846
+ function isBuilderCredentialAuthErrorInStream(message) {
847
+ if (!isBuilderCredentialAuthError(message))
848
+ return false;
849
+ const lowerMessage = message.toLowerCase();
850
+ return (lowerMessage.includes("private key") ||
851
+ lowerMessage.includes("access token") ||
852
+ lowerMessage.includes("invalid token") ||
853
+ lowerMessage.includes("invalid_token") ||
854
+ lowerMessage.includes("token invalid"));
855
+ }
829
856
  function normalizeBuilderGatewayFetchError(err, timedOut, timeoutMs) {
830
857
  if (timedOut) {
831
858
  return `Builder gateway timed out after ${formatTimeoutMs(timeoutMs)} before the hosting function limit. Please retry; if this keeps happening, reduce the prompt size or try again when the gateway is less busy.`;