@agent-native/core 0.108.0 → 0.109.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 (368) hide show
  1. package/corpus/README.md +2 -2
  2. package/corpus/core/CHANGELOG.md +25 -0
  3. package/corpus/core/package.json +1 -1
  4. package/corpus/core/src/a2a/client.ts +162 -17
  5. package/corpus/core/src/a2a/correlation.ts +50 -0
  6. package/corpus/core/src/a2a/handlers.ts +200 -14
  7. package/corpus/core/src/a2a/index.ts +7 -1
  8. package/corpus/core/src/a2a/invoke.ts +77 -1
  9. package/corpus/core/src/a2a/server.ts +13 -1
  10. package/corpus/core/src/a2a/task-store.ts +146 -6
  11. package/corpus/core/src/a2a/types.ts +32 -0
  12. package/corpus/core/src/action.ts +5 -2
  13. package/corpus/core/src/agent/production-agent.ts +33 -4
  14. package/corpus/core/src/client/AssistantChat.tsx +648 -603
  15. package/corpus/core/src/client/MultiTabAssistantChat.tsx +31 -4
  16. package/corpus/core/src/client/agent-chat-adapter.ts +23 -37
  17. package/corpus/core/src/client/agent-sidebar-state.ts +4 -0
  18. package/corpus/core/src/client/analytics.ts +84 -0
  19. package/corpus/core/src/client/chat/message-components.tsx +94 -22
  20. package/corpus/core/src/client/chat/tool-call-display.tsx +170 -47
  21. package/corpus/core/src/client/chat/use-agent-chat-lifecycle-tracking.ts +74 -0
  22. package/corpus/core/src/client/chat-thread-url.ts +11 -0
  23. package/corpus/core/src/client/error-capture.ts +12 -0
  24. package/corpus/core/src/client/extensions/ExtensionSlot.tsx +37 -1
  25. package/corpus/core/src/client/index.ts +2 -0
  26. package/corpus/core/src/client/route-chunk-recovery.ts +20 -8
  27. package/corpus/core/src/client/session-replay.ts +31 -0
  28. package/corpus/core/src/client/use-run-stuck-detection.ts +27 -1
  29. package/corpus/core/src/db/client.ts +55 -0
  30. package/corpus/core/src/extensions/actions.ts +2 -14
  31. package/corpus/core/src/extensions/store.ts +1 -1
  32. package/corpus/core/src/localization/default-messages.ts +3 -0
  33. package/corpus/core/src/mcp/build-server.ts +2 -2
  34. package/corpus/core/src/observability/traces.ts +172 -19
  35. package/corpus/core/src/progress/actions.ts +4 -2
  36. package/corpus/core/src/provider-api/index.ts +205 -105
  37. package/corpus/core/src/scripts/call-agent.ts +190 -19
  38. package/corpus/core/src/server/agent-chat/action-filters-a2a.ts +112 -25
  39. package/corpus/core/src/server/agent-chat-plugin.ts +136 -4
  40. package/corpus/core/src/styles/agent-conversation.css +7 -0
  41. package/corpus/core/src/templates/default/app/i18n/ar-SA.ts +20 -0
  42. package/corpus/core/src/templates/default/app/i18n/de-DE.ts +20 -0
  43. package/corpus/core/src/templates/default/app/i18n/en-US.ts +20 -0
  44. package/corpus/core/src/templates/default/app/i18n/es-ES.ts +20 -0
  45. package/corpus/core/src/templates/default/app/i18n/fr-FR.ts +21 -0
  46. package/corpus/core/src/templates/default/app/i18n/hi-IN.ts +19 -0
  47. package/corpus/core/src/templates/default/app/i18n/ja-JP.ts +20 -0
  48. package/corpus/core/src/templates/default/app/i18n/ko-KR.ts +19 -0
  49. package/corpus/core/src/templates/default/app/i18n/pt-BR.ts +20 -0
  50. package/corpus/core/src/templates/default/app/i18n/zh-CN.ts +19 -0
  51. package/corpus/core/src/templates/default/app/i18n/zh-TW.ts +19 -0
  52. package/corpus/core/src/templates/workspace-core/.agents/skills/a2a-protocol/SKILL.md +49 -0
  53. package/corpus/core/src/templates/workspace-core/.agents/skills/composable-mini-apps/SKILL.md +5 -0
  54. package/corpus/core/src/templates/workspace-core/.agents/skills/observability/SKILL.md +7 -1
  55. package/corpus/core/src/templates/workspace-core/.agents/skills/performance/SKILL.md +13 -0
  56. package/corpus/core/src/templates/workspace-core/.agents/skills/tracking/SKILL.md +1 -1
  57. package/corpus/templates/analytics/.agents/skills/dashboard-management/SKILL.md +29 -10
  58. package/corpus/templates/analytics/.agents/skills/gong/SKILL.md +54 -23
  59. package/corpus/templates/analytics/.builder/skills/apollo/SKILL.md +19 -41
  60. package/corpus/templates/analytics/.builder/skills/commonroom/SKILL.md +20 -35
  61. package/corpus/templates/analytics/.builder/skills/github/SKILL.md +23 -67
  62. package/corpus/templates/analytics/.builder/skills/pylon/SKILL.md +25 -43
  63. package/corpus/templates/analytics/AGENTS.md +22 -13
  64. package/corpus/templates/analytics/actions/account-deep-dive.ts +1 -0
  65. package/corpus/templates/analytics/actions/configure-gong-native-insights.ts +29 -0
  66. package/corpus/templates/analytics/actions/content-calendar-schema.ts +8 -4
  67. package/corpus/templates/analytics/actions/content-calendar.ts +12 -4
  68. package/corpus/templates/analytics/actions/dashboard-mutation-api.ts +2 -1
  69. package/corpus/templates/analytics/actions/gong-calls.ts +113 -22
  70. package/corpus/templates/analytics/actions/gong-native-insights.ts +166 -0
  71. package/corpus/templates/analytics/actions/hubspot-deals.ts +190 -46
  72. package/corpus/templates/analytics/actions/pylon-issues.ts +123 -0
  73. package/corpus/templates/analytics/actions/query-agent-native-analytics.ts +1 -1
  74. package/corpus/templates/analytics/actions/slack-messages.ts +179 -27
  75. package/corpus/templates/analytics/app/components/dashboard/SqlChart.tsx +48 -152
  76. package/corpus/templates/analytics/app/components/ui/chart.tsx +1 -1
  77. package/corpus/templates/analytics/app/hooks/use-chart-tooltip-flip.ts +21 -6
  78. package/corpus/templates/analytics/app/i18n/zh-TW.ts +13 -0
  79. package/corpus/templates/analytics/app/i18n-data.ts +134 -0
  80. package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/PanelEditorDialog.tsx +181 -30
  81. package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/SqlChartCard.tsx +6 -0
  82. package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/types.ts +4 -3
  83. package/corpus/templates/analytics/changelog/2026-07-17-analytics-now-includes-a-default-alert-for-spikes-in-stuck-agent-chats.md +6 -0
  84. package/corpus/templates/analytics/changelog/2026-07-17-dashboard-editors-can-add-shared-extensions-or-opt-into-per-.md +6 -0
  85. package/corpus/templates/analytics/changelog/2026-07-17-dashboard-extensions-show-a-loading-skeleton.md +6 -0
  86. package/corpus/templates/analytics/changelog/2026-07-17-errors-now-group-repeat-failures-consistently-and-keep-priva.md +6 -0
  87. package/corpus/templates/analytics/changelog/2026-07-17-gong-transcript-reviews-now-batch-bounded-call-windows-for-f.md +6 -0
  88. package/corpus/templates/analytics/changelog/2026-07-17-hubspot-deal-filters-now-run-in-hubspot-before-paging-result.md +6 -0
  89. package/corpus/templates/analytics/changelog/2026-07-17-notion-content-calendars-now-discover-the-matching-database-.md +6 -0
  90. package/corpus/templates/analytics/changelog/2026-07-17-pylon-dashboard-reads-now-use-the-paginated-issue-search-api.md +6 -0
  91. package/corpus/templates/analytics/changelog/2026-07-17-slack-reads-no-longer-join-channels-and-report-pagination-coverage.md +6 -0
  92. package/corpus/templates/analytics/docs/schemas/first-party-analytics.md +23 -14
  93. package/corpus/templates/analytics/docs/schemas/tracked-events.md +5 -1
  94. package/corpus/templates/analytics/server/handlers/notion.ts +14 -3
  95. package/corpus/templates/analytics/server/handlers/slack.ts +182 -29
  96. package/corpus/templates/analytics/server/jobs/analytics-alerts.ts +3 -3
  97. package/corpus/templates/analytics/server/lib/agent-chat-plan-mode.ts +2 -6
  98. package/corpus/templates/analytics/server/lib/analytics-alerts.ts +209 -87
  99. package/corpus/templates/analytics/server/lib/analytics-connector-catalog.ts +6 -2
  100. package/corpus/templates/analytics/server/lib/error-capture.ts +75 -8
  101. package/corpus/templates/analytics/server/lib/gong-native-policy.ts +72 -0
  102. package/corpus/templates/analytics/server/lib/gong.ts +54 -66
  103. package/corpus/templates/analytics/server/lib/hubspot.ts +40 -3
  104. package/corpus/templates/analytics/server/lib/notion.ts +83 -8
  105. package/corpus/templates/analytics/server/lib/real-data-actions.ts +4 -0
  106. package/corpus/templates/analytics/server/lib/slack.ts +242 -90
  107. package/corpus/templates/analytics/server/plugins/agent-chat.ts +3 -3
  108. package/corpus/templates/analytics/server/routes/api/pylon/accounts.get.ts +42 -1
  109. package/corpus/templates/analytics/server/routes/api/pylon/issues.get.ts +71 -1
  110. package/corpus/templates/analytics/server/routes/api/test-connection.post.ts +44 -4
  111. package/corpus/templates/clips/actions/finalize-recording.ts +541 -62
  112. package/corpus/templates/clips/app/components/library/bulk-action-toolbar.tsx +19 -1
  113. package/corpus/templates/clips/app/components/library/create-folder-dialog.tsx +123 -0
  114. package/corpus/templates/clips/app/components/library/library-grid.tsx +42 -4
  115. package/corpus/templates/clips/app/components/library/recording-card.tsx +30 -0
  116. package/corpus/templates/clips/app/components/player/playback-comment-overlay.tsx +17 -2
  117. package/corpus/templates/clips/app/components/player/video-player.tsx +14 -2
  118. package/corpus/templates/clips/app/components/recorder/recorder-engine.ts +2 -2
  119. package/corpus/templates/clips/app/entry.client.tsx +6 -1
  120. package/corpus/templates/clips/app/i18n/ar-SA.ts +12 -1
  121. package/corpus/templates/clips/app/i18n/de-DE.ts +12 -1
  122. package/corpus/templates/clips/app/i18n/en-US.ts +12 -1
  123. package/corpus/templates/clips/app/i18n/es-ES.ts +11 -1
  124. package/corpus/templates/clips/app/i18n/fr-FR.ts +11 -1
  125. package/corpus/templates/clips/app/i18n/hi-IN.ts +10 -1
  126. package/corpus/templates/clips/app/i18n/ja-JP.ts +12 -1
  127. package/corpus/templates/clips/app/i18n/ko-KR.ts +11 -1
  128. package/corpus/templates/clips/app/i18n/pt-BR.ts +11 -1
  129. package/corpus/templates/clips/app/i18n/zh-CN.ts +11 -1
  130. package/corpus/templates/clips/app/i18n/zh-TW.ts +11 -1
  131. package/corpus/templates/clips/app/routes/_app.settings._index.tsx +72 -1
  132. package/corpus/templates/clips/app/routes/r.$recordingId.tsx +1 -1
  133. package/corpus/templates/clips/app/routes/record.tsx +3 -3
  134. package/corpus/templates/clips/app/routes/share.$shareId.tsx +6 -3
  135. package/corpus/templates/clips/changelog/2026-07-17-choose-which-workspace-receives-new-clips-recordings-and-des.md +6 -0
  136. package/corpus/templates/clips/changelog/2026-07-17-clips-now-retries-storage-verification-in-the-background-ins.md +6 -0
  137. package/corpus/templates/clips/changelog/2026-07-17-create-folders-directly-from-the-move-menu.md +6 -0
  138. package/corpus/templates/clips/changelog/2026-07-17-failed-desktop-uploads-now-offer-a-direct-way-to-reopen-clip.md +6 -0
  139. package/corpus/templates/clips/changelog/2026-07-17-fixed-broken-thumbnail-icons-appearing-over-playable-clip-em.md +6 -0
  140. package/corpus/templates/clips/changelog/2026-07-17-playback-comments-stay-readable-at-faster-playback-speeds.md +6 -0
  141. package/corpus/templates/clips/chrome-extension/src/finalize-recovery.ts +3 -0
  142. package/corpus/templates/clips/chrome-extension/src/offscreen.ts +3 -3
  143. package/corpus/templates/clips/desktop/src/app.tsx +19 -7
  144. package/corpus/templates/clips/desktop/src/lib/recorder.ts +111 -13
  145. package/corpus/templates/clips/desktop/src/lib/upload-verification.ts +16 -7
  146. package/corpus/templates/clips/desktop/src-tauri/src/lib.rs +2 -4
  147. package/corpus/templates/clips/desktop/src-tauri/src/native_screen/live_upload.rs +32 -15
  148. package/corpus/templates/clips/desktop/src-tauri/src/native_screen.rs +45 -18
  149. package/corpus/templates/clips/server/jobs/media-verification.ts +130 -0
  150. package/corpus/templates/clips/server/lib/builder-media-compression.ts +15 -0
  151. package/corpus/templates/clips/server/lib/media-verification-state.ts +38 -0
  152. package/corpus/templates/clips/server/lib/player-thumbnail-url.ts +31 -0
  153. package/corpus/templates/clips/server/lib/post-finalize-dispatch.ts +10 -3
  154. package/corpus/templates/clips/server/plugins/auth.ts +5 -5
  155. package/corpus/templates/clips/server/plugins/calendar-jobs.ts +2 -0
  156. package/corpus/templates/clips/server/routes/api/_agent-native-background/post-finalize-worker.post.ts +12 -2
  157. package/corpus/templates/clips/server/routes/api/public-recording.get.ts +6 -1
  158. package/corpus/templates/clips/server/routes/api/thumbnail/[recordingId].get.ts +340 -0
  159. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/abort.post.ts +24 -7
  160. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/chunk.post.ts +91 -7
  161. package/corpus/templates/clips/server/routes/api/uploads/[recordingId]/status.get.ts +14 -0
  162. package/corpus/templates/clips/shared/finalize-recovery.ts +61 -2
  163. package/corpus/templates/clips/shared/share-meta.ts +1 -1
  164. package/corpus/templates/content/app/entry.client.tsx +6 -1
  165. package/corpus/templates/dispatch/AGENTS.md +5 -0
  166. package/corpus/templates/dispatch/changelog/2026-07-17-apps-page-links-to-other-available-apps.md +6 -0
  167. package/corpus/templates/dispatch/changelog/2026-07-17-curated-template-remixes.md +6 -0
  168. package/corpus/templates/mail/app/entry.client.tsx +6 -1
  169. package/corpus/templates/slides/.agents/skills/slide-images/SKILL.md +11 -7
  170. package/corpus/templates/slides/.env.example +0 -1
  171. package/corpus/templates/slides/AGENTS.md +4 -0
  172. package/corpus/templates/slides/DEVELOPING.md +2 -2
  173. package/corpus/templates/slides/actions/index-design-system-with-builder.ts +1 -1
  174. package/corpus/templates/slides/actions/logo-config.ts +6 -7
  175. package/corpus/templates/slides/actions/search-images.ts +11 -39
  176. package/corpus/templates/slides/actions/search-logos.ts +5 -52
  177. package/corpus/templates/slides/app/components/editor/ImageSearchPanel.tsx +1 -1
  178. package/corpus/templates/slides/app/components/editor/LogoSearchPanel.tsx +16 -26
  179. package/corpus/templates/slides/app/entry.client.tsx +6 -1
  180. package/corpus/templates/slides/server/lib/media-search-providers.ts +216 -0
  181. package/corpus/templates/slides/server/register-secrets.ts +30 -0
  182. package/dist/a2a/client.d.ts +47 -1
  183. package/dist/a2a/client.d.ts.map +1 -1
  184. package/dist/a2a/client.js +94 -12
  185. package/dist/a2a/client.js.map +1 -1
  186. package/dist/a2a/correlation.d.ts +10 -0
  187. package/dist/a2a/correlation.d.ts.map +1 -0
  188. package/dist/a2a/correlation.js +40 -0
  189. package/dist/a2a/correlation.js.map +1 -0
  190. package/dist/a2a/handlers.d.ts.map +1 -1
  191. package/dist/a2a/handlers.js +147 -15
  192. package/dist/a2a/handlers.js.map +1 -1
  193. package/dist/a2a/index.d.ts +4 -4
  194. package/dist/a2a/index.d.ts.map +1 -1
  195. package/dist/a2a/index.js +2 -2
  196. package/dist/a2a/index.js.map +1 -1
  197. package/dist/a2a/invoke.d.ts +29 -2
  198. package/dist/a2a/invoke.d.ts.map +1 -1
  199. package/dist/a2a/invoke.js +33 -1
  200. package/dist/a2a/invoke.js.map +1 -1
  201. package/dist/a2a/server.d.ts.map +1 -1
  202. package/dist/a2a/server.js +14 -1
  203. package/dist/a2a/server.js.map +1 -1
  204. package/dist/a2a/task-store.d.ts +12 -1
  205. package/dist/a2a/task-store.d.ts.map +1 -1
  206. package/dist/a2a/task-store.js +96 -6
  207. package/dist/a2a/task-store.js.map +1 -1
  208. package/dist/a2a/types.d.ts +27 -0
  209. package/dist/a2a/types.d.ts.map +1 -1
  210. package/dist/a2a/types.js.map +1 -1
  211. package/dist/action.d.ts +5 -2
  212. package/dist/action.d.ts.map +1 -1
  213. package/dist/action.js.map +1 -1
  214. package/dist/agent/production-agent.d.ts +14 -0
  215. package/dist/agent/production-agent.d.ts.map +1 -1
  216. package/dist/agent/production-agent.js +19 -3
  217. package/dist/agent/production-agent.js.map +1 -1
  218. package/dist/client/AssistantChat.d.ts +14 -1
  219. package/dist/client/AssistantChat.d.ts.map +1 -1
  220. package/dist/client/AssistantChat.js +158 -136
  221. package/dist/client/AssistantChat.js.map +1 -1
  222. package/dist/client/MultiTabAssistantChat.d.ts.map +1 -1
  223. package/dist/client/MultiTabAssistantChat.js +27 -4
  224. package/dist/client/MultiTabAssistantChat.js.map +1 -1
  225. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  226. package/dist/client/agent-chat-adapter.js +21 -39
  227. package/dist/client/agent-chat-adapter.js.map +1 -1
  228. package/dist/client/agent-sidebar-state.d.ts +1 -0
  229. package/dist/client/agent-sidebar-state.d.ts.map +1 -1
  230. package/dist/client/agent-sidebar-state.js +4 -0
  231. package/dist/client/agent-sidebar-state.js.map +1 -1
  232. package/dist/client/analytics.d.ts +14 -0
  233. package/dist/client/analytics.d.ts.map +1 -1
  234. package/dist/client/analytics.js +67 -0
  235. package/dist/client/analytics.js.map +1 -1
  236. package/dist/client/chat/message-components.d.ts +8 -0
  237. package/dist/client/chat/message-components.d.ts.map +1 -1
  238. package/dist/client/chat/message-components.js +62 -19
  239. package/dist/client/chat/message-components.js.map +1 -1
  240. package/dist/client/chat/tool-call-display.d.ts +6 -0
  241. package/dist/client/chat/tool-call-display.d.ts.map +1 -1
  242. package/dist/client/chat/tool-call-display.js +83 -14
  243. package/dist/client/chat/tool-call-display.js.map +1 -1
  244. package/dist/client/chat/use-agent-chat-lifecycle-tracking.d.ts +8 -0
  245. package/dist/client/chat/use-agent-chat-lifecycle-tracking.d.ts.map +1 -0
  246. package/dist/client/chat/use-agent-chat-lifecycle-tracking.js +51 -0
  247. package/dist/client/chat/use-agent-chat-lifecycle-tracking.js.map +1 -0
  248. package/dist/client/chat-thread-url.d.ts +2 -0
  249. package/dist/client/chat-thread-url.d.ts.map +1 -0
  250. package/dist/client/chat-thread-url.js +12 -0
  251. package/dist/client/chat-thread-url.js.map +1 -0
  252. package/dist/client/error-capture.d.ts.map +1 -1
  253. package/dist/client/error-capture.js +7 -0
  254. package/dist/client/error-capture.js.map +1 -1
  255. package/dist/client/extensions/ExtensionSlot.d.ts +3 -1
  256. package/dist/client/extensions/ExtensionSlot.d.ts.map +1 -1
  257. package/dist/client/extensions/ExtensionSlot.js +28 -3
  258. package/dist/client/extensions/ExtensionSlot.js.map +1 -1
  259. package/dist/client/index.d.ts +1 -1
  260. package/dist/client/index.d.ts.map +1 -1
  261. package/dist/client/index.js +1 -1
  262. package/dist/client/index.js.map +1 -1
  263. package/dist/client/route-chunk-recovery.d.ts.map +1 -1
  264. package/dist/client/route-chunk-recovery.js +14 -9
  265. package/dist/client/route-chunk-recovery.js.map +1 -1
  266. package/dist/client/session-replay.d.ts +15 -0
  267. package/dist/client/session-replay.d.ts.map +1 -1
  268. package/dist/client/session-replay.js +20 -0
  269. package/dist/client/session-replay.js.map +1 -1
  270. package/dist/client/use-run-stuck-detection.d.ts.map +1 -1
  271. package/dist/client/use-run-stuck-detection.js +25 -1
  272. package/dist/client/use-run-stuck-detection.js.map +1 -1
  273. package/dist/db/client.d.ts +7 -0
  274. package/dist/db/client.d.ts.map +1 -1
  275. package/dist/db/client.js +33 -0
  276. package/dist/db/client.js.map +1 -1
  277. package/dist/extensions/actions.d.ts.map +1 -1
  278. package/dist/extensions/actions.js +2 -10
  279. package/dist/extensions/actions.js.map +1 -1
  280. package/dist/extensions/store.js +1 -1
  281. package/dist/extensions/store.js.map +1 -1
  282. package/dist/localization/default-messages.d.ts +3 -0
  283. package/dist/localization/default-messages.d.ts.map +1 -1
  284. package/dist/localization/default-messages.js +3 -0
  285. package/dist/localization/default-messages.js.map +1 -1
  286. package/dist/mcp/build-server.d.ts +2 -0
  287. package/dist/mcp/build-server.d.ts.map +1 -1
  288. package/dist/mcp/build-server.js +2 -2
  289. package/dist/mcp/build-server.js.map +1 -1
  290. package/dist/notifications/routes.d.ts +2 -2
  291. package/dist/observability/routes.d.ts +5 -5
  292. package/dist/observability/traces.d.ts +9 -0
  293. package/dist/observability/traces.d.ts.map +1 -1
  294. package/dist/observability/traces.js +137 -19
  295. package/dist/observability/traces.js.map +1 -1
  296. package/dist/progress/actions.d.ts.map +1 -1
  297. package/dist/progress/actions.js +3 -2
  298. package/dist/progress/actions.js.map +1 -1
  299. package/dist/progress/routes.d.ts +1 -1
  300. package/dist/provider-api/corpus-jobs.d.ts +2 -2
  301. package/dist/provider-api/index.d.ts.map +1 -1
  302. package/dist/provider-api/index.js +91 -8
  303. package/dist/provider-api/index.js.map +1 -1
  304. package/dist/scripts/call-agent.d.ts.map +1 -1
  305. package/dist/scripts/call-agent.js +140 -17
  306. package/dist/scripts/call-agent.js.map +1 -1
  307. package/dist/secrets/routes.d.ts +9 -9
  308. package/dist/server/agent-chat/action-filters-a2a.d.ts +24 -2
  309. package/dist/server/agent-chat/action-filters-a2a.d.ts.map +1 -1
  310. package/dist/server/agent-chat/action-filters-a2a.js +62 -7
  311. package/dist/server/agent-chat/action-filters-a2a.js.map +1 -1
  312. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  313. package/dist/server/agent-chat-plugin.js +118 -5
  314. package/dist/server/agent-chat-plugin.js.map +1 -1
  315. package/dist/server/agent-engine-api-key-route.d.ts +1 -1
  316. package/dist/server/transcribe-voice.d.ts +1 -1
  317. package/dist/styles/agent-conversation.css +7 -0
  318. package/dist/templates/default/app/i18n/ar-SA.ts +20 -0
  319. package/dist/templates/default/app/i18n/de-DE.ts +20 -0
  320. package/dist/templates/default/app/i18n/en-US.ts +20 -0
  321. package/dist/templates/default/app/i18n/es-ES.ts +20 -0
  322. package/dist/templates/default/app/i18n/fr-FR.ts +21 -0
  323. package/dist/templates/default/app/i18n/hi-IN.ts +19 -0
  324. package/dist/templates/default/app/i18n/ja-JP.ts +20 -0
  325. package/dist/templates/default/app/i18n/ko-KR.ts +19 -0
  326. package/dist/templates/default/app/i18n/pt-BR.ts +20 -0
  327. package/dist/templates/default/app/i18n/zh-CN.ts +19 -0
  328. package/dist/templates/default/app/i18n/zh-TW.ts +19 -0
  329. package/dist/templates/workspace-core/.agents/skills/a2a-protocol/SKILL.md +49 -0
  330. package/dist/templates/workspace-core/.agents/skills/composable-mini-apps/SKILL.md +5 -0
  331. package/dist/templates/workspace-core/.agents/skills/observability/SKILL.md +7 -1
  332. package/dist/templates/workspace-core/.agents/skills/performance/SKILL.md +13 -0
  333. package/dist/templates/workspace-core/.agents/skills/tracking/SKILL.md +1 -1
  334. package/package.json +1 -1
  335. package/src/templates/default/app/i18n/ar-SA.ts +20 -0
  336. package/src/templates/default/app/i18n/de-DE.ts +20 -0
  337. package/src/templates/default/app/i18n/en-US.ts +20 -0
  338. package/src/templates/default/app/i18n/es-ES.ts +20 -0
  339. package/src/templates/default/app/i18n/fr-FR.ts +21 -0
  340. package/src/templates/default/app/i18n/hi-IN.ts +19 -0
  341. package/src/templates/default/app/i18n/ja-JP.ts +20 -0
  342. package/src/templates/default/app/i18n/ko-KR.ts +19 -0
  343. package/src/templates/default/app/i18n/pt-BR.ts +20 -0
  344. package/src/templates/default/app/i18n/zh-CN.ts +19 -0
  345. package/src/templates/default/app/i18n/zh-TW.ts +19 -0
  346. package/src/templates/workspace-core/.agents/skills/a2a-protocol/SKILL.md +49 -0
  347. package/src/templates/workspace-core/.agents/skills/composable-mini-apps/SKILL.md +5 -0
  348. package/src/templates/workspace-core/.agents/skills/observability/SKILL.md +7 -1
  349. package/src/templates/workspace-core/.agents/skills/performance/SKILL.md +13 -0
  350. package/src/templates/workspace-core/.agents/skills/tracking/SKILL.md +1 -1
  351. package/corpus/templates/analytics/server/handlers/github.ts +0 -200
  352. package/corpus/templates/analytics/server/handlers/pylon.ts +0 -43
  353. package/corpus/templates/analytics/server/lib/apollo.ts +0 -167
  354. package/corpus/templates/analytics/server/lib/commonroom.ts +0 -149
  355. package/corpus/templates/analytics/server/lib/github.ts +0 -660
  356. package/corpus/templates/analytics/server/lib/mixpanel.ts +0 -156
  357. package/corpus/templates/analytics/server/lib/posthog.ts +0 -194
  358. package/corpus/templates/analytics/server/lib/pylon.ts +0 -109
  359. package/corpus/templates/analytics/server/routes/api/github/graphql.post.ts +0 -1
  360. package/corpus/templates/analytics/server/routes/api/github/issue.get.ts +0 -1
  361. package/corpus/templates/analytics/server/routes/api/github/org-prs.get.ts +0 -1
  362. package/corpus/templates/analytics/server/routes/api/github/pr.get.ts +0 -1
  363. package/corpus/templates/analytics/server/routes/api/github/prs.get.ts +0 -1
  364. package/corpus/templates/analytics/server/routes/api/github/search.get.ts +0 -1
  365. package/corpus/templates/slides/actions/fetch-logos.ts +0 -90
  366. package/corpus/templates/slides/actions/image-search.ts +0 -64
  367. package/corpus/templates/slides/actions/import-github.ts +0 -182
  368. package/corpus/templates/slides/actions/logo-lookup.ts +0 -113
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/a2a/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,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AAC,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 type {\n A2AApprovedAction,\n AgentCard,\n JsonRpcRequest,\n JsonRpcResponse,\n Message,\n Task,\n} from \"./types.js\";\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 ): 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(url, body, this.apiKeyAttempts[i]);\n console.log(\n `[A2A Client] Response: ${res.status} in ${Date.now() - startTime}ms`,\n );\n\n if (res.ok) {\n this.endpointCandidates = [url];\n this.markApiKeySucceeded(this.apiKeyAttempts[i]);\n return res.json() as Promise<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 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?.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(taskId: string): Promise<Task> {\n const response = await this.rpc(\"tasks/get\", { id: taskId });\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 * 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 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 ...(opts?.approvedActions?.length\n ? { approvedActions: opts.approvedActions }\n : {}),\n async: true,\n });\n\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 await new Promise((r) => setTimeout(r, pollMs));\n try {\n current = await this.getTask(submitted.id);\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 ): Promise<Response> {\n const controller = this.requestTimeoutMs\n ? new AbortController()\n : undefined;\n const timer =\n controller && this.requestTimeoutMs\n ? setTimeout(() => controller.abort(), this.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 /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 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 /**\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 /** 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> = {};\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\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 = await client.sendAndWait(message, {\n contextId: opts?.contextId,\n metadata,\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 task = await client.send(message, {\n contextId: opts?.contextId,\n metadata,\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\nasync function buildA2AApiKeyAttempts(opts?: {\n apiKey?: string;\n userEmail?: string;\n orgDomain?: string;\n orgSecret?: 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\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 }),\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 }),\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 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;AAC5D,OAAO,EAAE,8BAA8B,EAAE,MAAM,kBAAkB,CAAC;AAYlE,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IACnC,MAAM,CAAS;IACf,QAAQ,CAAO;IACf,SAAS,CAAS;IAClB,SAAS,CAAS;IAE3B,YAAY,MAAc,EAAE,QAAc,EAAE,SAAiB;QAC3D,MAAM,SAAS,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC;QACxC,KAAK,CACH,YAAY,MAAM,4BAA4B,SAAS,mBAAmB,SAAS,GAAG,CACvF,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;QAClC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC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ChD,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 A2AReadOnlyActionResult,\n AgentCard,\n JsonRpcRequest,\n JsonRpcResponse,\n Message,\n Task,\n} from \"./types.js\";\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 ): 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(url, body, this.apiKeyAttempts[i]);\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(taskId: string): Promise<Task> {\n const response = await this.rpc(\"tasks/get\", { id: taskId });\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 await new Promise((r) => setTimeout(r, pollMs));\n try {\n current = await this.getTask(submitted.id);\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 ): Promise<Response> {\n const controller = this.requestTimeoutMs\n ? new AbortController()\n : undefined;\n const timer =\n controller && this.requestTimeoutMs\n ? setTimeout(() => controller.abort(), this.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 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 /** 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> = {};\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 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 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\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"]}
@@ -0,0 +1,10 @@
1
+ import type { A2ACorrelationMetadata } from "./types.js";
2
+ export declare const MAX_A2A_CORRELATION_VALUE_CHARS = 200;
3
+ export declare function sanitizeA2ACorrelationId(value: unknown): string | undefined;
4
+ /**
5
+ * Keep only bounded, opaque ASCII correlation identifiers. These values
6
+ * remain telemetry hints; authentication continues to come exclusively from
7
+ * the verified A2A token/request context.
8
+ */
9
+ export declare function sanitizeA2ACorrelationMetadata(value: unknown): A2ACorrelationMetadata;
10
+ //# sourceMappingURL=correlation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"correlation.d.ts","sourceRoot":"","sources":["../../src/a2a/correlation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAEzD,eAAO,MAAM,+BAA+B,MAAM,CAAC;AAqBnD,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAE3E;AAED;;;;GAIG;AACH,wBAAgB,8BAA8B,CAC5C,KAAK,EAAE,OAAO,GACb,sBAAsB,CAexB"}
@@ -0,0 +1,40 @@
1
+ export const MAX_A2A_CORRELATION_VALUE_CHARS = 200;
2
+ const APP_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
3
+ const CORRELATION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
4
+ function boundedIdentifier(value, pattern) {
5
+ if (typeof value !== "string")
6
+ return undefined;
7
+ const trimmed = value.trim();
8
+ if (!trimmed ||
9
+ trimmed.length > MAX_A2A_CORRELATION_VALUE_CHARS ||
10
+ !pattern.test(trimmed)) {
11
+ return undefined;
12
+ }
13
+ return trimmed;
14
+ }
15
+ export function sanitizeA2ACorrelationId(value) {
16
+ return boundedIdentifier(value, CORRELATION_ID_PATTERN);
17
+ }
18
+ /**
19
+ * Keep only bounded, opaque ASCII correlation identifiers. These values
20
+ * remain telemetry hints; authentication continues to come exclusively from
21
+ * the verified A2A token/request context.
22
+ */
23
+ export function sanitizeA2ACorrelationMetadata(value) {
24
+ if (!value || typeof value !== "object" || Array.isArray(value))
25
+ return {};
26
+ const metadata = value;
27
+ const callerApp = boundedIdentifier(metadata.callerApp, APP_ID_PATTERN);
28
+ const callerThreadId = sanitizeA2ACorrelationId(metadata.callerThreadId);
29
+ const parentRunId = sanitizeA2ACorrelationId(metadata.parentRunId);
30
+ const parentTurnId = sanitizeA2ACorrelationId(metadata.parentTurnId);
31
+ const invocationId = sanitizeA2ACorrelationId(metadata.invocationId);
32
+ return {
33
+ ...(callerApp ? { callerApp } : {}),
34
+ ...(callerThreadId ? { callerThreadId } : {}),
35
+ ...(parentRunId ? { parentRunId } : {}),
36
+ ...(parentTurnId ? { parentTurnId } : {}),
37
+ ...(invocationId ? { invocationId } : {}),
38
+ };
39
+ }
40
+ //# sourceMappingURL=correlation.js.map
@@ -0,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AAY,CAAC,CAAC;IACrE,OAAO;QACL,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACnC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7C,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACvC,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACzC,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC1C,CAAC;AACJ,CAAC","sourcesContent":["import type { A2ACorrelationMetadata } from \"./types.js\";\n\nexport const MAX_A2A_CORRELATION_VALUE_CHARS = 200;\n\nconst APP_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\nconst CORRELATION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;\n\nfunction boundedIdentifier(\n value: unknown,\n pattern: RegExp,\n): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n if (\n !trimmed ||\n trimmed.length > MAX_A2A_CORRELATION_VALUE_CHARS ||\n !pattern.test(trimmed)\n ) {\n return undefined;\n }\n return trimmed;\n}\n\nexport function sanitizeA2ACorrelationId(value: unknown): string | undefined {\n return boundedIdentifier(value, CORRELATION_ID_PATTERN);\n}\n\n/**\n * Keep only bounded, opaque ASCII correlation identifiers. These values\n * remain telemetry hints; authentication continues to come exclusively from\n * the verified A2A token/request context.\n */\nexport function sanitizeA2ACorrelationMetadata(\n value: unknown,\n): A2ACorrelationMetadata {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n const metadata = value as Record<string, unknown>;\n const callerApp = boundedIdentifier(metadata.callerApp, APP_ID_PATTERN);\n const callerThreadId = sanitizeA2ACorrelationId(metadata.callerThreadId);\n const parentRunId = sanitizeA2ACorrelationId(metadata.parentRunId);\n const parentTurnId = sanitizeA2ACorrelationId(metadata.parentTurnId);\n const invocationId = sanitizeA2ACorrelationId(metadata.invocationId);\n return {\n ...(callerApp ? { callerApp } : {}),\n ...(callerThreadId ? { callerThreadId } : {}),\n ...(parentRunId ? { parentRunId } : {}),\n ...(parentTurnId ? { parentTurnId } : {}),\n ...(invocationId ? { invocationId } : {}),\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"handlers.d.ts","sourceRoot":"","sources":["../../src/a2a/handlers.ts"],"names":[],"mappings":"AA+BA,OAAO,KAAK,EAEV,SAAS,EAIT,eAAe,EAGhB,MAAM,YAAY,CAAC;AA6LpB;;;;;;;;GAQG;AACH,wBAAsB,uBAAuB,CAC3C,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,SAAS,EACjB,KAAK,CAAC,EAAE,GAAG,GACV,OAAO,CAAC,IAAI,CAAC,CAsFf;AAitBD;;;GAGG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,GAAG,EACT,KAAK,EAAE,GAAG,EACV,MAAM,EAAE,SAAS,GAChB,OAAO,CAAC,eAAe,CAAC,CAyC1B"}
1
+ {"version":3,"file":"handlers.d.ts","sourceRoot":"","sources":["../../src/a2a/handlers.ts"],"names":[],"mappings":"AAuCA,OAAO,KAAK,EAEV,SAAS,EAIT,eAAe,EAGhB,MAAM,YAAY,CAAC;AAgMpB;;;;;;;;GAQG;AACH,wBAAsB,uBAAuB,CAC3C,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,SAAS,EACjB,KAAK,CAAC,EAAE,GAAG,GACV,OAAO,CAAC,IAAI,CAAC,CAsFf;AA43BD;;;GAGG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,GAAG,EACT,KAAK,EAAE,GAAG,EACV,MAAM,EAAE,SAAS,GAChB,OAAO,CAAC,eAAe,CAAC,CA6C1B"}
@@ -1,11 +1,15 @@
1
+ import crypto from "node:crypto";
1
2
  import { setResponseHeader, setResponseStatus } from "h3";
2
3
  import { AGENT_BACKGROUND_PROCESSOR_A2A, AGENT_BACKGROUND_PROCESSOR_FIELD, dispatchPathTargetsNetlifyBackgroundFunction, isAgentChatDurableBackgroundEnabled, resolveAgentChatProcessRunDispatchPath, } from "../agent/durable-background.js";
4
+ import { trackingIdentityProperties } from "../observability/tracking-identity.js";
3
5
  import { withConfiguredAppBasePath } from "../server/app-base-path.js";
4
6
  import { getOrigin, isConfiguredAppOrigin } from "../server/google-oauth.js";
5
7
  import { fireInternalDispatch } from "../server/self-dispatch.js";
6
8
  import { agentChat } from "../shared/agent-chat.js";
9
+ import { track } from "../tracking/registry.js";
7
10
  import { hasConfiguredA2ASecret, isA2AProductionRuntime, } from "./auth-policy.js";
8
- import { createTask, getTask, getTaskOwner, updateTask, claimA2ATaskForProcessing, getA2ATaskDispatchState, failStuckA2ATask, failStuckQueuedA2ATask, settleProcessingA2ATask, touchQueuedA2ATaskDispatch, touchProcessingA2ATask, pauseProcessingA2ATask, } from "./task-store.js";
11
+ import { sanitizeA2ACorrelationMetadata } from "./correlation.js";
12
+ import { createTask, createOrReuseTask, getTask, getTaskOwnership, updateTask, claimA2ATaskForProcessing, getA2ATaskDispatchState, failStuckA2ATask, failStuckQueuedA2ATask, settleProcessingA2ATask, touchQueuedA2ATaskDispatch, touchProcessingA2ATask, pauseProcessingA2ATask, MAX_A2A_IDEMPOTENCY_KEY_CHARS, A2A_PERSONAL_OWNER_SCOPE, } from "./task-store.js";
9
13
  // Inlined to avoid pulling the entire core-routes-plugin (and its h3
10
14
  // transitive deps) into the a2a/handlers test boundary. Must stay in sync
11
15
  // with FRAMEWORK_ROUTE_PREFIX in `server/core-routes-plugin.ts`.
@@ -15,6 +19,9 @@ const A2A_QUEUED_DISPATCH_STUCK_AFTER_MS = 10_000;
15
19
  const A2A_PROCESSING_STUCK_AFTER_MS = 5 * 60 * 1000;
16
20
  const A2A_PROCESSING_HEARTBEAT_MS = 30_000;
17
21
  const MAX_A2A_APPROVED_ACTIONS = 10;
22
+ const MAX_A2A_DIRECT_ACTION_NAME_CHARS = 200;
23
+ const MAX_A2A_DIRECT_ACTION_INPUT_BYTES = 64 * 1024;
24
+ const A2A_READ_INVOKE_EVENT = "$a2a_read_invoke";
18
25
  function trustedApprovedActions(value, event) {
19
26
  // Static API keys and unsigned requests do not prove which user authorized
20
27
  // a consequential action. Only a verified identity-bearing JWT may carry
@@ -428,6 +435,17 @@ async function runHandlerAndPersist(taskId, message, config, contextId, metadata
428
435
  });
429
436
  }
430
437
  }
438
+ function verifiedTaskOwner(event) {
439
+ const ownerEmail = event?.context?.__a2aVerifiedEmail ?? null;
440
+ return {
441
+ ownerEmail,
442
+ ownerScope: ownerEmail
443
+ ? (event?.context?.__a2aOrgDomain
444
+ ?.trim()
445
+ .toLowerCase() ?? A2A_PERSONAL_OWNER_SCOPE)
446
+ : null,
447
+ };
448
+ }
431
449
  async function handleSend(params, config, event) {
432
450
  const message = params.message;
433
451
  if (!message || !message.role || !Array.isArray(message.parts)) {
@@ -444,7 +462,24 @@ async function handleSend(params, config, event) {
444
462
  // on every subsequent tasks/get and tasks/cancel call. Caller-supplied
445
463
  // metadata.userEmail is NEVER used for ownership; that would re-introduce
446
464
  // the IDOR class fixed here.
447
- const ownerEmailForTask = event?.context?.__a2aVerifiedEmail ?? null;
465
+ const { ownerEmail: ownerEmailForTask, ownerScope: ownerScopeForTask } = verifiedTaskOwner(event);
466
+ let idempotencyKey;
467
+ if (ownerEmailForTask && params.idempotencyKey !== undefined) {
468
+ if (typeof params.idempotencyKey !== "string") {
469
+ return {
470
+ ...jsonRpcError(0, -32602, "Invalid params: idempotencyKey must be a string"),
471
+ _id: 0,
472
+ };
473
+ }
474
+ idempotencyKey = params.idempotencyKey.trim();
475
+ if (!idempotencyKey ||
476
+ idempotencyKey.length > MAX_A2A_IDEMPOTENCY_KEY_CHARS) {
477
+ return {
478
+ ...jsonRpcError(0, -32602, "Invalid params: idempotencyKey is invalid"),
479
+ _id: 0,
480
+ };
481
+ }
482
+ }
448
483
  // Async mode: return the task immediately in `working` state, run the
449
484
  // handler in the background, and let the caller poll `tasks/get`. This is
450
485
  // the workaround for synchronous serverless request timeouts when the handler
@@ -455,6 +490,8 @@ async function handleSend(params, config, event) {
455
490
  // requests. Async is also refused entirely when no auth is configured in
456
491
  // production — see the additional gate below.
457
492
  const asyncMode = params.async === true || (event && event.context?.__a2aForceAsync === true);
493
+ if (!asyncMode)
494
+ idempotencyKey = undefined;
458
495
  if (asyncMode) {
459
496
  // Refuse async mode entirely when no auth is configured in production.
460
497
  // The async dispatch path self-fires the `_process-task` route, which
@@ -494,7 +531,13 @@ async function handleSend(params, config, event) {
494
531
  approvedActions: approvedActions ?? null,
495
532
  },
496
533
  };
497
- const task = await createTask(message, contextId, taskMetadata, ownerEmailForTask);
534
+ const { task, reused } = await createOrReuseTask(message, contextId, taskMetadata, ownerEmailForTask, ownerScopeForTask, idempotencyKey);
535
+ if (reused) {
536
+ return {
537
+ ...jsonRpcResult(0, sanitizeTaskForResponse(task)),
538
+ _id: 0,
539
+ };
540
+ }
498
541
  const working = await updateTask(task.id, { state: "working" });
499
542
  // Awaited, not fire-and-forget: this handler is about to return, and a
500
543
  // detached dispatch fetch racing only a short settle timer can be killed
@@ -515,7 +558,13 @@ async function handleSend(params, config, event) {
515
558
  };
516
559
  }
517
560
  return withA2ARequestContext(metadata, event, async () => {
518
- const task = await createTask(message, contextId, undefined, ownerEmailForTask);
561
+ const { task, reused } = await createOrReuseTask(message, contextId, undefined, ownerEmailForTask, ownerScopeForTask, idempotencyKey);
562
+ if (reused) {
563
+ return {
564
+ ...jsonRpcResult(0, sanitizeTaskForResponse(task)),
565
+ _id: 0,
566
+ };
567
+ }
519
568
  await updateTask(task.id, { state: "working" });
520
569
  const ctx = makeHandlerContext(task.id, contextId, trustedA2AMetadata(metadata, event), event, approvedActions);
521
570
  try {
@@ -585,9 +634,9 @@ async function handleStream(params, config, res, event) {
585
634
  const contextId = params.contextId;
586
635
  const metadata = params.metadata;
587
636
  const approvedActions = trustedApprovedActions(params.approvedActions, event);
588
- const ownerEmailForTask = event?.context?.__a2aVerifiedEmail ?? null;
637
+ const { ownerEmail: ownerEmailForTask, ownerScope: ownerScopeForTask } = verifiedTaskOwner(event);
589
638
  await withA2ARequestContext(metadata, event, async () => {
590
- const task = await createTask(message, contextId, undefined, ownerEmailForTask);
639
+ const task = await createTask(message, contextId, undefined, ownerEmailForTask, ownerScopeForTask);
591
640
  await updateTask(task.id, { state: "working" });
592
641
  const { context, artifacts } = makeHandlerContext(task.id, contextId, trustedA2AMetadata(metadata, event), event, approvedActions);
593
642
  try {
@@ -650,9 +699,11 @@ const SENSITIVE_METADATA_KEYS = new Set([
650
699
  function sanitizeTaskForResponse(task) {
651
700
  if (!task || typeof task !== "object")
652
701
  return task;
653
- if (!task.metadata || typeof task.metadata !== "object")
654
- return task;
655
- const meta = task.metadata;
702
+ const { ownerEmail: _ownerEmail, ownerScope: _ownerScope, ...publicTask } = task;
703
+ if (!publicTask.metadata || typeof publicTask.metadata !== "object") {
704
+ return publicTask;
705
+ }
706
+ const meta = publicTask.metadata;
656
707
  const publicMeta = {};
657
708
  for (const [k, v] of Object.entries(meta)) {
658
709
  if (k === "__a2a_processor")
@@ -661,7 +712,7 @@ function sanitizeTaskForResponse(task) {
661
712
  continue;
662
713
  publicMeta[k] = v;
663
714
  }
664
- return { ...task, metadata: publicMeta };
715
+ return { ...publicTask, metadata: publicMeta };
665
716
  }
666
717
  /**
667
718
  * Reject access when the task has a recorded owner that doesn't match the
@@ -677,7 +728,7 @@ function sanitizeTaskForResponse(task) {
677
728
  * no way to authenticate the caller, so the only safe response is "not
678
729
  * found".
679
730
  */
680
- function authorizeTaskAccess(taskOwnerEmail, event, config) {
731
+ function authorizeTaskAccess(taskOwnerEmail, taskOwnerScope, event, config) {
681
732
  const verifiedEmail = event?.context?.__a2aVerifiedEmail ?? null;
682
733
  const hasA2ASecret = hasConfiguredA2ASecret();
683
734
  const hasApiKey = !!(config.apiKeyEnv && process.env[config.apiKeyEnv]);
@@ -693,6 +744,14 @@ function authorizeTaskAccess(taskOwnerEmail, event, config) {
693
744
  if (verifiedEmail.toLowerCase() !== taskOwnerEmail.toLowerCase()) {
694
745
  return jsonRpcError(0, -32001, "Task not found");
695
746
  }
747
+ if (taskOwnerScope) {
748
+ const verifiedScope = event?.context?.__a2aOrgDomain
749
+ ?.trim()
750
+ .toLowerCase() ?? A2A_PERSONAL_OWNER_SCOPE;
751
+ if (verifiedScope !== taskOwnerScope.toLowerCase()) {
752
+ return jsonRpcError(0, -32001, "Task not found");
753
+ }
754
+ }
696
755
  }
697
756
  // Legacy row (no owner_email recorded). The route-level auth gate is the
698
757
  // only thing protecting it — fall through and serve.
@@ -703,8 +762,8 @@ async function handleGet(params, event, config) {
703
762
  if (!id) {
704
763
  return jsonRpcError(0, -32602, "Invalid params: id required");
705
764
  }
706
- const ownerEmail = await getTaskOwner(id);
707
- const denied = authorizeTaskAccess(ownerEmail, event, config);
765
+ const ownership = await getTaskOwnership(id);
766
+ const denied = authorizeTaskAccess(ownership.ownerEmail, ownership.ownerScope, event, config);
708
767
  if (denied)
709
768
  return denied;
710
769
  const task = await getTask(id);
@@ -772,8 +831,8 @@ async function handleCancel(params, event, config) {
772
831
  if (!id) {
773
832
  return jsonRpcError(0, -32602, "Invalid params: id required");
774
833
  }
775
- const ownerEmail = await getTaskOwner(id);
776
- const denied = authorizeTaskAccess(ownerEmail, event, config);
834
+ const ownership = await getTaskOwnership(id);
835
+ const denied = authorizeTaskAccess(ownership.ownerEmail, ownership.ownerScope, event, config);
777
836
  if (denied)
778
837
  return denied;
779
838
  const task = await updateTask(id, { state: "canceled" });
@@ -782,6 +841,75 @@ async function handleCancel(params, event, config) {
782
841
  }
783
842
  return jsonRpcResult(0, sanitizeTaskForResponse(task));
784
843
  }
844
+ async function handleInvokeReadOnlyAction(params, event, config) {
845
+ const action = typeof params.action === "string" ? params.action.trim() : "";
846
+ const input = params.input ?? {};
847
+ if (!action) {
848
+ return jsonRpcError(0, -32602, "Invalid params: action required");
849
+ }
850
+ if (action.length > MAX_A2A_DIRECT_ACTION_NAME_CHARS) {
851
+ return jsonRpcError(0, -32602, "Invalid params: action is too long");
852
+ }
853
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
854
+ return jsonRpcError(0, -32602, "Invalid params: input must be an object");
855
+ }
856
+ let inputBytes;
857
+ try {
858
+ inputBytes = Buffer.byteLength(JSON.stringify(input), "utf8");
859
+ }
860
+ catch {
861
+ return jsonRpcError(0, -32602, "Invalid params: input must be JSON-safe");
862
+ }
863
+ if (inputBytes > MAX_A2A_DIRECT_ACTION_INPUT_BYTES) {
864
+ return jsonRpcError(0, -32602, "Invalid params: input is too large");
865
+ }
866
+ if (!event?.context?.__a2aVerifiedEmail ||
867
+ event?.context?.__a2aAudienceVerified !== true) {
868
+ return jsonRpcError(0, -32001, "A verified, audience-bound user identity is required for direct action invocation");
869
+ }
870
+ if (!config.executeReadOnlyAction) {
871
+ return jsonRpcError(0, -32601, "Direct action invocation not supported");
872
+ }
873
+ const startedAt = Date.now();
874
+ const correlation = sanitizeA2ACorrelationMetadata(params.metadata);
875
+ const invocationId = crypto.randomUUID();
876
+ const verifiedEmail = event.context.__a2aVerifiedEmail;
877
+ const emitTracking = (status) => {
878
+ const identity = trackingIdentityProperties();
879
+ track(A2A_READ_INVOKE_EVENT, {
880
+ ...identity,
881
+ action,
882
+ receiver_app: config.appId ?? identity.app ?? config.name,
883
+ caller_app: correlation.callerApp ?? "unknown",
884
+ duration_ms: Math.max(0, Date.now() - startedAt),
885
+ status,
886
+ invocation_id: invocationId,
887
+ ...(correlation.parentRunId
888
+ ? { parent_run_id: correlation.parentRunId }
889
+ : {}),
890
+ ...(correlation.parentTurnId
891
+ ? { parent_turn_id: correlation.parentTurnId }
892
+ : {}),
893
+ ...(correlation.invocationId
894
+ ? { caller_invocation_id: correlation.invocationId }
895
+ : {}),
896
+ }, { userId: verifiedEmail });
897
+ };
898
+ try {
899
+ const result = await withA2ARequestContext(undefined, event, () => config.executeReadOnlyAction({
900
+ action,
901
+ input: input,
902
+ invocationId,
903
+ }));
904
+ emitTracking(result.status);
905
+ return jsonRpcResult(0, { action, ...result });
906
+ }
907
+ catch (error) {
908
+ emitTracking("failed");
909
+ console.error(`[a2a] Direct action ${action} failed:`, error);
910
+ return jsonRpcError(0, -32000, "Direct action invocation failed");
911
+ }
912
+ }
785
913
  /**
786
914
  * H3-compatible JSON-RPC handler. Returns JSON directly (H3 serializes it).
787
915
  * Streaming is handled via H3's node response when needed.
@@ -822,6 +950,10 @@ export async function handleJsonRpcH3(body, event, config) {
822
950
  const result = await handleCancel(params, event, config);
823
951
  return { ...result, id };
824
952
  }
953
+ case "actions/invoke": {
954
+ const result = await handleInvokeReadOnlyAction(params, event, config);
955
+ return { ...result, id };
956
+ }
825
957
  default:
826
958
  return jsonRpcError(id, -32601, `Method not found: ${body.method}`);
827
959
  }