@agent-native/core 0.107.1 → 0.108.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (257) hide show
  1. package/corpus/README.md +2 -2
  2. package/corpus/core/CHANGELOG.md +12 -0
  3. package/corpus/core/docs/content/actions.mdx +48 -0
  4. package/corpus/core/docs/content/locales/ar-SA/actions.mdx +38 -0
  5. package/corpus/core/docs/content/locales/de-DE/actions.mdx +38 -0
  6. package/corpus/core/docs/content/locales/es-ES/actions.mdx +38 -0
  7. package/corpus/core/docs/content/locales/fr-FR/actions.mdx +38 -0
  8. package/corpus/core/docs/content/locales/hi-IN/actions.mdx +38 -0
  9. package/corpus/core/docs/content/locales/ja-JP/actions.mdx +38 -0
  10. package/corpus/core/docs/content/locales/ko-KR/actions.mdx +38 -0
  11. package/corpus/core/docs/content/locales/pt-BR/actions.mdx +38 -0
  12. package/corpus/core/docs/content/locales/zh-CN/actions.mdx +38 -0
  13. package/corpus/core/docs/content/locales/zh-TW/actions.mdx +38 -0
  14. package/corpus/core/package.json +5 -1
  15. package/corpus/core/src/a2a/artifact-response.ts +32 -10
  16. package/corpus/core/src/a2a-claims.ts +52 -0
  17. package/corpus/core/src/action.ts +6 -2
  18. package/corpus/core/src/audit/record.ts +6 -0
  19. package/corpus/core/src/client/feature-flags/FeatureFlagsPanel.tsx +519 -0
  20. package/corpus/core/src/client/feature-flags/helpers.ts +77 -0
  21. package/corpus/core/src/client/feature-flags/index.ts +13 -0
  22. package/corpus/core/src/client/feature-flags/types.ts +29 -0
  23. package/corpus/core/src/client/feature-flags/use-feature-flag.ts +26 -0
  24. package/corpus/core/src/client/index.ts +11 -0
  25. package/corpus/core/src/extensions/routes.ts +1 -1
  26. package/corpus/core/src/feature-flags/a2a-action-route.ts +56 -0
  27. package/corpus/core/src/feature-flags/actions/get-feature-flags.ts +24 -0
  28. package/corpus/core/src/feature-flags/actions/list-feature-flags.ts +69 -0
  29. package/corpus/core/src/feature-flags/actions/set-feature-flag.ts +89 -0
  30. package/corpus/core/src/feature-flags/index.ts +21 -0
  31. package/corpus/core/src/feature-flags/permissions.ts +53 -0
  32. package/corpus/core/src/feature-flags/plugin.ts +44 -0
  33. package/corpus/core/src/feature-flags/registry.ts +96 -0
  34. package/corpus/core/src/feature-flags/store.ts +176 -0
  35. package/corpus/core/src/index.ts +15 -0
  36. package/corpus/core/src/integrations/a2a-continuation-processor.ts +107 -3
  37. package/corpus/core/src/integrations/pending-tasks-store.ts +98 -1
  38. package/corpus/core/src/integrations/plugin.ts +129 -4
  39. package/corpus/core/src/integrations/webhook-handler.ts +339 -36
  40. package/corpus/core/src/localization/default-messages.ts +47 -0
  41. package/corpus/core/src/server/action-discovery.ts +12 -0
  42. package/corpus/core/src/server/action-routes.ts +47 -5
  43. package/corpus/core/src/server/agent-chat-plugin.ts +93 -8
  44. package/corpus/core/src/server/index.ts +1 -0
  45. package/corpus/core/src/settings/org-settings.ts +13 -0
  46. package/corpus/core/src/settings/store.ts +57 -0
  47. package/corpus/core/src/templates/default/.agents/skills/feature-flags/SKILL.md +169 -0
  48. package/corpus/core/src/templates/default/AGENTS.md +1 -0
  49. package/corpus/core/src/templates/headless/.agents/skills/feature-flags/SKILL.md +169 -0
  50. package/corpus/core/src/templates/workspace-core/.agents/skills/feature-flags/SKILL.md +169 -0
  51. package/corpus/core/src/templates/workspace-core/AGENTS.md +1 -1
  52. package/corpus/core/src/templates/workspace-root/AGENTS.md +1 -1
  53. package/corpus/core/src/vite/action-types-plugin.ts +12 -0
  54. package/corpus/templates/analytics/.agents/skills/feature-flags/SKILL.md +169 -0
  55. package/corpus/templates/analytics/AGENTS.md +15 -3
  56. package/corpus/templates/analytics/actions/list-workspace-feature-flags.ts +15 -0
  57. package/corpus/templates/analytics/actions/navigate.ts +2 -2
  58. package/corpus/templates/analytics/actions/set-workspace-feature-flag.ts +45 -0
  59. package/corpus/templates/analytics/actions/view-screen.ts +13 -0
  60. package/corpus/templates/analytics/app/components/agents/FeatureFlagsFleetPanel.tsx +243 -0
  61. package/corpus/templates/analytics/app/components/layout/CommandPalette.tsx +11 -3
  62. package/corpus/templates/analytics/app/hooks/use-navigation-state.ts +3 -1
  63. package/corpus/templates/analytics/app/i18n/zh-TW.ts +17 -0
  64. package/corpus/templates/analytics/app/i18n-data.ts +251 -0
  65. package/corpus/templates/analytics/app/pages/Agents.tsx +22 -2
  66. package/corpus/templates/analytics/changelog/2026-07-17-manage-feature-flag-rollouts-across-your-organization-s-apps.md +6 -0
  67. package/corpus/templates/analytics/server/lib/db-admin-connections.ts +13 -5
  68. package/corpus/templates/analytics/server/lib/workspace-feature-flags.ts +347 -0
  69. package/corpus/templates/assets/.agents/skills/feature-flags/SKILL.md +169 -0
  70. package/corpus/templates/brain/.agents/skills/feature-flags/SKILL.md +169 -0
  71. package/corpus/templates/calendar/.agents/skills/feature-flags/SKILL.md +169 -0
  72. package/corpus/templates/chat/.agents/skills/feature-flags/SKILL.md +169 -0
  73. package/corpus/templates/clips/.agents/skills/feature-flags/SKILL.md +169 -0
  74. package/corpus/templates/clips/server/plugins/feature-flags.ts +11 -0
  75. package/corpus/templates/clips/shared/feature-flags.ts +30 -37
  76. package/corpus/templates/content/.agents/skills/feature-flags/SKILL.md +169 -0
  77. package/corpus/templates/design/.agents/skills/feature-flags/SKILL.md +169 -0
  78. package/corpus/templates/design/AGENTS.md +5 -3
  79. package/corpus/templates/design/actions/add-fusion-screens.ts +4 -6
  80. package/corpus/templates/design/actions/apply-fusion-edits.ts +4 -6
  81. package/corpus/templates/design/actions/create-fusion-app.ts +5 -4
  82. package/corpus/templates/design/actions/deploy-fusion-app.ts +4 -3
  83. package/corpus/templates/design/actions/get-fusion-deploy-status.ts +4 -6
  84. package/corpus/templates/design/actions/list-fusion-edits.ts +4 -3
  85. package/corpus/templates/design/actions/push-fusion-app.ts +4 -6
  86. package/corpus/templates/design/actions/queue-fusion-edit.ts +4 -3
  87. package/corpus/templates/design/actions/send-fusion-message.ts +4 -6
  88. package/corpus/templates/design/actions/sync-fusion-app.ts +4 -3
  89. package/corpus/templates/design/app/components/editor/PromptDialog.tsx +1 -1
  90. package/corpus/templates/design/app/pages/Index.tsx +8 -6
  91. package/corpus/templates/design/server/plugins/feature-flags.ts +5 -0
  92. package/corpus/templates/design/shared/full-app.ts +10 -7
  93. package/corpus/templates/dispatch/.agents/skills/feature-flags/SKILL.md +169 -0
  94. package/corpus/templates/forms/.agents/skills/feature-flags/SKILL.md +169 -0
  95. package/corpus/templates/macros/.agents/skills/feature-flags/SKILL.md +169 -0
  96. package/corpus/templates/mail/.agents/skills/feature-flags/SKILL.md +169 -0
  97. package/corpus/templates/plan/.agents/skills/feature-flags/SKILL.md +169 -0
  98. package/corpus/templates/slides/.agents/skills/feature-flags/SKILL.md +169 -0
  99. package/corpus/templates/tasks/.agents/skills/feature-flags/SKILL.md +169 -0
  100. package/dist/a2a/artifact-response.d.ts +5 -1
  101. package/dist/a2a/artifact-response.d.ts.map +1 -1
  102. package/dist/a2a/artifact-response.js +18 -12
  103. package/dist/a2a/artifact-response.js.map +1 -1
  104. package/dist/a2a-claims.d.ts +10 -0
  105. package/dist/a2a-claims.d.ts.map +1 -0
  106. package/dist/a2a-claims.js +41 -0
  107. package/dist/a2a-claims.js.map +1 -0
  108. package/dist/action.d.ts +6 -2
  109. package/dist/action.d.ts.map +1 -1
  110. package/dist/action.js.map +1 -1
  111. package/dist/audit/record.d.ts +3 -0
  112. package/dist/audit/record.d.ts.map +1 -1
  113. package/dist/audit/record.js +3 -0
  114. package/dist/audit/record.js.map +1 -1
  115. package/dist/client/feature-flags/FeatureFlagsPanel.d.ts +10 -0
  116. package/dist/client/feature-flags/FeatureFlagsPanel.d.ts.map +1 -0
  117. package/dist/client/feature-flags/FeatureFlagsPanel.js +143 -0
  118. package/dist/client/feature-flags/FeatureFlagsPanel.js.map +1 -0
  119. package/dist/client/feature-flags/helpers.d.ts +16 -0
  120. package/dist/client/feature-flags/helpers.d.ts.map +1 -0
  121. package/dist/client/feature-flags/helpers.js +50 -0
  122. package/dist/client/feature-flags/helpers.js.map +1 -0
  123. package/dist/client/feature-flags/index.d.ts +5 -0
  124. package/dist/client/feature-flags/index.d.ts.map +1 -0
  125. package/dist/client/feature-flags/index.js +4 -0
  126. package/dist/client/feature-flags/index.js.map +1 -0
  127. package/dist/client/feature-flags/types.d.ts +27 -0
  128. package/dist/client/feature-flags/types.d.ts.map +1 -0
  129. package/dist/client/feature-flags/types.js +2 -0
  130. package/dist/client/feature-flags/types.js.map +1 -0
  131. package/dist/client/feature-flags/use-feature-flag.d.ts +8 -0
  132. package/dist/client/feature-flags/use-feature-flag.d.ts.map +1 -0
  133. package/dist/client/feature-flags/use-feature-flag.js +15 -0
  134. package/dist/client/feature-flags/use-feature-flag.js.map +1 -0
  135. package/dist/client/index.d.ts +1 -0
  136. package/dist/client/index.d.ts.map +1 -1
  137. package/dist/client/index.js +1 -0
  138. package/dist/client/index.js.map +1 -1
  139. package/dist/collab/routes.d.ts +1 -1
  140. package/dist/collab/struct-routes.d.ts +1 -1
  141. package/dist/extensions/routes.d.ts.map +1 -1
  142. package/dist/extensions/routes.js +1 -1
  143. package/dist/extensions/routes.js.map +1 -1
  144. package/dist/feature-flags/a2a-action-route.d.ts +14 -0
  145. package/dist/feature-flags/a2a-action-route.d.ts.map +1 -0
  146. package/dist/feature-flags/a2a-action-route.js +50 -0
  147. package/dist/feature-flags/a2a-action-route.js.map +1 -0
  148. package/dist/feature-flags/actions/get-feature-flags.d.ts +3 -0
  149. package/dist/feature-flags/actions/get-feature-flags.d.ts.map +1 -0
  150. package/dist/feature-flags/actions/get-feature-flags.js +18 -0
  151. package/dist/feature-flags/actions/get-feature-flags.js.map +1 -0
  152. package/dist/feature-flags/actions/list-feature-flags.d.ts +28 -0
  153. package/dist/feature-flags/actions/list-feature-flags.d.ts.map +1 -0
  154. package/dist/feature-flags/actions/list-feature-flags.js +60 -0
  155. package/dist/feature-flags/actions/list-feature-flags.js.map +1 -0
  156. package/dist/feature-flags/actions/set-feature-flag.d.ts +26 -0
  157. package/dist/feature-flags/actions/set-feature-flag.d.ts.map +1 -0
  158. package/dist/feature-flags/actions/set-feature-flag.js +78 -0
  159. package/dist/feature-flags/actions/set-feature-flag.js.map +1 -0
  160. package/dist/feature-flags/index.d.ts +5 -0
  161. package/dist/feature-flags/index.d.ts.map +1 -0
  162. package/dist/feature-flags/index.js +5 -0
  163. package/dist/feature-flags/index.js.map +1 -0
  164. package/dist/feature-flags/permissions.d.ts +13 -0
  165. package/dist/feature-flags/permissions.d.ts.map +1 -0
  166. package/dist/feature-flags/permissions.js +37 -0
  167. package/dist/feature-flags/permissions.js.map +1 -0
  168. package/dist/feature-flags/plugin.d.ts +17 -0
  169. package/dist/feature-flags/plugin.d.ts.map +1 -0
  170. package/dist/feature-flags/plugin.js +29 -0
  171. package/dist/feature-flags/plugin.js.map +1 -0
  172. package/dist/feature-flags/registry.d.ts +23 -0
  173. package/dist/feature-flags/registry.d.ts.map +1 -0
  174. package/dist/feature-flags/registry.js +59 -0
  175. package/dist/feature-flags/registry.js.map +1 -0
  176. package/dist/feature-flags/store.d.ts +31 -0
  177. package/dist/feature-flags/store.d.ts.map +1 -0
  178. package/dist/feature-flags/store.js +124 -0
  179. package/dist/feature-flags/store.js.map +1 -0
  180. package/dist/index.d.ts +1 -0
  181. package/dist/index.d.ts.map +1 -1
  182. package/dist/index.js +1 -0
  183. package/dist/index.js.map +1 -1
  184. package/dist/integrations/a2a-continuation-processor.js +62 -5
  185. package/dist/integrations/a2a-continuation-processor.js.map +1 -1
  186. package/dist/integrations/pending-tasks-store.d.ts +3 -0
  187. package/dist/integrations/pending-tasks-store.d.ts.map +1 -1
  188. package/dist/integrations/pending-tasks-store.js +75 -1
  189. package/dist/integrations/pending-tasks-store.js.map +1 -1
  190. package/dist/integrations/plugin.d.ts.map +1 -1
  191. package/dist/integrations/plugin.js +81 -5
  192. package/dist/integrations/plugin.js.map +1 -1
  193. package/dist/integrations/webhook-handler.d.ts +23 -2
  194. package/dist/integrations/webhook-handler.d.ts.map +1 -1
  195. package/dist/integrations/webhook-handler.js +257 -35
  196. package/dist/integrations/webhook-handler.js.map +1 -1
  197. package/dist/localization/default-messages.d.ts +42 -0
  198. package/dist/localization/default-messages.d.ts.map +1 -1
  199. package/dist/localization/default-messages.js +42 -0
  200. package/dist/localization/default-messages.js.map +1 -1
  201. package/dist/notifications/routes.d.ts +2 -2
  202. package/dist/observability/routes.d.ts +1 -1
  203. package/dist/progress/routes.d.ts +1 -1
  204. package/dist/server/action-discovery.d.ts.map +1 -1
  205. package/dist/server/action-discovery.js +12 -0
  206. package/dist/server/action-discovery.js.map +1 -1
  207. package/dist/server/action-routes.d.ts +3 -0
  208. package/dist/server/action-routes.d.ts.map +1 -1
  209. package/dist/server/action-routes.js +45 -5
  210. package/dist/server/action-routes.js.map +1 -1
  211. package/dist/server/agent-chat-plugin.d.ts +6 -0
  212. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  213. package/dist/server/agent-chat-plugin.js +71 -6
  214. package/dist/server/agent-chat-plugin.js.map +1 -1
  215. package/dist/server/agent-engine-api-key-route.d.ts +1 -1
  216. package/dist/server/index.d.ts +1 -0
  217. package/dist/server/index.d.ts.map +1 -1
  218. package/dist/server/index.js +1 -0
  219. package/dist/server/index.js.map +1 -1
  220. package/dist/settings/org-settings.d.ts +2 -0
  221. package/dist/settings/org-settings.d.ts.map +1 -1
  222. package/dist/settings/org-settings.js +5 -1
  223. package/dist/settings/org-settings.js.map +1 -1
  224. package/dist/settings/store.d.ts +8 -0
  225. package/dist/settings/store.d.ts.map +1 -1
  226. package/dist/settings/store.js +48 -0
  227. package/dist/settings/store.js.map +1 -1
  228. package/dist/templates/chat/.agents/skills/feature-flags/SKILL.md +169 -0
  229. package/dist/templates/default/.agents/skills/feature-flags/SKILL.md +169 -0
  230. package/dist/templates/default/AGENTS.md +1 -0
  231. package/dist/templates/headless/.agents/skills/feature-flags/SKILL.md +169 -0
  232. package/dist/templates/workspace-core/.agents/skills/feature-flags/SKILL.md +169 -0
  233. package/dist/templates/workspace-core/AGENTS.md +1 -1
  234. package/dist/templates/workspace-root/AGENTS.md +1 -1
  235. package/dist/vite/action-types-plugin.d.ts.map +1 -1
  236. package/dist/vite/action-types-plugin.js +12 -0
  237. package/dist/vite/action-types-plugin.js.map +1 -1
  238. package/docs/content/actions.mdx +48 -0
  239. package/docs/content/locales/ar-SA/actions.mdx +38 -0
  240. package/docs/content/locales/de-DE/actions.mdx +38 -0
  241. package/docs/content/locales/es-ES/actions.mdx +38 -0
  242. package/docs/content/locales/fr-FR/actions.mdx +38 -0
  243. package/docs/content/locales/hi-IN/actions.mdx +38 -0
  244. package/docs/content/locales/ja-JP/actions.mdx +38 -0
  245. package/docs/content/locales/ko-KR/actions.mdx +38 -0
  246. package/docs/content/locales/pt-BR/actions.mdx +38 -0
  247. package/docs/content/locales/zh-CN/actions.mdx +38 -0
  248. package/docs/content/locales/zh-TW/actions.mdx +38 -0
  249. package/package.json +5 -1
  250. package/src/templates/chat/.agents/skills/feature-flags/SKILL.md +169 -0
  251. package/src/templates/default/.agents/skills/feature-flags/SKILL.md +169 -0
  252. package/src/templates/default/AGENTS.md +1 -0
  253. package/src/templates/headless/.agents/skills/feature-flags/SKILL.md +169 -0
  254. package/src/templates/workspace-core/.agents/skills/feature-flags/SKILL.md +169 -0
  255. package/src/templates/workspace-core/AGENTS.md +1 -1
  256. package/src/templates/workspace-root/AGENTS.md +1 -1
  257. package/corpus/templates/clips/actions/get-feature-flags.ts +0 -30
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,mCAAmC;AACnC,+CAA+C;AAE/C,0BAA0B;AAC1B,OAAO,EACL,4BAA4B,EAU5B,aAAa;AACb,6DAA6D;AAC7D,QAAQ,GAIT,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,sBAAsB,EA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BAAoB,EACpB,kCAAkC,EAClC,iCAAiC,EACjC,iBAAiB,EACjB,8BAA8B,EAC9B,+BAA+B,EAC/B,mBAAmB,EACnB,gCAAgC,EAChC,6CAA6C,EAC7C,2CAA2C,EAC3C,sBAAsB,EACtB,mCAAmC,GA2BpC,MAAM,wBAAwB,CAAC;AAEhC,UAAU;AACV,OAAO,EACL,SAAS,EACT,OAAO,EACP,SAAS,EACT,aAAa,EACb,WAAW,EACX,kBAAkB,EAClB,SAAS,EACT,IAAI,GACL,MAAM,oBAAoB,CAAC;AAE5B,4EAA4E;AAC5E,wEAAwE;AACxE,mCAAmC;AACnC,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,iBAAiB,EACjB,aAAa,EACb,cAAc,EACd,eAAe,GAMhB,MAAM,oBAAoB,CAAC;AAE5B,cAAc,oBAAoB,CAAC;AACnC,cAAc,mBAAmB,CAAC;AAClC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,+BAA+B,CAAC;AAC9C,OAAO,EACL,yCAAyC,GAE1C,MAAM,8BAA8B,CAAC","sourcesContent":["// Framework for agent-native apps.\n// Import everything from \"@agent-native/core\".\n\n// Agent (production mode)\nexport {\n createProductionAgentHandler,\n type ActionEntry,\n type ScriptEntry,\n type ProductionAgentOptions,\n type ActionTool,\n type ScriptTool,\n type AgentMessage,\n type AgentChatRequest,\n type AgentChatEvent,\n type AgentChatAttachment,\n DEFAULT_MODEL,\n // In-loop processors (observers/guardrails for runAgentLoop)\n TripWire,\n type Processor,\n type ProcessorState,\n type ProcessorAbort,\n} from \"./agent/index.js\";\nexport {\n defineAction,\n AgentActionStopError,\n isAgentActionStopError,\n type ActionDefinition,\n type ActionHttpConfig,\n type AgentActionStopOptions,\n type PublicAgentActionConfig,\n type ActionDeepLink,\n type ActionLinkBuilder,\n MCP_APP_EXTENSION_ID,\n MCP_APP_MIME_TYPE,\n MCP_APP_RESOURCE_URI_META_KEY,\n type ActionMcpAppConfig,\n type ActionMcpAppCsp,\n type ActionMcpAppCspBuilder,\n type ActionMcpAppHtmlBuilder,\n type ActionMcpAppPermissions,\n type ActionMcpAppResourceConfig,\n type ActionMcpAppResourceMeta,\n} from \"./action.js\";\nexport {\n embedApp,\n MCP_APP_REQUEST_ORIGIN_CSP_SOURCE,\n type EmbedAppOptions,\n} from \"./mcp/embed-app.js\";\nexport {\n embedRoute,\n type EmbedRouteContext,\n type EmbedRouteOptions,\n type EmbedRoutePathBuilder,\n type EmbedRouteResult,\n} from \"./mcp/embed-route.js\";\nexport {\n ACTION_CHAT_UI_DATA_CHART_RENDERER,\n ACTION_CHAT_UI_DATA_INSIGHTS_RENDERER,\n ACTION_CHAT_UI_DATA_TABLE_RENDERER,\n ACTION_CHAT_UI_DATA_WIDGET_RENDERER,\n ACTION_CHAT_UI_INLINE_EXTENSION_RENDERER,\n type ActionChatUIConfig,\n} from \"./action-ui.js\";\nexport {\n DATA_CHART_WIDGET,\n DATA_INSIGHTS_WIDGET,\n DATA_TABLE_WIDGET,\n createDataChartWidgetResult,\n createDataInsightsWidgetResult,\n createDataTableWidgetResult,\n dataChartWidgetResultSchema,\n dataChartWidgetSchema,\n dataInsightsWidgetResultSchema,\n dataTableWidgetResultSchema,\n dataTableWidgetSchema,\n dataWidgetResultSchema,\n isDataChartWidget,\n isDataTableWidget,\n isDataWidgetResult,\n normalizeDataWidgetKind,\n normalizeDataWidgetResult,\n type DataChartSeriesDefinition,\n type DataChartWidget,\n type DataChartWidgetResult,\n type DataChartWidgetResultInput,\n type DataInsightsWidgetResult,\n type DataInsightsWidgetResultInput,\n type DataTableColumn,\n type DataTableWidget,\n type DataTableWidgetResult,\n type DataTableWidgetResultInput,\n type DataWidgetDisplay,\n type DataWidgetKind,\n type DataWidgetResult,\n type DataWidgetResultMetadata,\n} from \"./data-widgets/index.js\";\nexport { createDevScriptRegistry } from \"./scripts/dev/index.js\";\nexport {\n createAgentChatPlugin,\n defaultAgentChatPlugin,\n type AgentChatPluginOptions,\n} from \"./server/agent-chat-plugin.js\";\nexport {\n createAgentNativeEmbeddedPlugin,\n mountAgentNativeEmbedded,\n type AgentNativeEmbeddedPluginOptions,\n} from \"./server/embedded.js\";\nexport {\n BUILT_IN_INTEGRATION_CATALOG,\n INTEGRATION_CATEGORIES,\n getIntegrationCatalogEntry,\n listBuiltInChannelIntegrations,\n listIntegrationCatalog,\n type AutomationCapabilities,\n type BuiltInChannelId,\n type ChannelCapabilities,\n type IntegrationAvailability,\n type IntegrationCatalogEntry,\n type IntegrationCategory,\n type IntegrationCredentialRequirement,\n type IntegrationIconKey,\n type IntegrationSupportMaturity,\n} from \"./integrations/catalog.js\";\nexport {\n AutomationConnectorError,\n createAutomationCallbackHandler,\n createAutomationRuntime,\n createInvokeAutomationWorkflowAction,\n type AutomationCallbackAuthentication,\n type AutomationCallbackInput,\n type AutomationCallbackResult,\n type AutomationInboundDefinition,\n type AutomationInvocation,\n type AutomationInvocationResult,\n type AutomationInvocationStatus,\n type AutomationOutboundDefinition,\n type AutomationResponseMode,\n type AutomationRetryPolicy,\n type AutomationRuntime,\n type AutomationRuntimeOptions,\n type AutomationWorkflowCapabilities,\n type AutomationWorkflowDefinition,\n type JsonSchema,\n} from \"./automation/index.js\";\n\n// Server\nexport {\n createServer,\n createSSEHandler,\n defineNitroPlugin,\n autoMountAuth,\n getSession,\n type CreateServerOptions,\n type SSEHandlerOptions,\n type AuthSession,\n type AuthOptions,\n} from \"./server/index.js\";\n\n// Client\n//\n// IMPORTANT: this top-level entry (the package `default`/Node condition) must\n// stay server-safe. It is what `import { defineAction } from \"@agent-native/core\"`\n// resolves to in a headless / Node / SSR context, where React, react-router, and\n// @tanstack/react-query are NOT installed. The React client surface therefore\n// lives behind the `@agent-native/core/client` subpath instead of being\n// re-exported here — re-exporting \"./client/index.js\" from this module would\n// eagerly pull route-state.ts → \"@tanstack/react-query\" into the load graph and\n// crash any headless app at module load.\n//\n// Browser bundlers resolve \"@agent-native/core\" to the `browser` condition\n// (./index.browser.ts), which re-exports the client surface, so UI code that\n// imports client helpers from the bare specifier keeps working in the browser.\n// Code that runs through the Node entry (SSR, scripts, headless) must import\n// client helpers explicitly:\n//\n// import { useDbSync, cn } from \"@agent-native/core/client\";\n\n// Shared (isomorphic)\nexport {\n agentChat,\n type AgentChatCallOptions,\n type AgentChatResponse,\n} from \"./shared/index.js\";\nexport {\n EMBED_MODE_QUERY_PARAM,\n EMBED_SESSION_COOKIE,\n EMBED_START_PATH,\n EMBED_TOKEN_QUERY_PARAM,\n} from \"./shared/embed-auth.js\";\n\n// Agent Web surfaces\nexport {\n AGENT_WEB_CRAWLER_CATEGORIES,\n AGENT_WEB_CRAWLER_USER_AGENTS,\n DEFAULT_AGENT_WEB_CRAWLER_POLICY,\n absoluteUrl,\n agentWebConfigFromPackageJson,\n buildAgentWebStaticFiles,\n buildBaseJsonLd,\n buildLlmsFullTxt,\n buildLlmsTxt,\n buildMarkdownResponseHeaders,\n buildPageJsonLd,\n buildRobotsTxt,\n buildSitemapXml,\n deriveAgentWebPublicRoutes,\n estimateMarkdownTokens,\n markdownFilePathForPage,\n markdownUrlForPage,\n normalizeAgentWebConfig,\n pathPatternMatches,\n resolveAgentWebCrawlerPolicy,\n type AgentWebConfig,\n type AgentWebCrawlerCategory,\n type AgentWebCrawlerDecision,\n type AgentWebCrawlerOverrides,\n type AgentWebCrawlerPolicy,\n type AgentWebInputConfig,\n type AgentWebPage,\n type AgentWebStaticFile,\n type BuildAgentWebStaticFilesOptions,\n type DeriveAgentWebPublicRoutesOptions,\n type MarkdownResponseHeadersOptions,\n} from \"./agent-web/index.js\";\n\n// Token usage tracking\nexport {\n recordUsage,\n getUsageSummary,\n getUserUsageCents,\n calculateCost,\n usageBillingForEngine,\n builderCreditsFromCostCents,\n BUILDER_AGENT_CREDIT_MARGIN_MULTIPLIER,\n BUILDER_AGENT_CREDITS_PER_USD,\n BUILDER_CREDIT_USAGE_BILLING,\n USD_USAGE_BILLING,\n type UsageRecord,\n type UsageCostSource,\n type UsageCostAggregate,\n type UsageSummary,\n type UsageBillingMode,\n type UsageBillingUnit,\n type UsageBucket,\n type DailyBucket,\n type UsageRecentEntry,\n} from \"./usage/store.js\";\n\n// Workspace-scoped third-party connection metadata\nexport {\n deleteWorkspaceConnection,\n getWorkspaceConnectionAppAccess,\n getWorkspaceConnection,\n getWorkspaceConnectionGrant,\n listWorkspaceConnectionProviderCatalogForApp,\n listWorkspaceConnectionGrants,\n listWorkspaceConnections,\n resolveWorkspaceConnectionCredentialForApp,\n resolveWorkspaceConnectionCredentialsForApp,\n revokeWorkspaceConnectionGrant,\n serializeWorkspaceConnectionGrant,\n serializeWorkspaceConnection,\n summarizeWorkspaceConnectionProviderForApp,\n summarizeWorkspaceConnectionProviderReadiness,\n upsertWorkspaceConnectionGrant,\n upsertWorkspaceConnection,\n type ListWorkspaceConnectionProviderCatalogForAppOptions,\n type ListWorkspaceConnectionGrantsOptions,\n type ListWorkspaceConnectionsOptions,\n type ResolveWorkspaceConnectionCredentialForAppOptions,\n type ResolveWorkspaceConnectionCredentialsForAppOptions,\n type SerializedWorkspaceConnectionGrant,\n type SerializedWorkspaceConnection,\n type SummarizeWorkspaceConnectionProviderForAppOptions,\n type SummarizeWorkspaceConnectionProviderReadinessOptions,\n type UpsertWorkspaceConnectionGrantInput,\n type UpsertWorkspaceConnectionInput,\n type WorkspaceConnectionAppAccess,\n type WorkspaceConnectionAppAccessMode,\n type WorkspaceConnection,\n type WorkspaceConnectionCredentialBackend,\n type WorkspaceConnectionCredentialProvenance,\n type WorkspaceConnectionCredentialRef,\n type WorkspaceConnectionCredentialResolution,\n type WorkspaceConnectionCredentialResolutionCheck,\n type WorkspaceConnectionCredentialResolutionStatus,\n type WorkspaceConnectionCredentialsResolution,\n type WorkspaceConnectionExplicitGrantSummary,\n type WorkspaceConnectionForAppSummary,\n type WorkspaceConnectionGrant,\n type WorkspaceConnectionGrantAvailability,\n type WorkspaceConnectionGrantState,\n type WorkspaceConnectionProviderAppSummary,\n type WorkspaceConnectionProviderLike,\n type WorkspaceConnectionProviderCatalogForApp,\n type WorkspaceConnectionProviderCatalogForAppItem,\n type WorkspaceConnectionProviderReadiness,\n type WorkspaceConnectionProviderReadinessStatus,\n type WorkspaceConnectionPublicCredentialRef,\n type WorkspaceConnectionStatus,\n workspaceConnectionIsAvailableToApp,\n registerWorkspaceConnectionLifecycleListener,\n type WorkspaceConnectionLifecycleEvent,\n type WorkspaceConnectionLifecycleListener,\n} from \"./workspace-connections/index.js\";\n\n// Reusable workspace connection provider catalog\nexport {\n PROVIDER_READERS,\n ProviderReaderRuntimeError,\n WORKSPACE_CONNECTION_PROVIDERS,\n createProviderReaderRuntime,\n defineProviderReader,\n defineProviderReaderImplementation,\n defineWorkspaceConnectionProvider,\n getProviderReader,\n getWorkspaceConnectionProvider,\n isWorkspaceConnectionProviderId,\n listProviderReaders,\n listWorkspaceConnectionProviders,\n listWorkspaceConnectionProvidersForCapability,\n listWorkspaceConnectionProvidersForTemplate,\n providerReaderSupports,\n workspaceConnectionProviderSupports,\n type ListWorkspaceConnectionProvidersOptions,\n type ListProviderReadersOptions,\n type ProviderReaderCapability,\n type ProviderReaderCredentialRequirement,\n type ProviderReaderDefinition,\n type ProviderReaderImplementationStatus,\n type ProviderReaderOperation,\n type ProviderReaderOperationDescriptor,\n type ProviderReaderOperationParameter,\n type ProviderReaderRequest,\n type ProviderReaderRuntime,\n type ProviderReaderRuntimeConnection,\n type ProviderReaderRuntimeConnectionResolverOptions,\n type ProviderReaderRuntimeContext,\n type ProviderReaderRuntimeCredentialsResolverOptions,\n type ProviderReaderRuntimeErrorCode,\n type ProviderReaderRuntimeHandler,\n type ProviderReaderRuntimeImplementation,\n type ProviderReaderRuntimeItem,\n type ProviderReaderRuntimeOptions,\n type ProviderReaderRuntimeResponse,\n type WorkspaceConnectionCapability,\n type WorkspaceConnectionCredentialKey,\n type WorkspaceConnectionProvider,\n type WorkspaceConnectionProviderId,\n type WorkspaceConnectionTemplateUse,\n} from \"./connections/index.js\";\n\n// Scripts\nexport {\n runScript,\n loadEnv,\n parseArgs,\n camelCaseArgs,\n isValidPath,\n isValidProjectPath,\n ensureDir,\n fail,\n} from \"./scripts/index.js\";\n\n// Secrets registry — import from \"@agent-native/core/secrets\" when possible\n// (the subpath keeps the top-level entry point lean), but re-export the\n// public API here for convenience.\nexport {\n registerRequiredSecret,\n listRequiredSecrets,\n getRequiredSecret,\n readAppSecret,\n writeAppSecret,\n deleteAppSecret,\n type RegisteredSecret,\n type SecretScope,\n type SecretKind,\n type SecretValidator,\n type SecretRef,\n} from \"./secrets/index.js\";\n\nexport * from \"./history/index.js\";\nexport * from \"./review/index.js\";\nexport * from \"./org-team/index.js\";\nexport * from \"./navigation/index.js\";\nexport * from \"./command-navigation/index.js\";\nexport {\n registerWorkspaceConnectionOnboardingStep,\n type RegisterWorkspaceConnectionOnboardingStepOptions,\n} from \"./setup-connections/index.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,mCAAmC;AACnC,+CAA+C;AAE/C,0BAA0B;AAC1B,OAAO,EACL,4BAA4B,EAU5B,aAAa;AACb,6DAA6D;AAC7D,QAAQ,GAIT,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,sBAAsB,EAOtB,oBAAoB,EACpB,iBAAiB,EACjB,6BAA6B,GAQ9B,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,QAAQ,EACR,iCAAiC,GAElC,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,UAAU,GAKX,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,kCAAkC,EAClC,qCAAqC,EACrC,kCAAkC,EAClC,mCAAmC,EACnC,wCAAwC,GAEzC,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,iBAAiB,EACjB,2BAA2B,EAC3B,8BAA8B,EAC9B,2BAA2B,EAC3B,2BAA2B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AAO,EACP,SAAS,EACT,aAAa,EACb,WAAW,EACX,kBAAkB,EAClB,SAAS,EACT,IAAI,GACL,MAAM,oBAAoB,CAAC;AAE5B,4EAA4E;AAC5E,wEAAwE;AACxE,mCAAmC;AACnC,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,iBAAiB,EACjB,aAAa,EACb,cAAc,EACd,eAAe,GAMhB,MAAM,oBAAoB,CAAC;AAE5B,cAAc,oBAAoB,CAAC;AACnC,cAAc,mBAAmB,CAAC;AAClC,cAAc,qBAAqB,CAAC;AACpC,cAAc,uBAAuB,CAAC;AACtC,cAAc,+BAA+B,CAAC;AAC9C,OAAO,EACL,yCAAyC,GAE1C,MAAM,8BAA8B,CAAC","sourcesContent":["// Framework for agent-native apps.\n// Import everything from \"@agent-native/core\".\n\n// Agent (production mode)\nexport {\n createProductionAgentHandler,\n type ActionEntry,\n type ScriptEntry,\n type ProductionAgentOptions,\n type ActionTool,\n type ScriptTool,\n type AgentMessage,\n type AgentChatRequest,\n type AgentChatEvent,\n type AgentChatAttachment,\n DEFAULT_MODEL,\n // In-loop processors (observers/guardrails for runAgentLoop)\n TripWire,\n type Processor,\n type ProcessorState,\n type ProcessorAbort,\n} from \"./agent/index.js\";\nexport {\n defineAction,\n AgentActionStopError,\n isAgentActionStopError,\n type ActionDefinition,\n type ActionHttpConfig,\n type AgentActionStopOptions,\n type PublicAgentActionConfig,\n type ActionDeepLink,\n type ActionLinkBuilder,\n MCP_APP_EXTENSION_ID,\n MCP_APP_MIME_TYPE,\n MCP_APP_RESOURCE_URI_META_KEY,\n type ActionMcpAppConfig,\n type ActionMcpAppCsp,\n type ActionMcpAppCspBuilder,\n type ActionMcpAppHtmlBuilder,\n type ActionMcpAppPermissions,\n type ActionMcpAppResourceConfig,\n type ActionMcpAppResourceMeta,\n} from \"./action.js\";\nexport {\n embedApp,\n MCP_APP_REQUEST_ORIGIN_CSP_SOURCE,\n type EmbedAppOptions,\n} from \"./mcp/embed-app.js\";\nexport {\n embedRoute,\n type EmbedRouteContext,\n type EmbedRouteOptions,\n type EmbedRoutePathBuilder,\n type EmbedRouteResult,\n} from \"./mcp/embed-route.js\";\nexport {\n ACTION_CHAT_UI_DATA_CHART_RENDERER,\n ACTION_CHAT_UI_DATA_INSIGHTS_RENDERER,\n ACTION_CHAT_UI_DATA_TABLE_RENDERER,\n ACTION_CHAT_UI_DATA_WIDGET_RENDERER,\n ACTION_CHAT_UI_INLINE_EXTENSION_RENDERER,\n type ActionChatUIConfig,\n} from \"./action-ui.js\";\nexport {\n DATA_CHART_WIDGET,\n DATA_INSIGHTS_WIDGET,\n DATA_TABLE_WIDGET,\n createDataChartWidgetResult,\n createDataInsightsWidgetResult,\n createDataTableWidgetResult,\n dataChartWidgetResultSchema,\n dataChartWidgetSchema,\n dataInsightsWidgetResultSchema,\n dataTableWidgetResultSchema,\n dataTableWidgetSchema,\n dataWidgetResultSchema,\n isDataChartWidget,\n isDataTableWidget,\n isDataWidgetResult,\n normalizeDataWidgetKind,\n normalizeDataWidgetResult,\n type DataChartSeriesDefinition,\n type DataChartWidget,\n type DataChartWidgetResult,\n type DataChartWidgetResultInput,\n type DataInsightsWidgetResult,\n type DataInsightsWidgetResultInput,\n type DataTableColumn,\n type DataTableWidget,\n type DataTableWidgetResult,\n type DataTableWidgetResultInput,\n type DataWidgetDisplay,\n type DataWidgetKind,\n type DataWidgetResult,\n type DataWidgetResultMetadata,\n} from \"./data-widgets/index.js\";\nexport { createDevScriptRegistry } from \"./scripts/dev/index.js\";\nexport {\n createAgentChatPlugin,\n defaultAgentChatPlugin,\n type AgentChatPluginOptions,\n} from \"./server/agent-chat-plugin.js\";\nexport {\n createAgentNativeEmbeddedPlugin,\n mountAgentNativeEmbedded,\n type AgentNativeEmbeddedPluginOptions,\n} from \"./server/embedded.js\";\nexport {\n BUILT_IN_INTEGRATION_CATALOG,\n INTEGRATION_CATEGORIES,\n getIntegrationCatalogEntry,\n listBuiltInChannelIntegrations,\n listIntegrationCatalog,\n type AutomationCapabilities,\n type BuiltInChannelId,\n type ChannelCapabilities,\n type IntegrationAvailability,\n type IntegrationCatalogEntry,\n type IntegrationCategory,\n type IntegrationCredentialRequirement,\n type IntegrationIconKey,\n type IntegrationSupportMaturity,\n} from \"./integrations/catalog.js\";\nexport {\n AutomationConnectorError,\n createAutomationCallbackHandler,\n createAutomationRuntime,\n createInvokeAutomationWorkflowAction,\n type AutomationCallbackAuthentication,\n type AutomationCallbackInput,\n type AutomationCallbackResult,\n type AutomationInboundDefinition,\n type AutomationInvocation,\n type AutomationInvocationResult,\n type AutomationInvocationStatus,\n type AutomationOutboundDefinition,\n type AutomationResponseMode,\n type AutomationRetryPolicy,\n type AutomationRuntime,\n type AutomationRuntimeOptions,\n type AutomationWorkflowCapabilities,\n type AutomationWorkflowDefinition,\n type JsonSchema,\n} from \"./automation/index.js\";\nexport {\n createFeatureFlagsPlugin,\n defineFeatureFlag,\n defineFeatureFlags,\n evaluateFeatureFlag,\n getFeatureFlagDefinition,\n getFeatureFlagRules,\n isFeatureFlagEnabled,\n listFeatureFlags,\n registerFeatureFlags,\n type FeatureFlagDefinition,\n type FeatureFlagMode,\n type FeatureFlagRules,\n type FeatureFlagScope,\n} from \"./feature-flags/index.js\";\n\n// Server\nexport {\n createServer,\n createSSEHandler,\n defineNitroPlugin,\n autoMountAuth,\n getSession,\n type CreateServerOptions,\n type SSEHandlerOptions,\n type AuthSession,\n type AuthOptions,\n} from \"./server/index.js\";\n\n// Client\n//\n// IMPORTANT: this top-level entry (the package `default`/Node condition) must\n// stay server-safe. It is what `import { defineAction } from \"@agent-native/core\"`\n// resolves to in a headless / Node / SSR context, where React, react-router, and\n// @tanstack/react-query are NOT installed. The React client surface therefore\n// lives behind the `@agent-native/core/client` subpath instead of being\n// re-exported here — re-exporting \"./client/index.js\" from this module would\n// eagerly pull route-state.ts → \"@tanstack/react-query\" into the load graph and\n// crash any headless app at module load.\n//\n// Browser bundlers resolve \"@agent-native/core\" to the `browser` condition\n// (./index.browser.ts), which re-exports the client surface, so UI code that\n// imports client helpers from the bare specifier keeps working in the browser.\n// Code that runs through the Node entry (SSR, scripts, headless) must import\n// client helpers explicitly:\n//\n// import { useDbSync, cn } from \"@agent-native/core/client\";\n\n// Shared (isomorphic)\nexport {\n agentChat,\n type AgentChatCallOptions,\n type AgentChatResponse,\n} from \"./shared/index.js\";\nexport {\n EMBED_MODE_QUERY_PARAM,\n EMBED_SESSION_COOKIE,\n EMBED_START_PATH,\n EMBED_TOKEN_QUERY_PARAM,\n} from \"./shared/embed-auth.js\";\n\n// Agent Web surfaces\nexport {\n AGENT_WEB_CRAWLER_CATEGORIES,\n AGENT_WEB_CRAWLER_USER_AGENTS,\n DEFAULT_AGENT_WEB_CRAWLER_POLICY,\n absoluteUrl,\n agentWebConfigFromPackageJson,\n buildAgentWebStaticFiles,\n buildBaseJsonLd,\n buildLlmsFullTxt,\n buildLlmsTxt,\n buildMarkdownResponseHeaders,\n buildPageJsonLd,\n buildRobotsTxt,\n buildSitemapXml,\n deriveAgentWebPublicRoutes,\n estimateMarkdownTokens,\n markdownFilePathForPage,\n markdownUrlForPage,\n normalizeAgentWebConfig,\n pathPatternMatches,\n resolveAgentWebCrawlerPolicy,\n type AgentWebConfig,\n type AgentWebCrawlerCategory,\n type AgentWebCrawlerDecision,\n type AgentWebCrawlerOverrides,\n type AgentWebCrawlerPolicy,\n type AgentWebInputConfig,\n type AgentWebPage,\n type AgentWebStaticFile,\n type BuildAgentWebStaticFilesOptions,\n type DeriveAgentWebPublicRoutesOptions,\n type MarkdownResponseHeadersOptions,\n} from \"./agent-web/index.js\";\n\n// Token usage tracking\nexport {\n recordUsage,\n getUsageSummary,\n getUserUsageCents,\n calculateCost,\n usageBillingForEngine,\n builderCreditsFromCostCents,\n BUILDER_AGENT_CREDIT_MARGIN_MULTIPLIER,\n BUILDER_AGENT_CREDITS_PER_USD,\n BUILDER_CREDIT_USAGE_BILLING,\n USD_USAGE_BILLING,\n type UsageRecord,\n type UsageCostSource,\n type UsageCostAggregate,\n type UsageSummary,\n type UsageBillingMode,\n type UsageBillingUnit,\n type UsageBucket,\n type DailyBucket,\n type UsageRecentEntry,\n} from \"./usage/store.js\";\n\n// Workspace-scoped third-party connection metadata\nexport {\n deleteWorkspaceConnection,\n getWorkspaceConnectionAppAccess,\n getWorkspaceConnection,\n getWorkspaceConnectionGrant,\n listWorkspaceConnectionProviderCatalogForApp,\n listWorkspaceConnectionGrants,\n listWorkspaceConnections,\n resolveWorkspaceConnectionCredentialForApp,\n resolveWorkspaceConnectionCredentialsForApp,\n revokeWorkspaceConnectionGrant,\n serializeWorkspaceConnectionGrant,\n serializeWorkspaceConnection,\n summarizeWorkspaceConnectionProviderForApp,\n summarizeWorkspaceConnectionProviderReadiness,\n upsertWorkspaceConnectionGrant,\n upsertWorkspaceConnection,\n type ListWorkspaceConnectionProviderCatalogForAppOptions,\n type ListWorkspaceConnectionGrantsOptions,\n type ListWorkspaceConnectionsOptions,\n type ResolveWorkspaceConnectionCredentialForAppOptions,\n type ResolveWorkspaceConnectionCredentialsForAppOptions,\n type SerializedWorkspaceConnectionGrant,\n type SerializedWorkspaceConnection,\n type SummarizeWorkspaceConnectionProviderForAppOptions,\n type SummarizeWorkspaceConnectionProviderReadinessOptions,\n type UpsertWorkspaceConnectionGrantInput,\n type UpsertWorkspaceConnectionInput,\n type WorkspaceConnectionAppAccess,\n type WorkspaceConnectionAppAccessMode,\n type WorkspaceConnection,\n type WorkspaceConnectionCredentialBackend,\n type WorkspaceConnectionCredentialProvenance,\n type WorkspaceConnectionCredentialRef,\n type WorkspaceConnectionCredentialResolution,\n type WorkspaceConnectionCredentialResolutionCheck,\n type WorkspaceConnectionCredentialResolutionStatus,\n type WorkspaceConnectionCredentialsResolution,\n type WorkspaceConnectionExplicitGrantSummary,\n type WorkspaceConnectionForAppSummary,\n type WorkspaceConnectionGrant,\n type WorkspaceConnectionGrantAvailability,\n type WorkspaceConnectionGrantState,\n type WorkspaceConnectionProviderAppSummary,\n type WorkspaceConnectionProviderLike,\n type WorkspaceConnectionProviderCatalogForApp,\n type WorkspaceConnectionProviderCatalogForAppItem,\n type WorkspaceConnectionProviderReadiness,\n type WorkspaceConnectionProviderReadinessStatus,\n type WorkspaceConnectionPublicCredentialRef,\n type WorkspaceConnectionStatus,\n workspaceConnectionIsAvailableToApp,\n registerWorkspaceConnectionLifecycleListener,\n type WorkspaceConnectionLifecycleEvent,\n type WorkspaceConnectionLifecycleListener,\n} from \"./workspace-connections/index.js\";\n\n// Reusable workspace connection provider catalog\nexport {\n PROVIDER_READERS,\n ProviderReaderRuntimeError,\n WORKSPACE_CONNECTION_PROVIDERS,\n createProviderReaderRuntime,\n defineProviderReader,\n defineProviderReaderImplementation,\n defineWorkspaceConnectionProvider,\n getProviderReader,\n getWorkspaceConnectionProvider,\n isWorkspaceConnectionProviderId,\n listProviderReaders,\n listWorkspaceConnectionProviders,\n listWorkspaceConnectionProvidersForCapability,\n listWorkspaceConnectionProvidersForTemplate,\n providerReaderSupports,\n workspaceConnectionProviderSupports,\n type ListWorkspaceConnectionProvidersOptions,\n type ListProviderReadersOptions,\n type ProviderReaderCapability,\n type ProviderReaderCredentialRequirement,\n type ProviderReaderDefinition,\n type ProviderReaderImplementationStatus,\n type ProviderReaderOperation,\n type ProviderReaderOperationDescriptor,\n type ProviderReaderOperationParameter,\n type ProviderReaderRequest,\n type ProviderReaderRuntime,\n type ProviderReaderRuntimeConnection,\n type ProviderReaderRuntimeConnectionResolverOptions,\n type ProviderReaderRuntimeContext,\n type ProviderReaderRuntimeCredentialsResolverOptions,\n type ProviderReaderRuntimeErrorCode,\n type ProviderReaderRuntimeHandler,\n type ProviderReaderRuntimeImplementation,\n type ProviderReaderRuntimeItem,\n type ProviderReaderRuntimeOptions,\n type ProviderReaderRuntimeResponse,\n type WorkspaceConnectionCapability,\n type WorkspaceConnectionCredentialKey,\n type WorkspaceConnectionProvider,\n type WorkspaceConnectionProviderId,\n type WorkspaceConnectionTemplateUse,\n} from \"./connections/index.js\";\n\n// Scripts\nexport {\n runScript,\n loadEnv,\n parseArgs,\n camelCaseArgs,\n isValidPath,\n isValidProjectPath,\n ensureDir,\n fail,\n} from \"./scripts/index.js\";\n\n// Secrets registry — import from \"@agent-native/core/secrets\" when possible\n// (the subpath keeps the top-level entry point lean), but re-export the\n// public API here for convenience.\nexport {\n registerRequiredSecret,\n listRequiredSecrets,\n getRequiredSecret,\n readAppSecret,\n writeAppSecret,\n deleteAppSecret,\n type RegisteredSecret,\n type SecretScope,\n type SecretKind,\n type SecretValidator,\n type SecretRef,\n} from \"./secrets/index.js\";\n\nexport * from \"./history/index.js\";\nexport * from \"./review/index.js\";\nexport * from \"./org-team/index.js\";\nexport * from \"./navigation/index.js\";\nexport * from \"./command-navigation/index.js\";\nexport {\n registerWorkspaceConnectionOnboardingStep,\n type RegisterWorkspaceConnectionOnboardingStepOptions,\n} from \"./setup-connections/index.js\";\n"]}
@@ -103,10 +103,16 @@ async function processClaimedContinuation(continuation, options) {
103
103
  ...(auth.apiKeyFallbacks ? { fallbackApiKeys: auth.apiKeyFallbacks } : {}),
104
104
  });
105
105
  const deadline = Date.now() + PROCESSOR_WAIT_MS;
106
+ const recoverableArtifactSecrets = await resolveContinuationArtifactSecrets(continuation);
106
107
  let task = null;
108
+ let latestRecoverableArtifactText = null;
107
109
  try {
108
110
  while (Date.now() < deadline) {
109
111
  task = await client.getTask(continuation.a2aTaskId);
112
+ const recoverableArtifactText = extractVerifiedRecoverableArtifactText(task, continuation.agentUrl, recoverableArtifactSecrets);
113
+ if (recoverableArtifactText) {
114
+ latestRecoverableArtifactText = recoverableArtifactText;
115
+ }
110
116
  if (TERMINAL_STATES.has(task.status.state))
111
117
  break;
112
118
  await reportA2AContinuationProgress(continuation, progress, task);
@@ -116,6 +122,10 @@ async function processClaimedContinuation(continuation, options) {
116
122
  catch (err) {
117
123
  if (isTransientA2APollError(err)) {
118
124
  if (shouldStopPollingRemoteTask(continuation)) {
125
+ if (latestRecoverableArtifactText) {
126
+ await deliverAndCompleteA2AContinuation(continuation, adapter, formatRecoverableArtifactFallbackText(latestRecoverableArtifactText), progress);
127
+ return;
128
+ }
119
129
  await notifyAndFailA2AContinuation(continuation, adapter, remotePollFailureReason(continuation), progress);
120
130
  return;
121
131
  }
@@ -131,6 +141,10 @@ async function processClaimedContinuation(continuation, options) {
131
141
  }
132
142
  if (!task || !TERMINAL_STATES.has(task.status.state)) {
133
143
  if (shouldStopPollingRemoteTask(continuation)) {
144
+ if (latestRecoverableArtifactText) {
145
+ await deliverAndCompleteA2AContinuation(continuation, adapter, formatRecoverableArtifactFallbackText(latestRecoverableArtifactText), progress);
146
+ return;
147
+ }
134
148
  await notifyAndFailA2AContinuation(continuation, adapter, remotePollFailureReason(continuation), progress);
135
149
  return;
136
150
  }
@@ -138,6 +152,10 @@ async function processClaimedContinuation(continuation, options) {
138
152
  return;
139
153
  }
140
154
  if (task.status.state !== "completed") {
155
+ if (latestRecoverableArtifactText) {
156
+ await deliverAndCompleteA2AContinuation(continuation, adapter, formatRecoverableArtifactFallbackText(latestRecoverableArtifactText), progress);
157
+ return;
158
+ }
141
159
  const reason = extractTaskText(task) ||
142
160
  `Remote A2A task ${continuation.a2aTaskId} ended with state ${task.status.state}`;
143
161
  await notifyAndFailA2AContinuation(continuation, adapter, reason, progress);
@@ -145,6 +163,10 @@ async function processClaimedContinuation(continuation, options) {
145
163
  }
146
164
  const text = formatContinuationArtifactText(extractTaskText(task), continuation.agentUrl);
147
165
  if (!text.trim()) {
166
+ if (latestRecoverableArtifactText) {
167
+ await deliverAndCompleteA2AContinuation(continuation, adapter, formatRecoverableArtifactFallbackText(latestRecoverableArtifactText), progress);
168
+ return;
169
+ }
148
170
  await notifyAndFailA2AContinuation(continuation, adapter, `Remote A2A task ${continuation.a2aTaskId} completed without text`, progress);
149
171
  return;
150
172
  }
@@ -222,9 +244,10 @@ async function deliverAndCompleteA2AContinuation(continuation, adapter, text, pr
222
244
  const outgoing = adapter.formatAgentResponse(stripA2APersistedArtifactMarkers(text));
223
245
  const deliveryReceipt = await withTimeout(deliverA2AContinuationResponse(adapter, deliveryContinuation, outgoing, progress, "done"), PLATFORM_SEND_TIMEOUT_MS, `${deliveryContinuation.platform} response delivery timed out`);
224
246
  let persistenceError;
247
+ const artifactSecrets = await resolveContinuationArtifactSecrets(deliveryContinuation);
225
248
  for (let attempt = 0; attempt < 3; attempt += 1) {
226
249
  try {
227
- await persistA2AContinuationDelivery(deliveryContinuation, outgoing, deliveryReceipt, text);
250
+ await persistA2AContinuationDelivery(deliveryContinuation, outgoing, deliveryReceipt, text, artifactSecrets);
228
251
  persistenceError = undefined;
229
252
  break;
230
253
  }
@@ -281,7 +304,7 @@ async function deliverA2AContinuationResponse(adapter, continuation, message, pr
281
304
  }
282
305
  return receipt;
283
306
  }
284
- async function persistA2AContinuationDelivery(continuation, outgoing, receipt, artifactText) {
307
+ async function persistA2AContinuationDelivery(continuation, outgoing, receipt, artifactText, artifactSecrets) {
285
308
  const mapping = await getThreadMapping(continuation.platform, continuation.externalThreadId);
286
309
  if (!mapping)
287
310
  return;
@@ -297,9 +320,9 @@ async function persistA2AContinuationDelivery(continuation, outgoing, receipt, a
297
320
  }
298
321
  if (!Array.isArray(repo.messages))
299
322
  repo.messages = [];
300
- const artifacts = extractA2AArtifactIdentities([
301
- { tool: "call-agent", result: artifactText },
302
- ]);
323
+ const artifacts = extractA2AArtifactIdentities([{ tool: "call-agent", result: artifactText }], {
324
+ persistedArtifactSecrets: artifactSecrets,
325
+ });
303
326
  const metadata = {
304
327
  integrationDeliveryAttempted: true,
305
328
  integrationDelivery: {
@@ -479,6 +502,23 @@ async function signFreshContinuationTokens(continuation) {
479
502
  }
480
503
  return tokens;
481
504
  }
505
+ async function resolveContinuationArtifactSecrets(continuation) {
506
+ const secrets = [];
507
+ const add = (secret) => {
508
+ const value = secret?.trim();
509
+ if (value && !secrets.includes(value))
510
+ secrets.push(value);
511
+ };
512
+ add(process.env.A2A_SECRET);
513
+ if (continuation.orgId) {
514
+ try {
515
+ const { getOrgA2ASecret } = await import("../org/context.js");
516
+ add(await getOrgA2ASecret(continuation.orgId));
517
+ }
518
+ catch { }
519
+ }
520
+ return secrets;
521
+ }
482
522
  function isLikelyJwt(token) {
483
523
  return token.split(".").length === 3;
484
524
  }
@@ -491,6 +531,23 @@ function extractTaskText(task) {
491
531
  .map((part) => part.text)
492
532
  .join("\n");
493
533
  }
534
+ function extractVerifiedRecoverableArtifactText(task, agentUrl, artifactSecrets) {
535
+ if (task.status.message?.metadata?.agentNativeRecoverableArtifacts !== true) {
536
+ return null;
537
+ }
538
+ const text = formatContinuationArtifactText(extractTaskText(task), agentUrl);
539
+ if (!text.trim())
540
+ return null;
541
+ // Require the signed identity ledger so arbitrary peer progress prose cannot
542
+ // prematurely complete the continuation.
543
+ const artifacts = extractA2AArtifactIdentities([{ tool: "call-agent", result: text }], {
544
+ persistedArtifactSecrets: artifactSecrets,
545
+ });
546
+ return artifacts.length > 0 ? text : null;
547
+ }
548
+ function formatRecoverableArtifactFallbackText(text) {
549
+ return text.replace("The agent is still working on the full response, but these verified artifacts already exist:", "The downstream agent did not finish its full response, but these verified artifacts already exist:");
550
+ }
494
551
  function formatContinuationArtifactText(text, agentUrl) {
495
552
  const expandedText = expandRelativeUrls(text, agentUrl);
496
553
  return appendA2AArtifactLinks(expandedText, [{ tool: "call-agent", result: expandedText }], { baseUrl: resolveArtifactBaseUrl() });
@@ -1 +1 @@
1
- {"version":3,"file":"a2a-continuation-processor.js","sourceRoot":"","sources":["../../src/integrations/a2a-continuation-processor.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,4BAA4B,EAC5B,gCAAgC,GACjC,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAE3D,OAAO,EACL,+BAA+B,EAC/B,oBAAoB,EACpB,kCAAkC,GACnC,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE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Client, signA2AToken } from \"../a2a/client.js\";\nimport type { Task } from \"../a2a/types.js\";\nimport {\n formatLlmCredentialErrorMessage,\n isLlmCredentialError,\n LLM_MISSING_CREDENTIALS_ERROR_CODE,\n} from \"../agent/engine/credential-errors.js\";\nimport { extractThreadMeta } from \"../agent/thread-data-builder.js\";\nimport { getThread, updateThreadData } from \"../chat-threads/store.js\";\nimport { withConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport { FRAMEWORK_ROUTE_PREFIX } from \"../server/core-routes-plugin.js\";\nimport {\n claimA2AContinuation,\n claimA2AContinuationDelivery,\n claimDueA2AContinuations,\n completeA2AContinuation,\n failA2AContinuation,\n getA2AContinuation,\n rescheduleA2AContinuation,\n type A2AContinuation,\n} from \"./a2a-continuations-store.js\";\nimport { signInternalToken } from \"./internal-token.js\";\nimport { getThreadMapping } from \"./thread-mapping-store.js\";\nimport type {\n OutgoingMessage,\n PlatformAdapter,\n PlatformDeliveryReceipt,\n PlatformRunProgress,\n} from \"./types.js\";\n\nconst PROCESSOR_PATH = `${FRAMEWORK_ROUTE_PREFIX}/integrations/process-a2a-continuation`;\nconst TERMINAL_STATES = new Set([\"completed\", \"failed\", \"canceled\"]);\nconst MAX_ATTEMPTS = 30;\nconst MAX_REMOTE_WORK_MS = 20 * 60_000;\n// Re-dispatch continuations after a short delay. Serverless hosts do not keep\n// in-memory interval sweepers alive between requests, so delayed self-dispatch\n// is the portable retry mechanism.\nconst RESCHEDULE_DELAY_MS = 20_000;\nconst MAX_PRE_CLAIM_WAIT_MS = 25_000;\nconst POLL_INTERVAL_MS = 2_000;\nconst PROCESSOR_WAIT_MS = 10_000;\nconst POLL_REQUEST_TIMEOUT_MS = 8_000;\nconst PLATFORM_SEND_TIMEOUT_MS = 12_000;\nconst DISPATCH_SETTLE_WAIT_MS = 2_000;\nconst COMPLETE_AFTER_DELIVERY_ATTEMPTS = 3;\n\nexport async function dispatchA2AContinuation(\n continuationId: string,\n webhookBaseUrl?: string,\n): Promise<void> {\n const baseUrl =\n webhookBaseUrl ||\n process.env.WEBHOOK_BASE_URL ||\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n `http://localhost:${process.env.PORT || 3000}`;\n\n const url = `${withConfiguredAppBasePath(baseUrl)}${PROCESSOR_PATH}`;\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n try {\n headers[\"Authorization\"] = `Bearer ${signInternalToken(continuationId)}`;\n } catch (err) {\n if (process.env.NODE_ENV === \"production\") {\n console.error(\n `[integrations] Refusing to dispatch A2A continuation ${continuationId} — A2A_SECRET not configured.`,\n );\n return;\n }\n if (err instanceof Error && !/A2A_SECRET/i.test(err.message)) {\n console.error(\n `[integrations] signInternalToken failed unexpectedly for ${continuationId}:`,\n err,\n );\n }\n }\n\n const dispatchPromise = fetch(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ continuationId }),\n })\n .then(async (response) => {\n if (!response.ok) {\n await logFailedDispatchResponse(continuationId, response);\n }\n })\n .catch((err) => {\n console.error(\n `[integrations] Failed to dispatch A2A continuation ${continuationId}:`,\n err,\n );\n });\n\n await Promise.race([\n dispatchPromise,\n new Promise<void>((resolve) =>\n setTimeout(resolve, DISPATCH_SETTLE_WAIT_MS),\n ),\n ]);\n}\n\nasync function logFailedDispatchResponse(\n continuationId: string,\n response: Response,\n): Promise<void> {\n let body = \"\";\n try {\n body = await response.text();\n } catch {}\n\n const trimmedBody = body.trim();\n console.error(\n `[integrations] A2A continuation ${continuationId} processor dispatch returned HTTP ` +\n `${response.status}${response.statusText ? ` ${response.statusText}` : \"\"}` +\n `${trimmedBody ? `: ${trimmedBody.slice(0, 500)}` : \"\"}`,\n );\n}\n\nexport async function processA2AContinuationById(\n continuationId: string,\n options: { adapters: Map<string, PlatformAdapter> },\n): Promise<void> {\n const shouldClaim = await waitForContinuationDue(continuationId);\n if (!shouldClaim) return;\n const continuation = await claimA2AContinuation(continuationId);\n if (!continuation) return;\n await processClaimedContinuation(continuation, options);\n}\n\nexport async function processDueA2AContinuations(options: {\n adapters: Map<string, PlatformAdapter>;\n limit?: number;\n}): Promise<void> {\n const continuations = await claimDueA2AContinuations(options.limit ?? 5);\n for (const continuation of continuations) {\n await processClaimedContinuation(continuation, options).catch((err) =>\n console.error(\n `[integrations] A2A continuation ${continuation.id} failed:`,\n err,\n ),\n );\n }\n}\n\nasync function processClaimedContinuation(\n continuation: A2AContinuation,\n options: { adapters: Map<string, PlatformAdapter> },\n): Promise<void> {\n const adapter = options.adapters.get(continuation.platform);\n if (!adapter) {\n await failA2AContinuation(\n continuation.id,\n `Unknown platform: ${continuation.platform}`,\n );\n return;\n }\n\n const progress = await resumeA2AContinuationProgress(continuation, adapter);\n\n const auth = await signContinuationToken(continuation);\n const client = new A2AClient(continuation.agentUrl, auth.apiKey, {\n requestTimeoutMs: POLL_REQUEST_TIMEOUT_MS,\n ...(auth.apiKeyFallbacks ? { fallbackApiKeys: auth.apiKeyFallbacks } : {}),\n });\n const deadline = Date.now() + PROCESSOR_WAIT_MS;\n let task: Task | null = null;\n\n try {\n while (Date.now() < deadline) {\n task = await client.getTask(continuation.a2aTaskId);\n if (TERMINAL_STATES.has(task.status.state)) break;\n await reportA2AContinuationProgress(continuation, progress, task);\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n } catch (err) {\n if (isTransientA2APollError(err)) {\n if (shouldStopPollingRemoteTask(continuation)) {\n await notifyAndFailA2AContinuation(\n continuation,\n adapter,\n remotePollFailureReason(continuation),\n progress,\n );\n return;\n }\n await rescheduleAndRedispatchA2AContinuation(continuation.id);\n return;\n }\n if (continuation.attempts >= MAX_ATTEMPTS) {\n await notifyAndFailA2AContinuation(\n continuation,\n adapter,\n err instanceof Error ? err.message : String(err),\n progress,\n );\n return;\n }\n await rescheduleAndRedispatchA2AContinuation(continuation.id);\n return;\n }\n\n if (!task || !TERMINAL_STATES.has(task.status.state)) {\n if (shouldStopPollingRemoteTask(continuation)) {\n await notifyAndFailA2AContinuation(\n continuation,\n adapter,\n remotePollFailureReason(continuation),\n progress,\n );\n return;\n }\n await rescheduleAndRedispatchA2AContinuation(continuation.id);\n return;\n }\n\n if (task.status.state !== \"completed\") {\n const reason =\n extractTaskText(task) ||\n `Remote A2A task ${continuation.a2aTaskId} ended with state ${task.status.state}`;\n await notifyAndFailA2AContinuation(continuation, adapter, reason, progress);\n return;\n }\n\n const text = formatContinuationArtifactText(\n extractTaskText(task),\n continuation.agentUrl,\n );\n if (!text.trim()) {\n await notifyAndFailA2AContinuation(\n continuation,\n adapter,\n `Remote A2A task ${continuation.a2aTaskId} completed without text`,\n progress,\n );\n return;\n }\n\n await deliverAndCompleteA2AContinuation(\n continuation,\n adapter,\n text,\n progress,\n );\n}\n\nasync function resumeA2AContinuationProgress(\n continuation: A2AContinuation,\n adapter: PlatformAdapter,\n): Promise<PlatformRunProgress | null> {\n if (!continuation.progressRef || !adapter.resumeRunProgress) return null;\n try {\n const progress = await adapter.resumeRunProgress(\n continuation.incoming,\n continuation.progressRef,\n );\n if (!progress) return null;\n await progress.onEvent({\n type: \"agent_call_progress\",\n agent: continuation.agentName,\n state: \"working\",\n elapsedSeconds: Math.max(\n 0,\n Math.round((Date.now() - continuation.createdAt) / 1_000),\n ),\n detail: \"Continuing in the background\",\n });\n return progress;\n } catch {\n // A continuation still has a normal reply fallback. Do not log the\n // opaque provider reference or the inbound message payload.\n return null;\n }\n}\n\nasync function reportA2AContinuationProgress(\n continuation: A2AContinuation,\n progress: PlatformRunProgress | null,\n task: Task,\n): Promise<void> {\n if (!progress) return;\n await progress.onEvent({\n type: \"agent_call_progress\",\n agent: continuation.agentName,\n state: task.status.state,\n elapsedSeconds: Math.max(\n 0,\n Math.round((Date.now() - continuation.createdAt) / 1_000),\n ),\n detail: \"Still working on the delegated request\",\n });\n}\n\nasync function waitForContinuationDue(\n continuationId: string,\n): Promise<boolean> {\n const continuation = await getA2AContinuation(continuationId);\n if (!continuation) return false;\n if (continuation.status === \"completed\" || continuation.status === \"failed\") {\n return false;\n }\n if (continuation.status !== \"pending\") return true;\n\n const waitMs = continuation.nextCheckAt - Date.now();\n if (waitMs <= 0) return true;\n\n if (waitMs > MAX_PRE_CLAIM_WAIT_MS) return false;\n\n await sleep(waitMs);\n return true;\n}\n\nasync function notifyAndFailA2AContinuation(\n continuation: A2AContinuation,\n adapter: PlatformAdapter,\n reason: string,\n progress: PlatformRunProgress | null = null,\n): Promise<void> {\n const deliveryContinuation = await claimA2AContinuationDelivery(\n continuation.id,\n );\n if (!deliveryContinuation) return;\n\n const message = formatContinuationFailureMessage(\n deliveryContinuation,\n reason,\n );\n try {\n const outgoing = adapter.formatAgentResponse(message);\n await withTimeout(\n deliverA2AContinuationResponse(\n adapter,\n deliveryContinuation,\n outgoing,\n progress,\n \"error\",\n ),\n PLATFORM_SEND_TIMEOUT_MS,\n `${deliveryContinuation.platform} failure notification timed out`,\n );\n } catch (err) {\n console.error(\n `[integrations] Failed to notify ${deliveryContinuation.platform} about failed A2A continuation ${deliveryContinuation.id}:`,\n err,\n );\n }\n\n await failA2AContinuation(deliveryContinuation.id, reason);\n}\n\nasync function deliverAndCompleteA2AContinuation(\n continuation: A2AContinuation,\n adapter: PlatformAdapter,\n text: string,\n progress: PlatformRunProgress | null = null,\n): Promise<void> {\n const deliveryContinuation = await claimA2AContinuationDelivery(\n continuation.id,\n );\n if (!deliveryContinuation) return;\n\n try {\n const outgoing = adapter.formatAgentResponse(\n stripA2APersistedArtifactMarkers(text),\n );\n const deliveryReceipt = await withTimeout(\n deliverA2AContinuationResponse(\n adapter,\n deliveryContinuation,\n outgoing,\n progress,\n \"done\",\n ),\n PLATFORM_SEND_TIMEOUT_MS,\n `${deliveryContinuation.platform} response delivery timed out`,\n );\n let persistenceError: unknown;\n for (let attempt = 0; attempt < 3; attempt += 1) {\n try {\n await persistA2AContinuationDelivery(\n deliveryContinuation,\n outgoing,\n deliveryReceipt,\n text,\n );\n persistenceError = undefined;\n break;\n } catch (err) {\n persistenceError = err;\n }\n }\n if (persistenceError) {\n console.error(\n `[integrations] Delivered A2A continuation ${deliveryContinuation.id} but could not persist its thread history:`,\n persistenceError,\n );\n }\n } catch (err) {\n if (deliveryContinuation.attempts >= MAX_ATTEMPTS) {\n await failA2AContinuation(\n deliveryContinuation.id,\n err instanceof Error ? err.message : String(err),\n );\n return;\n }\n await rescheduleAndRedispatchA2AContinuation(deliveryContinuation.id);\n return;\n }\n\n await completeAfterSuccessfulDelivery(deliveryContinuation);\n}\n\nasync function deliverA2AContinuationResponse(\n adapter: PlatformAdapter,\n continuation: A2AContinuation,\n message: OutgoingMessage,\n progress: PlatformRunProgress | null,\n status: \"done\" | \"error\",\n): Promise<PlatformDeliveryReceipt> {\n if (progress) {\n try {\n await progress.onEvent({\n type: \"agent_call\",\n agent: continuation.agentName,\n status,\n });\n const receipt = await progress.complete(message);\n if (receipt?.status === \"delivered\") return receipt;\n throw new Error(\"Continuation progress completed without delivery proof\");\n } catch {\n // A resumed Slack stream can no longer be finalized (for example when\n // chat.stopStream rejects). Preserve the final answer with the same\n // thread reply fallback used by the initial webhook run. Also ask the\n // adapter to terminate the native stream: otherwise Slack can keep the\n // task card in its working state after the thread fallback succeeds.\n try {\n await progress.fail?.(\n \"I couldn't update the live response, but I posted the final result in this thread.\",\n );\n } catch {\n // The thread reply below is still the authoritative final answer.\n }\n }\n }\n const receipt = await adapter.sendResponse(message, continuation.incoming, {\n placeholderRef: continuation.placeholderRef ?? undefined,\n });\n if (receipt?.status !== \"delivered\") {\n throw new Error(\"Continuation response completed without delivery proof\");\n }\n return receipt;\n}\n\nasync function persistA2AContinuationDelivery(\n continuation: A2AContinuation,\n outgoing: OutgoingMessage,\n receipt: PlatformDeliveryReceipt,\n artifactText: string,\n): Promise<void> {\n const mapping = await getThreadMapping(\n continuation.platform,\n continuation.externalThreadId,\n );\n if (!mapping) return;\n const thread = await getThread(mapping.internalThreadId);\n if (!thread) return;\n\n let repo: any;\n try {\n repo = JSON.parse(thread.threadData || \"{}\");\n } catch {\n repo = {};\n }\n if (!Array.isArray(repo.messages)) repo.messages = [];\n\n const artifacts = extractA2AArtifactIdentities([\n { tool: \"call-agent\", result: artifactText },\n ]);\n const metadata: Record<string, unknown> = {\n integrationDeliveryAttempted: true,\n integrationDelivery: {\n platform: continuation.platform,\n status: \"delivered\",\n text: outgoing.text,\n deliveredAt: new Date().toISOString(),\n ...(receipt.messageRefs?.length\n ? { messageRefs: receipt.messageRefs }\n : {}),\n },\n };\n if (artifacts.length > 0) metadata.integrationArtifacts = artifacts;\n\n repo.messages.push({\n id: `msg-${Date.now()}-assistant-continuation`,\n role: \"assistant\",\n content: [{ type: \"text\", text: outgoing.text }],\n createdAt: new Date().toISOString(),\n metadata,\n });\n const meta = extractThreadMeta(repo);\n await updateThreadData(\n mapping.internalThreadId,\n JSON.stringify(repo),\n meta.title || thread.title || \"Integration Chat\",\n meta.preview || thread.preview || \"\",\n repo.messages.length,\n );\n}\n\nasync function rescheduleAndRedispatchA2AContinuation(\n continuationId: string,\n): Promise<void> {\n await rescheduleA2AContinuation(continuationId, RESCHEDULE_DELAY_MS);\n await dispatchA2AContinuation(continuationId).catch((err) => {\n console.error(\n `[integrations] Failed to redispatch A2A continuation ${continuationId}:`,\n err,\n );\n });\n}\n\nasync function completeAfterSuccessfulDelivery(\n continuation: A2AContinuation,\n): Promise<void> {\n let lastError: unknown;\n for (let attempt = 0; attempt < COMPLETE_AFTER_DELIVERY_ATTEMPTS; attempt++) {\n try {\n await completeA2AContinuation(continuation.id);\n return;\n } catch (err) {\n lastError = err;\n }\n }\n\n console.error(\n `[integrations] ${continuation.platform} accepted A2A continuation ${continuation.id}, ` +\n \"but marking it completed failed. Leaving it in delivering for stale-delivery recovery.\",\n lastError,\n );\n}\n\nfunction formatContinuationFailureMessage(\n continuation: A2AContinuation,\n reason: string,\n): string {\n const explicitCode = extractFailureCode(reason);\n const diagnostics = formatContinuationFailureDiagnostics(\n continuation,\n reason,\n );\n if (isLlmCredentialError(reason, explicitCode)) {\n return (\n formatLlmCredentialErrorMessage({\n agentName: continuation.agentName,\n }) + diagnostics\n );\n }\n\n return `The ${continuation.agentName} agent could not finish this request: ${sanitizeFailureReason(\n reason,\n )}${diagnostics}`;\n}\n\nfunction formatContinuationFailureDiagnostics(\n continuation: A2AContinuation,\n reason: string,\n): string {\n return `\\n\\nError code: \\`${continuationFailureCode(reason)}\\`\\nRequest ID: \\`${continuation.integrationTaskId}\\`\\nContinuation ID: \\`${continuation.id}\\`\\nDownstream task ID: \\`${continuation.a2aTaskId}\\``;\n}\n\nfunction continuationFailureCode(reason: string): string {\n const explicitCode = extractFailureCode(reason);\n if (explicitCode) return explicitCode;\n if (isLlmCredentialError(reason, explicitCode)) {\n return LLM_MISSING_CREDENTIALS_ERROR_CODE;\n }\n if (/\\btimed out polling\\b/i.test(reason)) return \"a2a_remote_timeout\";\n return \"a2a_downstream_error\";\n}\n\nfunction extractFailureCode(reason: string): string | null {\n const match = /\\bcode\\s*[:=]\\s*[`\"']?([a-z][a-z0-9_]{0,79})\\b/i.exec(reason);\n return match?.[1]?.toLowerCase() ?? null;\n}\n\nfunction isRemoteWorkExpired(continuation: A2AContinuation): boolean {\n return Date.now() - continuation.createdAt >= MAX_REMOTE_WORK_MS;\n}\n\nfunction shouldStopPollingRemoteTask(continuation: A2AContinuation): boolean {\n return (\n continuation.attempts >= MAX_ATTEMPTS || isRemoteWorkExpired(continuation)\n );\n}\n\nfunction isTransientA2APollError(err: unknown): boolean {\n if (!(err instanceof Error)) return false;\n if (err.name === \"AbortError\") return true;\n return /operation was aborted|aborted|timed out|timeout|Invalid or expired A2A token|A2A request failed \\((?:401|508)\\)/i.test(\n err.message,\n );\n}\n\nfunction remotePollFailureReason(continuation: A2AContinuation): string {\n if (isRemoteWorkExpired(continuation)) {\n return `Timed out polling the ${continuation.agentName} A2A task ${continuation.a2aTaskId} after ${Math.round(\n MAX_REMOTE_WORK_MS / 60_000,\n )} minutes. The downstream agent did not return a final result.`;\n }\n\n return `Timed out polling the ${continuation.agentName} A2A task ${continuation.a2aTaskId} after ${MAX_ATTEMPTS} attempts. The downstream agent did not return a final result.`;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n message: string,\n): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(message)), timeoutMs);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nfunction sanitizeFailureReason(reason: string): string {\n const oneLine = reason.replace(/\\s+/g, \" \").trim();\n const withoutEnvNames = oneLine.replace(\n /\\b[A-Z][A-Z0-9_]*(?:API_KEY|PRIVATE_KEY|SECRET|TOKEN)\\b/g,\n \"a required credential\",\n );\n return (\n withoutEnvNames.slice(0, 500) ||\n \"the downstream agent returned an empty error\"\n );\n}\n\nasync function signContinuationToken(\n continuation: A2AContinuation,\n): Promise<{ apiKey?: string; apiKeyFallbacks?: string[] }> {\n if (continuation.a2aAuthToken === \"\") {\n return {};\n }\n\n const storedToken = continuation.a2aAuthToken;\n if (storedToken && !isLikelyJwt(storedToken)) return { apiKey: storedToken };\n\n const freshTokens = await signFreshContinuationTokens(continuation);\n if (freshTokens.length > 0) {\n return {\n apiKey: freshTokens[0],\n ...(freshTokens.length > 1\n ? { apiKeyFallbacks: freshTokens.slice(1) }\n : {}),\n };\n }\n if (!storedToken) return {};\n\n // Older continuations may have persisted the initial short-lived JWT. Avoid\n // replaying it forever after expiry; opaque legacy bearer keys can still be\n // reused because we cannot re-mint those.\n if (isLikelyJwt(storedToken)) return {};\n return { apiKey: storedToken };\n}\n\nasync function signFreshContinuationTokens(\n continuation: A2AContinuation,\n): Promise<string[]> {\n let orgDomain: string | undefined;\n let orgSecret: string | undefined;\n if (continuation.orgId) {\n try {\n const { getOrgDomain, getOrgA2ASecret } =\n await import(\"../org/context.js\");\n orgDomain = (await getOrgDomain(continuation.orgId)) ?? undefined;\n orgSecret = (await getOrgA2ASecret(continuation.orgId)) ?? undefined;\n } catch {}\n }\n\n if (!continuation.ownerEmail || !(orgSecret || process.env.A2A_SECRET)) {\n return [];\n }\n\n const tokens: string[] = [];\n const add = (token: string | undefined) => {\n if (token && !tokens.includes(token)) tokens.push(token);\n };\n\n if (process.env.A2A_SECRET?.trim()) {\n try {\n add(\n await signA2AToken(continuation.ownerEmail, orgDomain, orgSecret, {\n expiresIn: \"30m\",\n preferGlobalSecret: true,\n }),\n );\n } catch {}\n }\n if (orgSecret) {\n try {\n add(\n await signA2AToken(continuation.ownerEmail, orgDomain, orgSecret, {\n expiresIn: \"30m\",\n preferGlobalSecret: false,\n }),\n );\n } catch {}\n }\n return tokens;\n}\n\nfunction isLikelyJwt(token: string): boolean {\n return token.split(\".\").length === 3;\n}\n\nfunction extractTaskText(task: Task): string {\n const parts = task.status.message?.parts ?? [];\n return parts\n .filter((part): part is { type: \"text\"; text: string } => {\n return part.type === \"text\" && typeof part.text === \"string\";\n })\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\nfunction formatContinuationArtifactText(\n text: string,\n agentUrl: string,\n): string {\n const expandedText = expandRelativeUrls(text, agentUrl);\n return appendA2AArtifactLinks(\n expandedText,\n [{ tool: \"call-agent\", result: expandedText }],\n { baseUrl: resolveArtifactBaseUrl() },\n );\n}\n\nfunction resolveArtifactBaseUrl(): string | undefined {\n const baseUrl =\n process.env.APP_URL || process.env.URL || process.env.DEPLOY_URL;\n return baseUrl ? withConfiguredAppBasePath(baseUrl) : undefined;\n}\n\nfunction expandRelativeUrls(text: string, agentUrl: string): string {\n if (!text || !agentUrl) return text;\n const base = publicAgentBaseUrl(agentUrl);\n return text.replace(\n /(^|[\\s([<\"'`])(\\/[a-z0-9_-][a-z0-9_/?&=%#.,:-]*)/gi,\n (_match, lead, path) => `${lead}${base}${path}`,\n );\n}\n\nfunction publicAgentBaseUrl(agentUrl: string): string {\n try {\n const url = new URL(agentUrl);\n const routeIndex = url.pathname.indexOf(FRAMEWORK_ROUTE_PREFIX);\n url.pathname =\n routeIndex >= 0\n ? url.pathname.slice(0, routeIndex) || \"/\"\n : url.pathname.replace(/\\/+$/, \"\") || \"/\";\n url.search = \"\";\n url.hash = \"\";\n return url.toString().replace(/\\/$/, \"\");\n } catch {\n return agentUrl.replace(/\\/$/, \"\");\n }\n}\n"]}
1
+ {"version":3,"file":"a2a-continuation-processor.js","sourceRoot":"","sources":["../../src/integrations/a2a-continuation-processor.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,4BAA4B,EAC5B,gCAAgC,GACjC,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAE3D,OAAO,EACL,+BAA+B,EAC/B,oBAAoB,EACpB,kCAAkC,GACnC,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AACzE,OAAO,EACL,oBAAoB,EACpB,4BAA4B,EAC5B,wBAAwB,EACxB,uBAAuB,EACvB,mBAAmB,EACnB,kBAAkB,EAClB,yBAAyB,GAE1B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAQ7D,MAAM,cAAc,GAAG,GAAG,sBAAsB,wCAAwC,CAAC;AACzF,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC;AACrE,MAAM,YAAY,GAAG,EAAE,CA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;YACV,UAAU,IAAI,CAAC;gBACb,CAAC,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,UAAU,CAAC,IAAI,GAAG;gBAC1C,CAAC,CAAC,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC;QAC9C,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;QAChB,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC;QACd,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IAC3C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACrC,CAAC;AACH,CAAC","sourcesContent":["import {\n appendA2AArtifactLinks,\n extractA2AArtifactIdentities,\n stripA2APersistedArtifactMarkers,\n} from \"../a2a/artifact-response.js\";\nimport { A2AClient, signA2AToken } from \"../a2a/client.js\";\nimport type { Task } from \"../a2a/types.js\";\nimport {\n formatLlmCredentialErrorMessage,\n isLlmCredentialError,\n LLM_MISSING_CREDENTIALS_ERROR_CODE,\n} from \"../agent/engine/credential-errors.js\";\nimport { extractThreadMeta } from \"../agent/thread-data-builder.js\";\nimport { getThread, updateThreadData } from \"../chat-threads/store.js\";\nimport { withConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport { FRAMEWORK_ROUTE_PREFIX } from \"../server/core-routes-plugin.js\";\nimport {\n claimA2AContinuation,\n claimA2AContinuationDelivery,\n claimDueA2AContinuations,\n completeA2AContinuation,\n failA2AContinuation,\n getA2AContinuation,\n rescheduleA2AContinuation,\n type A2AContinuation,\n} from \"./a2a-continuations-store.js\";\nimport { signInternalToken } from \"./internal-token.js\";\nimport { getThreadMapping } from \"./thread-mapping-store.js\";\nimport type {\n OutgoingMessage,\n PlatformAdapter,\n PlatformDeliveryReceipt,\n PlatformRunProgress,\n} from \"./types.js\";\n\nconst PROCESSOR_PATH = `${FRAMEWORK_ROUTE_PREFIX}/integrations/process-a2a-continuation`;\nconst TERMINAL_STATES = new Set([\"completed\", \"failed\", \"canceled\"]);\nconst MAX_ATTEMPTS = 30;\nconst MAX_REMOTE_WORK_MS = 20 * 60_000;\n// Re-dispatch continuations after a short delay. Serverless hosts do not keep\n// in-memory interval sweepers alive between requests, so delayed self-dispatch\n// is the portable retry mechanism.\nconst RESCHEDULE_DELAY_MS = 20_000;\nconst MAX_PRE_CLAIM_WAIT_MS = 25_000;\nconst POLL_INTERVAL_MS = 2_000;\nconst PROCESSOR_WAIT_MS = 10_000;\nconst POLL_REQUEST_TIMEOUT_MS = 8_000;\nconst PLATFORM_SEND_TIMEOUT_MS = 12_000;\nconst DISPATCH_SETTLE_WAIT_MS = 2_000;\nconst COMPLETE_AFTER_DELIVERY_ATTEMPTS = 3;\n\nexport async function dispatchA2AContinuation(\n continuationId: string,\n webhookBaseUrl?: string,\n): Promise<void> {\n const baseUrl =\n webhookBaseUrl ||\n process.env.WEBHOOK_BASE_URL ||\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n `http://localhost:${process.env.PORT || 3000}`;\n\n const url = `${withConfiguredAppBasePath(baseUrl)}${PROCESSOR_PATH}`;\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n try {\n headers[\"Authorization\"] = `Bearer ${signInternalToken(continuationId)}`;\n } catch (err) {\n if (process.env.NODE_ENV === \"production\") {\n console.error(\n `[integrations] Refusing to dispatch A2A continuation ${continuationId} — A2A_SECRET not configured.`,\n );\n return;\n }\n if (err instanceof Error && !/A2A_SECRET/i.test(err.message)) {\n console.error(\n `[integrations] signInternalToken failed unexpectedly for ${continuationId}:`,\n err,\n );\n }\n }\n\n const dispatchPromise = fetch(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ continuationId }),\n })\n .then(async (response) => {\n if (!response.ok) {\n await logFailedDispatchResponse(continuationId, response);\n }\n })\n .catch((err) => {\n console.error(\n `[integrations] Failed to dispatch A2A continuation ${continuationId}:`,\n err,\n );\n });\n\n await Promise.race([\n dispatchPromise,\n new Promise<void>((resolve) =>\n setTimeout(resolve, DISPATCH_SETTLE_WAIT_MS),\n ),\n ]);\n}\n\nasync function logFailedDispatchResponse(\n continuationId: string,\n response: Response,\n): Promise<void> {\n let body = \"\";\n try {\n body = await response.text();\n } catch {}\n\n const trimmedBody = body.trim();\n console.error(\n `[integrations] A2A continuation ${continuationId} processor dispatch returned HTTP ` +\n `${response.status}${response.statusText ? ` ${response.statusText}` : \"\"}` +\n `${trimmedBody ? `: ${trimmedBody.slice(0, 500)}` : \"\"}`,\n );\n}\n\nexport async function processA2AContinuationById(\n continuationId: string,\n options: { adapters: Map<string, PlatformAdapter> },\n): Promise<void> {\n const shouldClaim = await waitForContinuationDue(continuationId);\n if (!shouldClaim) return;\n const continuation = await claimA2AContinuation(continuationId);\n if (!continuation) return;\n await processClaimedContinuation(continuation, options);\n}\n\nexport async function processDueA2AContinuations(options: {\n adapters: Map<string, PlatformAdapter>;\n limit?: number;\n}): Promise<void> {\n const continuations = await claimDueA2AContinuations(options.limit ?? 5);\n for (const continuation of continuations) {\n await processClaimedContinuation(continuation, options).catch((err) =>\n console.error(\n `[integrations] A2A continuation ${continuation.id} failed:`,\n err,\n ),\n );\n }\n}\n\nasync function processClaimedContinuation(\n continuation: A2AContinuation,\n options: { adapters: Map<string, PlatformAdapter> },\n): Promise<void> {\n const adapter = options.adapters.get(continuation.platform);\n if (!adapter) {\n await failA2AContinuation(\n continuation.id,\n `Unknown platform: ${continuation.platform}`,\n );\n return;\n }\n\n const progress = await resumeA2AContinuationProgress(continuation, adapter);\n\n const auth = await signContinuationToken(continuation);\n const client = new A2AClient(continuation.agentUrl, auth.apiKey, {\n requestTimeoutMs: POLL_REQUEST_TIMEOUT_MS,\n ...(auth.apiKeyFallbacks ? { fallbackApiKeys: auth.apiKeyFallbacks } : {}),\n });\n const deadline = Date.now() + PROCESSOR_WAIT_MS;\n const recoverableArtifactSecrets =\n await resolveContinuationArtifactSecrets(continuation);\n let task: Task | null = null;\n let latestRecoverableArtifactText: string | null = null;\n\n try {\n while (Date.now() < deadline) {\n task = await client.getTask(continuation.a2aTaskId);\n const recoverableArtifactText = extractVerifiedRecoverableArtifactText(\n task,\n continuation.agentUrl,\n recoverableArtifactSecrets,\n );\n if (recoverableArtifactText) {\n latestRecoverableArtifactText = recoverableArtifactText;\n }\n if (TERMINAL_STATES.has(task.status.state)) break;\n await reportA2AContinuationProgress(continuation, progress, task);\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n } catch (err) {\n if (isTransientA2APollError(err)) {\n if (shouldStopPollingRemoteTask(continuation)) {\n if (latestRecoverableArtifactText) {\n await deliverAndCompleteA2AContinuation(\n continuation,\n adapter,\n formatRecoverableArtifactFallbackText(\n latestRecoverableArtifactText,\n ),\n progress,\n );\n return;\n }\n await notifyAndFailA2AContinuation(\n continuation,\n adapter,\n remotePollFailureReason(continuation),\n progress,\n );\n return;\n }\n await rescheduleAndRedispatchA2AContinuation(continuation.id);\n return;\n }\n if (continuation.attempts >= MAX_ATTEMPTS) {\n await notifyAndFailA2AContinuation(\n continuation,\n adapter,\n err instanceof Error ? err.message : String(err),\n progress,\n );\n return;\n }\n await rescheduleAndRedispatchA2AContinuation(continuation.id);\n return;\n }\n\n if (!task || !TERMINAL_STATES.has(task.status.state)) {\n if (shouldStopPollingRemoteTask(continuation)) {\n if (latestRecoverableArtifactText) {\n await deliverAndCompleteA2AContinuation(\n continuation,\n adapter,\n formatRecoverableArtifactFallbackText(latestRecoverableArtifactText),\n progress,\n );\n return;\n }\n await notifyAndFailA2AContinuation(\n continuation,\n adapter,\n remotePollFailureReason(continuation),\n progress,\n );\n return;\n }\n await rescheduleAndRedispatchA2AContinuation(continuation.id);\n return;\n }\n\n if (task.status.state !== \"completed\") {\n if (latestRecoverableArtifactText) {\n await deliverAndCompleteA2AContinuation(\n continuation,\n adapter,\n formatRecoverableArtifactFallbackText(latestRecoverableArtifactText),\n progress,\n );\n return;\n }\n const reason =\n extractTaskText(task) ||\n `Remote A2A task ${continuation.a2aTaskId} ended with state ${task.status.state}`;\n await notifyAndFailA2AContinuation(continuation, adapter, reason, progress);\n return;\n }\n\n const text = formatContinuationArtifactText(\n extractTaskText(task),\n continuation.agentUrl,\n );\n if (!text.trim()) {\n if (latestRecoverableArtifactText) {\n await deliverAndCompleteA2AContinuation(\n continuation,\n adapter,\n formatRecoverableArtifactFallbackText(latestRecoverableArtifactText),\n progress,\n );\n return;\n }\n await notifyAndFailA2AContinuation(\n continuation,\n adapter,\n `Remote A2A task ${continuation.a2aTaskId} completed without text`,\n progress,\n );\n return;\n }\n\n await deliverAndCompleteA2AContinuation(\n continuation,\n adapter,\n text,\n progress,\n );\n}\n\nasync function resumeA2AContinuationProgress(\n continuation: A2AContinuation,\n adapter: PlatformAdapter,\n): Promise<PlatformRunProgress | null> {\n if (!continuation.progressRef || !adapter.resumeRunProgress) return null;\n try {\n const progress = await adapter.resumeRunProgress(\n continuation.incoming,\n continuation.progressRef,\n );\n if (!progress) return null;\n await progress.onEvent({\n type: \"agent_call_progress\",\n agent: continuation.agentName,\n state: \"working\",\n elapsedSeconds: Math.max(\n 0,\n Math.round((Date.now() - continuation.createdAt) / 1_000),\n ),\n detail: \"Continuing in the background\",\n });\n return progress;\n } catch {\n // A continuation still has a normal reply fallback. Do not log the\n // opaque provider reference or the inbound message payload.\n return null;\n }\n}\n\nasync function reportA2AContinuationProgress(\n continuation: A2AContinuation,\n progress: PlatformRunProgress | null,\n task: Task,\n): Promise<void> {\n if (!progress) return;\n await progress.onEvent({\n type: \"agent_call_progress\",\n agent: continuation.agentName,\n state: task.status.state,\n elapsedSeconds: Math.max(\n 0,\n Math.round((Date.now() - continuation.createdAt) / 1_000),\n ),\n detail: \"Still working on the delegated request\",\n });\n}\n\nasync function waitForContinuationDue(\n continuationId: string,\n): Promise<boolean> {\n const continuation = await getA2AContinuation(continuationId);\n if (!continuation) return false;\n if (continuation.status === \"completed\" || continuation.status === \"failed\") {\n return false;\n }\n if (continuation.status !== \"pending\") return true;\n\n const waitMs = continuation.nextCheckAt - Date.now();\n if (waitMs <= 0) return true;\n\n if (waitMs > MAX_PRE_CLAIM_WAIT_MS) return false;\n\n await sleep(waitMs);\n return true;\n}\n\nasync function notifyAndFailA2AContinuation(\n continuation: A2AContinuation,\n adapter: PlatformAdapter,\n reason: string,\n progress: PlatformRunProgress | null = null,\n): Promise<void> {\n const deliveryContinuation = await claimA2AContinuationDelivery(\n continuation.id,\n );\n if (!deliveryContinuation) return;\n\n const message = formatContinuationFailureMessage(\n deliveryContinuation,\n reason,\n );\n try {\n const outgoing = adapter.formatAgentResponse(message);\n await withTimeout(\n deliverA2AContinuationResponse(\n adapter,\n deliveryContinuation,\n outgoing,\n progress,\n \"error\",\n ),\n PLATFORM_SEND_TIMEOUT_MS,\n `${deliveryContinuation.platform} failure notification timed out`,\n );\n } catch (err) {\n console.error(\n `[integrations] Failed to notify ${deliveryContinuation.platform} about failed A2A continuation ${deliveryContinuation.id}:`,\n err,\n );\n }\n\n await failA2AContinuation(deliveryContinuation.id, reason);\n}\n\nasync function deliverAndCompleteA2AContinuation(\n continuation: A2AContinuation,\n adapter: PlatformAdapter,\n text: string,\n progress: PlatformRunProgress | null = null,\n): Promise<void> {\n const deliveryContinuation = await claimA2AContinuationDelivery(\n continuation.id,\n );\n if (!deliveryContinuation) return;\n\n try {\n const outgoing = adapter.formatAgentResponse(\n stripA2APersistedArtifactMarkers(text),\n );\n const deliveryReceipt = await withTimeout(\n deliverA2AContinuationResponse(\n adapter,\n deliveryContinuation,\n outgoing,\n progress,\n \"done\",\n ),\n PLATFORM_SEND_TIMEOUT_MS,\n `${deliveryContinuation.platform} response delivery timed out`,\n );\n let persistenceError: unknown;\n const artifactSecrets =\n await resolveContinuationArtifactSecrets(deliveryContinuation);\n for (let attempt = 0; attempt < 3; attempt += 1) {\n try {\n await persistA2AContinuationDelivery(\n deliveryContinuation,\n outgoing,\n deliveryReceipt,\n text,\n artifactSecrets,\n );\n persistenceError = undefined;\n break;\n } catch (err) {\n persistenceError = err;\n }\n }\n if (persistenceError) {\n console.error(\n `[integrations] Delivered A2A continuation ${deliveryContinuation.id} but could not persist its thread history:`,\n persistenceError,\n );\n }\n } catch (err) {\n if (deliveryContinuation.attempts >= MAX_ATTEMPTS) {\n await failA2AContinuation(\n deliveryContinuation.id,\n err instanceof Error ? err.message : String(err),\n );\n return;\n }\n await rescheduleAndRedispatchA2AContinuation(deliveryContinuation.id);\n return;\n }\n\n await completeAfterSuccessfulDelivery(deliveryContinuation);\n}\n\nasync function deliverA2AContinuationResponse(\n adapter: PlatformAdapter,\n continuation: A2AContinuation,\n message: OutgoingMessage,\n progress: PlatformRunProgress | null,\n status: \"done\" | \"error\",\n): Promise<PlatformDeliveryReceipt> {\n if (progress) {\n try {\n await progress.onEvent({\n type: \"agent_call\",\n agent: continuation.agentName,\n status,\n });\n const receipt = await progress.complete(message);\n if (receipt?.status === \"delivered\") return receipt;\n throw new Error(\"Continuation progress completed without delivery proof\");\n } catch {\n // A resumed Slack stream can no longer be finalized (for example when\n // chat.stopStream rejects). Preserve the final answer with the same\n // thread reply fallback used by the initial webhook run. Also ask the\n // adapter to terminate the native stream: otherwise Slack can keep the\n // task card in its working state after the thread fallback succeeds.\n try {\n await progress.fail?.(\n \"I couldn't update the live response, but I posted the final result in this thread.\",\n );\n } catch {\n // The thread reply below is still the authoritative final answer.\n }\n }\n }\n const receipt = await adapter.sendResponse(message, continuation.incoming, {\n placeholderRef: continuation.placeholderRef ?? undefined,\n });\n if (receipt?.status !== \"delivered\") {\n throw new Error(\"Continuation response completed without delivery proof\");\n }\n return receipt;\n}\n\nasync function persistA2AContinuationDelivery(\n continuation: A2AContinuation,\n outgoing: OutgoingMessage,\n receipt: PlatformDeliveryReceipt,\n artifactText: string,\n artifactSecrets: readonly string[],\n): Promise<void> {\n const mapping = await getThreadMapping(\n continuation.platform,\n continuation.externalThreadId,\n );\n if (!mapping) return;\n const thread = await getThread(mapping.internalThreadId);\n if (!thread) return;\n\n let repo: any;\n try {\n repo = JSON.parse(thread.threadData || \"{}\");\n } catch {\n repo = {};\n }\n if (!Array.isArray(repo.messages)) repo.messages = [];\n\n const artifacts = extractA2AArtifactIdentities(\n [{ tool: \"call-agent\", result: artifactText }],\n {\n persistedArtifactSecrets: artifactSecrets,\n },\n );\n const metadata: Record<string, unknown> = {\n integrationDeliveryAttempted: true,\n integrationDelivery: {\n platform: continuation.platform,\n status: \"delivered\",\n text: outgoing.text,\n deliveredAt: new Date().toISOString(),\n ...(receipt.messageRefs?.length\n ? { messageRefs: receipt.messageRefs }\n : {}),\n },\n };\n if (artifacts.length > 0) metadata.integrationArtifacts = artifacts;\n\n repo.messages.push({\n id: `msg-${Date.now()}-assistant-continuation`,\n role: \"assistant\",\n content: [{ type: \"text\", text: outgoing.text }],\n createdAt: new Date().toISOString(),\n metadata,\n });\n const meta = extractThreadMeta(repo);\n await updateThreadData(\n mapping.internalThreadId,\n JSON.stringify(repo),\n meta.title || thread.title || \"Integration Chat\",\n meta.preview || thread.preview || \"\",\n repo.messages.length,\n );\n}\n\nasync function rescheduleAndRedispatchA2AContinuation(\n continuationId: string,\n): Promise<void> {\n await rescheduleA2AContinuation(continuationId, RESCHEDULE_DELAY_MS);\n await dispatchA2AContinuation(continuationId).catch((err) => {\n console.error(\n `[integrations] Failed to redispatch A2A continuation ${continuationId}:`,\n err,\n );\n });\n}\n\nasync function completeAfterSuccessfulDelivery(\n continuation: A2AContinuation,\n): Promise<void> {\n let lastError: unknown;\n for (let attempt = 0; attempt < COMPLETE_AFTER_DELIVERY_ATTEMPTS; attempt++) {\n try {\n await completeA2AContinuation(continuation.id);\n return;\n } catch (err) {\n lastError = err;\n }\n }\n\n console.error(\n `[integrations] ${continuation.platform} accepted A2A continuation ${continuation.id}, ` +\n \"but marking it completed failed. Leaving it in delivering for stale-delivery recovery.\",\n lastError,\n );\n}\n\nfunction formatContinuationFailureMessage(\n continuation: A2AContinuation,\n reason: string,\n): string {\n const explicitCode = extractFailureCode(reason);\n const diagnostics = formatContinuationFailureDiagnostics(\n continuation,\n reason,\n );\n if (isLlmCredentialError(reason, explicitCode)) {\n return (\n formatLlmCredentialErrorMessage({\n agentName: continuation.agentName,\n }) + diagnostics\n );\n }\n\n return `The ${continuation.agentName} agent could not finish this request: ${sanitizeFailureReason(\n reason,\n )}${diagnostics}`;\n}\n\nfunction formatContinuationFailureDiagnostics(\n continuation: A2AContinuation,\n reason: string,\n): string {\n return `\\n\\nError code: \\`${continuationFailureCode(reason)}\\`\\nRequest ID: \\`${continuation.integrationTaskId}\\`\\nContinuation ID: \\`${continuation.id}\\`\\nDownstream task ID: \\`${continuation.a2aTaskId}\\``;\n}\n\nfunction continuationFailureCode(reason: string): string {\n const explicitCode = extractFailureCode(reason);\n if (explicitCode) return explicitCode;\n if (isLlmCredentialError(reason, explicitCode)) {\n return LLM_MISSING_CREDENTIALS_ERROR_CODE;\n }\n if (/\\btimed out polling\\b/i.test(reason)) return \"a2a_remote_timeout\";\n return \"a2a_downstream_error\";\n}\n\nfunction extractFailureCode(reason: string): string | null {\n const match = /\\bcode\\s*[:=]\\s*[`\"']?([a-z][a-z0-9_]{0,79})\\b/i.exec(reason);\n return match?.[1]?.toLowerCase() ?? null;\n}\n\nfunction isRemoteWorkExpired(continuation: A2AContinuation): boolean {\n return Date.now() - continuation.createdAt >= MAX_REMOTE_WORK_MS;\n}\n\nfunction shouldStopPollingRemoteTask(continuation: A2AContinuation): boolean {\n return (\n continuation.attempts >= MAX_ATTEMPTS || isRemoteWorkExpired(continuation)\n );\n}\n\nfunction isTransientA2APollError(err: unknown): boolean {\n if (!(err instanceof Error)) return false;\n if (err.name === \"AbortError\") return true;\n return /operation was aborted|aborted|timed out|timeout|Invalid or expired A2A token|A2A request failed \\((?:401|508)\\)/i.test(\n err.message,\n );\n}\n\nfunction remotePollFailureReason(continuation: A2AContinuation): string {\n if (isRemoteWorkExpired(continuation)) {\n return `Timed out polling the ${continuation.agentName} A2A task ${continuation.a2aTaskId} after ${Math.round(\n MAX_REMOTE_WORK_MS / 60_000,\n )} minutes. The downstream agent did not return a final result.`;\n }\n\n return `Timed out polling the ${continuation.agentName} A2A task ${continuation.a2aTaskId} after ${MAX_ATTEMPTS} attempts. The downstream agent did not return a final result.`;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n message: string,\n): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(message)), timeoutMs);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nfunction sanitizeFailureReason(reason: string): string {\n const oneLine = reason.replace(/\\s+/g, \" \").trim();\n const withoutEnvNames = oneLine.replace(\n /\\b[A-Z][A-Z0-9_]*(?:API_KEY|PRIVATE_KEY|SECRET|TOKEN)\\b/g,\n \"a required credential\",\n );\n return (\n withoutEnvNames.slice(0, 500) ||\n \"the downstream agent returned an empty error\"\n );\n}\n\nasync function signContinuationToken(\n continuation: A2AContinuation,\n): Promise<{ apiKey?: string; apiKeyFallbacks?: string[] }> {\n if (continuation.a2aAuthToken === \"\") {\n return {};\n }\n\n const storedToken = continuation.a2aAuthToken;\n if (storedToken && !isLikelyJwt(storedToken)) return { apiKey: storedToken };\n\n const freshTokens = await signFreshContinuationTokens(continuation);\n if (freshTokens.length > 0) {\n return {\n apiKey: freshTokens[0],\n ...(freshTokens.length > 1\n ? { apiKeyFallbacks: freshTokens.slice(1) }\n : {}),\n };\n }\n if (!storedToken) return {};\n\n // Older continuations may have persisted the initial short-lived JWT. Avoid\n // replaying it forever after expiry; opaque legacy bearer keys can still be\n // reused because we cannot re-mint those.\n if (isLikelyJwt(storedToken)) return {};\n return { apiKey: storedToken };\n}\n\nasync function signFreshContinuationTokens(\n continuation: A2AContinuation,\n): Promise<string[]> {\n let orgDomain: string | undefined;\n let orgSecret: string | undefined;\n if (continuation.orgId) {\n try {\n const { getOrgDomain, getOrgA2ASecret } =\n await import(\"../org/context.js\");\n orgDomain = (await getOrgDomain(continuation.orgId)) ?? undefined;\n orgSecret = (await getOrgA2ASecret(continuation.orgId)) ?? undefined;\n } catch {}\n }\n\n if (!continuation.ownerEmail || !(orgSecret || process.env.A2A_SECRET)) {\n return [];\n }\n\n const tokens: string[] = [];\n const add = (token: string | undefined) => {\n if (token && !tokens.includes(token)) tokens.push(token);\n };\n\n if (process.env.A2A_SECRET?.trim()) {\n try {\n add(\n await signA2AToken(continuation.ownerEmail, orgDomain, orgSecret, {\n expiresIn: \"30m\",\n preferGlobalSecret: true,\n }),\n );\n } catch {}\n }\n if (orgSecret) {\n try {\n add(\n await signA2AToken(continuation.ownerEmail, orgDomain, orgSecret, {\n expiresIn: \"30m\",\n preferGlobalSecret: false,\n }),\n );\n } catch {}\n }\n return tokens;\n}\n\nasync function resolveContinuationArtifactSecrets(\n continuation: A2AContinuation,\n): Promise<string[]> {\n const secrets: string[] = [];\n const add = (secret: string | null | undefined) => {\n const value = secret?.trim();\n if (value && !secrets.includes(value)) secrets.push(value);\n };\n add(process.env.A2A_SECRET);\n if (continuation.orgId) {\n try {\n const { getOrgA2ASecret } = await import(\"../org/context.js\");\n add(await getOrgA2ASecret(continuation.orgId));\n } catch {}\n }\n return secrets;\n}\n\nfunction isLikelyJwt(token: string): boolean {\n return token.split(\".\").length === 3;\n}\n\nfunction extractTaskText(task: Task): string {\n const parts = task.status.message?.parts ?? [];\n return parts\n .filter((part): part is { type: \"text\"; text: string } => {\n return part.type === \"text\" && typeof part.text === \"string\";\n })\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\nfunction extractVerifiedRecoverableArtifactText(\n task: Task,\n agentUrl: string,\n artifactSecrets: readonly string[],\n): string | null {\n if (task.status.message?.metadata?.agentNativeRecoverableArtifacts !== true) {\n return null;\n }\n\n const text = formatContinuationArtifactText(extractTaskText(task), agentUrl);\n if (!text.trim()) return null;\n\n // Require the signed identity ledger so arbitrary peer progress prose cannot\n // prematurely complete the continuation.\n const artifacts = extractA2AArtifactIdentities(\n [{ tool: \"call-agent\", result: text }],\n {\n persistedArtifactSecrets: artifactSecrets,\n },\n );\n return artifacts.length > 0 ? text : null;\n}\n\nfunction formatRecoverableArtifactFallbackText(text: string): string {\n return text.replace(\n \"The agent is still working on the full response, but these verified artifacts already exist:\",\n \"The downstream agent did not finish its full response, but these verified artifacts already exist:\",\n );\n}\n\nfunction formatContinuationArtifactText(\n text: string,\n agentUrl: string,\n): string {\n const expandedText = expandRelativeUrls(text, agentUrl);\n return appendA2AArtifactLinks(\n expandedText,\n [{ tool: \"call-agent\", result: expandedText }],\n { baseUrl: resolveArtifactBaseUrl() },\n );\n}\n\nfunction resolveArtifactBaseUrl(): string | undefined {\n const baseUrl =\n process.env.APP_URL || process.env.URL || process.env.DEPLOY_URL;\n return baseUrl ? withConfiguredAppBasePath(baseUrl) : undefined;\n}\n\nfunction expandRelativeUrls(text: string, agentUrl: string): string {\n if (!text || !agentUrl) return text;\n const base = publicAgentBaseUrl(agentUrl);\n return text.replace(\n /(^|[\\s([<\"'`])(\\/[a-z0-9_-][a-z0-9_/?&=%#.,:-]*)/gi,\n (_match, lead, path) => `${lead}${base}${path}`,\n );\n}\n\nfunction publicAgentBaseUrl(agentUrl: string): string {\n try {\n const url = new URL(agentUrl);\n const routeIndex = url.pathname.indexOf(FRAMEWORK_ROUTE_PREFIX);\n url.pathname =\n routeIndex >= 0\n ? url.pathname.slice(0, routeIndex) || \"/\"\n : url.pathname.replace(/\\/+$/, \"\") || \"/\";\n url.search = \"\";\n url.hash = \"\";\n return url.toString().replace(/\\/$/, \"\");\n } catch {\n return agentUrl.replace(/\\/$/, \"\");\n }\n}\n"]}
@@ -68,6 +68,9 @@ export declare function markTaskCompleted(id: string): Promise<void>;
68
68
  * scrubbed only when the task reaches a permanent terminal state.
69
69
  */
70
70
  export declare function markTaskRetryable(id: string, errorMessage: string): Promise<void>;
71
+ export declare function stageTaskDeliveryPayload(id: string, payload: string): Promise<void>;
72
+ export declare function markTaskDeliveryRetryable(id: string, payload: string, errorMessage: string): Promise<void>;
73
+ export declare function failTaskDeliveryTransition(id: string, errorMessage: string): Promise<void>;
71
74
  /** Mark a task as failed and stash an error message. */
72
75
  export declare function markTaskFailed(id: string, errorMessage: string): Promise<void>;
73
76
  //# sourceMappingURL=pending-tasks-store.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"pending-tasks-store.d.ts","sourceRoot":"","sources":["../../src/integrations/pending-tasks-store.ts"],"names":[],"mappings":"AAoBA,eAAO,MAAM,yBAAyB,IAAI,CAAC;AAyF3C,qDAAqD;AACrD,MAAM,MAAM,iBAAiB,GACzB,SAAS,GACT,YAAY,GACZ,WAAW,GACX,QAAQ,CAAC;AAEb,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB,gBAAgB,EAAE,MAAM,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,MAAM,EAAE,iBAAiB,CAAC;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B;AAED;;;;;;GAMG;AACH,wBAAsB,oBAAoB,CACxC,QAAQ,EAAE,MAAM,EAChB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC,OAAO,CAAC,CAalB;AAoBD;;;;;;;;GAQG;AACH,wBAAsB,iBAAiB,CAAC,KAAK,EAAE;IAC7C,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB,gBAAgB,EAAE,MAAM,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAClC,GAAG,OAAO,CAAC,IAAI,CAAC,CAsBhB;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAU3D;AAED,kCAAkC;AAClC,wBAAsB,cAAc,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAU5E;AAED;;;;GAIG;AACH,wBAAsB,gBAAgB,CACpC,EAAE,EAAE,MAAM,GACT,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAgD7B;AAED,+EAA+E;AAC/E,wBAAsB,6BAA6B,CACjD,QAAQ,EAAE,MAAM,EAChB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CASxB;AAED,gCAAgC;AAChC,wBAAsB,iBAAiB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAajE;AAED;;;;GAIG;AACH,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,MAAM,EACV,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,IAAI,CAAC,CAUf;AAED,wDAAwD;AACxD,wBAAsB,cAAc,CAClC,EAAE,EAAE,MAAM,EACV,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,IAAI,CAAC,CAUf"}
1
+ {"version":3,"file":"pending-tasks-store.d.ts","sourceRoot":"","sources":["../../src/integrations/pending-tasks-store.ts"],"names":[],"mappings":"AAoBA,eAAO,MAAM,yBAAyB,IAAI,CAAC;AAyF3C,qDAAqD;AACrD,MAAM,MAAM,iBAAiB,GACzB,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AAC,WAAW,GAAG,IAAI,CAAC,CA0E7B;AAED,+EAA+E;AAC/E,wBAAsB,6BAA6B,CACjD,QAAQ,EAAE,MAAM,EAChB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CASxB;AAED,gCAAgC;AAChC,wBAAsB,iBAAiB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAajE;AAED;;;;GAIG;AACH,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,MAAM,EACV,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,IAAI,CAAC,CAUf;AAED,wBAAsB,wBAAwB,CAC5C,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,IAAI,CAAC,CAkBf;AAED,wBAAsB,yBAAyB,CAC7C,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,MAAM,EACf,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,IAAI,CAAC,CAmBf;AAED,wBAAsB,0BAA0B,CAC9C,EAAE,EAAE,MAAM,EACV,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,IAAI,CAAC,CAkBf;AAED,wDAAwD;AACxD,wBAAsB,cAAc,CAClC,EAAE,EAAE,MAAM,EACV,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,IAAI,CAAC,CAUf"}
@@ -200,6 +200,19 @@ export async function claimPendingTask(id) {
200
200
  AND active.status = 'processing'
201
201
  AND active.id <> integration_pending_tasks.id
202
202
  )
203
+ AND NOT EXISTS (
204
+ SELECT 1 FROM integration_pending_tasks earlier
205
+ WHERE earlier.platform = integration_pending_tasks.platform
206
+ AND earlier.external_thread_id = integration_pending_tasks.external_thread_id
207
+ AND earlier.status = 'pending'
208
+ AND (
209
+ earlier.created_at < integration_pending_tasks.created_at
210
+ OR (
211
+ earlier.created_at = integration_pending_tasks.created_at
212
+ AND earlier.id < integration_pending_tasks.id
213
+ )
214
+ )
215
+ )
203
216
  RETURNING id, platform, external_thread_id, payload, owner_email, org_id, status, attempts, error_message, created_at, updated_at, completed_at`
204
217
  : `UPDATE integration_pending_tasks
205
218
  SET status = ?, attempts = attempts + 1, updated_at = ?
@@ -210,6 +223,19 @@ export async function claimPendingTask(id) {
210
223
  AND active.external_thread_id = integration_pending_tasks.external_thread_id
211
224
  AND active.status = 'processing'
212
225
  AND active.id <> integration_pending_tasks.id
226
+ )
227
+ AND NOT EXISTS (
228
+ SELECT 1 FROM integration_pending_tasks earlier
229
+ WHERE earlier.platform = integration_pending_tasks.platform
230
+ AND earlier.external_thread_id = integration_pending_tasks.external_thread_id
231
+ AND earlier.status = 'pending'
232
+ AND (
233
+ earlier.created_at < integration_pending_tasks.created_at
234
+ OR (
235
+ earlier.created_at = integration_pending_tasks.created_at
236
+ AND earlier.id < integration_pending_tasks.id
237
+ )
238
+ )
213
239
  )`,
214
240
  args: ["processing", now, id],
215
241
  });
@@ -236,7 +262,7 @@ export async function getNextPendingTaskIdForThread(platform, externalThreadId)
236
262
  const { rows } = await getDbExec().execute({
237
263
  sql: `SELECT id FROM integration_pending_tasks
238
264
  WHERE platform = ? AND external_thread_id = ? AND status = 'pending'
239
- ORDER BY created_at ASC LIMIT 1`,
265
+ ORDER BY created_at ASC, id ASC LIMIT 1`,
240
266
  args: [platform, externalThreadId],
241
267
  });
242
268
  return rows[0]?.id ? String(rows[0].id) : null;
@@ -272,6 +298,54 @@ export async function markTaskRetryable(id, errorMessage) {
272
298
  args: ["pending", now, errorMessage.slice(0, 2000), id],
273
299
  });
274
300
  }
301
+ export async function stageTaskDeliveryPayload(id, payload) {
302
+ await ensureTable();
303
+ const client = getDbExec();
304
+ const now = Date.now();
305
+ const result = await client.execute({
306
+ sql: `UPDATE integration_pending_tasks
307
+ SET payload = ?, updated_at = ?
308
+ WHERE id = ? AND status = 'processing'`,
309
+ args: [payload, now, id],
310
+ });
311
+ const affected = Number(result.rowsAffected ??
312
+ result.rowCount ??
313
+ 0);
314
+ if (affected === 0) {
315
+ throw new Error("Integration task is no longer claimable for delivery");
316
+ }
317
+ }
318
+ export async function markTaskDeliveryRetryable(id, payload, errorMessage) {
319
+ await ensureTable();
320
+ const client = getDbExec();
321
+ const result = await client.execute({
322
+ sql: `UPDATE integration_pending_tasks
323
+ SET status = ?, payload = ?, updated_at = ?, error_message = ?
324
+ WHERE id = ? AND status = 'processing'`,
325
+ args: ["pending", payload, Date.now(), errorMessage.slice(0, 2000), id],
326
+ });
327
+ const affected = Number(result.rowsAffected ??
328
+ result.rowCount ??
329
+ 0);
330
+ if (affected === 0) {
331
+ throw new Error("Integration task is no longer claimable for delivery retry");
332
+ }
333
+ }
334
+ export async function failTaskDeliveryTransition(id, errorMessage) {
335
+ await ensureTable();
336
+ const result = await getDbExec().execute({
337
+ sql: `UPDATE integration_pending_tasks
338
+ SET status = ?, updated_at = ?, error_message = ?, payload = ?
339
+ WHERE id = ? AND status = 'processing'`,
340
+ args: ["failed", Date.now(), errorMessage.slice(0, 2000), "{}", id],
341
+ });
342
+ const affected = Number(result.rowsAffected ??
343
+ result.rowCount ??
344
+ 0);
345
+ if (affected === 0) {
346
+ throw new Error("Integration task delivery failure transition lost its race");
347
+ }
348
+ }
275
349
  /** Mark a task as failed and stash an error message. */
276
350
  export async function markTaskFailed(id, errorMessage) {
277
351
  await ensureTable();