@agent-native/core 0.113.0 → 0.114.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 (1508) hide show
  1. package/agent-native.eject.json +164 -0
  2. package/corpus/README.md +3 -3
  3. package/corpus/core/CHANGELOG.md +11 -0
  4. package/corpus/core/README.md +61 -174
  5. package/corpus/core/agent-native.eject.json +164 -0
  6. package/corpus/core/docs/content/agent-native-toolkit.mdx +38 -0
  7. package/corpus/core/docs/content/package-lifecycle.mdx +54 -4
  8. package/corpus/core/package.json +15 -2
  9. package/corpus/core/src/cli/eject.ts +1594 -0
  10. package/corpus/core/src/cli/index.ts +16 -0
  11. package/corpus/core/src/client/index.ts +4 -0
  12. package/corpus/core/src/client/resources/McpConnectionSuggestion.tsx +8 -2
  13. package/corpus/core/src/client/resources/McpIntegrationDialog.tsx +7 -2
  14. package/corpus/core/src/client/resources/ResourcesPanel.tsx +17 -3
  15. package/corpus/core/src/client/resources/index.ts +19 -0
  16. package/corpus/core/src/client/resources/mcp-integration-catalog.ts +9 -1
  17. package/corpus/core/src/client/resources/runtime.ts +1 -0
  18. package/corpus/core/src/client/setup-connections/catalog.ts +6 -0
  19. package/corpus/core/src/client/setup-connections/index.ts +1 -0
  20. package/corpus/core/src/client/setup-connections/runtime.ts +1 -0
  21. package/corpus/core/src/connections/catalog.ts +41 -24
  22. package/corpus/core/src/connections/index.ts +1 -0
  23. package/corpus/core/src/connections/runtime.ts +1 -0
  24. package/corpus/core/src/eject/provider-api-definitions.ts +193 -0
  25. package/corpus/core/src/eject/remote-mcp-presets.ts +137 -0
  26. package/corpus/core/src/eject/setup-readiness-ui.tsx +29 -0
  27. package/corpus/core/src/eject/workspace-connections.ts +92 -0
  28. package/corpus/core/src/index.ts +1 -0
  29. package/corpus/core/src/integrations/adapter-overrides.ts +12 -0
  30. package/corpus/core/src/integrations/eject/messaging-adapters.ts +85 -0
  31. package/corpus/core/src/integrations/index.ts +5 -1
  32. package/corpus/core/src/integrations/plugin.ts +34 -12
  33. package/corpus/core/src/integrations/runtime.ts +1 -0
  34. package/corpus/core/src/integrations/types.ts +3 -1
  35. package/corpus/core/src/package-lifecycle/eject-manifest.ts +345 -0
  36. package/corpus/core/src/package-lifecycle/index.ts +1 -0
  37. package/corpus/core/src/provider-api/index.ts +46 -12
  38. package/corpus/core/src/provider-api/runtime.ts +1 -0
  39. package/corpus/core/src/setup-connections/index.ts +1 -0
  40. package/corpus/core/src/shared/merge-by-id.ts +14 -0
  41. package/corpus/core/src/templates/default/.agents/skills/agent-native-docs/SKILL.md +15 -13
  42. package/corpus/core/src/templates/default/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  43. package/corpus/core/src/templates/default/.agents/skills/self-modifying-code/SKILL.md +9 -6
  44. package/corpus/core/src/templates/default/AGENTS.md +6 -5
  45. package/corpus/core/src/templates/headless/.agents/skills/agent-native-docs/SKILL.md +15 -13
  46. package/corpus/core/src/templates/headless/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  47. package/corpus/core/src/templates/headless/AGENTS.md +5 -4
  48. package/corpus/core/src/templates/workspace-core/.agents/skills/agent-native-docs/SKILL.md +15 -13
  49. package/corpus/core/src/templates/workspace-core/.agents/skills/agent-native-toolkit/SKILL.md +3 -2
  50. package/corpus/core/src/templates/workspace-core/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  51. package/corpus/core/src/templates/workspace-core/.agents/skills/self-modifying-code/SKILL.md +9 -6
  52. package/corpus/core/src/templates/workspace-core/AGENTS.md +4 -4
  53. package/corpus/core/src/templates/workspace-root/AGENTS.md +4 -4
  54. package/corpus/core/src/vite/client.ts +25 -2
  55. package/corpus/templates/analytics/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  56. package/corpus/templates/analytics/.agents/skills/self-modifying-code/SKILL.md +9 -6
  57. package/corpus/templates/assets/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  58. package/corpus/templates/assets/.agents/skills/self-modifying-code/SKILL.md +9 -6
  59. package/corpus/templates/brain/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  60. package/corpus/templates/brain/.agents/skills/self-modifying-code/SKILL.md +9 -6
  61. package/corpus/templates/brain/actions/remediate-legacy-capture-audiences.ts +167 -0
  62. package/corpus/templates/brain/app/lib/brain-chat-readiness.ts +6 -0
  63. package/corpus/templates/brain/app/routes/_index.tsx +8 -0
  64. package/corpus/templates/brain/app/routes.ts +1 -0
  65. package/corpus/templates/brain/changelog/2026-07-19-ask-starts-immediately-when-builder-s-managed-ai-connection-.md +6 -0
  66. package/corpus/templates/brain/changelog/2026-07-19-slack-and-granola-backfills-now-process-captures-concurrentl.md +6 -0
  67. package/corpus/templates/brain/changelog/2026-07-19-source-review-settings-now-control-knowledge-approval.md +6 -0
  68. package/corpus/templates/brain/changelog/2026-07-19-the-manage-agent-page-now-opens-correctly-from-brain-navigat.md +6 -0
  69. package/corpus/templates/brain/server/db/schema.ts +3 -0
  70. package/corpus/templates/brain/server/lib/brain.ts +41 -2
  71. package/corpus/templates/brain/server/lib/connectors.ts +379 -113
  72. package/corpus/templates/brain/server/lib/meeting-audience.ts +38 -0
  73. package/corpus/templates/brain/server/plugins/db.ts +10 -0
  74. package/corpus/templates/brain/server/routes/api/_agent-native/brain/ingest.post.ts +6 -4
  75. package/corpus/templates/calendar/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  76. package/corpus/templates/calendar/.agents/skills/self-modifying-code/SKILL.md +9 -6
  77. package/corpus/templates/chat/.agents/skills/agent-native-docs/SKILL.md +15 -13
  78. package/corpus/templates/chat/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  79. package/corpus/templates/chat/.agents/skills/self-modifying-code/SKILL.md +9 -6
  80. package/corpus/templates/chat/AGENTS.md +3 -2
  81. package/corpus/templates/clips/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  82. package/corpus/templates/clips/.agents/skills/self-modifying-code/SKILL.md +9 -6
  83. package/corpus/templates/content/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  84. package/corpus/templates/content/.agents/skills/self-modifying-code/SKILL.md +9 -6
  85. package/corpus/templates/design/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  86. package/corpus/templates/design/.agents/skills/self-modifying-code/SKILL.md +9 -6
  87. package/corpus/templates/dispatch/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  88. package/corpus/templates/dispatch/.agents/skills/self-modifying-code/SKILL.md +9 -6
  89. package/corpus/templates/forms/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  90. package/corpus/templates/forms/.agents/skills/self-modifying-code/SKILL.md +9 -6
  91. package/corpus/templates/macros/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  92. package/corpus/templates/mail/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  93. package/corpus/templates/mail/.agents/skills/self-modifying-code/SKILL.md +9 -6
  94. package/corpus/templates/plan/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  95. package/corpus/templates/plan/.agents/skills/self-modifying-code/SKILL.md +9 -6
  96. package/corpus/templates/slides/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  97. package/corpus/templates/slides/.agents/skills/self-modifying-code/SKILL.md +9 -6
  98. package/corpus/templates/tasks/.agents/skills/agent-native-docs/SKILL.md +15 -13
  99. package/corpus/templates/tasks/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  100. package/corpus/templates/tasks/.agents/skills/self-modifying-code/SKILL.md +9 -6
  101. package/corpus/toolkit/CHANGELOG.md +6 -0
  102. package/corpus/toolkit/agent-native.eject.json +411 -0
  103. package/corpus/toolkit/package.json +5 -2
  104. package/dist/cli/eject.d.ts +21 -0
  105. package/dist/cli/eject.d.ts.map +1 -0
  106. package/dist/cli/eject.js +1145 -0
  107. package/dist/cli/eject.js.map +1 -0
  108. package/dist/cli/index.js +15 -0
  109. package/dist/cli/index.js.map +1 -1
  110. package/dist/client/index.d.ts +1 -1
  111. package/dist/client/index.d.ts.map +1 -1
  112. package/dist/client/index.js +1 -1
  113. package/dist/client/index.js.map +1 -1
  114. package/dist/client/resources/McpConnectionSuggestion.d.ts +4 -3
  115. package/dist/client/resources/McpConnectionSuggestion.d.ts.map +1 -1
  116. package/dist/client/resources/McpConnectionSuggestion.js +3 -3
  117. package/dist/client/resources/McpConnectionSuggestion.js.map +1 -1
  118. package/dist/client/resources/McpIntegrationDialog.d.ts +4 -3
  119. package/dist/client/resources/McpIntegrationDialog.d.ts.map +1 -1
  120. package/dist/client/resources/McpIntegrationDialog.js +2 -2
  121. package/dist/client/resources/McpIntegrationDialog.js.map +1 -1
  122. package/dist/client/resources/ResourcesPanel.d.ts +4 -1
  123. package/dist/client/resources/ResourcesPanel.d.ts.map +1 -1
  124. package/dist/client/resources/ResourcesPanel.js +9 -7
  125. package/dist/client/resources/ResourcesPanel.js.map +1 -1
  126. package/dist/client/resources/index.d.ts +3 -0
  127. package/dist/client/resources/index.d.ts.map +1 -1
  128. package/dist/client/resources/index.js +3 -0
  129. package/dist/client/resources/index.js.map +1 -1
  130. package/dist/client/resources/mcp-integration-catalog.d.ts +2 -1
  131. package/dist/client/resources/mcp-integration-catalog.d.ts.map +1 -1
  132. package/dist/client/resources/mcp-integration-catalog.js +6 -2
  133. package/dist/client/resources/mcp-integration-catalog.js.map +1 -1
  134. package/dist/client/resources/runtime.d.ts +2 -0
  135. package/dist/client/resources/runtime.d.ts.map +1 -0
  136. package/dist/client/resources/runtime.js +2 -0
  137. package/dist/client/resources/runtime.js.map +1 -0
  138. package/dist/client/setup-connections/catalog.d.ts +2 -0
  139. package/dist/client/setup-connections/catalog.d.ts.map +1 -0
  140. package/dist/client/setup-connections/catalog.js +7 -0
  141. package/dist/client/setup-connections/catalog.js.map +1 -0
  142. package/dist/client/setup-connections/index.d.ts +1 -0
  143. package/dist/client/setup-connections/index.d.ts.map +1 -1
  144. package/dist/client/setup-connections/index.js +1 -0
  145. package/dist/client/setup-connections/index.js.map +1 -1
  146. package/dist/client/setup-connections/runtime.d.ts +2 -0
  147. package/dist/client/setup-connections/runtime.d.ts.map +1 -0
  148. package/dist/client/setup-connections/runtime.js +2 -0
  149. package/dist/client/setup-connections/runtime.js.map +1 -0
  150. package/dist/collab/awareness.d.ts +2 -2
  151. package/dist/collab/awareness.d.ts.map +1 -1
  152. package/dist/collab/routes.d.ts +1 -1
  153. package/dist/connections/catalog.d.ts +5 -3
  154. package/dist/connections/catalog.d.ts.map +1 -1
  155. package/dist/connections/catalog.js +16 -8
  156. package/dist/connections/catalog.js.map +1 -1
  157. package/dist/connections/index.d.ts +1 -1
  158. package/dist/connections/index.d.ts.map +1 -1
  159. package/dist/connections/index.js +1 -1
  160. package/dist/connections/index.js.map +1 -1
  161. package/dist/connections/runtime.d.ts +2 -0
  162. package/dist/connections/runtime.d.ts.map +1 -0
  163. package/dist/connections/runtime.js +2 -0
  164. package/dist/connections/runtime.js.map +1 -0
  165. package/dist/eject/provider-api-definitions.d.ts +34 -0
  166. package/dist/eject/provider-api-definitions.d.ts.map +1 -0
  167. package/dist/eject/provider-api-definitions.js +88 -0
  168. package/dist/eject/provider-api-definitions.js.map +1 -0
  169. package/dist/eject/remote-mcp-presets.d.ts +17 -0
  170. package/dist/eject/remote-mcp-presets.d.ts.map +1 -0
  171. package/dist/eject/remote-mcp-presets.js +81 -0
  172. package/dist/eject/remote-mcp-presets.js.map +1 -0
  173. package/dist/eject/setup-readiness-ui.d.ts +7 -0
  174. package/dist/eject/setup-readiness-ui.d.ts.map +1 -0
  175. package/dist/eject/setup-readiness-ui.js +13 -0
  176. package/dist/eject/setup-readiness-ui.js.map +1 -0
  177. package/dist/eject/workspace-connections.d.ts +11 -0
  178. package/dist/eject/workspace-connections.d.ts.map +1 -0
  179. package/dist/eject/workspace-connections.js +47 -0
  180. package/dist/eject/workspace-connections.js.map +1 -0
  181. package/dist/index.d.ts +1 -1
  182. package/dist/index.d.ts.map +1 -1
  183. package/dist/index.js +1 -1
  184. package/dist/index.js.map +1 -1
  185. package/dist/integrations/adapter-overrides.d.ts +3 -0
  186. package/dist/integrations/adapter-overrides.d.ts.map +1 -0
  187. package/dist/integrations/adapter-overrides.js +7 -0
  188. package/dist/integrations/adapter-overrides.js.map +1 -0
  189. package/dist/integrations/eject/messaging-adapters.d.ts +12 -0
  190. package/dist/integrations/eject/messaging-adapters.d.ts.map +1 -0
  191. package/dist/integrations/eject/messaging-adapters.js +49 -0
  192. package/dist/integrations/eject/messaging-adapters.js.map +1 -0
  193. package/dist/integrations/index.d.ts +3 -2
  194. package/dist/integrations/index.d.ts.map +1 -1
  195. package/dist/integrations/index.js +2 -1
  196. package/dist/integrations/index.js.map +1 -1
  197. package/dist/integrations/plugin.d.ts +32 -1
  198. package/dist/integrations/plugin.d.ts.map +1 -1
  199. package/dist/integrations/plugin.js +19 -12
  200. package/dist/integrations/plugin.js.map +1 -1
  201. package/dist/integrations/runtime.d.ts +2 -0
  202. package/dist/integrations/runtime.d.ts.map +1 -0
  203. package/dist/integrations/runtime.js +2 -0
  204. package/dist/integrations/runtime.js.map +1 -0
  205. package/dist/integrations/types.d.ts +3 -1
  206. package/dist/integrations/types.d.ts.map +1 -1
  207. package/dist/integrations/types.js.map +1 -1
  208. package/dist/notifications/routes.d.ts +3 -3
  209. package/dist/package-lifecycle/eject-manifest.d.ts +43 -0
  210. package/dist/package-lifecycle/eject-manifest.d.ts.map +1 -0
  211. package/dist/package-lifecycle/eject-manifest.js +219 -0
  212. package/dist/package-lifecycle/eject-manifest.js.map +1 -0
  213. package/dist/package-lifecycle/index.d.ts +1 -0
  214. package/dist/package-lifecycle/index.d.ts.map +1 -1
  215. package/dist/package-lifecycle/index.js +1 -0
  216. package/dist/package-lifecycle/index.js.map +1 -1
  217. package/dist/progress/routes.d.ts +1 -1
  218. package/dist/provider-api/actions/custom-provider-registration.d.ts +4 -4
  219. package/dist/provider-api/actions/provider-api.d.ts +8 -8
  220. package/dist/provider-api/corpus-jobs.d.ts +2 -2
  221. package/dist/provider-api/index.d.ts +6 -2
  222. package/dist/provider-api/index.d.ts.map +1 -1
  223. package/dist/provider-api/index.js +25 -12
  224. package/dist/provider-api/index.js.map +1 -1
  225. package/dist/provider-api/runtime.d.ts +2 -0
  226. package/dist/provider-api/runtime.d.ts.map +1 -0
  227. package/dist/provider-api/runtime.js +2 -0
  228. package/dist/provider-api/runtime.js.map +1 -0
  229. package/dist/secrets/routes.d.ts +9 -9
  230. package/dist/server/agent-engine-api-key-route.d.ts +1 -1
  231. package/dist/server/transcribe-voice.d.ts +1 -1
  232. package/dist/setup-connections/index.d.ts +1 -1
  233. package/dist/setup-connections/index.d.ts.map +1 -1
  234. package/dist/setup-connections/index.js +1 -1
  235. package/dist/setup-connections/index.js.map +1 -1
  236. package/dist/shared/merge-by-id.d.ts +5 -0
  237. package/dist/shared/merge-by-id.d.ts.map +1 -0
  238. package/dist/shared/merge-by-id.js +7 -0
  239. package/dist/shared/merge-by-id.js.map +1 -0
  240. package/dist/templates/chat/.agents/skills/agent-native-docs/SKILL.md +15 -13
  241. package/dist/templates/chat/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  242. package/dist/templates/chat/.agents/skills/self-modifying-code/SKILL.md +9 -6
  243. package/dist/templates/chat/AGENTS.md +3 -2
  244. package/dist/templates/default/.agents/skills/agent-native-docs/SKILL.md +15 -13
  245. package/dist/templates/default/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  246. package/dist/templates/default/.agents/skills/self-modifying-code/SKILL.md +9 -6
  247. package/dist/templates/default/AGENTS.md +6 -5
  248. package/dist/templates/headless/.agents/skills/agent-native-docs/SKILL.md +15 -13
  249. package/dist/templates/headless/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  250. package/dist/templates/headless/AGENTS.md +5 -4
  251. package/dist/templates/workspace-core/.agents/skills/agent-native-docs/SKILL.md +15 -13
  252. package/dist/templates/workspace-core/.agents/skills/agent-native-toolkit/SKILL.md +3 -2
  253. package/dist/templates/workspace-core/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  254. package/dist/templates/workspace-core/.agents/skills/self-modifying-code/SKILL.md +9 -6
  255. package/dist/templates/workspace-core/AGENTS.md +4 -4
  256. package/dist/templates/workspace-root/AGENTS.md +4 -4
  257. package/dist/vite/client.d.ts.map +1 -1
  258. package/dist/vite/client.js +22 -2
  259. package/dist/vite/client.js.map +1 -1
  260. package/docs/content/agent-native-toolkit.mdx +38 -0
  261. package/docs/content/package-lifecycle.mdx +54 -4
  262. package/package.json +15 -2
  263. package/src/a2a/agent-card.ts +83 -0
  264. package/src/a2a/artifact-response.ts +1648 -0
  265. package/src/a2a/auth-policy.ts +66 -0
  266. package/src/a2a/caller-auth.ts +102 -0
  267. package/src/a2a/client.ts +876 -0
  268. package/src/a2a/correlation.ts +50 -0
  269. package/src/a2a/handlers.ts +1285 -0
  270. package/src/a2a/index.ts +50 -0
  271. package/src/a2a/invoke.ts +348 -0
  272. package/src/a2a/response-text.ts +53 -0
  273. package/src/a2a/server.ts +586 -0
  274. package/src/a2a/task-store.ts +917 -0
  275. package/src/a2a/types.ts +221 -0
  276. package/src/a2a-claims.ts +52 -0
  277. package/src/action-change-marker.ts +74 -0
  278. package/src/action-ui.ts +38 -0
  279. package/src/action.ts +1406 -0
  280. package/src/adapters/cli/index.ts +6 -0
  281. package/src/adapters/cli/registry.ts +73 -0
  282. package/src/adapters/cli/shell-adapter.ts +92 -0
  283. package/src/adapters/cli/types.ts +27 -0
  284. package/src/agent/action-continuation-guidance.ts +38 -0
  285. package/src/agent/app-model-defaults.ts +201 -0
  286. package/src/agent/context-xray/actions/context-evict.ts +56 -0
  287. package/src/agent/context-xray/actions/context-manifest-get.ts +75 -0
  288. package/src/agent/context-xray/actions/context-pin.ts +56 -0
  289. package/src/agent/context-xray/actions/context-preview-get.ts +134 -0
  290. package/src/agent/context-xray/actions/context-report.ts +75 -0
  291. package/src/agent/context-xray/actions/context-restore.ts +51 -0
  292. package/src/agent/context-xray/actions/errors.ts +40 -0
  293. package/src/agent/context-xray/apply-directives.ts +137 -0
  294. package/src/agent/context-xray/directives-store.ts +178 -0
  295. package/src/agent/context-xray/identity.ts +37 -0
  296. package/src/agent/context-xray/manifest.ts +284 -0
  297. package/src/agent/context-xray/migrations.ts +32 -0
  298. package/src/agent/context-xray/plugin.ts +23 -0
  299. package/src/agent/context-xray/schema.ts +17 -0
  300. package/src/agent/context-xray/segments.ts +194 -0
  301. package/src/agent/context-xray/tokenize.ts +93 -0
  302. package/src/agent/default-model.ts +5 -0
  303. package/src/agent/durable-background.ts +547 -0
  304. package/src/agent/engine/ai-sdk-engine.ts +565 -0
  305. package/src/agent/engine/anthropic-engine.ts +320 -0
  306. package/src/agent/engine/builder-engine.ts +1110 -0
  307. package/src/agent/engine/builder-gateway-headers.ts +44 -0
  308. package/src/agent/engine/builtin.ts +122 -0
  309. package/src/agent/engine/context-directives-transform.ts +73 -0
  310. package/src/agent/engine/continuation-dispatch-retry.ts +168 -0
  311. package/src/agent/engine/credential-errors.ts +69 -0
  312. package/src/agent/engine/index.ts +54 -0
  313. package/src/agent/engine/openai-compatible-endpoint.ts +25 -0
  314. package/src/agent/engine/output-tokens.ts +181 -0
  315. package/src/agent/engine/provider-env-vars.ts +69 -0
  316. package/src/agent/engine/registry.ts +853 -0
  317. package/src/agent/engine/tool-call-journal-seed.ts +85 -0
  318. package/src/agent/engine/translate-ai-sdk.ts +407 -0
  319. package/src/agent/engine/translate-anthropic.ts +611 -0
  320. package/src/agent/engine/types.ts +310 -0
  321. package/src/agent/harness/acp-adapter.ts +893 -0
  322. package/src/agent/harness/acp-builtin.ts +70 -0
  323. package/src/agent/harness/ai-sdk-adapter.ts +509 -0
  324. package/src/agent/harness/background.ts +365 -0
  325. package/src/agent/harness/builtin.ts +50 -0
  326. package/src/agent/harness/index.ts +86 -0
  327. package/src/agent/harness/lifecycle.ts +498 -0
  328. package/src/agent/harness/registry.ts +97 -0
  329. package/src/agent/harness/runner.ts +182 -0
  330. package/src/agent/harness/store.ts +466 -0
  331. package/src/agent/harness/translate.ts +130 -0
  332. package/src/agent/harness/types.ts +129 -0
  333. package/src/agent/index.ts +32 -0
  334. package/src/agent/loop-settings.ts +186 -0
  335. package/src/agent/model-config.ts +363 -0
  336. package/src/agent/observational-memory/compactor.ts +78 -0
  337. package/src/agent/observational-memory/config.ts +78 -0
  338. package/src/agent/observational-memory/index.ts +79 -0
  339. package/src/agent/observational-memory/internal-run.ts +89 -0
  340. package/src/agent/observational-memory/message-text.ts +49 -0
  341. package/src/agent/observational-memory/migrations.ts +44 -0
  342. package/src/agent/observational-memory/observer.ts +128 -0
  343. package/src/agent/observational-memory/plugin.ts +35 -0
  344. package/src/agent/observational-memory/prompts.ts +53 -0
  345. package/src/agent/observational-memory/read.ts +131 -0
  346. package/src/agent/observational-memory/reflector.ts +119 -0
  347. package/src/agent/observational-memory/schema.ts +48 -0
  348. package/src/agent/observational-memory/store.ts +275 -0
  349. package/src/agent/observational-memory/types.ts +65 -0
  350. package/src/agent/processors.ts +209 -0
  351. package/src/agent/production-agent.ts +8254 -0
  352. package/src/agent/run-loop-with-resume.ts +394 -0
  353. package/src/agent/run-manager.ts +1825 -0
  354. package/src/agent/run-ownership.ts +75 -0
  355. package/src/agent/run-store.ts +2601 -0
  356. package/src/agent/runtime-context.ts +169 -0
  357. package/src/agent/thread-data-builder.ts +1584 -0
  358. package/src/agent/tool-call-journal.ts +368 -0
  359. package/src/agent/tool-error-redaction.ts +52 -0
  360. package/src/agent/tool-result-images.ts +178 -0
  361. package/src/agent/tool-search.ts +376 -0
  362. package/src/agent/types.ts +372 -0
  363. package/src/agent-native/index.ts +198 -0
  364. package/src/agent-web/config.ts +253 -0
  365. package/src/agent-web/generator.ts +382 -0
  366. package/src/agent-web/index.ts +36 -0
  367. package/src/appearance/actions/change-appearance.ts +35 -0
  368. package/src/application-state/emitter.ts +81 -0
  369. package/src/application-state/handlers.ts +121 -0
  370. package/src/application-state/index.ts +44 -0
  371. package/src/application-state/script-helpers.ts +155 -0
  372. package/src/application-state/store.ts +274 -0
  373. package/src/assets/branding/agent-native.icon/Assets/background.svg +3 -0
  374. package/src/assets/branding/agent-native.icon/Assets/foreground.svg +12 -0
  375. package/src/assets/branding/agent-native.icon/icon.json +49 -0
  376. package/src/assets/branding/favicon.png +0 -0
  377. package/src/assets/branding/favicon.svg +1 -0
  378. package/src/assets/branding/icon-on-dark.svg +10 -0
  379. package/src/assets/branding/icon-on-light.svg +10 -0
  380. package/src/assets/branding/mac-app-icon.svg +1 -0
  381. package/src/assets/branding/slack-bot/agent-native-1024.png +0 -0
  382. package/src/assets/branding/slack-bot/agent-native-512.png +0 -0
  383. package/src/assets/branding/tray-icon.svg +6 -0
  384. package/src/assets/branding/wordmark-on-dark.svg +21 -0
  385. package/src/assets/branding/wordmark-on-light.svg +21 -0
  386. package/src/assets/fonts/LICENSE_LIBERATION +96 -0
  387. package/src/assets/fonts/LICENSE_NOTO_NASKH_ARABIC +93 -0
  388. package/src/assets/fonts/LiberationSans-Bold.ttf +0 -0
  389. package/src/assets/fonts/LiberationSans-Regular.ttf +0 -0
  390. package/src/assets/fonts/NotoNaskhArabic-Variable.ttf +0 -0
  391. package/src/audit/actions/export-audit-events.ts +162 -0
  392. package/src/audit/actions/get-audit-event.ts +24 -0
  393. package/src/audit/actions/list-audit-events.ts +66 -0
  394. package/src/audit/cleanup-job.ts +100 -0
  395. package/src/audit/config.ts +90 -0
  396. package/src/audit/index.ts +43 -0
  397. package/src/audit/record.ts +180 -0
  398. package/src/audit/redact.ts +109 -0
  399. package/src/audit/store.ts +346 -0
  400. package/src/audit/types.ts +141 -0
  401. package/src/automation/index.ts +802 -0
  402. package/src/brand-kit/brand-signals.ts +124 -0
  403. package/src/brand-kit/fig/index.ts +64 -0
  404. package/src/brand-kit/index.ts +72 -0
  405. package/src/brand-kit/types.ts +113 -0
  406. package/src/browser-sessions/actions.ts +302 -0
  407. package/src/browser-sessions/routes.ts +234 -0
  408. package/src/browser-sessions/store.ts +679 -0
  409. package/src/browser-sessions/types.ts +84 -0
  410. package/src/changelog/parse.ts +328 -0
  411. package/src/chat-threads/emitter.ts +22 -0
  412. package/src/chat-threads/schema.ts +43 -0
  413. package/src/chat-threads/store.ts +1311 -0
  414. package/src/checkpoints/index.ts +15 -0
  415. package/src/checkpoints/service.ts +142 -0
  416. package/src/checkpoints/store.ts +153 -0
  417. package/src/cli/add.ts +425 -0
  418. package/src/cli/agent.ts +424 -0
  419. package/src/cli/agents.ts +122 -0
  420. package/src/cli/app-skill.ts +1455 -0
  421. package/src/cli/atomic-json-file.ts +324 -0
  422. package/src/cli/audit-agent-web.ts +324 -0
  423. package/src/cli/changelog.ts +199 -0
  424. package/src/cli/claude-code-participant.ts +515 -0
  425. package/src/cli/code-agent-commands.ts +270 -0
  426. package/src/cli/code-agent-connector.ts +1109 -0
  427. package/src/cli/code-agent-executor.ts +1970 -0
  428. package/src/cli/code-agent-output-smoother.ts +140 -0
  429. package/src/cli/code-agent-runs.concurrent-worker.ts +33 -0
  430. package/src/cli/code-agent-runs.ts +548 -0
  431. package/src/cli/code.ts +1805 -0
  432. package/src/cli/codex-cli-participant.ts +496 -0
  433. package/src/cli/connect.ts +2714 -0
  434. package/src/cli/content-local.ts +442 -0
  435. package/src/cli/context-xray-local.ts +2193 -0
  436. package/src/cli/create-workspace.ts +30 -0
  437. package/src/cli/create.ts +2247 -0
  438. package/src/cli/deploy-build.ts +50 -0
  439. package/src/cli/design-connect.ts +3187 -0
  440. package/src/cli/doctor.ts +472 -0
  441. package/src/cli/eject.ts +1594 -0
  442. package/src/cli/eval.ts +134 -0
  443. package/src/cli/gateway-helpers.ts +70 -0
  444. package/src/cli/index.ts +1217 -0
  445. package/src/cli/info.ts +105 -0
  446. package/src/cli/invoke.ts +288 -0
  447. package/src/cli/mcp-config-writers.ts +857 -0
  448. package/src/cli/mcp.ts +594 -0
  449. package/src/cli/migrate.ts +1813 -0
  450. package/src/cli/migration-codemod.ts +646 -0
  451. package/src/cli/multi-frontier-runs.ts +1952 -0
  452. package/src/cli/package-lifecycle.ts +823 -0
  453. package/src/cli/plan-blocks.ts +143 -0
  454. package/src/cli/plan-local.ts +3189 -0
  455. package/src/cli/plan-publish-store.ts +138 -0
  456. package/src/cli/pr-visual-recap-workflow.ts +2 -0
  457. package/src/cli/recap.ts +5 -0
  458. package/src/cli/setup-agents.ts +120 -0
  459. package/src/cli/skills-content/assets-skill.ts +83 -0
  460. package/src/cli/skills-content/canvas.ts +153 -0
  461. package/src/cli/skills-content/connection.ts +52 -0
  462. package/src/cli/skills-content/content-skill.ts +120 -0
  463. package/src/cli/skills-content/design-exploration-skill.ts +118 -0
  464. package/src/cli/skills-content/design-visual-edit-skill.ts +228 -0
  465. package/src/cli/skills-content/document-quality.ts +196 -0
  466. package/src/cli/skills-content/exemplar.ts +69 -0
  467. package/src/cli/skills-content/help.ts +77 -0
  468. package/src/cli/skills-content/index.ts +22 -0
  469. package/src/cli/skills-content/local-files.ts +100 -0
  470. package/src/cli/skills-content/plan-setup-auth.ts +80 -0
  471. package/src/cli/skills-content/visual-plan-skill.ts +493 -0
  472. package/src/cli/skills-content/visual-recap-skill.ts +553 -0
  473. package/src/cli/skills-content/visualize-repo-skill.ts +93 -0
  474. package/src/cli/skills-content/wireframe.ts +349 -0
  475. package/src/cli/skills.ts +4340 -0
  476. package/src/cli/sync-builder-starter-manifest.ts +631 -0
  477. package/src/cli/telemetry.ts +136 -0
  478. package/src/cli/templates-meta.ts +269 -0
  479. package/src/cli/upgrade.ts +956 -0
  480. package/src/cli/visualize-repo.ts +715 -0
  481. package/src/cli/workspace-dev.ts +1486 -0
  482. package/src/cli/workspacify.ts +258 -0
  483. package/src/client/AgentAskPopover.tsx +89 -0
  484. package/src/client/AgentChatHome.tsx +66 -0
  485. package/src/client/AgentNative.tsx +161 -0
  486. package/src/client/AgentNativeEmbedded.tsx +288 -0
  487. package/src/client/AgentNativeFrame.tsx +151 -0
  488. package/src/client/AgentPanel.tsx +3437 -0
  489. package/src/client/AgentTaskCard.tsx +273 -0
  490. package/src/client/AppearancePicker.tsx +79 -0
  491. package/src/client/AssistantChat.tsx +5793 -0
  492. package/src/client/ClientOnly.tsx +22 -0
  493. package/src/client/CommandMenu.tsx +726 -0
  494. package/src/client/ConnectBuilderCard.tsx +390 -0
  495. package/src/client/DefaultSpinner.tsx +47 -0
  496. package/src/client/ErrorBoundary.tsx +359 -0
  497. package/src/client/ErrorReportActions.tsx +69 -0
  498. package/src/client/FeedbackButton.tsx +553 -0
  499. package/src/client/HighlightedCodeBlock.tsx +173 -0
  500. package/src/client/IframeEmbed.tsx +151 -0
  501. package/src/client/KeepTabOpenNotice.tsx +181 -0
  502. package/src/client/MultiTabAssistantChat.tsx +2576 -0
  503. package/src/client/NewWorkspaceAppFlow.tsx +525 -0
  504. package/src/client/PoweredByBadge.tsx +284 -0
  505. package/src/client/RunStuckBanner.tsx +431 -0
  506. package/src/client/StarfieldBackground.tsx +466 -0
  507. package/src/client/Turnstile.tsx +125 -0
  508. package/src/client/active-run-state.ts +139 -0
  509. package/src/client/agent-chat/index.ts +279 -0
  510. package/src/client/agent-chat-adapter.ts +3692 -0
  511. package/src/client/agent-chat.ts +1233 -0
  512. package/src/client/agent-engine-key.ts +122 -0
  513. package/src/client/agent-page/AgentContextTab.tsx +487 -0
  514. package/src/client/agent-page/AgentEmptyState.tsx +44 -0
  515. package/src/client/agent-page/AgentJobsTab.tsx +441 -0
  516. package/src/client/agent-page/AgentTabFrame.tsx +39 -0
  517. package/src/client/agent-page/AgentTabsPage.tsx +1096 -0
  518. package/src/client/agent-page/types.ts +18 -0
  519. package/src/client/agent-page/use-jobs.ts +150 -0
  520. package/src/client/agent-sidebar-state.ts +166 -0
  521. package/src/client/analytics/index.ts +40 -0
  522. package/src/client/analytics-session.ts +70 -0
  523. package/src/client/analytics.ts +1757 -0
  524. package/src/client/api-path.ts +124 -0
  525. package/src/client/app-providers.tsx +230 -0
  526. package/src/client/appearance.ts +130 -0
  527. package/src/client/application-state.ts +154 -0
  528. package/src/client/assistant-ui-recovery.tsx +205 -0
  529. package/src/client/automation/index.ts +4 -0
  530. package/src/client/automation.ts +22 -0
  531. package/src/client/blocks/AiEditableField.tsx +30 -0
  532. package/src/client/blocks/BlockView.tsx +145 -0
  533. package/src/client/blocks/RegistryBlockDataProvider.tsx +121 -0
  534. package/src/client/blocks/SchemaBlockEditor.tsx +457 -0
  535. package/src/client/blocks/agent.ts +95 -0
  536. package/src/client/blocks/code-block-direction.ts +21 -0
  537. package/src/client/blocks/index.ts +308 -0
  538. package/src/client/blocks/library/AnnotatedCodeBlock.tsx +710 -0
  539. package/src/client/blocks/library/ApiEndpointBlock.tsx +1120 -0
  540. package/src/client/blocks/library/DataModelBlock.tsx +775 -0
  541. package/src/client/blocks/library/DiffBlock.tsx +1854 -0
  542. package/src/client/blocks/library/FileTreeBlock.tsx +868 -0
  543. package/src/client/blocks/library/HighlightedCode.tsx +260 -0
  544. package/src/client/blocks/library/JsonExplorerBlock.tsx +608 -0
  545. package/src/client/blocks/library/MermaidBlock.tsx +362 -0
  546. package/src/client/blocks/library/OpenApiSpecBlock.tsx +998 -0
  547. package/src/client/blocks/library/annotated-code.config.ts +101 -0
  548. package/src/client/blocks/library/annotation-rail.tsx +1020 -0
  549. package/src/client/blocks/library/api-endpoint.config.ts +207 -0
  550. package/src/client/blocks/library/block-copy.ts +399 -0
  551. package/src/client/blocks/library/callout.config.ts +57 -0
  552. package/src/client/blocks/library/callout.tsx +149 -0
  553. package/src/client/blocks/library/checklist.config.ts +56 -0
  554. package/src/client/blocks/library/checklist.tsx +208 -0
  555. package/src/client/blocks/library/code-filename-label.tsx +59 -0
  556. package/src/client/blocks/library/code-highlight.tsx +178 -0
  557. package/src/client/blocks/library/code-tabs.config.ts +70 -0
  558. package/src/client/blocks/library/code-tabs.tsx +606 -0
  559. package/src/client/blocks/library/code.config.ts +69 -0
  560. package/src/client/blocks/library/code.tsx +440 -0
  561. package/src/client/blocks/library/columns.config.ts +85 -0
  562. package/src/client/blocks/library/columns.tsx +334 -0
  563. package/src/client/blocks/library/data-model.config.ts +152 -0
  564. package/src/client/blocks/library/dev-doc-ui.tsx +191 -0
  565. package/src/client/blocks/library/diagram.config.ts +222 -0
  566. package/src/client/blocks/library/diagram.tsx +958 -0
  567. package/src/client/blocks/library/diff.config.ts +115 -0
  568. package/src/client/blocks/library/file-tree.config.ts +92 -0
  569. package/src/client/blocks/library/html.config.ts +79 -0
  570. package/src/client/blocks/library/html.tsx +258 -0
  571. package/src/client/blocks/library/json-explorer.config.ts +74 -0
  572. package/src/client/blocks/library/mermaid.config.ts +49 -0
  573. package/src/client/blocks/library/narrow-container.tsx +37 -0
  574. package/src/client/blocks/library/openapi-spec.config.ts +66 -0
  575. package/src/client/blocks/library/question-form.config.ts +127 -0
  576. package/src/client/blocks/library/question-form.tsx +944 -0
  577. package/src/client/blocks/library/sanitize-html.ts +343 -0
  578. package/src/client/blocks/library/server-specs.ts +338 -0
  579. package/src/client/blocks/library/specs.tsx +308 -0
  580. package/src/client/blocks/library/table.config.ts +61 -0
  581. package/src/client/blocks/library/table.tsx +449 -0
  582. package/src/client/blocks/library/tabs.config.ts +96 -0
  583. package/src/client/blocks/library/tabs.tsx +665 -0
  584. package/src/client/blocks/library/wireframe-icons.ts +210 -0
  585. package/src/client/blocks/library/wireframe-kit.tsx +1850 -0
  586. package/src/client/blocks/library/wireframe.config.ts +539 -0
  587. package/src/client/blocks/library/wireframe.tsx +535 -0
  588. package/src/client/blocks/mdx.ts +364 -0
  589. package/src/client/blocks/provider.tsx +51 -0
  590. package/src/client/blocks/registry.ts +83 -0
  591. package/src/client/blocks/schema-form/introspect.ts +201 -0
  592. package/src/client/blocks/server.ts +170 -0
  593. package/src/client/blocks/types.ts +415 -0
  594. package/src/client/browser-session-bridge.ts +548 -0
  595. package/src/client/browser-tab-id.ts +36 -0
  596. package/src/client/builder-frame.ts +194 -0
  597. package/src/client/builder-mark.tsx +21 -0
  598. package/src/client/changelog/Changelog.tsx +333 -0
  599. package/src/client/changelog/index.ts +1 -0
  600. package/src/client/chat/ChatHistoryList.tsx +7 -0
  601. package/src/client/chat/attachment-adapters.ts +426 -0
  602. package/src/client/chat/connectors.ts +1579 -0
  603. package/src/client/chat/index.ts +160 -0
  604. package/src/client/chat/markdown-renderer.tsx +693 -0
  605. package/src/client/chat/message-components.tsx +1326 -0
  606. package/src/client/chat/repo-helpers.ts +281 -0
  607. package/src/client/chat/run-recovery.tsx +994 -0
  608. package/src/client/chat/runtime.ts +1810 -0
  609. package/src/client/chat/tool-call-display.tsx +1270 -0
  610. package/src/client/chat/tool-render-registry.tsx +144 -0
  611. package/src/client/chat/use-agent-chat-lifecycle-tracking.ts +74 -0
  612. package/src/client/chat/use-reconnect-reader-owner.ts +28 -0
  613. package/src/client/chat/widgets/DataChartRenderer.tsx +242 -0
  614. package/src/client/chat/widgets/DataChartWidget.tsx +51 -0
  615. package/src/client/chat/widgets/DataInsightsWidget.tsx +59 -0
  616. package/src/client/chat/widgets/DataTableWidget.tsx +240 -0
  617. package/src/client/chat/widgets/InlineExtensionWidget.tsx +60 -0
  618. package/src/client/chat/widgets/builtin-tool-renderers.tsx +213 -0
  619. package/src/client/chat/widgets/data-widget-types.ts +1 -0
  620. package/src/client/chat/widgets/inline-extension-result.ts +86 -0
  621. package/src/client/chat-model-groups.ts +171 -0
  622. package/src/client/chat-thread-url.ts +11 -0
  623. package/src/client/chat-view-transition.ts +213 -0
  624. package/src/client/client-action.ts +21 -0
  625. package/src/client/client-bootstrap.ts +7 -0
  626. package/src/client/client-surface.ts +41 -0
  627. package/src/client/clipboard.ts +89 -0
  628. package/src/client/code-agent-chat-adapter.ts +537 -0
  629. package/src/client/collab/index.ts +60 -0
  630. package/src/client/command-navigation/index.ts +15 -0
  631. package/src/client/comments-review/index.ts +1 -0
  632. package/src/client/components/AgentPresenceChip.tsx +4 -0
  633. package/src/client/components/ApiKeySettings.tsx +309 -0
  634. package/src/client/components/CodeAgentIndicator.tsx +59 -0
  635. package/src/client/components/CodeRequiredDialog.tsx +470 -0
  636. package/src/client/components/LiveCursorOverlay.tsx +5 -0
  637. package/src/client/components/MissingKeyCard.tsx +61 -0
  638. package/src/client/components/PresenceBar.tsx +4 -0
  639. package/src/client/components/RecentEditHighlights.tsx +4 -0
  640. package/src/client/components/RemoteSelectionRings.tsx +5 -0
  641. package/src/client/components/icons/AgentNativeIcon.tsx +46 -0
  642. package/src/client/components/ui/dialog.tsx +1 -0
  643. package/src/client/components/ui/dropdown-menu.tsx +1 -0
  644. package/src/client/components/ui/hover-card.tsx +1 -0
  645. package/src/client/components/ui/message-scroller.tsx +131 -0
  646. package/src/client/components/ui/popover.tsx +1 -0
  647. package/src/client/components/ui/sheet.tsx +1 -0
  648. package/src/client/components/ui/tooltip.tsx +1 -0
  649. package/src/client/composer/index.ts +11 -0
  650. package/src/client/composer/runtime-adapters.tsx +123 -0
  651. package/src/client/composer/use-mention-search.ts +7 -0
  652. package/src/client/composer/wired-components.tsx +53 -0
  653. package/src/client/context-xray/ContextMeter.tsx +124 -0
  654. package/src/client/context-xray/ContextSegmentRow.tsx +27 -0
  655. package/src/client/context-xray/ContextTreemap.tsx +24 -0
  656. package/src/client/context-xray/ContextXRayPanel.tsx +59 -0
  657. package/src/client/context-xray/SegmentProvenancePopover.tsx +18 -0
  658. package/src/client/context-xray/format.ts +27 -0
  659. package/src/client/conversation/AgentConversation.tsx +555 -0
  660. package/src/client/conversation/code-agent-transcript.ts +283 -0
  661. package/src/client/conversation/index.ts +22 -0
  662. package/src/client/conversation/types.ts +85 -0
  663. package/src/client/conversation/use-near-bottom-autoscroll.ts +278 -0
  664. package/src/client/create-query-client.ts +86 -0
  665. package/src/client/db-admin/DataGrid.tsx +551 -0
  666. package/src/client/db-admin/DbAdminPage.tsx +218 -0
  667. package/src/client/db-admin/DevDatabaseLink.tsx +16 -0
  668. package/src/client/db-admin/EditableCell.tsx +451 -0
  669. package/src/client/db-admin/FilterBar.tsx +203 -0
  670. package/src/client/db-admin/ResultsGrid.tsx +114 -0
  671. package/src/client/db-admin/RowSidePanel.tsx +337 -0
  672. package/src/client/db-admin/SqlEditor.tsx +840 -0
  673. package/src/client/db-admin/TableBrowser.tsx +212 -0
  674. package/src/client/db-admin/TableEditor.tsx +760 -0
  675. package/src/client/db-admin/cell-format.ts +246 -0
  676. package/src/client/db-admin/changeset.ts +296 -0
  677. package/src/client/db-admin/export-utils.ts +78 -0
  678. package/src/client/db-admin/index.ts +33 -0
  679. package/src/client/db-admin/sql-storage.ts +134 -0
  680. package/src/client/db-admin/storage.ts +68 -0
  681. package/src/client/db-admin/useAgentSync.ts +226 -0
  682. package/src/client/db-admin/useDbAdmin.ts +294 -0
  683. package/src/client/dev-overlay/DevOverlay.tsx +576 -0
  684. package/src/client/dev-overlay/builtins.ts +40 -0
  685. package/src/client/dev-overlay/index.ts +23 -0
  686. package/src/client/dev-overlay/registry.ts +67 -0
  687. package/src/client/dev-overlay/types.ts +64 -0
  688. package/src/client/dev-overlay/use-dev-option.ts +78 -0
  689. package/src/client/dev-overlay/use-dev-overlay-shortcut.ts +31 -0
  690. package/src/client/dynamic-suggestions.ts +455 -0
  691. package/src/client/embed-auth.ts +544 -0
  692. package/src/client/embed.ts +54 -0
  693. package/src/client/error-capture.ts +690 -0
  694. package/src/client/error-format.ts +211 -0
  695. package/src/client/error-reporting.ts +100 -0
  696. package/src/client/extensions/AgentNativeExtensionFrame.e2e-host.tsx +136 -0
  697. package/src/client/extensions/AgentNativeExtensionFrame.tsx +708 -0
  698. package/src/client/extensions/EmbeddedExtension.tsx +604 -0
  699. package/src/client/extensions/ExtensionEditor.tsx +450 -0
  700. package/src/client/extensions/ExtensionQueryErrorState.tsx +47 -0
  701. package/src/client/extensions/ExtensionSlot.tsx +345 -0
  702. package/src/client/extensions/ExtensionViewer.tsx +1502 -0
  703. package/src/client/extensions/ExtensionViewerPage.tsx +32 -0
  704. package/src/client/extensions/ExtensionsListPage.tsx +432 -0
  705. package/src/client/extensions/ExtensionsSidebarSection.tsx +1259 -0
  706. package/src/client/extensions/InlineExtensionFrame.tsx +660 -0
  707. package/src/client/extensions/agent-native-extension-runtime.ts +495 -0
  708. package/src/client/extensions/delete-extension.ts +76 -0
  709. package/src/client/extensions/extension-load-error.ts +26 -0
  710. package/src/client/extensions/extension-order.ts +49 -0
  711. package/src/client/extensions/extension-popularity.ts +61 -0
  712. package/src/client/extensions/iframe-bridge.ts +377 -0
  713. package/src/client/extensions/index.ts +84 -0
  714. package/src/client/extensions/portable-extension.ts +712 -0
  715. package/src/client/feature-flags/FeatureFlagsPanel.tsx +519 -0
  716. package/src/client/feature-flags/helpers.ts +77 -0
  717. package/src/client/feature-flags/index.ts +13 -0
  718. package/src/client/feature-flags/types.ts +29 -0
  719. package/src/client/feature-flags/use-feature-flag.ts +26 -0
  720. package/src/client/feedback-context.ts +90 -0
  721. package/src/client/frame-protocol.ts +168 -0
  722. package/src/client/frame.ts +329 -0
  723. package/src/client/guided-questions.tsx +1152 -0
  724. package/src/client/history/VersionHistoryPanel.tsx +175 -0
  725. package/src/client/history/index.ts +21 -0
  726. package/src/client/history/use-history.ts +114 -0
  727. package/src/client/hooks/index.ts +46 -0
  728. package/src/client/host/index.ts +170 -0
  729. package/src/client/host-bridge.ts +1272 -0
  730. package/src/client/host-tools.ts +190 -0
  731. package/src/client/i18n.tsx +798 -0
  732. package/src/client/index.ts +370 -0
  733. package/src/client/integrations/IntegrationCard.tsx +186 -0
  734. package/src/client/integrations/IntegrationsPanel.tsx +633 -0
  735. package/src/client/integrations/api.ts +295 -0
  736. package/src/client/integrations/index.ts +29 -0
  737. package/src/client/integrations/useIntegrationStatus.ts +52 -0
  738. package/src/client/mcp-app-host.ts +720 -0
  739. package/src/client/mcp-apps/McpAppRenderer.tsx +760 -0
  740. package/src/client/navigation/index.ts +54 -0
  741. package/src/client/notifications/NotificationsBell.tsx +383 -0
  742. package/src/client/notifications/index.ts +1 -0
  743. package/src/client/observability/ObservabilityDashboard.tsx +890 -0
  744. package/src/client/observability/ThumbsFeedback.tsx +160 -0
  745. package/src/client/observability/index.ts +20 -0
  746. package/src/client/observability/useObservability.ts +266 -0
  747. package/src/client/onboarding/OnboardingBanner.tsx +73 -0
  748. package/src/client/onboarding/OnboardingPanel.tsx +1036 -0
  749. package/src/client/onboarding/SetupButton.tsx +64 -0
  750. package/src/client/onboarding/index.ts +25 -0
  751. package/src/client/onboarding/use-onboarding.ts +164 -0
  752. package/src/client/onboarding/use-preview-mode.ts +40 -0
  753. package/src/client/org/InvitationBanner.tsx +148 -0
  754. package/src/client/org/OrgSwitcher.tsx +754 -0
  755. package/src/client/org/RequireActiveOrg.tsx +337 -0
  756. package/src/client/org/TeamPage.tsx +1432 -0
  757. package/src/client/org/hooks.ts +359 -0
  758. package/src/client/org/index.ts +70 -0
  759. package/src/client/org/workspace-app-links.ts +367 -0
  760. package/src/client/org-team/index.ts +1 -0
  761. package/src/client/progress/RunsTray.tsx +680 -0
  762. package/src/client/progress/index.ts +1 -0
  763. package/src/client/require-session.tsx +142 -0
  764. package/src/client/resources/BuiltinCapabilityDetail.tsx +258 -0
  765. package/src/client/resources/McpConnectionSuggestion.tsx +276 -0
  766. package/src/client/resources/McpIntegrationDialog.tsx +808 -0
  767. package/src/client/resources/McpServerDetail.tsx +230 -0
  768. package/src/client/resources/ResourceEditor.tsx +872 -0
  769. package/src/client/resources/ResourceTree.tsx +860 -0
  770. package/src/client/resources/ResourcesPanel.tsx +1960 -0
  771. package/src/client/resources/index.ts +25 -0
  772. package/src/client/resources/mcp-integration-catalog.ts +771 -0
  773. package/src/client/resources/mcp-integration-logos.ts +108 -0
  774. package/src/client/resources/runtime.ts +1 -0
  775. package/src/client/resources/use-builtin-capabilities.ts +113 -0
  776. package/src/client/resources/use-mcp-servers.ts +217 -0
  777. package/src/client/resources/use-resources.ts +402 -0
  778. package/src/client/review/ReviewCommentComposer.tsx +123 -0
  779. package/src/client/review/ReviewStatusBadge.tsx +39 -0
  780. package/src/client/review/ReviewThreadPanel.tsx +625 -0
  781. package/src/client/review/index.ts +38 -0
  782. package/src/client/review/use-review.ts +186 -0
  783. package/src/client/route-chunk-recovery/index.ts +1 -0
  784. package/src/client/route-chunk-recovery.ts +331 -0
  785. package/src/client/route-state.ts +455 -0
  786. package/src/client/route-warmup.tsx +543 -0
  787. package/src/client/session-replay-iframe.e2e-host.tsx +100 -0
  788. package/src/client/session-replay.ts +3417 -0
  789. package/src/client/settings/AgentsSection.tsx +441 -0
  790. package/src/client/settings/AutomationsSection.tsx +516 -0
  791. package/src/client/settings/BackgroundAgentSection.tsx +189 -0
  792. package/src/client/settings/BrowserSection.tsx +110 -0
  793. package/src/client/settings/DemoModeSection.tsx +48 -0
  794. package/src/client/settings/SecretsSection.tsx +875 -0
  795. package/src/client/settings/SettingsPanel.tsx +3162 -0
  796. package/src/client/settings/SettingsSection.tsx +283 -0
  797. package/src/client/settings/SettingsTabsPage.tsx +592 -0
  798. package/src/client/settings/UsageSection.tsx +401 -0
  799. package/src/client/settings/VoiceTranscriptionSection.tsx +960 -0
  800. package/src/client/settings/agent-settings-search.ts +220 -0
  801. package/src/client/settings/index.ts +27 -0
  802. package/src/client/settings/useBuilderStatus.ts +1055 -0
  803. package/src/client/setup-connections/BuilderConnectCard.tsx +89 -0
  804. package/src/client/setup-connections/ProviderReadinessBadge.tsx +73 -0
  805. package/src/client/setup-connections/SetupConnectionsPage.tsx +94 -0
  806. package/src/client/setup-connections/catalog.ts +6 -0
  807. package/src/client/setup-connections/index.ts +47 -0
  808. package/src/client/setup-connections/runtime.ts +1 -0
  809. package/src/client/sharing/ShareButton.tsx +1748 -0
  810. package/src/client/sharing/ShareDialog.tsx +846 -0
  811. package/src/client/sharing/VisibilityBadge.tsx +4 -0
  812. package/src/client/sharing/index.ts +2 -0
  813. package/src/client/sse-event-processor.ts +2002 -0
  814. package/src/client/terminal/AgentTerminal.tsx +488 -0
  815. package/src/client/terminal/index.ts +7 -0
  816. package/src/client/theme.ts +27 -0
  817. package/src/client/tombstone/agent-presence-chip.ts +17 -0
  818. package/src/client/tombstone/editor.ts +265 -0
  819. package/src/client/tombstone/live-cursor-overlay.ts +21 -0
  820. package/src/client/tombstone/presence-bar.ts +17 -0
  821. package/src/client/tombstone/recent-edit-highlights.ts +17 -0
  822. package/src/client/tombstone/remote-selection-rings.ts +21 -0
  823. package/src/client/tombstone/rich-markdown-editor.ts +265 -0
  824. package/src/client/tombstone/ui-dialog.ts +49 -0
  825. package/src/client/tombstone/ui-dropdown-menu.ts +69 -0
  826. package/src/client/tombstone/ui-hover-card.ts +21 -0
  827. package/src/client/tombstone/ui-popover.ts +25 -0
  828. package/src/client/tombstone/ui-sheet.ts +49 -0
  829. package/src/client/tombstone/ui-tooltip.ts +29 -0
  830. package/src/client/tombstone/visual-style-controls.ts +61 -0
  831. package/src/client/tool-cells/BashCell.tsx +164 -0
  832. package/src/client/tool-cells/EditCell.tsx +303 -0
  833. package/src/client/tool-cells/FilesChangedSummary.tsx +208 -0
  834. package/src/client/tool-cells/WriteCell.tsx +145 -0
  835. package/src/client/tool-cells/index.ts +7 -0
  836. package/src/client/tool-display.ts +41 -0
  837. package/src/client/track.ts +57 -0
  838. package/src/client/transcription/BuilderTranscriptionCta.tsx +120 -0
  839. package/src/client/transcription/use-live-transcription.ts +292 -0
  840. package/src/client/ui/index.ts +55 -0
  841. package/src/client/uploads/index.ts +6 -0
  842. package/src/client/uploads/upload-editor-image.ts +79 -0
  843. package/src/client/uploads/use-upload-resource.ts +24 -0
  844. package/src/client/url-scrub.ts +51 -0
  845. package/src/client/use-action.ts +766 -0
  846. package/src/client/use-agent-chat-context.ts +63 -0
  847. package/src/client/use-agent-chat-home-handoff.ts +207 -0
  848. package/src/client/use-agent-chat.ts +53 -0
  849. package/src/client/use-agent-engine-configured.ts +211 -0
  850. package/src/client/use-avatar.ts +127 -0
  851. package/src/client/use-change-version.ts +150 -0
  852. package/src/client/use-chat-models.ts +252 -0
  853. package/src/client/use-chat-threads.ts +1262 -0
  854. package/src/client/use-db-sync.ts +1112 -0
  855. package/src/client/use-demo-mode-status.ts +30 -0
  856. package/src/client/use-dev-mode.ts +177 -0
  857. package/src/client/use-external-value.ts +40 -0
  858. package/src/client/use-pausing-interval.ts +65 -0
  859. package/src/client/use-pinch-zoom.ts +202 -0
  860. package/src/client/use-run-stuck-detection.ts +427 -0
  861. package/src/client/use-send-to-agent-chat.ts +85 -0
  862. package/src/client/use-session.ts +114 -0
  863. package/src/client/utils.ts +7 -0
  864. package/src/client/visual-style-controls.tsx +1 -0
  865. package/src/client/vite-dev-recovery-script.ts +226 -0
  866. package/src/client/voice-provider-status.ts +44 -0
  867. package/src/client/widgets/index.ts +41 -0
  868. package/src/code-agents/background-controller.ts +398 -0
  869. package/src/code-agents/background-run.ts +156 -0
  870. package/src/code-agents/index.ts +95 -0
  871. package/src/code-agents/prompt-attachments.ts +39 -0
  872. package/src/code-agents/transcript-normalizer.ts +750 -0
  873. package/src/code-agents/transcript-order.ts +73 -0
  874. package/src/coding-tools/index.ts +742 -0
  875. package/src/coding-tools/run-code.ts +1662 -0
  876. package/src/coding-tools/sandbox/adapter.ts +82 -0
  877. package/src/coding-tools/sandbox/background.ts +406 -0
  878. package/src/coding-tools/sandbox/executions-store.ts +517 -0
  879. package/src/coding-tools/sandbox/index.ts +132 -0
  880. package/src/coding-tools/sandbox/local-child-process-adapter.ts +217 -0
  881. package/src/collab/agent-identity.ts +5 -0
  882. package/src/collab/agent-presence.ts +341 -0
  883. package/src/collab/awareness-store.ts +196 -0
  884. package/src/collab/awareness.ts +317 -0
  885. package/src/collab/client-struct.ts +366 -0
  886. package/src/collab/client.ts +1205 -0
  887. package/src/collab/emitter.ts +31 -0
  888. package/src/collab/follow-mode.ts +107 -0
  889. package/src/collab/index.ts +151 -0
  890. package/src/collab/json-to-yjs.ts +504 -0
  891. package/src/collab/presence.ts +207 -0
  892. package/src/collab/recent-edits.ts +215 -0
  893. package/src/collab/routes.ts +191 -0
  894. package/src/collab/storage.ts +228 -0
  895. package/src/collab/struct-routes.ts +133 -0
  896. package/src/collab/text-to-yjs.ts +79 -0
  897. package/src/collab/undo.ts +432 -0
  898. package/src/collab/xml-ops.ts +68 -0
  899. package/src/collab/ydoc-manager.ts +544 -0
  900. package/src/command-navigation/actions.ts +100 -0
  901. package/src/command-navigation/index.ts +12 -0
  902. package/src/comments-review/index.ts +1 -0
  903. package/src/connections/catalog.ts +451 -0
  904. package/src/connections/index.ts +48 -0
  905. package/src/connections/reader.ts +911 -0
  906. package/src/connections/runtime.ts +1 -0
  907. package/src/credentials/index.ts +187 -0
  908. package/src/data-programs/actions.ts +335 -0
  909. package/src/data-programs/contract.ts +284 -0
  910. package/src/data-programs/execute.ts +693 -0
  911. package/src/data-programs/index.ts +72 -0
  912. package/src/data-programs/schema.ts +148 -0
  913. package/src/data-programs/store.ts +755 -0
  914. package/src/data-widgets/index.ts +376 -0
  915. package/src/db/client.ts +1627 -0
  916. package/src/db/create-get-db.ts +579 -0
  917. package/src/db/ddl-guard.ts +302 -0
  918. package/src/db/drizzle-config.ts +190 -0
  919. package/src/db/ensure-additive-columns.ts +430 -0
  920. package/src/db/index.ts +57 -0
  921. package/src/db/migrations.ts +691 -0
  922. package/src/db/request-telemetry.ts +154 -0
  923. package/src/db/runtime-diagnostics.ts +331 -0
  924. package/src/db/schema.ts +121 -0
  925. package/src/db/widen-columns.ts +75 -0
  926. package/src/db-admin/agent-tools.ts +202 -0
  927. package/src/db-admin/index.ts +26 -0
  928. package/src/db-admin/operations.ts +803 -0
  929. package/src/db-admin/routes.ts +174 -0
  930. package/src/db-admin/types.ts +110 -0
  931. package/src/demo/browser-state.ts +47 -0
  932. package/src/demo/fetch-interceptor.ts +175 -0
  933. package/src/demo/redact.ts +575 -0
  934. package/src/deploy/build.ts +3935 -0
  935. package/src/deploy/immutable-assets.ts +65 -0
  936. package/src/deploy/route-discovery.ts +458 -0
  937. package/src/deploy/workspace-core.ts +282 -0
  938. package/src/deploy/workspace-deploy.ts +1488 -0
  939. package/src/eject/provider-api-definitions.ts +193 -0
  940. package/src/eject/remote-mcp-presets.ts +137 -0
  941. package/src/eject/setup-readiness-ui.tsx +29 -0
  942. package/src/eject/workspace-connections.ts +92 -0
  943. package/src/embedding/agent.ts +159 -0
  944. package/src/embedding/bridge.ts +297 -0
  945. package/src/embedding/index.ts +43 -0
  946. package/src/embedding/protocol.ts +185 -0
  947. package/src/embedding/react.tsx +319 -0
  948. package/src/embeddings/index.ts +233 -0
  949. package/src/eval/agent-runner.ts +210 -0
  950. package/src/eval/define-eval.ts +55 -0
  951. package/src/eval/index.ts +49 -0
  952. package/src/eval/report.ts +75 -0
  953. package/src/eval/runner.ts +369 -0
  954. package/src/eval/scorer.ts +244 -0
  955. package/src/eval/types.ts +188 -0
  956. package/src/event-bus/bus.ts +140 -0
  957. package/src/event-bus/index.ts +3 -0
  958. package/src/event-bus/registry.ts +79 -0
  959. package/src/event-bus/types.ts +29 -0
  960. package/src/extensions/actions.ts +1636 -0
  961. package/src/extensions/change-marker.ts +54 -0
  962. package/src/extensions/content-patch.ts +468 -0
  963. package/src/extensions/fetch-tool.ts +461 -0
  964. package/src/extensions/html-shell.ts +803 -0
  965. package/src/extensions/local.ts +462 -0
  966. package/src/extensions/path.ts +40 -0
  967. package/src/extensions/proxy-security.ts +171 -0
  968. package/src/extensions/routes.ts +1080 -0
  969. package/src/extensions/schema.ts +269 -0
  970. package/src/extensions/session-replay-iframe.ts +131 -0
  971. package/src/extensions/slots/routes.ts +126 -0
  972. package/src/extensions/slots/schema.ts +87 -0
  973. package/src/extensions/slots/store.ts +450 -0
  974. package/src/extensions/store.ts +1347 -0
  975. package/src/extensions/theme.ts +114 -0
  976. package/src/extensions/url-safety.ts +316 -0
  977. package/src/extensions/web-content.ts +663 -0
  978. package/src/extensions/web-search-tool.ts +437 -0
  979. package/src/feature-flags/a2a-action-route.ts +56 -0
  980. package/src/feature-flags/actions/get-feature-flags.ts +24 -0
  981. package/src/feature-flags/actions/list-feature-flags.ts +69 -0
  982. package/src/feature-flags/actions/set-feature-flag.ts +89 -0
  983. package/src/feature-flags/index.ts +21 -0
  984. package/src/feature-flags/permissions.ts +53 -0
  985. package/src/feature-flags/plugin.ts +44 -0
  986. package/src/feature-flags/registry.ts +96 -0
  987. package/src/feature-flags/store.ts +176 -0
  988. package/src/file-upload/actions/upload-image.ts +213 -0
  989. package/src/file-upload/builder.ts +431 -0
  990. package/src/file-upload/index.ts +24 -0
  991. package/src/file-upload/pre-upload-attachments.ts +305 -0
  992. package/src/file-upload/registry.ts +125 -0
  993. package/src/file-upload/types.ts +89 -0
  994. package/src/guards/db-tool-scoping.ts +129 -0
  995. package/src/guards/index.ts +23 -0
  996. package/src/guards/no-drizzle-push.ts +116 -0
  997. package/src/guards/no-env-credentials.ts +229 -0
  998. package/src/guards/no-env-mutation.ts +114 -0
  999. package/src/guards/no-localhost-fallback.ts +124 -0
  1000. package/src/guards/no-unscoped-credentials.ts +227 -0
  1001. package/src/guards/no-unscoped-queries.ts +834 -0
  1002. package/src/guards/scan-utils.ts +105 -0
  1003. package/src/guards/types.ts +30 -0
  1004. package/src/history/actions/create-resource-version.ts +92 -0
  1005. package/src/history/actions/get-resource-version.ts +60 -0
  1006. package/src/history/actions/list-resource-history.ts +53 -0
  1007. package/src/history/actions/list-resource-versions.ts +43 -0
  1008. package/src/history/actions/restore-resource-version.ts +96 -0
  1009. package/src/history/index.ts +26 -0
  1010. package/src/history/registry.ts +111 -0
  1011. package/src/history/store.ts +379 -0
  1012. package/src/history/types.ts +69 -0
  1013. package/src/index.browser.ts +155 -0
  1014. package/src/index.ts +408 -0
  1015. package/src/ingestion/docx.ts +158 -0
  1016. package/src/ingestion/figma-node-to-html.ts +1860 -0
  1017. package/src/ingestion/figma.ts +548 -0
  1018. package/src/ingestion/index.ts +107 -0
  1019. package/src/ingestion/media.ts +264 -0
  1020. package/src/ingestion/notion.ts +121 -0
  1021. package/src/ingestion/office.ts +213 -0
  1022. package/src/ingestion/orchestration.ts +160 -0
  1023. package/src/ingestion/pptx.ts +331 -0
  1024. package/src/ingestion/selection.ts +81 -0
  1025. package/src/ingestion/website.ts +151 -0
  1026. package/src/integrations/a2a-continuation-marker.ts +2 -0
  1027. package/src/integrations/a2a-continuation-processor.ts +888 -0
  1028. package/src/integrations/a2a-continuations-store.ts +643 -0
  1029. package/src/integrations/adapter-overrides.ts +12 -0
  1030. package/src/integrations/adapters/discord.ts +364 -0
  1031. package/src/integrations/adapters/email.ts +1164 -0
  1032. package/src/integrations/adapters/google-docs.ts +371 -0
  1033. package/src/integrations/adapters/index.ts +29 -0
  1034. package/src/integrations/adapters/microsoft-teams.ts +413 -0
  1035. package/src/integrations/adapters/slack.ts +1914 -0
  1036. package/src/integrations/adapters/telegram.ts +386 -0
  1037. package/src/integrations/adapters/whatsapp.ts +358 -0
  1038. package/src/integrations/awaiting-input-store.ts +130 -0
  1039. package/src/integrations/catalog.ts +571 -0
  1040. package/src/integrations/computer-supervision-store.ts +423 -0
  1041. package/src/integrations/computer-supervision.ts +213 -0
  1042. package/src/integrations/config-store.ts +131 -0
  1043. package/src/integrations/controls-store.ts +187 -0
  1044. package/src/integrations/eject/messaging-adapters.ts +85 -0
  1045. package/src/integrations/google-docs-poller.ts +671 -0
  1046. package/src/integrations/identity-links-store.ts +210 -0
  1047. package/src/integrations/identity.ts +196 -0
  1048. package/src/integrations/index.ts +220 -0
  1049. package/src/integrations/installations-store.ts +677 -0
  1050. package/src/integrations/integration-memory.ts +187 -0
  1051. package/src/integrations/internal-token.ts +106 -0
  1052. package/src/integrations/pending-tasks-retry-job.ts +286 -0
  1053. package/src/integrations/pending-tasks-store.ts +468 -0
  1054. package/src/integrations/plugin.ts +3048 -0
  1055. package/src/integrations/remote-commands-store.ts +690 -0
  1056. package/src/integrations/remote-devices-store.ts +492 -0
  1057. package/src/integrations/remote-json-safety.ts +127 -0
  1058. package/src/integrations/remote-push-delivery-job.ts +48 -0
  1059. package/src/integrations/remote-push-delivery.ts +370 -0
  1060. package/src/integrations/remote-push-store.ts +664 -0
  1061. package/src/integrations/remote-retry-job.ts +55 -0
  1062. package/src/integrations/remote-run-events-store.ts +222 -0
  1063. package/src/integrations/remote-types.ts +186 -0
  1064. package/src/integrations/runtime.ts +1 -0
  1065. package/src/integrations/scope-store.ts +498 -0
  1066. package/src/integrations/slack-manifest.ts +78 -0
  1067. package/src/integrations/slack-oauth.ts +344 -0
  1068. package/src/integrations/task-queue-stats.ts +144 -0
  1069. package/src/integrations/thread-mapping-store.ts +134 -0
  1070. package/src/integrations/types.ts +485 -0
  1071. package/src/integrations/usage-budget-store.ts +906 -0
  1072. package/src/integrations/webhook-delivery.ts +55 -0
  1073. package/src/integrations/webhook-handler.ts +1939 -0
  1074. package/src/jobs/actions/list-recurring-jobs.ts +105 -0
  1075. package/src/jobs/actions/manage-recurring-job.ts +85 -0
  1076. package/src/jobs/cron.ts +126 -0
  1077. package/src/jobs/index.ts +9 -0
  1078. package/src/jobs/scheduler.ts +703 -0
  1079. package/src/jobs/tools.ts +367 -0
  1080. package/src/local-artifacts/index.ts +1372 -0
  1081. package/src/localization/actions/get-localization-preference.ts +24 -0
  1082. package/src/localization/actions/set-localization-preference.ts +32 -0
  1083. package/src/localization/default-messages.ts +1009 -0
  1084. package/src/localization/index.ts +2 -0
  1085. package/src/localization/server.ts +131 -0
  1086. package/src/localization/shared.ts +208 -0
  1087. package/src/mcp/actions/call-mcp-tool.ts +19 -0
  1088. package/src/mcp/actions/create-org-service-token.ts +87 -0
  1089. package/src/mcp/actions/list-mcp-tools.ts +18 -0
  1090. package/src/mcp/actions/list-org-service-tokens.ts +44 -0
  1091. package/src/mcp/actions/revoke-org-service-token.ts +30 -0
  1092. package/src/mcp/actions/service-token-access.ts +121 -0
  1093. package/src/mcp/ask-app-inline-tasks.ts +125 -0
  1094. package/src/mcp/build-server.ts +2356 -0
  1095. package/src/mcp/builtin-tools.ts +1506 -0
  1096. package/src/mcp/connect-route.ts +1460 -0
  1097. package/src/mcp/connect-store.ts +680 -0
  1098. package/src/mcp/embed-app.ts +2051 -0
  1099. package/src/mcp/embed-route.ts +84 -0
  1100. package/src/mcp/external-agent-policy.ts +18 -0
  1101. package/src/mcp/index.ts +47 -0
  1102. package/src/mcp/oauth-route.ts +1016 -0
  1103. package/src/mcp/oauth-store.ts +581 -0
  1104. package/src/mcp/oauth-token.ts +227 -0
  1105. package/src/mcp/org-directory.ts +343 -0
  1106. package/src/mcp/route-paths.ts +34 -0
  1107. package/src/mcp/screen-memory-stdio.ts +290 -0
  1108. package/src/mcp/server.ts +507 -0
  1109. package/src/mcp/stdio.ts +328 -0
  1110. package/src/mcp/workspace-resolve.ts +261 -0
  1111. package/src/mcp-client/app-api.ts +136 -0
  1112. package/src/mcp-client/app-result.ts +64 -0
  1113. package/src/mcp-client/builtin-capabilities.ts +146 -0
  1114. package/src/mcp-client/builtin-store.ts +93 -0
  1115. package/src/mcp-client/config.ts +281 -0
  1116. package/src/mcp-client/errors.ts +54 -0
  1117. package/src/mcp-client/hub-client.ts +172 -0
  1118. package/src/mcp-client/hub-routes.ts +198 -0
  1119. package/src/mcp-client/index.ts +504 -0
  1120. package/src/mcp-client/manager.ts +968 -0
  1121. package/src/mcp-client/oauth-client.ts +462 -0
  1122. package/src/mcp-client/oauth-routes.ts +307 -0
  1123. package/src/mcp-client/remote-store.ts +674 -0
  1124. package/src/mcp-client/remote-url.ts +97 -0
  1125. package/src/mcp-client/routes.ts +1093 -0
  1126. package/src/mcp-client/screen-memory-local.ts +461 -0
  1127. package/src/mcp-client/tool-policy.ts +182 -0
  1128. package/src/mcp-client/visibility.ts +56 -0
  1129. package/src/mcp-client/workspace-servers.ts +379 -0
  1130. package/src/navigation/index.ts +170 -0
  1131. package/src/notifications/actions.ts +151 -0
  1132. package/src/notifications/channels.ts +410 -0
  1133. package/src/notifications/index.ts +22 -0
  1134. package/src/notifications/registry.ts +216 -0
  1135. package/src/notifications/routes.ts +106 -0
  1136. package/src/notifications/store.ts +236 -0
  1137. package/src/notifications/types.ts +52 -0
  1138. package/src/oauth-tokens/google-refresh.ts +175 -0
  1139. package/src/oauth-tokens/index.ts +15 -0
  1140. package/src/oauth-tokens/store.ts +384 -0
  1141. package/src/observability/cleanup-job.ts +124 -0
  1142. package/src/observability/evals.ts +507 -0
  1143. package/src/observability/experiments.ts +359 -0
  1144. package/src/observability/feedback.ts +332 -0
  1145. package/src/observability/hosted-model-experiment.ts +118 -0
  1146. package/src/observability/index.ts +62 -0
  1147. package/src/observability/plugin.ts +31 -0
  1148. package/src/observability/routes.ts +431 -0
  1149. package/src/observability/sentiment.ts +261 -0
  1150. package/src/observability/store.ts +1347 -0
  1151. package/src/observability/traces.ts +789 -0
  1152. package/src/observability/tracing.ts +157 -0
  1153. package/src/observability/tracking-identity.ts +55 -0
  1154. package/src/observability/types.ts +211 -0
  1155. package/src/onboarding/default-steps.ts +428 -0
  1156. package/src/onboarding/index.ts +22 -0
  1157. package/src/onboarding/plugin.ts +262 -0
  1158. package/src/onboarding/registry.ts +47 -0
  1159. package/src/onboarding/types.ts +96 -0
  1160. package/src/org/accept-pending.ts +98 -0
  1161. package/src/org/auto-join-domain.ts +113 -0
  1162. package/src/org/context.ts +614 -0
  1163. package/src/org/free-email-providers.ts +124 -0
  1164. package/src/org/handlers.ts +1153 -0
  1165. package/src/org/index.ts +63 -0
  1166. package/src/org/migrations.ts +105 -0
  1167. package/src/org/permissions.ts +30 -0
  1168. package/src/org/plugin.ts +255 -0
  1169. package/src/org/schema.ts +28 -0
  1170. package/src/org/types.ts +57 -0
  1171. package/src/org-team/index.ts +1 -0
  1172. package/src/package-lifecycle/deprecated-imports.ts +179 -0
  1173. package/src/package-lifecycle/eject-manifest.ts +345 -0
  1174. package/src/package-lifecycle/index.ts +7 -0
  1175. package/src/package-lifecycle/manifest.ts +120 -0
  1176. package/src/package-lifecycle/migration-manifest.ts +159 -0
  1177. package/src/package-lifecycle/migration-message.ts +6 -0
  1178. package/src/package-lifecycle/tombstone.ts +58 -0
  1179. package/src/package-lifecycle/upgrade-error.ts +37 -0
  1180. package/src/private-blob/index.ts +18 -0
  1181. package/src/private-blob/registry.ts +242 -0
  1182. package/src/private-blob/types.ts +55 -0
  1183. package/src/progress/actions.ts +179 -0
  1184. package/src/progress/index.ts +16 -0
  1185. package/src/progress/registry.ts +127 -0
  1186. package/src/progress/routes.ts +89 -0
  1187. package/src/progress/store.ts +353 -0
  1188. package/src/progress/types.ts +59 -0
  1189. package/src/provider-api/actions/custom-provider-registration.ts +197 -0
  1190. package/src/provider-api/actions/delete-staged-dataset.ts +5 -0
  1191. package/src/provider-api/actions/github-repo-files.ts +266 -0
  1192. package/src/provider-api/actions/list-staged-datasets.ts +5 -0
  1193. package/src/provider-api/actions/provider-api-audit.ts +88 -0
  1194. package/src/provider-api/actions/provider-api.ts +460 -0
  1195. package/src/provider-api/actions/query-staged-dataset.ts +5 -0
  1196. package/src/provider-api/actions/staged-datasets.ts +359 -0
  1197. package/src/provider-api/corpus-jobs-store.ts +522 -0
  1198. package/src/provider-api/corpus-jobs.ts +1817 -0
  1199. package/src/provider-api/custom-registry.ts +456 -0
  1200. package/src/provider-api/github-repo.ts +675 -0
  1201. package/src/provider-api/gong.ts +108 -0
  1202. package/src/provider-api/index.ts +5444 -0
  1203. package/src/provider-api/quota-governor.ts +562 -0
  1204. package/src/provider-api/runtime.ts +1 -0
  1205. package/src/provider-api/staged-datasets-aggregate.ts +304 -0
  1206. package/src/provider-api/staged-datasets-store.ts +441 -0
  1207. package/src/provider-api/staging.ts +483 -0
  1208. package/src/resources/agents.ts +65 -0
  1209. package/src/resources/emitter.ts +54 -0
  1210. package/src/resources/handlers.ts +728 -0
  1211. package/src/resources/index.ts +4 -0
  1212. package/src/resources/metadata.ts +252 -0
  1213. package/src/resources/script-helpers.ts +160 -0
  1214. package/src/resources/store.ts +1618 -0
  1215. package/src/review/actions/consume-review-feedback.ts +48 -0
  1216. package/src/review/actions/create-review-comment.ts +108 -0
  1217. package/src/review/actions/delete-review-comment.ts +67 -0
  1218. package/src/review/actions/get-review-feedback.ts +49 -0
  1219. package/src/review/actions/list-review-comments.ts +87 -0
  1220. package/src/review/actions/reply-review-comment.ts +118 -0
  1221. package/src/review/actions/resolve-review-thread.ts +94 -0
  1222. package/src/review/actions/send-review-thread-to-agent.ts +62 -0
  1223. package/src/review/actions/set-review-status.ts +58 -0
  1224. package/src/review/identity.ts +101 -0
  1225. package/src/review/index.ts +45 -0
  1226. package/src/review/mentions.ts +44 -0
  1227. package/src/review/registry.ts +111 -0
  1228. package/src/review/store.ts +997 -0
  1229. package/src/review/types.ts +101 -0
  1230. package/src/router/index.ts +24 -0
  1231. package/src/scripts/agent-engines/list-agent-engines.ts +130 -0
  1232. package/src/scripts/agent-engines/manage-agent-engine.ts +197 -0
  1233. package/src/scripts/agent-engines/set-agent-engine.ts +84 -0
  1234. package/src/scripts/agent-engines/test-agent-engine.ts +174 -0
  1235. package/src/scripts/call-agent.ts +792 -0
  1236. package/src/scripts/chat/index.ts +8 -0
  1237. package/src/scripts/chat/open-chat.ts +56 -0
  1238. package/src/scripts/chat/search-chats.ts +121 -0
  1239. package/src/scripts/core-scripts.ts +22 -0
  1240. package/src/scripts/db/check-scoping.ts +212 -0
  1241. package/src/scripts/db/exec.ts +791 -0
  1242. package/src/scripts/db/index.ts +19 -0
  1243. package/src/scripts/db/migrate-encrypt-credentials.ts +223 -0
  1244. package/src/scripts/db/migrate-encrypt-oauth-tokens.ts +213 -0
  1245. package/src/scripts/db/migrate-user-api-keys.ts +257 -0
  1246. package/src/scripts/db/patch.ts +820 -0
  1247. package/src/scripts/db/query.ts +299 -0
  1248. package/src/scripts/db/reset-dev-owner.ts +285 -0
  1249. package/src/scripts/db/safety.ts +286 -0
  1250. package/src/scripts/db/schema.ts +364 -0
  1251. package/src/scripts/db/scoping.ts +341 -0
  1252. package/src/scripts/db/sqlite-client.ts +78 -0
  1253. package/src/scripts/db/tool-mode.ts +23 -0
  1254. package/src/scripts/db/tool-schemas.ts +31 -0
  1255. package/src/scripts/db/wipe-leaked-builder-keys.ts +201 -0
  1256. package/src/scripts/dev/index.ts +296 -0
  1257. package/src/scripts/dev/list-files.ts +119 -0
  1258. package/src/scripts/dev/read-file.ts +77 -0
  1259. package/src/scripts/dev/search-files.ts +151 -0
  1260. package/src/scripts/dev/shell.ts +111 -0
  1261. package/src/scripts/dev/write-file.ts +56 -0
  1262. package/src/scripts/dev-session.ts +96 -0
  1263. package/src/scripts/docs/index.ts +8 -0
  1264. package/src/scripts/docs/search.ts +274 -0
  1265. package/src/scripts/docs/source-search.ts +363 -0
  1266. package/src/scripts/index.ts +15 -0
  1267. package/src/scripts/manage-agent-loop-settings.ts +84 -0
  1268. package/src/scripts/parse-args.ts +46 -0
  1269. package/src/scripts/resources/delete-memory.ts +67 -0
  1270. package/src/scripts/resources/delete.ts +69 -0
  1271. package/src/scripts/resources/effective.ts +71 -0
  1272. package/src/scripts/resources/index.ts +18 -0
  1273. package/src/scripts/resources/list.ts +103 -0
  1274. package/src/scripts/resources/migrate-learnings.ts +40 -0
  1275. package/src/scripts/resources/read.ts +107 -0
  1276. package/src/scripts/resources/save-memory.ts +99 -0
  1277. package/src/scripts/resources/write.ts +158 -0
  1278. package/src/scripts/runner.ts +339 -0
  1279. package/src/scripts/utils.ts +130 -0
  1280. package/src/search/index.ts +413 -0
  1281. package/src/search-utils/index.ts +112 -0
  1282. package/src/secrets/crypto.ts +228 -0
  1283. package/src/secrets/index.ts +65 -0
  1284. package/src/secrets/onboarding.ts +101 -0
  1285. package/src/secrets/register-framework-secrets.ts +228 -0
  1286. package/src/secrets/register.ts +129 -0
  1287. package/src/secrets/routes.ts +697 -0
  1288. package/src/secrets/schema.ts +52 -0
  1289. package/src/secrets/storage.ts +561 -0
  1290. package/src/secrets/substitution.ts +305 -0
  1291. package/src/server/__snapshots__/agent-chat-plugin.surface.spec.ts.snap +150 -0
  1292. package/src/server/action-change.ts +66 -0
  1293. package/src/server/action-discovery.ts +774 -0
  1294. package/src/server/action-routes.ts +608 -0
  1295. package/src/server/agent-access.ts +72 -0
  1296. package/src/server/agent-chat/action-filters-a2a.ts +339 -0
  1297. package/src/server/agent-chat/browser-team-tools.ts +510 -0
  1298. package/src/server/agent-chat/context-tools.ts +599 -0
  1299. package/src/server/agent-chat/framework-prompts.ts +467 -0
  1300. package/src/server/agent-chat/lazy-fs.ts +11 -0
  1301. package/src/server/agent-chat/mcp-glue.ts +91 -0
  1302. package/src/server/agent-chat/plugin-options.ts +379 -0
  1303. package/src/server/agent-chat/process-run-failure.ts +62 -0
  1304. package/src/server/agent-chat/prompt-resources.ts +1004 -0
  1305. package/src/server/agent-chat/recurring-jobs-runtime.ts +80 -0
  1306. package/src/server/agent-chat/request-surface.ts +71 -0
  1307. package/src/server/agent-chat/run-code-tools.ts +67 -0
  1308. package/src/server/agent-chat/script-entries.ts +796 -0
  1309. package/src/server/agent-chat/shared-thread.ts +301 -0
  1310. package/src/server/agent-chat/skill-frontmatter.ts +41 -0
  1311. package/src/server/agent-chat-plugin.ts +5930 -0
  1312. package/src/server/agent-discovery.ts +706 -0
  1313. package/src/server/agent-engine-api-key-route.ts +236 -0
  1314. package/src/server/agent-run-context.ts +204 -0
  1315. package/src/server/agent-teams-run-queue.ts +344 -0
  1316. package/src/server/agent-teams.ts +2257 -0
  1317. package/src/server/agents-bundle.ts +464 -0
  1318. package/src/server/analytics.ts +105 -0
  1319. package/src/server/app-base-path.ts +79 -0
  1320. package/src/server/app-name.ts +53 -0
  1321. package/src/server/app-url.ts +184 -0
  1322. package/src/server/attachment-actions.ts +276 -0
  1323. package/src/server/attribution.ts +214 -0
  1324. package/src/server/auth-marketing.ts +260 -0
  1325. package/src/server/auth-plugin.ts +27 -0
  1326. package/src/server/auth.ts +3803 -0
  1327. package/src/server/better-auth-instance.ts +1197 -0
  1328. package/src/server/builder-browser.ts +1701 -0
  1329. package/src/server/builder-design-systems.ts +668 -0
  1330. package/src/server/builder-space.ts +176 -0
  1331. package/src/server/captcha.ts +63 -0
  1332. package/src/server/capture-error.ts +64 -0
  1333. package/src/server/cli-capture.ts +141 -0
  1334. package/src/server/collab-plugin.ts +391 -0
  1335. package/src/server/complete-text.ts +231 -0
  1336. package/src/server/cookie-namespace.ts +159 -0
  1337. package/src/server/core-routes-plugin.ts +4122 -0
  1338. package/src/server/cors-origins.ts +60 -0
  1339. package/src/server/create-server.ts +268 -0
  1340. package/src/server/credential-provider.ts +1202 -0
  1341. package/src/server/csrf.ts +229 -0
  1342. package/src/server/date-utils.ts +42 -0
  1343. package/src/server/deep-link.ts +119 -0
  1344. package/src/server/derived-secret.ts +32 -0
  1345. package/src/server/design-token-utils.ts +1032 -0
  1346. package/src/server/desktop-sso.ts +83 -0
  1347. package/src/server/edge.ts +69 -0
  1348. package/src/server/email-actions.ts +218 -0
  1349. package/src/server/email-template.ts +192 -0
  1350. package/src/server/email-templates.ts +148 -0
  1351. package/src/server/email.ts +219 -0
  1352. package/src/server/embed-route.ts +283 -0
  1353. package/src/server/embed-session.ts +805 -0
  1354. package/src/server/embedded.ts +252 -0
  1355. package/src/server/entry-server.tsx +154 -0
  1356. package/src/server/framework-request-handler.ts +848 -0
  1357. package/src/server/fusion-app.ts +447 -0
  1358. package/src/server/google-auth-mode.ts +34 -0
  1359. package/src/server/google-auth-plugin.ts +496 -0
  1360. package/src/server/google-oauth-credentials.ts +128 -0
  1361. package/src/server/google-oauth.ts +972 -0
  1362. package/src/server/google-realtime-session.ts +182 -0
  1363. package/src/server/h3-helpers.ts +174 -0
  1364. package/src/server/http-response-telemetry.ts +396 -0
  1365. package/src/server/identity-sso-store.ts +304 -0
  1366. package/src/server/identity-sso.ts +514 -0
  1367. package/src/server/index.ts +593 -0
  1368. package/src/server/missing-key.ts +36 -0
  1369. package/src/server/oauth-helpers.ts +44 -0
  1370. package/src/server/oauth-public-origin.ts +44 -0
  1371. package/src/server/oauth-return-url.ts +120 -0
  1372. package/src/server/og-fonts-data.ts +15 -0
  1373. package/src/server/og-fonts.ts +75 -0
  1374. package/src/server/onboarding-html.ts +4040 -0
  1375. package/src/server/open-route.ts +311 -0
  1376. package/src/server/org-admin.ts +28 -0
  1377. package/src/server/poll-events.ts +88 -0
  1378. package/src/server/poll.ts +1224 -0
  1379. package/src/server/prompts/framework-core-compact.ts +107 -0
  1380. package/src/server/prompts/framework-core.ts +143 -0
  1381. package/src/server/prompts/index.ts +16 -0
  1382. package/src/server/prompts/model-overlays.ts +54 -0
  1383. package/src/server/prompts/shared-rules.ts +104 -0
  1384. package/src/server/realtime-voice.ts +967 -0
  1385. package/src/server/recap-image-route.ts +242 -0
  1386. package/src/server/recap-image-store.ts +185 -0
  1387. package/src/server/request-context.ts +416 -0
  1388. package/src/server/request-origin.ts +67 -0
  1389. package/src/server/resources-plugin.ts +119 -0
  1390. package/src/server/schema-prompt.ts +429 -0
  1391. package/src/server/scoped-key-storage.ts +223 -0
  1392. package/src/server/security-headers.ts +170 -0
  1393. package/src/server/self-dispatch.ts +224 -0
  1394. package/src/server/sentry-config.ts +73 -0
  1395. package/src/server/sentry-plugin.ts +138 -0
  1396. package/src/server/sentry.ts +444 -0
  1397. package/src/server/short-lived-token.ts +170 -0
  1398. package/src/server/social-og-image.ts +454 -0
  1399. package/src/server/sse.ts +102 -0
  1400. package/src/server/ssr-handler.ts +466 -0
  1401. package/src/server/transcribe-voice.ts +1076 -0
  1402. package/src/server/voice-providers-status.ts +118 -0
  1403. package/src/server/workspace-oauth.ts +31 -0
  1404. package/src/server/workspace-provider-oauth.ts +970 -0
  1405. package/src/session-replay-iframe-protocol.ts +58 -0
  1406. package/src/settings/handlers.ts +44 -0
  1407. package/src/settings/index.ts +34 -0
  1408. package/src/settings/org-settings.ts +83 -0
  1409. package/src/settings/script-helpers.ts +24 -0
  1410. package/src/settings/store.ts +247 -0
  1411. package/src/settings/user-settings.ts +47 -0
  1412. package/src/setup-connections/index.ts +90 -0
  1413. package/src/setup-connections/onboarding.ts +47 -0
  1414. package/src/shared/agent-access.ts +112 -0
  1415. package/src/shared/agent-chat.ts +124 -0
  1416. package/src/shared/agent-env.ts +46 -0
  1417. package/src/shared/agent-readable-resource.ts +111 -0
  1418. package/src/shared/agent-sidebar-url.ts +39 -0
  1419. package/src/shared/cache-control.ts +25 -0
  1420. package/src/shared/cloudflare-globals.d.ts +34 -0
  1421. package/src/shared/context-xray.ts +172 -0
  1422. package/src/shared/embed-auth.ts +6 -0
  1423. package/src/shared/index.ts +83 -0
  1424. package/src/shared/llm-connection.ts +42 -0
  1425. package/src/shared/markdown-block-split.ts +129 -0
  1426. package/src/shared/mcp-connect-content.ts +130 -0
  1427. package/src/shared/mcp-embed-headers.ts +175 -0
  1428. package/src/shared/mcp-integration-config.ts +101 -0
  1429. package/src/shared/merge-by-id.ts +14 -0
  1430. package/src/shared/oauth-state.ts +39 -0
  1431. package/src/shared/reasoning-effort.ts +228 -0
  1432. package/src/shared/route-warmup-config.ts +128 -0
  1433. package/src/shared/runtime.ts +31 -0
  1434. package/src/shared/social-meta.ts +82 -0
  1435. package/src/shared/streaming-text-smoothing.ts +184 -0
  1436. package/src/shared/truncate.ts +13 -0
  1437. package/src/shared/workspace-app-audience.ts +177 -0
  1438. package/src/shared/workspace-app-id.ts +54 -0
  1439. package/src/sharing/access.ts +585 -0
  1440. package/src/sharing/actions/create-agent-resource-link.ts +91 -0
  1441. package/src/sharing/actions/extension-change.ts +22 -0
  1442. package/src/sharing/actions/list-resource-shares.ts +93 -0
  1443. package/src/sharing/actions/set-resource-visibility.ts +91 -0
  1444. package/src/sharing/actions/share-resource.ts +322 -0
  1445. package/src/sharing/actions/unshare-resource.ts +72 -0
  1446. package/src/sharing/index.ts +35 -0
  1447. package/src/sharing/registry.ts +201 -0
  1448. package/src/sharing/schema.ts +99 -0
  1449. package/src/styles/agent-conversation.css +766 -0
  1450. package/src/styles/agent-native.css +938 -0
  1451. package/src/styles/blocks.css +1717 -0
  1452. package/src/styles/chat-history-list.css +1 -0
  1453. package/src/styles/rich-markdown-editor.css +1 -0
  1454. package/src/tailwind.preset.ts +140 -0
  1455. package/src/templates/chat/.agents/skills/agent-native-docs/SKILL.md +15 -13
  1456. package/src/templates/chat/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  1457. package/src/templates/chat/.agents/skills/self-modifying-code/SKILL.md +9 -6
  1458. package/src/templates/chat/AGENTS.md +3 -2
  1459. package/src/templates/default/.agents/skills/agent-native-docs/SKILL.md +15 -13
  1460. package/src/templates/default/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  1461. package/src/templates/default/.agents/skills/self-modifying-code/SKILL.md +9 -6
  1462. package/src/templates/default/AGENTS.md +6 -5
  1463. package/src/templates/headless/.agents/skills/agent-native-docs/SKILL.md +15 -13
  1464. package/src/templates/headless/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  1465. package/src/templates/headless/AGENTS.md +5 -4
  1466. package/src/templates/workspace-core/.agents/skills/agent-native-docs/SKILL.md +15 -13
  1467. package/src/templates/workspace-core/.agents/skills/agent-native-toolkit/SKILL.md +3 -2
  1468. package/src/templates/workspace-core/.agents/skills/customizing-agent-native/SKILL.md +63 -20
  1469. package/src/templates/workspace-core/.agents/skills/self-modifying-code/SKILL.md +9 -6
  1470. package/src/templates/workspace-core/AGENTS.md +4 -4
  1471. package/src/templates/workspace-root/AGENTS.md +4 -4
  1472. package/src/terminal/cli-registry.ts +57 -0
  1473. package/src/terminal/index.ts +22 -0
  1474. package/src/terminal/pty-server.ts +389 -0
  1475. package/src/terminal/terminal-plugin.ts +265 -0
  1476. package/src/testing.ts +23 -0
  1477. package/src/tracking/index.ts +10 -0
  1478. package/src/tracking/providers.ts +422 -0
  1479. package/src/tracking/registry.ts +102 -0
  1480. package/src/tracking/route.ts +108 -0
  1481. package/src/tracking/types.ts +16 -0
  1482. package/src/transcription/builder-transcription.ts +118 -0
  1483. package/src/triggers/actions/list-automations.ts +99 -0
  1484. package/src/triggers/actions/manage-automation.ts +78 -0
  1485. package/src/triggers/actions.ts +333 -0
  1486. package/src/triggers/condition-evaluator.ts +163 -0
  1487. package/src/triggers/dispatcher.ts +536 -0
  1488. package/src/triggers/index.ts +13 -0
  1489. package/src/triggers/routes.ts +322 -0
  1490. package/src/triggers/types.ts +42 -0
  1491. package/src/types/pglite.d.ts +26 -0
  1492. package/src/usage/store.ts +698 -0
  1493. package/src/vite/action-types-plugin.ts +481 -0
  1494. package/src/vite/agent-web-plugin.ts +78 -0
  1495. package/src/vite/agents-bundle-plugin.ts +185 -0
  1496. package/src/vite/client.ts +3039 -0
  1497. package/src/vite/index.ts +21 -0
  1498. package/src/voice/index.ts +18 -0
  1499. package/src/voice/voice-cleanup-prompt.ts +38 -0
  1500. package/src/voice/voice-context.ts +217 -0
  1501. package/src/voice/voice-replacements.ts +75 -0
  1502. package/src/workspace-connections/credentials.ts +603 -0
  1503. package/src/workspace-connections/index.ts +72 -0
  1504. package/src/workspace-connections/lifecycle.ts +43 -0
  1505. package/src/workspace-connections/store.ts +1943 -0
  1506. package/src/workspace-files/index.ts +18 -0
  1507. package/src/workspace-files/store.ts +339 -0
  1508. package/src/workspace-files/tool.ts +266 -0
@@ -0,0 +1,2002 @@
1
+ import type { ChatModelRunResult } from "@assistant-ui/react";
2
+
3
+ import type { ActionChatUIConfig } from "../action-ui.js";
4
+ import {
5
+ LLM_MISSING_CREDENTIALS_ERROR_CODE,
6
+ LLM_MISSING_CREDENTIALS_MESSAGE,
7
+ } from "../agent/engine/credential-errors.js";
8
+ import type { AgentMcpAppPayload } from "../mcp-client/app-result.js";
9
+ import { formatChatErrorText, normalizeChatError } from "./error-format.js";
10
+ import {
11
+ humanizeToolLabelText,
12
+ humanizeToolName,
13
+ runningToolLabel,
14
+ } from "./tool-display.js";
15
+
16
+ export type ContentPart =
17
+ | { type: "text"; text: string }
18
+ | {
19
+ /**
20
+ * Model chain-of-thought / extended-thinking prose. Streamed from
21
+ * server `thinking` SSE events (and code-agent thinking transcript
22
+ * items). Rendered as a collapsible plain-English cell — not a tool
23
+ * call.
24
+ */
25
+ type: "reasoning";
26
+ text: string;
27
+ }
28
+ | {
29
+ type: "tool-call";
30
+ toolCallId: string;
31
+ toolName: string;
32
+ argsText: string;
33
+ args: Record<string, string>;
34
+ result?: string;
35
+ isError?: boolean;
36
+ completedSideEffect?: boolean;
37
+ mcpApp?: AgentMcpAppPayload;
38
+ chatUI?: ActionChatUIConfig;
39
+ activity?: boolean;
40
+ repeatCount?: number;
41
+ /**
42
+ * Set when the server emitted an `approval_required` event for this tool
43
+ * call (opt-in `needsApproval` actions). The action did NOT run; the UI
44
+ * renders an Approve/Deny affordance. `approvalKey` is echoed back in
45
+ * `approvedToolCalls` to approve, `dismissed` records a local Deny.
46
+ */
47
+ approval?: { approvalKey: string; dismissed?: boolean };
48
+ /**
49
+ * Structured metadata from the coding-tools executor side-channel.
50
+ * Present only on code-agent tool calls from executors new enough to
51
+ * emit it. The `toolKind` discriminant identifies the shape.
52
+ */
53
+ structuredMeta?: Record<string, unknown>;
54
+ };
55
+
56
+ export interface SSEEvent {
57
+ type: string;
58
+ text?: string;
59
+ tool?: string;
60
+ /** Server-assigned call identifier emitted on tool_start / tool_done events. */
61
+ id?: string;
62
+ label?: string;
63
+ progressBytes?: number;
64
+ input?: Record<string, string>;
65
+ result?: string;
66
+ isError?: boolean;
67
+ completedSideEffect?: boolean;
68
+ mcpApp?: AgentMcpAppPayload;
69
+ chatUI?: ActionChatUIConfig;
70
+ /** Stable key the client echoes back in `approvedToolCalls` to approve a
71
+ * paused `needsApproval` tool call. Present on `approval_required` events. */
72
+ approvalKey?: string;
73
+ error?: string;
74
+ seq?: number;
75
+ agent?: string;
76
+ status?: string;
77
+ reason?: string;
78
+ // Agent task fields
79
+ taskId?: string;
80
+ threadId?: string;
81
+ description?: string;
82
+ preview?: string;
83
+ currentStep?: string;
84
+ summary?: string;
85
+ // Structured error metadata — Builder gateway sets these on quota/auth/setup
86
+ // failures so the UI can render a CTA alongside the error text.
87
+ errorCode?: string;
88
+ upgradeUrl?: string;
89
+ details?: string;
90
+ recoverable?: boolean;
91
+ maxIterations?: number;
92
+ }
93
+
94
+ export type AgentAutoContinueReason =
95
+ | "run_timeout"
96
+ | "loop_limit"
97
+ | "no_progress"
98
+ | "stream_ended"
99
+ | "stale_run";
100
+
101
+ export type AgentActivityTrailEntry = { label: string; tool?: string };
102
+
103
+ export interface AgentAutoContinueErrorInfo {
104
+ message: string;
105
+ details?: string;
106
+ errorCode?: string;
107
+ recoverable?: boolean;
108
+ upgradeUrl?: string;
109
+ }
110
+
111
+ const INTERRUPTED_TOOL_RESULT =
112
+ "Interrupted before this tool returned a result.";
113
+ const INTERRUPTED_ACTIVITY_RESULT = "Stopped before this action started.";
114
+
115
+ /**
116
+ * Maximum number of assistant-ui repository updates we deliver in one browser
117
+ * event-loop turn. Durable-run replay can put hundreds of SSE frames into the
118
+ * stream queue before the client attaches; draining all of them through
119
+ * assistant-ui without a macrotask boundary synchronously nests React external
120
+ * store notifications until React throws "Maximum update depth exceeded."
121
+ *
122
+ * A timer scheduled on the first result resets the count when the stream is
123
+ * naturally idle between network chunks. We only await it when results are
124
+ * arriving densely enough to hit this bound, so normal live token streaming
125
+ * keeps its existing latency while replay bursts yield cooperatively.
126
+ */
127
+ const SSE_RENDER_UPDATES_PER_EVENT_LOOP_TURN = 20;
128
+
129
+ export function settleInterruptedToolCalls(
130
+ content: ContentPart[],
131
+ result = INTERRUPTED_TOOL_RESULT,
132
+ options?: { includeActivity?: boolean; activityResult?: string },
133
+ ): boolean {
134
+ let changed = false;
135
+ for (const part of content) {
136
+ if (
137
+ part.type === "tool-call" &&
138
+ part.result === undefined &&
139
+ (part.activity !== true || options?.includeActivity === true)
140
+ ) {
141
+ part.result =
142
+ part.activity === true
143
+ ? (options?.activityResult ?? INTERRUPTED_ACTIVITY_RESULT)
144
+ : result;
145
+ part.isError = true;
146
+ changed = true;
147
+ }
148
+ }
149
+ return changed;
150
+ }
151
+
152
+ export class AgentAutoContinueSignal extends Error {
153
+ readonly reason: AgentAutoContinueReason;
154
+ readonly maxIterations?: number;
155
+ readonly activityTrail: AgentActivityTrailEntry[];
156
+ readonly errorInfo?: AgentAutoContinueErrorInfo;
157
+
158
+ constructor(options: {
159
+ reason: AgentAutoContinueReason;
160
+ maxIterations?: number;
161
+ activityTrail?: AgentActivityTrailEntry[];
162
+ errorInfo?: AgentAutoContinueErrorInfo;
163
+ }) {
164
+ super(`Agent run needs automatic continuation: ${options.reason}`);
165
+ this.name = "AgentAutoContinueSignal";
166
+ this.reason = options.reason;
167
+ this.maxIterations = options.maxIterations;
168
+ this.activityTrail = options.activityTrail ?? [];
169
+ this.errorInfo = options.errorInfo;
170
+ }
171
+ }
172
+
173
+ export const SSE_NO_PROGRESS_TIMEOUT_MS = 75_000;
174
+ export const SSE_ACTION_PREPARATION_STALL_TIMEOUT_MS = 90_000;
175
+ /**
176
+ * Widened client watchdog windows for durable background runs. The SERVER is
177
+ * the recovery brain for these runs: its run-manager no-progress backstop
178
+ * emits `auto_continue` over the same stream the client is already reading,
179
+ * and its unclaimed-run sweep reaps dead workers into loud terminal errors.
180
+ * The client watchdogs therefore sit ABOVE the server's durable-background
181
+ * backstop so a healthy background run never trips them — the server's own
182
+ * recovery event arrives first over the wire. When one does fire, the thrown
183
+ * signal only means "reattach the read" (the adapter's background follow loop
184
+ * re-polls /runs/active); it never escalates to a client-declared error or a
185
+ * synthetic continuation POST. Progress ACCOUNTING (what counts as a
186
+ * meaningful event) is unchanged — only the client-initiated recovery timing
187
+ * is relaxed.
188
+ */
189
+ export const SSE_DURABLE_NO_PROGRESS_TIMEOUT_MS = 13 * 60_000;
190
+ export const SSE_DURABLE_ACTION_PREPARATION_STALL_TIMEOUT_MS = 13 * 60_000;
191
+
192
+ export function sseNoProgressTimeoutMs(options?: SSEStreamOptions): number {
193
+ return options?.durableBackgroundRun === true
194
+ ? SSE_DURABLE_NO_PROGRESS_TIMEOUT_MS
195
+ : SSE_NO_PROGRESS_TIMEOUT_MS;
196
+ }
197
+
198
+ function sseActionPreparationStallTimeoutMs(
199
+ options?: SSEStreamOptions,
200
+ ): number {
201
+ return options?.durableBackgroundRun === true
202
+ ? SSE_DURABLE_ACTION_PREPARATION_STALL_TIMEOUT_MS
203
+ : SSE_ACTION_PREPARATION_STALL_TIMEOUT_MS;
204
+ }
205
+
206
+ export interface SSEStreamOptions {
207
+ /**
208
+ * Durable background runs have their own server-side liveness budget and
209
+ * heartbeat. While one is active, generic keepalive-only periods keep the
210
+ * client attached. Tool-input preparation is stricter: real byte progress
211
+ * keeps long payloads alive, but zero-byte/silent preparation still recovers
212
+ * so one stuck action cannot pin the chat forever — just on the wider
213
+ * durable windows above (behind the server's own 150s backstop) instead of
214
+ * the tight foreground 75s/90s windows.
215
+ */
216
+ durableBackgroundRun?: boolean;
217
+ /**
218
+ * Optional caller-owned preparation watchdog state. Passing the same object
219
+ * across reconnect reads keeps a stuck action preparation from getting a
220
+ * fresh stall budget every time the browser reattaches to the same run.
221
+ */
222
+ preparingActionState?: PreparingActionState;
223
+ }
224
+
225
+ type ActivityTrailEntry = AgentActivityTrailEntry;
226
+
227
+ type PreparingActionEntry = {
228
+ tool: string;
229
+ startedAt?: number;
230
+ lastProgressBytes?: number;
231
+ /**
232
+ * Timestamp of the last real streaming progress for the in-preparation tool
233
+ * input. The server emits a throttled `activity` heartbeat per
234
+ * `tool-input-delta`, so while the model is actively streaming a (possibly
235
+ * very large) tool argument this keeps advancing. The stall guard measures
236
+ * silence from HERE — not from `startedAt` — so a legitimately large, still-
237
+ * streaming input is never aborted; only genuine silence (keepalive-only, no
238
+ * further deltas) can trip it.
239
+ */
240
+ lastProgressAt?: number;
241
+ };
242
+
243
+ export type PreparingActionState = {
244
+ entries?: Map<string, PreparingActionEntry>;
245
+ toolEntries?: Map<string, PreparingActionEntry>;
246
+ };
247
+
248
+ function activityProgressBytes(ev: SSEEvent): number | undefined {
249
+ return typeof ev.progressBytes === "number" &&
250
+ Number.isFinite(ev.progressBytes) &&
251
+ ev.progressBytes >= 0
252
+ ? Math.floor(ev.progressBytes)
253
+ : undefined;
254
+ }
255
+
256
+ function isPreparingActionActivity(ev: SSEEvent): boolean {
257
+ if (ev.type !== "activity") return false;
258
+ const label = (ev.label ?? "").trim().toLowerCase();
259
+ return label.startsWith("preparing ") && label.includes(" action");
260
+ }
261
+
262
+ function isMeaningfulProgressEvent(
263
+ ev: SSEEvent,
264
+ actionPreparationProgress?: boolean,
265
+ options?: SSEStreamOptions,
266
+ ): boolean {
267
+ if (ev.type === "stream_keepalive") {
268
+ return options?.durableBackgroundRun === true;
269
+ }
270
+ if (ev.type === "activity" && isPreparingActionActivity(ev)) {
271
+ if (options?.durableBackgroundRun === true) return true;
272
+ return actionPreparationProgress === true;
273
+ }
274
+ return true;
275
+ }
276
+
277
+ function baseActivityLabel(ev: SSEEvent, tool?: string): string {
278
+ return humanizeToolLabelText(ev.label ?? "Working", tool);
279
+ }
280
+
281
+ function preparationActivityLabel(
282
+ tool: string | undefined,
283
+ progressBytes: number | undefined,
284
+ ): string {
285
+ const action = humanizeToolName(tool);
286
+ if (progressBytes === undefined) {
287
+ return `Starting ${action}...`;
288
+ }
289
+ if (progressBytes <= 0) {
290
+ return `Preparing ${action}...`;
291
+ }
292
+ return `Writing ${action}...`;
293
+ }
294
+
295
+ function visibleActivityLabel(ev: SSEEvent, tool?: string): string {
296
+ const progressBytes = activityProgressBytes(ev);
297
+ if (isPreparingActionActivity(ev)) {
298
+ return preparationActivityLabel(tool, progressBytes);
299
+ }
300
+ return baseActivityLabel(ev, tool);
301
+ }
302
+
303
+ function findPendingToolCallIndex(
304
+ content: ContentPart[],
305
+ toolName: string,
306
+ toolCallId?: string,
307
+ ): number {
308
+ // Prefer id-based match when the event carries an id: parallel same-name
309
+ // calls can be in flight simultaneously, and name-only matching would
310
+ // attach a result to the wrong call.
311
+ if (toolCallId) {
312
+ const exactIndex = findPendingToolCallIndexById(content, toolCallId);
313
+ if (exactIndex >= 0) return exactIndex;
314
+ // Fall through to name-matching: the start event may have arrived before
315
+ // the server started emitting ids (e.g. older server build), so the
316
+ // stored toolCallId is the locally-generated "tc_N" value rather than the
317
+ // server-assigned one. In that case match by name as a fallback.
318
+ }
319
+ for (let i = content.length - 1; i >= 0; i--) {
320
+ const part = content[i];
321
+ if (
322
+ part.type === "tool-call" &&
323
+ part.toolName === toolName &&
324
+ part.result === undefined
325
+ ) {
326
+ return i;
327
+ }
328
+ }
329
+ return -1;
330
+ }
331
+
332
+ function findPendingToolCallIndexById(
333
+ content: ContentPart[],
334
+ toolCallId: string,
335
+ ): number {
336
+ for (let i = content.length - 1; i >= 0; i--) {
337
+ const part = content[i];
338
+ if (
339
+ part.type === "tool-call" &&
340
+ part.toolCallId === toolCallId &&
341
+ part.result === undefined
342
+ ) {
343
+ return i;
344
+ }
345
+ }
346
+ return -1;
347
+ }
348
+
349
+ function findOldestPendingActivityToolCallIndex(
350
+ content: ContentPart[],
351
+ toolName: string,
352
+ ): number {
353
+ for (let i = 0; i < content.length; i += 1) {
354
+ const part = content[i];
355
+ if (
356
+ part.type === "tool-call" &&
357
+ part.toolName === toolName &&
358
+ part.activity === true &&
359
+ part.result === undefined
360
+ ) {
361
+ return i;
362
+ }
363
+ }
364
+ return -1;
365
+ }
366
+
367
+ function findPendingActivityToolCallIndex(
368
+ content: ContentPart[],
369
+ toolName: string,
370
+ toolCallId?: string,
371
+ ): number {
372
+ if (!toolCallId) {
373
+ return findPendingToolCallIndex(content, toolName);
374
+ }
375
+
376
+ // Activity events emitted while the model is assembling tool input already
377
+ // carry the engine's stable call id. Match that id exactly so repeated
378
+ // progress for one call updates one placeholder while parallel same-name
379
+ // calls retain separate cards.
380
+ const exactIndex = findPendingToolCallIndexById(content, toolCallId);
381
+ if (exactIndex >= 0) return exactIndex;
382
+
383
+ // Older activity events may omit the id before a later progress event adds
384
+ // it. Upgrade one unambiguous reader-local placeholder instead of painting a
385
+ // second card for the same logical call.
386
+ const readerLocalCandidates: number[] = [];
387
+ for (let i = 0; i < content.length; i += 1) {
388
+ const part = content[i];
389
+ if (
390
+ part.type === "tool-call" &&
391
+ part.toolName === toolName &&
392
+ part.activity === true &&
393
+ part.result === undefined &&
394
+ /^tc_\d+$/.test(part.toolCallId)
395
+ ) {
396
+ readerLocalCandidates.push(i);
397
+ }
398
+ }
399
+ return readerLocalCandidates.length === 1 ? readerLocalCandidates[0] : -1;
400
+ }
401
+
402
+ function findCompletedToolCallIndex(
403
+ content: ContentPart[],
404
+ toolCallId?: string,
405
+ ): number {
406
+ if (!toolCallId) return -1;
407
+ for (let i = content.length - 1; i >= 0; i--) {
408
+ const part = content[i];
409
+ if (
410
+ part.type === "tool-call" &&
411
+ part.toolCallId === toolCallId &&
412
+ part.result !== undefined
413
+ ) {
414
+ return i;
415
+ }
416
+ }
417
+ return -1;
418
+ }
419
+
420
+ function appendActivityTrail(
421
+ trail: ActivityTrailEntry[],
422
+ next: ActivityTrailEntry,
423
+ ) {
424
+ const label = next.label.trim();
425
+ if (!label) return;
426
+ const tool = next.tool?.trim();
427
+ const last = trail[trail.length - 1];
428
+ if (last?.label === label && last.tool === tool) return;
429
+ trail.push({ label, ...(tool ? { tool } : {}) });
430
+ if (trail.length > 8) {
431
+ trail.splice(0, trail.length - 8);
432
+ }
433
+ }
434
+
435
+ function refreshPreparingToolEntry(state: PreparingActionState, tool: string) {
436
+ const remainingEntries = [...(state.entries?.values() ?? [])].filter(
437
+ (entry) => entry.tool === tool,
438
+ );
439
+ if (remainingEntries.length === 0) {
440
+ state.toolEntries?.delete(tool);
441
+ return;
442
+ }
443
+ const deadlineBasis = (entry: PreparingActionEntry) =>
444
+ entry.lastProgressAt ?? entry.startedAt ?? Number.POSITIVE_INFINITY;
445
+ const oldestEntry = remainingEntries.reduce((oldest, entry) =>
446
+ deadlineBasis(entry) < deadlineBasis(oldest) ? entry : oldest,
447
+ );
448
+ const lastProgressBytes = remainingEntries.reduce<number | undefined>(
449
+ (max, entry) =>
450
+ entry.lastProgressBytes === undefined
451
+ ? max
452
+ : Math.max(max ?? 0, entry.lastProgressBytes),
453
+ undefined,
454
+ );
455
+ const toolEntries =
456
+ state.toolEntries ?? new Map<string, PreparingActionEntry>();
457
+ state.toolEntries = toolEntries;
458
+ toolEntries.set(tool, {
459
+ tool,
460
+ startedAt: oldestEntry.startedAt,
461
+ lastProgressAt: oldestEntry.lastProgressAt,
462
+ lastProgressBytes,
463
+ });
464
+ }
465
+
466
+ function updatePreparingActionState(
467
+ state: PreparingActionState,
468
+ ev: SSEEvent,
469
+ now: number,
470
+ ): boolean | undefined {
471
+ if (ev.type === "activity" && isPreparingActionActivity(ev)) {
472
+ const tool = ev.tool?.trim() || undefined;
473
+ if (!tool) return false;
474
+ const id = ev.id?.trim();
475
+ const key = id || tool;
476
+ const entries = state.entries ?? new Map<string, PreparingActionEntry>();
477
+ state.entries = entries;
478
+ let entry = entries.get(key);
479
+ if (!entry) {
480
+ entry = {
481
+ tool,
482
+ startedAt: now,
483
+ lastProgressAt: undefined,
484
+ lastProgressBytes: undefined,
485
+ };
486
+ entries.set(key, entry);
487
+ }
488
+ const toolEntries =
489
+ state.toolEntries ?? new Map<string, PreparingActionEntry>();
490
+ state.toolEntries = toolEntries;
491
+ let toolEntry = toolEntries.get(tool);
492
+ if (!toolEntry) {
493
+ toolEntry = {
494
+ tool,
495
+ startedAt: now,
496
+ lastProgressAt: undefined,
497
+ lastProgressBytes: undefined,
498
+ };
499
+ toolEntries.set(tool, toolEntry);
500
+ }
501
+ const progressBytes = activityProgressBytes(ev);
502
+ const previousBytes = entry.lastProgressBytes ?? 0;
503
+ let madeProgress = false;
504
+ if (progressBytes !== undefined) {
505
+ entry.lastProgressBytes = Math.max(previousBytes, progressBytes);
506
+ toolEntry.lastProgressBytes = Math.max(
507
+ toolEntry.lastProgressBytes ?? 0,
508
+ progressBytes,
509
+ );
510
+ madeProgress = id ? progressBytes > previousBytes : progressBytes > 0;
511
+ }
512
+ if (madeProgress) {
513
+ // A byte increase is proof the model is still streaming this action's
514
+ // argument. Repeated zero-byte prep activity is only a heartbeat.
515
+ entry.lastProgressAt = now;
516
+ toolEntry.lastProgressAt = now;
517
+ return true;
518
+ }
519
+ return false;
520
+ }
521
+
522
+ if (
523
+ ev.type === "clear" ||
524
+ ev.type === "text" ||
525
+ ev.type === "tool_start" ||
526
+ ev.type === "tool_done" ||
527
+ ev.type === "done" ||
528
+ ev.type === "error" ||
529
+ ev.type === "missing_api_key"
530
+ ) {
531
+ if (ev.type === "tool_start" || ev.type === "tool_done") {
532
+ const tool = ev.tool?.trim();
533
+ const id = ev.id?.trim();
534
+ for (const [key, entry] of state.entries ?? []) {
535
+ if ((id && key === id) || (!id && tool && entry.tool === tool)) {
536
+ state.entries?.delete(key);
537
+ }
538
+ }
539
+ if (tool) {
540
+ refreshPreparingToolEntry(state, tool);
541
+ }
542
+ } else {
543
+ state.entries?.clear();
544
+ state.toolEntries?.clear();
545
+ }
546
+ }
547
+ return undefined;
548
+ }
549
+
550
+ function hasStalledPreparingAction(
551
+ state: PreparingActionState,
552
+ now: number,
553
+ stallTimeoutMs: number,
554
+ ) {
555
+ // Fire only when a tool input has gone SILENT — no further streaming deltas
556
+ // for the whole window — never merely because a large input has been
557
+ // streaming for a long time. `lastProgressAt` advances on every delta
558
+ // heartbeat, so an actively-streaming large output keeps resetting this and
559
+ // survives; a genuinely stuck prep (keepalive-only, no deltas) trips it.
560
+ // Durable background reads pass the wider durable window so the server's
561
+ // own 150s no-progress backstop gets first chance to recover the stall.
562
+ for (const entry of [
563
+ ...(state.toolEntries?.values() ?? []),
564
+ ...(state.entries?.values() ?? []),
565
+ ]) {
566
+ if (
567
+ entry.startedAt !== undefined &&
568
+ now - (entry.lastProgressAt ?? entry.startedAt) >= stallTimeoutMs
569
+ ) {
570
+ return true;
571
+ }
572
+ }
573
+ return false;
574
+ }
575
+
576
+ async function readChunkWithProgressTimeout(
577
+ reader: ReadableStreamDefaultReader<Uint8Array>,
578
+ lastMeaningfulEventAt: number,
579
+ noProgressTimeoutMs: number,
580
+ ): Promise<ReadableStreamReadResult<Uint8Array>> {
581
+ const elapsed = Date.now() - lastMeaningfulEventAt;
582
+ const timeoutMs = Math.max(0, noProgressTimeoutMs - elapsed);
583
+ let timeoutId: ReturnType<typeof setTimeout> | null = null;
584
+ const readPromise = reader.read();
585
+ // If the timeout wins and cancellation causes the pending read to reject,
586
+ // swallow that rejection because the generator is already recovering.
587
+ void readPromise.catch(() => {});
588
+
589
+ const timeoutPromise = new Promise<"timeout">((resolve) => {
590
+ timeoutId = setTimeout(() => resolve("timeout"), timeoutMs);
591
+ });
592
+ const result = await Promise.race([readPromise, timeoutPromise]);
593
+ if (timeoutId) {
594
+ clearTimeout(timeoutId);
595
+ }
596
+ if (result === "timeout") {
597
+ await reader.cancel("no_progress").catch(() => {});
598
+ throw new AgentAutoContinueSignal({ reason: "no_progress" });
599
+ }
600
+ return result;
601
+ }
602
+
603
+ function isAutoRecoverableError(ev: SSEEvent, errMsg: string): boolean {
604
+ const code = String(ev.errorCode ?? "").toLowerCase();
605
+ const msg = errMsg.toLowerCase();
606
+
607
+ if (
608
+ code === "context_length_exceeded" ||
609
+ code === "input_too_long" ||
610
+ code.startsWith("credits-limit") ||
611
+ code === "billing_error" ||
612
+ code === "unauthorized" ||
613
+ code === "authentication_error" ||
614
+ code === "permission_error" ||
615
+ code === "http_401" ||
616
+ code === "http_403" ||
617
+ code === "rate_limit_exceeded" ||
618
+ code === "gateway_not_enabled" ||
619
+ code === "missing_api_key" ||
620
+ code === "missing_credentials" ||
621
+ code === "invalid_request_error" ||
622
+ code === "request_too_large" ||
623
+ code === "not_found_error" ||
624
+ code === "model_not_found" ||
625
+ code === "provider_rate_limited" ||
626
+ // `builder_gateway_error` is the no-detail fallback the Builder engine
627
+ // emits when the gateway returns `{type:"stop",reason:"error"}` with no
628
+ // explanation — almost always the upstream provider giving up (model
629
+ // quota hit, account misconfiguration, opaque downstream failure). The
630
+ // production-agent already retries this synchronously up to MAX_RETRIES
631
+ // before the error escapes to the SSE stream, so by the time the client
632
+ // sees it, retrying again with another POST /agent-chat will hit the
633
+ // same wall. This used to send the chat into a 32-continuation runaway
634
+ // (each turn cleared+regenerated visible content) for users hitting a
635
+ // misbehaving Builder route. Surface the error instead.
636
+ code === "builder_gateway_error" ||
637
+ // The hosted run exhausted its in-invocation continuation budget without
638
+ // finishing (run-loop-with-resume.ts). It's flagged `recoverable: true` so
639
+ // the recovery banner reads "stopped before finishing", but it must NOT
640
+ // auto-continue: another POST would hit the same ~40s wall and churn. The
641
+ // user retries deliberately (ideally as a single bulk action).
642
+ code === "run_budget_exhausted"
643
+ ) {
644
+ return false;
645
+ }
646
+
647
+ if (
648
+ code === "builder_gateway_network_error" ||
649
+ code === "builder_gateway_timeout" ||
650
+ code === "provider_network_error" ||
651
+ code === "stale_run" ||
652
+ code === "timeout" ||
653
+ code === "timeout_error" ||
654
+ code === "http_408" ||
655
+ code === "http_429" ||
656
+ code === "http_500" ||
657
+ code === "http_502" ||
658
+ code === "http_503" ||
659
+ code === "http_504" ||
660
+ code === "rate_limited" ||
661
+ code === "too_many_concurrent_requests" ||
662
+ code === "overloaded_error"
663
+ ) {
664
+ return true;
665
+ }
666
+
667
+ if (ev.recoverable === true) return true;
668
+
669
+ if (msg.includes("daily gateway request cap")) return false;
670
+
671
+ // "gateway error" intentionally absent — that's the no-detail Builder
672
+ // gateway fallback and the production-agent already retries it
673
+ // synchronously up to MAX_RETRIES before the error escapes here. Treating
674
+ // it as auto-recoverable on top of that produced a 32-continuation
675
+ // runaway in production for users hitting a misbehaving Builder route.
676
+ // (See `code === "builder_gateway_error"` in the not-recoverable list.)
677
+ return (
678
+ msg.includes("overloaded") ||
679
+ msg.includes("rate_limit") ||
680
+ msg.includes("too many requests") ||
681
+ msg.includes("timeout") ||
682
+ msg.includes("gateway timeout") ||
683
+ msg.includes("inactivity timeout") ||
684
+ msg.includes("socket hang up") ||
685
+ msg.includes("connection reset") ||
686
+ msg.includes("connection") ||
687
+ msg.includes("network") ||
688
+ msg.includes("stream closed") ||
689
+ msg.includes("stream ended") ||
690
+ msg.includes("temporarily unavailable") ||
691
+ msg.includes("502") ||
692
+ msg.includes("503") ||
693
+ msg.includes("504") ||
694
+ msg.includes("529")
695
+ );
696
+ }
697
+
698
+ function isMissingCredentialText(message: string, errorCode?: string): boolean {
699
+ const code = String(errorCode ?? "").toLowerCase();
700
+ const msg = message.toLowerCase();
701
+ return (
702
+ code === "missing_api_key" ||
703
+ code === "missing_credentials" ||
704
+ msg.includes("apikey") ||
705
+ msg.includes("authtoken") ||
706
+ msg.includes("anthropic_api_key") ||
707
+ msg.includes("missing_api_key") ||
708
+ msg.includes("missing api key") ||
709
+ msg.includes("missing credentials") ||
710
+ msg.includes("no llm provider") ||
711
+ msg.includes("llm provider is connected")
712
+ );
713
+ }
714
+
715
+ function dispatchActivityClear(tabId: string | undefined) {
716
+ if (typeof window === "undefined") return;
717
+ window.dispatchEvent(
718
+ new CustomEvent("agent-chat:activity-clear", {
719
+ detail: { tabId },
720
+ }),
721
+ );
722
+ }
723
+
724
+ // Fires once per chunk (see ProcessEventState.streamProgressDispatched) the
725
+ // moment a chunk produces real model output (visible text or a reasoning
726
+ // delta). Unlike `agent-chat:activity-clear` — which also fires for
727
+ // old-chunk `tool_done` replays and server-retry `clear` events, and so
728
+ // cannot be used to detect genuine forward progress — this event exists
729
+ // solely so listeners can distinguish "the run is actually producing new
730
+ // output" from those replay/retry cases.
731
+ function dispatchStreamProgress(tabId: string | undefined) {
732
+ if (typeof window === "undefined") return;
733
+ window.dispatchEvent(
734
+ new CustomEvent("agent-chat:stream-progress", {
735
+ detail: { tabId },
736
+ }),
737
+ );
738
+ }
739
+
740
+ function dispatchMissingApiKey(tabId: string | undefined) {
741
+ if (typeof window === "undefined") return;
742
+ window.dispatchEvent(
743
+ new CustomEvent("agent-chat:missing-api-key", {
744
+ detail: { tabId },
745
+ }),
746
+ );
747
+ }
748
+
749
+ function pendingToolNames(content: ContentPart[]): {
750
+ activity: string[];
751
+ running: string[];
752
+ } {
753
+ const activity = new Set<string>();
754
+ const running = new Set<string>();
755
+ for (const part of content) {
756
+ if (part.type === "tool-call" && part.result === undefined) {
757
+ if (part.activity === true) {
758
+ activity.add(part.toolName);
759
+ } else {
760
+ running.add(part.toolName);
761
+ }
762
+ }
763
+ }
764
+ return { activity: [...activity], running: [...running] };
765
+ }
766
+
767
+ function contentSnapshot(content: ContentPart[]): ContentPart[] {
768
+ return content.map((part) => {
769
+ if (part.type === "text" || part.type === "reasoning") return { ...part };
770
+ return {
771
+ ...part,
772
+ args: { ...part.args },
773
+ ...(part.mcpApp ? { mcpApp: { ...part.mcpApp } } : {}),
774
+ ...(part.chatUI ? { chatUI: { ...part.chatUI } } : {}),
775
+ ...(part.approval ? { approval: { ...part.approval } } : {}),
776
+ ...(part.structuredMeta
777
+ ? { structuredMeta: { ...part.structuredMeta } }
778
+ : {}),
779
+ };
780
+ });
781
+ }
782
+
783
+ function repeatSignatureValue(value: unknown): string {
784
+ try {
785
+ return JSON.stringify(value);
786
+ } catch {
787
+ return String(value ?? "");
788
+ }
789
+ }
790
+
791
+ function completedToolRepeatSignature(
792
+ part: Extract<ContentPart, { type: "tool-call" }>,
793
+ ): string | null {
794
+ if (
795
+ part.result === undefined ||
796
+ part.activity === true ||
797
+ part.approval ||
798
+ part.mcpApp ||
799
+ part.chatUI ||
800
+ part.structuredMeta
801
+ ) {
802
+ return null;
803
+ }
804
+ return [
805
+ part.toolName,
806
+ part.argsText,
807
+ repeatSignatureValue(part.args),
808
+ part.result,
809
+ part.isError === true ? "error" : "",
810
+ part.completedSideEffect === true ? "side-effect" : "",
811
+ ].join("\u0000");
812
+ }
813
+
814
+ /**
815
+ * Result prefixes the server emits when a tool_start/tool_done pair is a
816
+ * REPLAY of a call that already executed in an earlier interrupted chunk of
817
+ * this turn (tool-call journal hard-block and zombie-ledger recovery in
818
+ * production-agent.ts). These are not new calls — rendering them as separate
819
+ * cards produces the "same tool twice, one spinning / one done" duplicate.
820
+ */
821
+ const JOURNAL_RECOVERY_RESULT_PREFIXES = [
822
+ "(Already completed in an earlier interrupted attempt",
823
+ "(Recovered from prior interrupted chunk",
824
+ ] as const;
825
+
826
+ function isJournalRecoveryResult(result: unknown): boolean {
827
+ return (
828
+ typeof result === "string" &&
829
+ JOURNAL_RECOVERY_RESULT_PREFIXES.some((prefix) => result.startsWith(prefix))
830
+ );
831
+ }
832
+
833
+ /**
834
+ * Merge a journal/ledger-recovered tool_done into the earlier card for the
835
+ * same logical call instead of leaving a duplicate pair. Two shapes occur:
836
+ *
837
+ * 1. The original card already completed (reconnect/continuation replay): the
838
+ * recovery card at `completedIndex` is redundant — drop it, keeping the
839
+ * original result.
840
+ * 2. The recovery result attached to the ORIGINAL still-pending card (the
841
+ * id-less replay tool_done name-matches the earliest pending card): the
842
+ * replay's own tool_start pushed a second pending card AFTER it that no
843
+ * tool_done will ever resolve — remove that stuck-spinner artifact.
844
+ *
845
+ * Gated strictly on the recovery result markers so genuinely repeated
846
+ * identical calls are never collapsed. Returns true when it spliced the card
847
+ * at `completedIndex` (callers must not reuse the index afterwards).
848
+ */
849
+ function coalesceJournalRecoveredTool(
850
+ content: ContentPart[],
851
+ completedIndex: number,
852
+ ): boolean {
853
+ const current = content[completedIndex];
854
+ if (!current || current.type !== "tool-call") return false;
855
+ if (!isJournalRecoveryResult(current.result)) return false;
856
+ const matchesCurrentCall = (
857
+ part: ContentPart,
858
+ ): part is Extract<ContentPart, { type: "tool-call" }> =>
859
+ part.type === "tool-call" &&
860
+ part.activity !== true &&
861
+ part.toolName === current.toolName &&
862
+ part.argsText === current.argsText;
863
+
864
+ for (let i = completedIndex - 1; i >= 0; i--) {
865
+ const prior = content[i];
866
+ if (!matchesCurrentCall(prior)) continue;
867
+ if (prior.result === undefined) {
868
+ // The original was interrupted mid-flight (spinner) — resolve it with
869
+ // the recovered result instead of showing a second card.
870
+ prior.result = current.result;
871
+ if (current.isError !== undefined) prior.isError = current.isError;
872
+ if (current.completedSideEffect !== undefined) {
873
+ prior.completedSideEffect = current.completedSideEffect;
874
+ }
875
+ if (current.mcpApp) prior.mcpApp = current.mcpApp;
876
+ if (current.chatUI) prior.chatUI = current.chatUI;
877
+ }
878
+ content.splice(completedIndex, 1);
879
+ return true;
880
+ }
881
+
882
+ // No earlier card — the recovery result landed on the original pending card
883
+ // itself. Remove any later still-pending replay-start artifact for the same
884
+ // call so it doesn't spin forever.
885
+ for (let i = content.length - 1; i > completedIndex; i--) {
886
+ const later = content[i];
887
+ if (
888
+ later.type === "tool-call" &&
889
+ matchesCurrentCall(later) &&
890
+ later.result === undefined
891
+ ) {
892
+ content.splice(i, 1);
893
+ }
894
+ }
895
+ return false;
896
+ }
897
+
898
+ function coalesceCompletedToolRepeat(
899
+ content: ContentPart[],
900
+ completedIndex: number,
901
+ ): void {
902
+ const current = content[completedIndex];
903
+ const previous = content[completedIndex - 1];
904
+ if (
905
+ !current ||
906
+ !previous ||
907
+ current.type !== "tool-call" ||
908
+ previous.type !== "tool-call"
909
+ ) {
910
+ return;
911
+ }
912
+
913
+ const currentSignature = completedToolRepeatSignature(current);
914
+ if (
915
+ !currentSignature ||
916
+ currentSignature !== completedToolRepeatSignature(previous)
917
+ ) {
918
+ return;
919
+ }
920
+
921
+ previous.repeatCount =
922
+ (previous.repeatCount ?? 1) + (current.repeatCount ?? 1);
923
+ content.splice(completedIndex, 1);
924
+ }
925
+
926
+ function formatToolNames(tools: string[]): string {
927
+ const names = tools.map(humanizeToolName);
928
+ if (names.length === 0) return "the promised action";
929
+ if (names.length === 1) return `the ${names[0]} action`;
930
+ return `these actions: ${names.join(", ")}`;
931
+ }
932
+
933
+ function interruptedToolMessage(pending: {
934
+ activity: string[];
935
+ running: string[];
936
+ }): string {
937
+ if (pending.running.length > 0) {
938
+ return `The agent stopped before ${formatToolNames(pending.running)} returned a result. The requested changes may not have been made.`;
939
+ }
940
+ const actionLabel = formatToolNames(pending.activity);
941
+ return `The agent stopped before starting ${actionLabel}. No tool result was returned, so the requested changes were not made.`;
942
+ }
943
+
944
+ function lastAssistantTextIndex(content: ContentPart[]): number {
945
+ for (let i = content.length - 1; i >= 0; i--) {
946
+ const part = content[i];
947
+ if (part.type === "text" && part.text.trim().length > 0) return i;
948
+ }
949
+ return -1;
950
+ }
951
+
952
+ function completedToolNamesAfterLastAssistantText(
953
+ content: ContentPart[],
954
+ ): string[] {
955
+ const lastTextIndex = lastAssistantTextIndex(content);
956
+ const names = new Set<string>();
957
+ for (let i = lastTextIndex + 1; i < content.length; i++) {
958
+ const part = content[i];
959
+ if (
960
+ part.type === "tool-call" &&
961
+ part.activity !== true &&
962
+ part.result !== undefined &&
963
+ part.isError !== true
964
+ ) {
965
+ names.add(part.toolName);
966
+ }
967
+ }
968
+ return [...names];
969
+ }
970
+
971
+ function completedToolOnlyMessage(toolNames: string[]): string | null {
972
+ if (toolNames.length === 0) return null;
973
+ const label = formatToolNames(toolNames);
974
+ return `The agent completed ${label}, but stopped before sending a final message. Review the completed tool card above or ask the agent to continue.`;
975
+ }
976
+
977
+ interface ProcessEventState {
978
+ completedToolsAfterLastAssistantText: Set<string>;
979
+ /** Set once `agent-chat:stream-progress` has been dispatched for the
980
+ * current chunk, so a burst of per-token text/reasoning deltas only fires
981
+ * it once. Cleared by `resetProcessEventState` on a server `clear` retry
982
+ * so the next batch of real output re-arms it. */
983
+ streamProgressDispatched: boolean;
984
+ }
985
+
986
+ function markAssistantText(state: ProcessEventState | undefined) {
987
+ state?.completedToolsAfterLastAssistantText.clear();
988
+ }
989
+
990
+ function markCompletedToolAfterAssistantText(
991
+ state: ProcessEventState | undefined,
992
+ toolName: string,
993
+ ) {
994
+ state?.completedToolsAfterLastAssistantText.add(toolName);
995
+ }
996
+
997
+ function resetProcessEventState(state: ProcessEventState | undefined) {
998
+ state?.completedToolsAfterLastAssistantText.clear();
999
+ if (state) state.streamProgressDispatched = false;
1000
+ }
1001
+
1002
+ // Returns true the first time it's called for a given state (or every time
1003
+ // when state is unavailable, since there is nothing to dedupe against) and
1004
+ // false on subsequent calls until `resetProcessEventState` re-arms it.
1005
+ function shouldDispatchStreamProgress(
1006
+ state: ProcessEventState | undefined,
1007
+ ): boolean {
1008
+ if (state?.streamProgressDispatched) return false;
1009
+ if (state) state.streamProgressDispatched = true;
1010
+ return true;
1011
+ }
1012
+
1013
+ /**
1014
+ * Process a single SSE event and update the content accumulator.
1015
+ * Returns: "continue" to keep going, "done" to stop, or a yield-ready result.
1016
+ */
1017
+ export function processEvent(
1018
+ ev: SSEEvent,
1019
+ content: ContentPart[],
1020
+ toolCallCounter: { value: number },
1021
+ tabId: string | undefined,
1022
+ state?: ProcessEventState,
1023
+ ): {
1024
+ action:
1025
+ | "continue"
1026
+ | "done"
1027
+ | "yield"
1028
+ | "error"
1029
+ | "missing_api_key"
1030
+ | "auto_continue";
1031
+ result?: ChatModelRunResult;
1032
+ autoContinue?: {
1033
+ reason: AgentAutoContinueReason;
1034
+ maxIterations?: number;
1035
+ errorInfo?: AgentAutoContinueErrorInfo;
1036
+ };
1037
+ } {
1038
+ if (ev.type === "clear") {
1039
+ // Server is retrying — discard rejected draft text and unfinished tool
1040
+ // output while keeping completed tool results visible.
1041
+ clearAssistantDraftContent(content);
1042
+ resetProcessEventState(state);
1043
+ dispatchActivityClear(tabId);
1044
+ return {
1045
+ action: "yield",
1046
+ result: { content: contentSnapshot(content) } as ChatModelRunResult,
1047
+ };
1048
+ }
1049
+
1050
+ if (ev.type === "text") {
1051
+ // Visible output means the run is plainly not hanging — drop any running
1052
+ // activity label so a transient "Contacting model" / "Still generating
1053
+ // image" doesn't linger beside streamed text. Idempotent (clears once, then
1054
+ // no-ops) so per-token text deltas stay cheap.
1055
+ if (ev.text) {
1056
+ dispatchActivityClear(tabId);
1057
+ // Real output resumed — let listeners (e.g. the auto-resume "Resuming…"
1058
+ // indicator) clear state that must NOT be cleared by activity-clear
1059
+ // alone, since activity-clear also fires for old-chunk/retry replays.
1060
+ if (shouldDispatchStreamProgress(state)) dispatchStreamProgress(tabId);
1061
+ }
1062
+ if (ev.text?.trim()) markAssistantText(state);
1063
+ const lastPart = content[content.length - 1];
1064
+ if (lastPart && lastPart.type === "text") {
1065
+ lastPart.text += ev.text ?? "";
1066
+ } else {
1067
+ content.push({ type: "text", text: ev.text ?? "" });
1068
+ }
1069
+ return {
1070
+ action: "yield",
1071
+ result: { content: contentSnapshot(content) } as ChatModelRunResult,
1072
+ };
1073
+ }
1074
+
1075
+ if (ev.type === "thinking" || ev.type === "reasoning") {
1076
+ // Model chain-of-thought. Coalesce consecutive deltas into one reasoning
1077
+ // part so the UI can render a single collapsible "Thinking" cell.
1078
+ const delta = ev.text ?? "";
1079
+ if (!delta) return { action: "continue" };
1080
+ if (shouldDispatchStreamProgress(state)) dispatchStreamProgress(tabId);
1081
+ const lastPart = content[content.length - 1];
1082
+ if (lastPart && lastPart.type === "reasoning") {
1083
+ lastPart.text += delta;
1084
+ } else {
1085
+ content.push({ type: "reasoning", text: delta });
1086
+ }
1087
+ return {
1088
+ action: "yield",
1089
+ result: { content: contentSnapshot(content) } as ChatModelRunResult,
1090
+ };
1091
+ }
1092
+
1093
+ if (ev.type === "stream_keepalive") {
1094
+ return { action: "continue" };
1095
+ }
1096
+
1097
+ if (ev.type === "activity") {
1098
+ const tool = ev.tool?.trim() || undefined;
1099
+ const label = visibleActivityLabel(ev, tool);
1100
+ if (typeof window !== "undefined") {
1101
+ window.dispatchEvent(
1102
+ new CustomEvent("agent-chat:activity", {
1103
+ detail: {
1104
+ label,
1105
+ ...(tool ? { tool } : {}),
1106
+ tabId,
1107
+ },
1108
+ }),
1109
+ );
1110
+ }
1111
+ if (!tool) return { action: "continue" };
1112
+
1113
+ const pendingToolCallIndex = findPendingActivityToolCallIndex(
1114
+ content,
1115
+ tool,
1116
+ ev.id,
1117
+ );
1118
+ if (pendingToolCallIndex >= 0 && ev.id) {
1119
+ const pending = content[pendingToolCallIndex];
1120
+ if (pending?.type === "tool-call" && pending.toolCallId !== ev.id) {
1121
+ content[pendingToolCallIndex] = { ...pending, toolCallId: ev.id };
1122
+ }
1123
+ }
1124
+ if (pendingToolCallIndex === -1) {
1125
+ // Only surface a placeholder spinner when this tool has no card yet. A
1126
+ // trailing activity heartbeat that arrives after the matching tool_done
1127
+ // (e.g. reordered reconnect replay) must NOT resurrect a spinner for an
1128
+ // already-completed call — that is the "pop back to an older state"
1129
+ // flicker. The real card reappears on the next tool_start regardless.
1130
+ const hasCompletedSameTool = content.some(
1131
+ (part) =>
1132
+ part.type === "tool-call" &&
1133
+ part.toolName === tool &&
1134
+ part.result !== undefined &&
1135
+ (!ev.id || part.toolCallId === ev.id),
1136
+ );
1137
+ if (!hasCompletedSameTool) {
1138
+ content.push({
1139
+ type: "tool-call",
1140
+ toolCallId: ev.id ?? `tc_${++toolCallCounter.value}`,
1141
+ toolName: tool,
1142
+ argsText: "",
1143
+ args: {},
1144
+ activity: true,
1145
+ });
1146
+ }
1147
+ }
1148
+ return {
1149
+ action: "yield",
1150
+ result: { content: contentSnapshot(content) } as ChatModelRunResult,
1151
+ };
1152
+ }
1153
+
1154
+ if (ev.type === "tool_start") {
1155
+ const args = (ev.input ?? {}) as Record<string, string>;
1156
+ const tool = ev.tool ?? "unknown";
1157
+ if (findCompletedToolCallIndex(content, ev.id) >= 0) {
1158
+ return { action: "continue" };
1159
+ }
1160
+ if (typeof window !== "undefined") {
1161
+ window.dispatchEvent(
1162
+ new CustomEvent("agent-native:tool-start", {
1163
+ detail: { tool, input: args },
1164
+ }),
1165
+ );
1166
+ window.dispatchEvent(
1167
+ new CustomEvent("agent-chat:activity", {
1168
+ detail: {
1169
+ label: runningToolLabel(tool),
1170
+ tool,
1171
+ tabId,
1172
+ },
1173
+ }),
1174
+ );
1175
+ }
1176
+ // Pass the server-assigned id so we upgrade the pending activity card
1177
+ // using id-match when available (parallel same-name calls stay separate).
1178
+ const pendingToolCallIndex = ev.id
1179
+ ? findPendingActivityToolCallIndex(content, tool, ev.id)
1180
+ : findOldestPendingActivityToolCallIndex(content, tool);
1181
+ const pendingToolCall =
1182
+ pendingToolCallIndex >= 0 ? content[pendingToolCallIndex] : undefined;
1183
+ const pendingIsActivityPlaceholder =
1184
+ pendingToolCall?.type === "tool-call" &&
1185
+ pendingToolCall.activity === true &&
1186
+ pendingToolCall.argsText === "" &&
1187
+ Object.keys(pendingToolCall.args).length === 0;
1188
+ // A re-emitted start for the SAME id — a retry/auto-continue clear that
1189
+ // keeps the in-flight card mounted, or a reconnect replay — must update the
1190
+ // existing card in place instead of pushing a duplicate. Matching on id
1191
+ // keeps genuinely parallel same-name calls, which carry distinct ids,
1192
+ // separate.
1193
+ const pendingIsSameIdReplay =
1194
+ pendingToolCall?.type === "tool-call" &&
1195
+ ev.id !== undefined &&
1196
+ pendingToolCall.toolCallId === ev.id;
1197
+ if (
1198
+ pendingToolCall &&
1199
+ pendingToolCall.type === "tool-call" &&
1200
+ (pendingIsActivityPlaceholder || pendingIsSameIdReplay)
1201
+ ) {
1202
+ // Upgrade the pending card in place. Prefer the server-assigned id so the
1203
+ // subsequent tool_done can match it precisely (parallel same-name calls
1204
+ // each carry their own id). Fall back to the locally-generated id.
1205
+ content[pendingToolCallIndex] = {
1206
+ type: "tool-call",
1207
+ toolCallId: ev.id ?? pendingToolCall.toolCallId,
1208
+ toolName: tool,
1209
+ argsText: JSON.stringify(args),
1210
+ args,
1211
+ };
1212
+ } else {
1213
+ content.push({
1214
+ type: "tool-call",
1215
+ toolCallId: ev.id ?? `tc_${++toolCallCounter.value}`,
1216
+ toolName: tool,
1217
+ argsText: JSON.stringify(args),
1218
+ args,
1219
+ });
1220
+ }
1221
+ return {
1222
+ action: "yield",
1223
+ result: { content: contentSnapshot(content) } as ChatModelRunResult,
1224
+ };
1225
+ }
1226
+
1227
+ if (ev.type === "approval_required") {
1228
+ // Opt-in `needsApproval` gate: the server emitted `tool_start` immediately
1229
+ // before this, so the matching tool-call part already exists. Mark it as
1230
+ // awaiting approval so the UI can render the Approve/Deny affordance. The
1231
+ // action did NOT execute; a paused `tool_done` follows.
1232
+ const approvalTool = ev.tool ?? "unknown";
1233
+ const approvalKey = ev.approvalKey;
1234
+ if (approvalKey) {
1235
+ const idx = findPendingToolCallIndex(content, approvalTool, ev.id);
1236
+ if (idx >= 0) {
1237
+ const part = content[idx];
1238
+ if (part.type === "tool-call") {
1239
+ part.approval = { approvalKey };
1240
+ }
1241
+ }
1242
+ }
1243
+ return {
1244
+ action: "yield",
1245
+ result: { content: contentSnapshot(content) } as ChatModelRunResult,
1246
+ };
1247
+ }
1248
+
1249
+ if (ev.type === "tool_done") {
1250
+ // Normalize identically to tool_start (which stores `ev.tool ?? "unknown"`)
1251
+ // so a tool_done frame with an undefined tool name still matches its
1252
+ // pending tool-call entry instead of leaving it forever unresolved.
1253
+ const doneTool = ev.tool ?? "unknown";
1254
+ if (findCompletedToolCallIndex(content, ev.id) >= 0) {
1255
+ return { action: "continue" };
1256
+ }
1257
+ if (typeof window !== "undefined") {
1258
+ window.dispatchEvent(
1259
+ new CustomEvent("agent-native:tool-done", {
1260
+ detail: { tool: doneTool, result: ev.result },
1261
+ }),
1262
+ );
1263
+ }
1264
+ // Clear any sticky running-activity label (e.g. "Still generating image"):
1265
+ // the tool that was emitting activity heartbeats has finished, so the label
1266
+ // must not linger while the model streams its follow-up text or reasoning.
1267
+ dispatchActivityClear(tabId);
1268
+ // Use id-based lookup when available so parallel same-name tool calls
1269
+ // get their results correctly assigned; fall back to name-matching.
1270
+ const doneIdx = findPendingToolCallIndex(content, doneTool, ev.id);
1271
+ if (doneIdx >= 0) {
1272
+ const part = content[doneIdx];
1273
+ if (part.type === "tool-call") {
1274
+ part.result = ev.result ?? "";
1275
+ if (ev.isError !== undefined) part.isError = ev.isError;
1276
+ if (ev.completedSideEffect !== undefined) {
1277
+ part.completedSideEffect = ev.completedSideEffect;
1278
+ }
1279
+ if (ev.mcpApp) part.mcpApp = ev.mcpApp;
1280
+ if (ev.chatUI) part.chatUI = ev.chatUI;
1281
+ if (part.activity !== true && part.isError !== true) {
1282
+ markCompletedToolAfterAssistantText(state, part.toolName);
1283
+ }
1284
+ // Journal/ledger replay merge first (may splice the card at doneIdx —
1285
+ // when it does, the adjacent-repeat coalesce below must not run on the
1286
+ // stale index).
1287
+ if (!coalesceJournalRecoveredTool(content, doneIdx)) {
1288
+ coalesceCompletedToolRepeat(content, doneIdx);
1289
+ }
1290
+ }
1291
+ }
1292
+ return {
1293
+ action: "yield",
1294
+ result: { content: contentSnapshot(content) } as ChatModelRunResult,
1295
+ };
1296
+ }
1297
+
1298
+ if (ev.type === "agent_call") {
1299
+ const agentName = ev.agent ?? "agent";
1300
+ if (ev.status === "start") {
1301
+ const toolCallId = `tc_${++toolCallCounter.value}`;
1302
+ content.push({
1303
+ type: "tool-call",
1304
+ toolCallId,
1305
+ toolName: `agent:${agentName}`,
1306
+ argsText: "",
1307
+ args: {},
1308
+ });
1309
+ } else if (ev.status === "done" || ev.status === "error") {
1310
+ for (let i = content.length - 1; i >= 0; i--) {
1311
+ const part = content[i];
1312
+ if (
1313
+ part.type === "tool-call" &&
1314
+ part.toolName === `agent:${agentName}` &&
1315
+ part.result === undefined
1316
+ ) {
1317
+ part.result = ev.status === "error" ? "Error calling agent" : "Done";
1318
+ break;
1319
+ }
1320
+ }
1321
+ }
1322
+ return {
1323
+ action: "yield",
1324
+ result: { content: contentSnapshot(content) } as ChatModelRunResult,
1325
+ };
1326
+ }
1327
+
1328
+ if (ev.type === "agent_call_text") {
1329
+ const agentName = ev.agent ?? "agent";
1330
+ // Find the in-progress agent tool-call and append streaming text to argsText
1331
+ for (let i = content.length - 1; i >= 0; i--) {
1332
+ const part = content[i];
1333
+ if (
1334
+ part.type === "tool-call" &&
1335
+ part.toolName === `agent:${agentName}` &&
1336
+ part.result === undefined
1337
+ ) {
1338
+ part.argsText += ev.text ?? "";
1339
+ break;
1340
+ }
1341
+ }
1342
+ return {
1343
+ action: "yield",
1344
+ result: { content: contentSnapshot(content) } as ChatModelRunResult,
1345
+ };
1346
+ }
1347
+
1348
+ // ─── Agent task events (sub-agent chips) ─────────────────────────
1349
+ // These events are dispatched as CustomEvents so AgentTaskCard components
1350
+ // can listen for updates to their specific taskId.
1351
+ if (
1352
+ ev.type === "agent_task" ||
1353
+ ev.type === "agent_task_update" ||
1354
+ ev.type === "agent_task_complete"
1355
+ ) {
1356
+ if (typeof window !== "undefined") {
1357
+ window.dispatchEvent(new CustomEvent("agent-task-event", { detail: ev }));
1358
+ }
1359
+ // Don't add to content — the agent-teams tool call handles rendering
1360
+ return { action: "continue" };
1361
+ }
1362
+
1363
+ if (ev.type === "missing_api_key") {
1364
+ const errMsg = LLM_MISSING_CREDENTIALS_MESSAGE;
1365
+ const errorCode = LLM_MISSING_CREDENTIALS_ERROR_CODE;
1366
+ const runError = {
1367
+ message: normalizeChatError(errMsg, errorCode).message,
1368
+ errorCode,
1369
+ };
1370
+ if (typeof window !== "undefined") {
1371
+ dispatchMissingApiKey(tabId);
1372
+ window.dispatchEvent(
1373
+ new CustomEvent("agent-chat:run-error", {
1374
+ detail: { ...runError, tabId },
1375
+ }),
1376
+ );
1377
+ }
1378
+ settleInterruptedToolCalls(content, undefined, { includeActivity: true });
1379
+ content.push({
1380
+ type: "text",
1381
+ text: formatChatErrorText(errMsg, undefined, errorCode),
1382
+ });
1383
+ return {
1384
+ action: "missing_api_key",
1385
+ result: {
1386
+ content: contentSnapshot(content),
1387
+ status: { type: "incomplete" as const, reason: "error" as const },
1388
+ metadata: { custom: { runError } },
1389
+ } as ChatModelRunResult,
1390
+ };
1391
+ }
1392
+
1393
+ if (ev.type === "loop_limit") {
1394
+ const maxIterations =
1395
+ typeof ev.maxIterations === "number" ? ev.maxIterations : undefined;
1396
+ return {
1397
+ action: "auto_continue",
1398
+ autoContinue: {
1399
+ reason: "loop_limit",
1400
+ ...(maxIterations ? { maxIterations } : {}),
1401
+ },
1402
+ };
1403
+ }
1404
+
1405
+ if (ev.type === "auto_continue") {
1406
+ const reason =
1407
+ ev.reason === "stream_ended" ||
1408
+ ev.reason === "loop_limit" ||
1409
+ ev.reason === "no_progress" ||
1410
+ ev.reason === "run_timeout"
1411
+ ? ev.reason
1412
+ : ev.errorCode === "stream_ended" ||
1413
+ ev.errorCode === "loop_limit" ||
1414
+ ev.errorCode === "no_progress" ||
1415
+ ev.errorCode === "run_timeout"
1416
+ ? ev.errorCode
1417
+ : ev.error === "stream_ended" ||
1418
+ ev.error === "loop_limit" ||
1419
+ ev.error === "no_progress" ||
1420
+ ev.error === "run_timeout"
1421
+ ? ev.error
1422
+ : ev.status === "stream_ended" ||
1423
+ ev.status === "loop_limit" ||
1424
+ ev.status === "no_progress" ||
1425
+ ev.status === "run_timeout"
1426
+ ? ev.status
1427
+ : "run_timeout";
1428
+ return {
1429
+ action: "auto_continue",
1430
+ autoContinue: {
1431
+ reason,
1432
+ ...(typeof ev.maxIterations === "number"
1433
+ ? { maxIterations: ev.maxIterations }
1434
+ : {}),
1435
+ },
1436
+ };
1437
+ }
1438
+
1439
+ if (ev.type === "error") {
1440
+ const errMsg = ev.error ?? "Unknown error";
1441
+ if (
1442
+ (ev.errorCode === "run_timeout" && ev.recoverable) ||
1443
+ isAutoRecoverableError(ev, errMsg)
1444
+ ) {
1445
+ const normalized = normalizeChatError(errMsg, ev.errorCode);
1446
+ return {
1447
+ action: "auto_continue",
1448
+ autoContinue: {
1449
+ reason:
1450
+ ev.errorCode === "stale_run"
1451
+ ? "stale_run"
1452
+ : ev.errorCode === "builder_gateway_timeout" ||
1453
+ ev.errorCode === "run_timeout" ||
1454
+ errMsg.toLowerCase().includes("timeout")
1455
+ ? "run_timeout"
1456
+ : "stream_ended",
1457
+ errorInfo: {
1458
+ message: normalized.message,
1459
+ ...(ev.details || normalized.details
1460
+ ? { details: ev.details ?? normalized.details }
1461
+ : {}),
1462
+ ...(ev.errorCode ? { errorCode: ev.errorCode } : {}),
1463
+ recoverable: ev.recoverable ?? true,
1464
+ ...(ev.upgradeUrl ? { upgradeUrl: ev.upgradeUrl } : {}),
1465
+ },
1466
+ },
1467
+ };
1468
+ }
1469
+ const normalized = normalizeChatError(errMsg, ev.errorCode);
1470
+ if (isMissingCredentialText(errMsg, ev.errorCode)) {
1471
+ dispatchMissingApiKey(tabId);
1472
+ }
1473
+ const runError = {
1474
+ message: normalized.message,
1475
+ ...(normalized.details || ev.details
1476
+ ? { details: ev.details ?? normalized.details }
1477
+ : {}),
1478
+ ...(ev.errorCode ? { errorCode: ev.errorCode } : {}),
1479
+ ...(ev.recoverable ? { recoverable: ev.recoverable } : {}),
1480
+ };
1481
+ if (typeof window !== "undefined") {
1482
+ window.dispatchEvent(
1483
+ new CustomEvent("agent-chat:run-error", {
1484
+ detail: { ...runError, tabId },
1485
+ }),
1486
+ );
1487
+ }
1488
+ settleInterruptedToolCalls(content, undefined, { includeActivity: true });
1489
+ content.push({
1490
+ type: "text",
1491
+ text: formatChatErrorText(errMsg, ev.upgradeUrl, ev.errorCode),
1492
+ });
1493
+ return {
1494
+ action: "error",
1495
+ result: {
1496
+ content: contentSnapshot(content),
1497
+ status: { type: "incomplete" as const, reason: "error" as const },
1498
+ metadata: { custom: { runError } },
1499
+ } as ChatModelRunResult,
1500
+ };
1501
+ }
1502
+
1503
+ if (ev.type === "done") {
1504
+ const interruptedTools = pendingToolNames(content);
1505
+ const allInterruptedTools = [
1506
+ ...interruptedTools.running,
1507
+ ...interruptedTools.activity,
1508
+ ];
1509
+ if (allInterruptedTools.length > 0) {
1510
+ settleInterruptedToolCalls(content, undefined, { includeActivity: true });
1511
+ const message = interruptedToolMessage(interruptedTools);
1512
+ const runError = {
1513
+ message,
1514
+ details: `interrupted_actions: ${allInterruptedTools.join(", ")}`,
1515
+ errorCode: "action_not_started",
1516
+ recoverable: true,
1517
+ };
1518
+ if (typeof window !== "undefined") {
1519
+ window.dispatchEvent(
1520
+ new CustomEvent("agent-chat:run-error", {
1521
+ detail: { ...runError, tabId },
1522
+ }),
1523
+ );
1524
+ }
1525
+ content.push({
1526
+ type: "text",
1527
+ text: formatChatErrorText(message, undefined, runError.errorCode),
1528
+ });
1529
+ return {
1530
+ action: "error",
1531
+ result: {
1532
+ content: contentSnapshot(content),
1533
+ status: { type: "incomplete" as const, reason: "error" as const },
1534
+ metadata: { custom: { runError } },
1535
+ } as ChatModelRunResult,
1536
+ };
1537
+ }
1538
+ const toolOnlyMessage = completedToolOnlyMessage(
1539
+ state
1540
+ ? [...state.completedToolsAfterLastAssistantText]
1541
+ : completedToolNamesAfterLastAssistantText(content),
1542
+ );
1543
+ if (toolOnlyMessage) {
1544
+ content.push({
1545
+ type: "text",
1546
+ text: toolOnlyMessage,
1547
+ });
1548
+ return {
1549
+ action: "done",
1550
+ result: {
1551
+ content: contentSnapshot(content),
1552
+ status: { type: "complete" as const, reason: "stop" as const },
1553
+ metadata: {
1554
+ custom: {
1555
+ runWarning: {
1556
+ message: toolOnlyMessage,
1557
+ errorCode: "final_response_missing_after_tool",
1558
+ recoverable: true,
1559
+ },
1560
+ },
1561
+ },
1562
+ } as ChatModelRunResult,
1563
+ };
1564
+ }
1565
+ return {
1566
+ action: "done",
1567
+ result: { content: contentSnapshot(content) } as ChatModelRunResult,
1568
+ };
1569
+ }
1570
+
1571
+ return { action: "continue" };
1572
+ }
1573
+
1574
+ function clearAssistantDraftContent(content: ContentPart[]): void {
1575
+ for (let index = content.length - 1; index >= 0; index--) {
1576
+ const part = content[index];
1577
+ if (!part) continue;
1578
+ if (part.type === "text" || part.type === "reasoning") {
1579
+ content.splice(index, 1);
1580
+ continue;
1581
+ }
1582
+ if (part.type === "tool-call" && part.result === undefined) {
1583
+ // Only drop ephemeral placeholders. Materialized in-flight tool cards
1584
+ // (real args from tool_start) stay mounted so a retry/auto-continue clear
1585
+ // does not hide→show the same call when the next chunk re-emits it.
1586
+ const isEphemeral =
1587
+ part.activity === true ||
1588
+ part.argsText === "" ||
1589
+ Object.keys(part.args ?? {}).length === 0;
1590
+ if (isEphemeral) content.splice(index, 1);
1591
+ }
1592
+ }
1593
+ }
1594
+
1595
+ /**
1596
+ * Read and process SSE events from a ReadableStream response body.
1597
+ * Yields ChatModelRunResult for each meaningful event.
1598
+ *
1599
+ * When `runId` is provided, every yielded result carries
1600
+ * `metadata.custom.runId` so the UI can expose the trace ID via
1601
+ * "Copy Request ID" — including mid-stream, so users can grab it before
1602
+ * the run completes (or if the run hangs / ends prematurely).
1603
+ */
1604
+ export async function* readSSEStream(
1605
+ body: ReadableStream<Uint8Array>,
1606
+ content: ContentPart[],
1607
+ toolCallCounter: { value: number },
1608
+ tabId: string | undefined,
1609
+ onSeq?: (seq: number) => void,
1610
+ runId?: string | null,
1611
+ options?: SSEStreamOptions,
1612
+ ): AsyncGenerator<ChatModelRunResult> {
1613
+ const reader = body.getReader();
1614
+ const decoder = new TextDecoder();
1615
+ let buf = "";
1616
+ let lastMeaningfulEventAt = Date.now();
1617
+ const noProgressTimeoutMs = sseNoProgressTimeoutMs(options);
1618
+ const preparationStallTimeoutMs = sseActionPreparationStallTimeoutMs(options);
1619
+ const activityTrail: ActivityTrailEntry[] = [];
1620
+ const preparingActionState: PreparingActionState =
1621
+ options?.preparingActionState ?? {};
1622
+ const processEventState: ProcessEventState = {
1623
+ completedToolsAfterLastAssistantText: new Set(),
1624
+ streamProgressDispatched: false,
1625
+ };
1626
+ let renderUpdatesThisTurn = 0;
1627
+ let nextEventLoopTurn: Promise<void> | null = null;
1628
+
1629
+ const paceRenderUpdate = async (): Promise<void> => {
1630
+ renderUpdatesThisTurn += 1;
1631
+ if (!nextEventLoopTurn) {
1632
+ nextEventLoopTurn = new Promise<void>((resolve) => {
1633
+ setTimeout(() => {
1634
+ renderUpdatesThisTurn = 0;
1635
+ nextEventLoopTurn = null;
1636
+ resolve();
1637
+ }, 0);
1638
+ });
1639
+ }
1640
+ if (renderUpdatesThisTurn >= SSE_RENDER_UPDATES_PER_EVENT_LOOP_TURN) {
1641
+ await nextEventLoopTurn;
1642
+ }
1643
+ };
1644
+
1645
+ const withStreamMetadata = (r: ChatModelRunResult): ChatModelRunResult => {
1646
+ if (!runId && activityTrail.length === 0) return r;
1647
+ const metadata = (r.metadata ?? {}) as Record<string, unknown>;
1648
+ const custom =
1649
+ metadata.custom && typeof metadata.custom === "object"
1650
+ ? (metadata.custom as Record<string, unknown>)
1651
+ : {};
1652
+ const runError =
1653
+ runId && custom.runError && typeof custom.runError === "object"
1654
+ ? {
1655
+ ...(custom.runError as Record<string, unknown>),
1656
+ runId,
1657
+ }
1658
+ : custom.runError;
1659
+ return {
1660
+ ...r,
1661
+ metadata: {
1662
+ ...metadata,
1663
+ custom: {
1664
+ ...custom,
1665
+ ...(runId ? { runId } : {}),
1666
+ ...(runError ? { runError } : {}),
1667
+ ...(activityTrail.length > 0
1668
+ ? { activityTrail: [...activityTrail] }
1669
+ : {}),
1670
+ },
1671
+ },
1672
+ };
1673
+ };
1674
+
1675
+ try {
1676
+ while (true) {
1677
+ let readResult: ReadableStreamReadResult<Uint8Array>;
1678
+ try {
1679
+ readResult = await readChunkWithProgressTimeout(
1680
+ reader,
1681
+ lastMeaningfulEventAt,
1682
+ noProgressTimeoutMs,
1683
+ );
1684
+ } catch (err) {
1685
+ if (err instanceof AgentAutoContinueSignal) {
1686
+ throw new AgentAutoContinueSignal({
1687
+ reason: err.reason,
1688
+ maxIterations: err.maxIterations,
1689
+ activityTrail: [...activityTrail],
1690
+ errorInfo: err.errorInfo,
1691
+ });
1692
+ }
1693
+ throw err;
1694
+ }
1695
+ const { done, value } = readResult;
1696
+ if (done) break;
1697
+
1698
+ buf += decoder.decode(value, { stream: true });
1699
+ const lines = buf.split("\n");
1700
+ buf = lines.pop() ?? "";
1701
+ let sawProgressEvent = false;
1702
+
1703
+ for (const line of lines) {
1704
+ if (!line.startsWith("data: ")) continue;
1705
+ const raw = line.slice(6).trim();
1706
+ if (!raw) continue;
1707
+
1708
+ let ev: SSEEvent;
1709
+ try {
1710
+ ev = JSON.parse(raw);
1711
+ } catch {
1712
+ continue;
1713
+ }
1714
+ const now = Date.now();
1715
+ const actionPreparationProgress = updatePreparingActionState(
1716
+ preparingActionState,
1717
+ ev,
1718
+ now,
1719
+ );
1720
+ if (isMeaningfulProgressEvent(ev, actionPreparationProgress, options)) {
1721
+ sawProgressEvent = true;
1722
+ lastMeaningfulEventAt = now;
1723
+ }
1724
+
1725
+ // Track sequence number for reconnection
1726
+ if (ev.seq !== undefined && onSeq) {
1727
+ onSeq(ev.seq);
1728
+ }
1729
+
1730
+ if (ev.type === "clear") {
1731
+ activityTrail.length = 0;
1732
+ } else if (ev.type === "activity") {
1733
+ const tool = ev.tool?.trim() || undefined;
1734
+ appendActivityTrail(activityTrail, {
1735
+ label: baseActivityLabel(ev, tool),
1736
+ ...(tool ? { tool } : {}),
1737
+ });
1738
+ } else if (ev.type === "tool_start") {
1739
+ const tool = ev.tool ?? "unknown";
1740
+ appendActivityTrail(activityTrail, {
1741
+ label: runningToolLabel(tool),
1742
+ tool,
1743
+ });
1744
+ } else if (ev.type === "tool_done") {
1745
+ const tool = ev.tool ?? "unknown";
1746
+ for (let i = activityTrail.length - 1; i >= 0; i--) {
1747
+ if (activityTrail[i]?.tool === tool) {
1748
+ activityTrail.splice(i, 1);
1749
+ }
1750
+ }
1751
+ }
1752
+
1753
+ const { action, result, autoContinue } = processEvent(
1754
+ ev,
1755
+ content,
1756
+ toolCallCounter,
1757
+ tabId,
1758
+ processEventState,
1759
+ );
1760
+
1761
+ if (result) {
1762
+ await paceRenderUpdate();
1763
+ yield withStreamMetadata(result);
1764
+ }
1765
+ if (
1766
+ hasStalledPreparingAction(
1767
+ preparingActionState,
1768
+ Date.now(),
1769
+ preparationStallTimeoutMs,
1770
+ )
1771
+ ) {
1772
+ throw new AgentAutoContinueSignal({
1773
+ reason: "no_progress",
1774
+ activityTrail: [...activityTrail],
1775
+ });
1776
+ }
1777
+ if (action === "auto_continue") {
1778
+ throw new AgentAutoContinueSignal(
1779
+ autoContinue
1780
+ ? { ...autoContinue, activityTrail: [...activityTrail] }
1781
+ : { reason: "stream_ended", activityTrail: [...activityTrail] },
1782
+ );
1783
+ }
1784
+ if (
1785
+ action === "done" ||
1786
+ action === "error" ||
1787
+ action === "missing_api_key"
1788
+ ) {
1789
+ return;
1790
+ }
1791
+ }
1792
+
1793
+ if (
1794
+ !sawProgressEvent &&
1795
+ Date.now() - lastMeaningfulEventAt >= noProgressTimeoutMs
1796
+ ) {
1797
+ throw new AgentAutoContinueSignal({
1798
+ reason: "no_progress",
1799
+ activityTrail: [...activityTrail],
1800
+ });
1801
+ }
1802
+ }
1803
+ } finally {
1804
+ try {
1805
+ reader.releaseLock();
1806
+ } catch {
1807
+ // The timeout path cancels the stream before unwinding; some runtimes
1808
+ // still consider the pending read active for a tick.
1809
+ }
1810
+ }
1811
+
1812
+ // Stream ended without explicit done event. Even an empty content array is
1813
+ // abnormal here: a healthy run emits a terminal `done` event. Treat this as
1814
+ // recoverable so the adapter can first reconnect to the run, then continue
1815
+ // from durable history if the producer is gone.
1816
+ throw new AgentAutoContinueSignal({
1817
+ reason: "stream_ended",
1818
+ activityTrail: [...activityTrail],
1819
+ });
1820
+ }
1821
+
1822
+ /**
1823
+ * Read raw SSE events from a ReadableStream and process them into ContentPart[].
1824
+ * Unlike readSSEStream, this doesn't yield ChatModelRunResult — it updates the
1825
+ * content array in-place and calls onUpdate for each meaningful change.
1826
+ * Designed for reconnection scenarios where we render outside assistant-ui's runtime.
1827
+ */
1828
+ export async function readSSEStreamRaw(
1829
+ body: ReadableStream<Uint8Array>,
1830
+ content: ContentPart[],
1831
+ toolCallCounter: { value: number },
1832
+ tabId: string | undefined,
1833
+ onUpdate: (content: ContentPart[]) => void,
1834
+ onSeq?: (seq: number) => void,
1835
+ options?: SSEStreamOptions,
1836
+ ): Promise<void> {
1837
+ const reader = body.getReader();
1838
+ const decoder = new TextDecoder();
1839
+ let buf = "";
1840
+ let lastMeaningfulEventAt = Date.now();
1841
+ const noProgressTimeoutMs = sseNoProgressTimeoutMs(options);
1842
+ const preparationStallTimeoutMs = sseActionPreparationStallTimeoutMs(options);
1843
+ const activityTrail: ActivityTrailEntry[] = [];
1844
+ const preparingActionState: PreparingActionState =
1845
+ options?.preparingActionState ?? {};
1846
+ const processEventState: ProcessEventState = {
1847
+ completedToolsAfterLastAssistantText: new Set(),
1848
+ streamProgressDispatched: false,
1849
+ };
1850
+ // Tracks whether the most recent content state was already pushed via
1851
+ // onUpdate inside the loop, so the post-loop flush below doesn't emit the
1852
+ // identical content a second time when the stream closes without a terminal
1853
+ // event.
1854
+ let emittedLatestContent = false;
1855
+
1856
+ try {
1857
+ while (true) {
1858
+ let readResult: ReadableStreamReadResult<Uint8Array>;
1859
+ try {
1860
+ readResult = await readChunkWithProgressTimeout(
1861
+ reader,
1862
+ lastMeaningfulEventAt,
1863
+ noProgressTimeoutMs,
1864
+ );
1865
+ } catch (err) {
1866
+ if (err instanceof AgentAutoContinueSignal) {
1867
+ throw new AgentAutoContinueSignal({
1868
+ reason: err.reason,
1869
+ maxIterations: err.maxIterations,
1870
+ activityTrail: [...activityTrail],
1871
+ errorInfo: err.errorInfo,
1872
+ });
1873
+ }
1874
+ throw err;
1875
+ }
1876
+ const { done, value } = readResult;
1877
+ if (done) break;
1878
+
1879
+ buf += decoder.decode(value, { stream: true });
1880
+ const lines = buf.split("\n");
1881
+ buf = lines.pop() ?? "";
1882
+
1883
+ let sawProgressEvent = false;
1884
+ for (const line of lines) {
1885
+ if (!line.startsWith("data: ")) continue;
1886
+ const raw = line.slice(6).trim();
1887
+ if (!raw) continue;
1888
+
1889
+ let ev: SSEEvent;
1890
+ try {
1891
+ ev = JSON.parse(raw);
1892
+ } catch {
1893
+ continue;
1894
+ }
1895
+ const now = Date.now();
1896
+ const actionPreparationProgress = updatePreparingActionState(
1897
+ preparingActionState,
1898
+ ev,
1899
+ now,
1900
+ );
1901
+ if (isMeaningfulProgressEvent(ev, actionPreparationProgress, options)) {
1902
+ sawProgressEvent = true;
1903
+ lastMeaningfulEventAt = now;
1904
+ }
1905
+
1906
+ if (ev.seq !== undefined && onSeq) {
1907
+ onSeq(ev.seq);
1908
+ }
1909
+
1910
+ if (ev.type === "clear") {
1911
+ activityTrail.length = 0;
1912
+ } else if (ev.type === "activity") {
1913
+ const tool = ev.tool?.trim() || undefined;
1914
+ appendActivityTrail(activityTrail, {
1915
+ label: baseActivityLabel(ev, tool),
1916
+ ...(tool ? { tool } : {}),
1917
+ });
1918
+ } else if (ev.type === "tool_start") {
1919
+ const tool = ev.tool ?? "unknown";
1920
+ appendActivityTrail(activityTrail, {
1921
+ label: runningToolLabel(tool),
1922
+ tool,
1923
+ });
1924
+ } else if (ev.type === "tool_done") {
1925
+ const tool = ev.tool ?? "unknown";
1926
+ for (let i = activityTrail.length - 1; i >= 0; i--) {
1927
+ if (activityTrail[i]?.tool === tool) {
1928
+ activityTrail.splice(i, 1);
1929
+ }
1930
+ }
1931
+ }
1932
+
1933
+ const { action, autoContinue } = processEvent(
1934
+ ev,
1935
+ content,
1936
+ toolCallCounter,
1937
+ tabId,
1938
+ processEventState,
1939
+ );
1940
+
1941
+ if (
1942
+ action === "yield" ||
1943
+ action === "done" ||
1944
+ action === "error" ||
1945
+ action === "missing_api_key"
1946
+ ) {
1947
+ onUpdate(contentSnapshot(content));
1948
+ emittedLatestContent = true;
1949
+ }
1950
+ if (action === "auto_continue") {
1951
+ onUpdate(contentSnapshot(content));
1952
+ emittedLatestContent = true;
1953
+ throw new AgentAutoContinueSignal(
1954
+ autoContinue
1955
+ ? { ...autoContinue, activityTrail: [...activityTrail] }
1956
+ : { reason: "stream_ended", activityTrail: [...activityTrail] },
1957
+ );
1958
+ }
1959
+ if (
1960
+ hasStalledPreparingAction(
1961
+ preparingActionState,
1962
+ Date.now(),
1963
+ preparationStallTimeoutMs,
1964
+ )
1965
+ ) {
1966
+ onUpdate(contentSnapshot(content));
1967
+ throw new AgentAutoContinueSignal({
1968
+ reason: "no_progress",
1969
+ activityTrail: [...activityTrail],
1970
+ });
1971
+ }
1972
+ if (
1973
+ action === "done" ||
1974
+ action === "error" ||
1975
+ action === "missing_api_key"
1976
+ ) {
1977
+ return;
1978
+ }
1979
+ }
1980
+
1981
+ if (
1982
+ !sawProgressEvent &&
1983
+ Date.now() - lastMeaningfulEventAt >= noProgressTimeoutMs
1984
+ ) {
1985
+ throw new AgentAutoContinueSignal({
1986
+ reason: "no_progress",
1987
+ activityTrail: [...activityTrail],
1988
+ });
1989
+ }
1990
+ }
1991
+ } finally {
1992
+ try {
1993
+ reader.releaseLock();
1994
+ } catch {
1995
+ // See readSSEStream: cancellation may race lock release in browsers.
1996
+ }
1997
+ }
1998
+ if (content.length > 0 && !emittedLatestContent) {
1999
+ onUpdate(contentSnapshot(content));
2000
+ }
2001
+ throw new AgentAutoContinueSignal({ reason: "stream_ended" });
2002
+ }