@superblocksteam/vite-plugin-file-sync 2.0.178-next.3 → 2.0.179-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (389) hide show
  1. package/dist/agent-tool-executor/claude-sandbox.d.ts +1 -2
  2. package/dist/agent-tool-executor/claude-sandbox.d.ts.map +1 -1
  3. package/dist/agent-tool-executor/claude-sandbox.js +1 -3
  4. package/dist/agent-tool-executor/claude-sandbox.js.map +1 -1
  5. package/dist/agent-tool-executor/claude-shell.d.ts +1 -14
  6. package/dist/agent-tool-executor/claude-shell.d.ts.map +1 -1
  7. package/dist/agent-tool-executor/claude-shell.js +7 -61
  8. package/dist/agent-tool-executor/claude-shell.js.map +1 -1
  9. package/dist/agent-tool-executor/claude-tools.d.ts +0 -4
  10. package/dist/agent-tool-executor/claude-tools.d.ts.map +1 -1
  11. package/dist/agent-tool-executor/claude-tools.js +1 -1
  12. package/dist/agent-tool-executor/claude-tools.js.map +1 -1
  13. package/dist/agent-tool-executor/codex-drafts.d.ts +1 -2
  14. package/dist/agent-tool-executor/codex-drafts.d.ts.map +1 -1
  15. package/dist/agent-tool-executor/codex-drafts.js +1 -4
  16. package/dist/agent-tool-executor/codex-drafts.js.map +1 -1
  17. package/dist/agent-tool-executor/codex-execution-policy.d.ts +1 -1
  18. package/dist/agent-tool-executor/codex-execution-policy.d.ts.map +1 -1
  19. package/dist/agent-tool-executor/codex-execution-policy.js +15 -2
  20. package/dist/agent-tool-executor/codex-execution-policy.js.map +1 -1
  21. package/dist/agent-tool-executor/native-os-sandbox.d.ts +2 -2
  22. package/dist/agent-tool-executor/native-os-sandbox.js +2 -2
  23. package/dist/agent-tool-executor/native-tool-servers.d.ts +10 -5
  24. package/dist/agent-tool-executor/native-tool-servers.d.ts.map +1 -1
  25. package/dist/agent-tool-executor/native-tool-servers.js +23 -9
  26. package/dist/agent-tool-executor/native-tool-servers.js.map +1 -1
  27. package/dist/ai-service/agent/middleware.d.ts.map +1 -1
  28. package/dist/ai-service/agent/middleware.js +1 -0
  29. package/dist/ai-service/agent/middleware.js.map +1 -1
  30. package/dist/ai-service/agent/prompts/build-base-system-prompt.d.ts +6 -0
  31. package/dist/ai-service/agent/prompts/build-base-system-prompt.d.ts.map +1 -1
  32. package/dist/ai-service/agent/prompts/build-base-system-prompt.js +4 -0
  33. package/dist/ai-service/agent/prompts/build-base-system-prompt.js.map +1 -1
  34. package/dist/ai-service/agent/prompts/project-prompt.d.ts +11 -0
  35. package/dist/ai-service/agent/prompts/project-prompt.d.ts.map +1 -0
  36. package/dist/ai-service/agent/prompts/project-prompt.js +20 -0
  37. package/dist/ai-service/agent/prompts/project-prompt.js.map +1 -0
  38. package/dist/ai-service/agent/tools/apis/test-api.d.ts +57 -0
  39. package/dist/ai-service/agent/tools/apis/test-api.d.ts.map +1 -1
  40. package/dist/ai-service/agent/tools/apis/test-api.js +1 -1
  41. package/dist/ai-service/agent/tools/apis/test-api.js.map +1 -1
  42. package/dist/ai-service/agent/tools/branching/branch-tools.d.ts +2 -8
  43. package/dist/ai-service/agent/tools/branching/branch-tools.d.ts.map +1 -1
  44. package/dist/ai-service/agent/tools/branching/branch-tools.js +8 -8
  45. package/dist/ai-service/agent/tools/branching/branch-tools.js.map +1 -1
  46. package/dist/ai-service/agent/tools/build-capture-screenshot.d.ts +1 -0
  47. package/dist/ai-service/agent/tools/build-capture-screenshot.d.ts.map +1 -1
  48. package/dist/ai-service/agent/tools/build-capture-screenshot.js +24 -1
  49. package/dist/ai-service/agent/tools/build-capture-screenshot.js.map +1 -1
  50. package/dist/ai-service/agent/tools/build-list-files.d.ts +1 -1
  51. package/dist/ai-service/agent/tools/build-list-files.d.ts.map +1 -1
  52. package/dist/ai-service/agent/tools/build-list-files.js +14 -1
  53. package/dist/ai-service/agent/tools/build-list-files.js.map +1 -1
  54. package/dist/ai-service/agent/tools/databases/dev-database-tools.d.ts +6 -6
  55. package/dist/ai-service/agent/tools/databases/dev-database-tools.d.ts.map +1 -1
  56. package/dist/ai-service/agent/tools/search-web.d.ts +22 -0
  57. package/dist/ai-service/agent/tools/search-web.d.ts.map +1 -0
  58. package/dist/ai-service/agent/tools/search-web.js +87 -0
  59. package/dist/ai-service/agent/tools/search-web.js.map +1 -0
  60. package/dist/ai-service/attachments/artifact-reference.d.ts +14 -0
  61. package/dist/ai-service/attachments/artifact-reference.d.ts.map +1 -0
  62. package/dist/ai-service/attachments/artifact-reference.js +28 -0
  63. package/dist/ai-service/attachments/artifact-reference.js.map +1 -0
  64. package/dist/ai-service/attachments/artifact-storage.d.ts +61 -0
  65. package/dist/ai-service/attachments/artifact-storage.d.ts.map +1 -0
  66. package/dist/ai-service/attachments/artifact-storage.js +178 -0
  67. package/dist/ai-service/attachments/artifact-storage.js.map +1 -0
  68. package/dist/ai-service/attachments/native-attachment-preparations.d.ts +32 -0
  69. package/dist/ai-service/attachments/native-attachment-preparations.d.ts.map +1 -0
  70. package/dist/ai-service/attachments/native-attachment-preparations.js +80 -0
  71. package/dist/ai-service/attachments/native-attachment-preparations.js.map +1 -0
  72. package/dist/ai-service/attachments/text-upload-artifacts.d.ts +14 -10
  73. package/dist/ai-service/attachments/text-upload-artifacts.d.ts.map +1 -1
  74. package/dist/ai-service/attachments/text-upload-artifacts.js +21 -86
  75. package/dist/ai-service/attachments/text-upload-artifacts.js.map +1 -1
  76. package/dist/ai-service/attachments/upload-artifact-paths.d.ts +2 -0
  77. package/dist/ai-service/attachments/upload-artifact-paths.d.ts.map +1 -1
  78. package/dist/ai-service/attachments/upload-artifact-paths.js +2 -0
  79. package/dist/ai-service/attachments/upload-artifact-paths.js.map +1 -1
  80. package/dist/ai-service/attachments/uploaded-content-part.d.ts +1 -0
  81. package/dist/ai-service/attachments/uploaded-content-part.d.ts.map +1 -1
  82. package/dist/ai-service/attachments/uploaded-content-part.js +3 -7
  83. package/dist/ai-service/attachments/uploaded-content-part.js.map +1 -1
  84. package/dist/ai-service/attachments/validate-prompt-attachments.d.ts +12 -3
  85. package/dist/ai-service/attachments/validate-prompt-attachments.d.ts.map +1 -1
  86. package/dist/ai-service/attachments/validate-prompt-attachments.js +171 -55
  87. package/dist/ai-service/attachments/validate-prompt-attachments.js.map +1 -1
  88. package/dist/ai-service/builder-context-usage.d.ts +12 -0
  89. package/dist/ai-service/builder-context-usage.d.ts.map +1 -0
  90. package/dist/ai-service/builder-context-usage.js +23 -0
  91. package/dist/ai-service/builder-context-usage.js.map +1 -0
  92. package/dist/ai-service/builder-conversation.d.ts +65 -9
  93. package/dist/ai-service/builder-conversation.d.ts.map +1 -1
  94. package/dist/ai-service/builder-conversation.js +229 -62
  95. package/dist/ai-service/builder-conversation.js.map +1 -1
  96. package/dist/ai-service/builder-core-prompt.d.ts +23 -0
  97. package/dist/ai-service/builder-core-prompt.d.ts.map +1 -0
  98. package/dist/ai-service/builder-core-prompt.js +148 -0
  99. package/dist/ai-service/builder-core-prompt.js.map +1 -0
  100. package/dist/ai-service/builder-failure-drain.d.ts +25 -0
  101. package/dist/ai-service/builder-failure-drain.d.ts.map +1 -0
  102. package/dist/ai-service/builder-failure-drain.js +67 -0
  103. package/dist/ai-service/builder-failure-drain.js.map +1 -0
  104. package/dist/ai-service/builder-failure-notice.d.ts +21 -0
  105. package/dist/ai-service/builder-failure-notice.d.ts.map +1 -0
  106. package/dist/ai-service/builder-failure-notice.js +47 -0
  107. package/dist/ai-service/builder-failure-notice.js.map +1 -0
  108. package/dist/ai-service/builder-inference-auth.d.ts +5 -2
  109. package/dist/ai-service/builder-inference-auth.d.ts.map +1 -1
  110. package/dist/ai-service/builder-inference-auth.js +25 -4
  111. package/dist/ai-service/builder-inference-auth.js.map +1 -1
  112. package/dist/ai-service/builder-runtime-auth-metrics.d.ts +15 -0
  113. package/dist/ai-service/builder-runtime-auth-metrics.d.ts.map +1 -0
  114. package/dist/ai-service/builder-runtime-auth-metrics.js +40 -0
  115. package/dist/ai-service/builder-runtime-auth-metrics.js.map +1 -0
  116. package/dist/ai-service/builder-runtime-auth.d.ts +53 -0
  117. package/dist/ai-service/builder-runtime-auth.d.ts.map +1 -0
  118. package/dist/ai-service/builder-runtime-auth.js +166 -0
  119. package/dist/ai-service/builder-runtime-auth.js.map +1 -0
  120. package/dist/ai-service/builder-runtime.d.ts +201 -23
  121. package/dist/ai-service/builder-runtime.d.ts.map +1 -1
  122. package/dist/ai-service/builder-runtime.js +355 -109
  123. package/dist/ai-service/builder-runtime.js.map +1 -1
  124. package/dist/ai-service/builder-skills-auth.d.ts +16 -0
  125. package/dist/ai-service/builder-skills-auth.d.ts.map +1 -0
  126. package/dist/ai-service/builder-skills-auth.js +107 -0
  127. package/dist/ai-service/builder-skills-auth.js.map +1 -0
  128. package/dist/ai-service/builder-subagents.d.ts +37 -0
  129. package/dist/ai-service/builder-subagents.d.ts.map +1 -0
  130. package/dist/ai-service/builder-subagents.js +103 -0
  131. package/dist/ai-service/builder-subagents.js.map +1 -0
  132. package/dist/ai-service/builder-tool-callbacks.d.ts.map +1 -1
  133. package/dist/ai-service/builder-tool-callbacks.js +21 -4
  134. package/dist/ai-service/builder-tool-callbacks.js.map +1 -1
  135. package/dist/ai-service/builder-tools.d.ts +11 -7
  136. package/dist/ai-service/builder-tools.d.ts.map +1 -1
  137. package/dist/ai-service/builder-tools.js +89 -34
  138. package/dist/ai-service/builder-tools.js.map +1 -1
  139. package/dist/ai-service/builder-workspace.d.ts +48 -0
  140. package/dist/ai-service/builder-workspace.d.ts.map +1 -1
  141. package/dist/ai-service/builder-workspace.js +139 -19
  142. package/dist/ai-service/builder-workspace.js.map +1 -1
  143. package/dist/ai-service/chat/chat-session-store.d.ts +31 -3
  144. package/dist/ai-service/chat/chat-session-store.d.ts.map +1 -1
  145. package/dist/ai-service/chat/chat-session-store.js +104 -10
  146. package/dist/ai-service/chat/chat-session-store.js.map +1 -1
  147. package/dist/ai-service/context-download.d.ts +4 -2
  148. package/dist/ai-service/context-download.d.ts.map +1 -1
  149. package/dist/ai-service/context-download.js +13 -3
  150. package/dist/ai-service/context-download.js.map +1 -1
  151. package/dist/ai-service/demo-agents/api-tools.d.ts +14 -0
  152. package/dist/ai-service/demo-agents/api-tools.d.ts.map +1 -0
  153. package/dist/ai-service/demo-agents/api-tools.js +58 -0
  154. package/dist/ai-service/demo-agents/api-tools.js.map +1 -0
  155. package/dist/ai-service/demo-agents/enabled.d.ts +7 -0
  156. package/dist/ai-service/demo-agents/enabled.d.ts.map +1 -0
  157. package/dist/ai-service/demo-agents/enabled.js +8 -0
  158. package/dist/ai-service/demo-agents/enabled.js.map +1 -0
  159. package/dist/ai-service/demo-agents/handlers.d.ts +77 -0
  160. package/dist/ai-service/demo-agents/handlers.d.ts.map +1 -0
  161. package/dist/ai-service/demo-agents/handlers.js +95 -0
  162. package/dist/ai-service/demo-agents/handlers.js.map +1 -0
  163. package/dist/ai-service/demo-agents/load-agents.d.ts +9 -0
  164. package/dist/ai-service/demo-agents/load-agents.d.ts.map +1 -0
  165. package/dist/ai-service/demo-agents/load-agents.js +76 -0
  166. package/dist/ai-service/demo-agents/load-agents.js.map +1 -0
  167. package/dist/ai-service/demo-agents/run-agent.d.ts +39 -0
  168. package/dist/ai-service/demo-agents/run-agent.d.ts.map +1 -0
  169. package/dist/ai-service/demo-agents/run-agent.js +119 -0
  170. package/dist/ai-service/demo-agents/run-agent.js.map +1 -0
  171. package/dist/ai-service/demo-agents/sessions.d.ts +5 -0
  172. package/dist/ai-service/demo-agents/sessions.d.ts.map +1 -0
  173. package/dist/ai-service/demo-agents/sessions.js +33 -0
  174. package/dist/ai-service/demo-agents/sessions.js.map +1 -0
  175. package/dist/ai-service/demo-agents/system-prompt.d.ts +12 -0
  176. package/dist/ai-service/demo-agents/system-prompt.d.ts.map +1 -0
  177. package/dist/ai-service/demo-agents/system-prompt.js +56 -0
  178. package/dist/ai-service/demo-agents/system-prompt.js.map +1 -0
  179. package/dist/ai-service/demo-agents/types.d.ts +95 -0
  180. package/dist/ai-service/demo-agents/types.d.ts.map +1 -0
  181. package/dist/ai-service/demo-agents/types.js +15 -0
  182. package/dist/ai-service/demo-agents/types.js.map +1 -0
  183. package/dist/ai-service/features.d.ts +11 -0
  184. package/dist/ai-service/features.d.ts.map +1 -1
  185. package/dist/ai-service/features.js +11 -0
  186. package/dist/ai-service/features.js.map +1 -1
  187. package/dist/ai-service/index.d.ts +202 -4
  188. package/dist/ai-service/index.d.ts.map +1 -1
  189. package/dist/ai-service/index.js +1020 -104
  190. package/dist/ai-service/index.js.map +1 -1
  191. package/dist/ai-service/judge/tools/playwright-action.d.ts +5 -5
  192. package/dist/ai-service/llm/context-v2/compaction/server-side.d.ts +5 -1
  193. package/dist/ai-service/llm/context-v2/compaction/server-side.d.ts.map +1 -1
  194. package/dist/ai-service/llm/context-v2/compaction/server-side.js +9 -2
  195. package/dist/ai-service/llm/context-v2/compaction/server-side.js.map +1 -1
  196. package/dist/ai-service/llm/context-v2/context-management.d.ts +5 -0
  197. package/dist/ai-service/llm/context-v2/context-management.d.ts.map +1 -1
  198. package/dist/ai-service/llm/context-v2/context-management.js +3 -0
  199. package/dist/ai-service/llm/context-v2/context-management.js.map +1 -1
  200. package/dist/ai-service/llm/context-v2/context-metrics.d.ts.map +1 -1
  201. package/dist/ai-service/llm/context-v2/context-metrics.js +3 -2
  202. package/dist/ai-service/llm/context-v2/context-metrics.js.map +1 -1
  203. package/dist/ai-service/llm/context-v2/manager.d.ts +2 -1
  204. package/dist/ai-service/llm/context-v2/manager.d.ts.map +1 -1
  205. package/dist/ai-service/llm/context-v2/manager.js +12 -1
  206. package/dist/ai-service/llm/context-v2/manager.js.map +1 -1
  207. package/dist/ai-service/llm/context-v2/types.d.ts +10 -0
  208. package/dist/ai-service/llm/context-v2/types.d.ts.map +1 -1
  209. package/dist/ai-service/llm/context-v2/types.js +43 -8
  210. package/dist/ai-service/llm/context-v2/types.js.map +1 -1
  211. package/dist/ai-service/llm/error.d.ts +16 -0
  212. package/dist/ai-service/llm/error.d.ts.map +1 -1
  213. package/dist/ai-service/llm/error.js +69 -0
  214. package/dist/ai-service/llm/error.js.map +1 -1
  215. package/dist/ai-service/llm/stream/config.d.ts +2 -2
  216. package/dist/ai-service/llm/stream/config.d.ts.map +1 -1
  217. package/dist/ai-service/llm/stream/config.js +6 -4
  218. package/dist/ai-service/llm/stream/config.js.map +1 -1
  219. package/dist/ai-service/llm/stream/observers/retry-notification.d.ts.map +1 -1
  220. package/dist/ai-service/llm/stream/observers/retry-notification.js +8 -1
  221. package/dist/ai-service/llm/stream/observers/retry-notification.js.map +1 -1
  222. package/dist/ai-service/llm/stream/orchestrator.d.ts +1 -0
  223. package/dist/ai-service/llm/stream/orchestrator.d.ts.map +1 -1
  224. package/dist/ai-service/llm/stream/orchestrator.js +53 -1
  225. package/dist/ai-service/llm/stream/orchestrator.js.map +1 -1
  226. package/dist/ai-service/llm/stream/retry-engine.d.ts +3 -1
  227. package/dist/ai-service/llm/stream/retry-engine.d.ts.map +1 -1
  228. package/dist/ai-service/llm/stream/retry-engine.js +21 -4
  229. package/dist/ai-service/llm/stream/retry-engine.js.map +1 -1
  230. package/dist/ai-service/llm/stream/retry-schedule.d.ts +27 -0
  231. package/dist/ai-service/llm/stream/retry-schedule.d.ts.map +1 -0
  232. package/dist/ai-service/llm/stream/retry-schedule.js +28 -0
  233. package/dist/ai-service/llm/stream/retry-schedule.js.map +1 -0
  234. package/dist/ai-service/llm/stream/session.d.ts +2 -0
  235. package/dist/ai-service/llm/stream/session.d.ts.map +1 -1
  236. package/dist/ai-service/llm/stream/session.js +2 -0
  237. package/dist/ai-service/llm/stream/session.js.map +1 -1
  238. package/dist/ai-service/llm/terminal-error-message.d.ts +67 -0
  239. package/dist/ai-service/llm/terminal-error-message.d.ts.map +1 -0
  240. package/dist/ai-service/llm/terminal-error-message.js +154 -0
  241. package/dist/ai-service/llm/terminal-error-message.js.map +1 -0
  242. package/dist/ai-service/native-secret-redactor.js +1 -1
  243. package/dist/ai-service/native-secret-redactor.js.map +1 -1
  244. package/dist/ai-service/native-turn-failure.d.ts +35 -0
  245. package/dist/ai-service/native-turn-failure.d.ts.map +1 -0
  246. package/dist/ai-service/native-turn-failure.js +149 -0
  247. package/dist/ai-service/native-turn-failure.js.map +1 -0
  248. package/dist/ai-service/outbound-trace-context.d.ts +18 -0
  249. package/dist/ai-service/outbound-trace-context.d.ts.map +1 -0
  250. package/dist/ai-service/outbound-trace-context.js +20 -0
  251. package/dist/ai-service/outbound-trace-context.js.map +1 -0
  252. package/dist/ai-service/policy-gate-review.d.ts +18 -3
  253. package/dist/ai-service/policy-gate-review.d.ts.map +1 -1
  254. package/dist/ai-service/policy-gate-review.js +32 -10
  255. package/dist/ai-service/policy-gate-review.js.map +1 -1
  256. package/dist/ai-service/security/secret-scanner-service.d.ts +2 -1
  257. package/dist/ai-service/security/secret-scanner-service.d.ts.map +1 -1
  258. package/dist/ai-service/security/secret-scanner-service.js +60 -9
  259. package/dist/ai-service/security/secret-scanner-service.js.map +1 -1
  260. package/dist/ai-service/security/secret-scanner.d.ts +17 -16
  261. package/dist/ai-service/security/secret-scanner.d.ts.map +1 -1
  262. package/dist/ai-service/security/secret-scanner.js +91 -159
  263. package/dist/ai-service/security/secret-scanner.js.map +1 -1
  264. package/dist/ai-service/security/trufflehog-diagnostics.d.ts +17 -0
  265. package/dist/ai-service/security/trufflehog-diagnostics.d.ts.map +1 -0
  266. package/dist/ai-service/security/trufflehog-diagnostics.js +20 -0
  267. package/dist/ai-service/security/trufflehog-diagnostics.js.map +1 -0
  268. package/dist/ai-service/security/trufflehog-process.d.ts +80 -0
  269. package/dist/ai-service/security/trufflehog-process.d.ts.map +1 -0
  270. package/dist/ai-service/security/trufflehog-process.js +305 -0
  271. package/dist/ai-service/security/trufflehog-process.js.map +1 -0
  272. package/dist/ai-service/state-machine/clark-fsm.d.ts +3 -0
  273. package/dist/ai-service/state-machine/clark-fsm.d.ts.map +1 -1
  274. package/dist/ai-service/state-machine/clark-fsm.js.map +1 -1
  275. package/dist/ai-service/state-machine/handlers/agent-planning.d.ts +0 -12
  276. package/dist/ai-service/state-machine/handlers/agent-planning.d.ts.map +1 -1
  277. package/dist/ai-service/state-machine/handlers/agent-planning.js +3 -121
  278. package/dist/ai-service/state-machine/handlers/agent-planning.js.map +1 -1
  279. package/dist/ai-service/state-machine/handlers/idle.d.ts.map +1 -1
  280. package/dist/ai-service/state-machine/handlers/idle.js +3 -2
  281. package/dist/ai-service/state-machine/handlers/idle.js.map +1 -1
  282. package/dist/ai-service/state-machine/handlers/llm-generating.d.ts.map +1 -1
  283. package/dist/ai-service/state-machine/handlers/llm-generating.js +27 -11
  284. package/dist/ai-service/state-machine/handlers/llm-generating.js.map +1 -1
  285. package/dist/ai-service/state-machine/helpers/stable-peer.d.ts.map +1 -1
  286. package/dist/ai-service/state-machine/helpers/stable-peer.js +14 -5
  287. package/dist/ai-service/state-machine/helpers/stable-peer.js.map +1 -1
  288. package/dist/ai-service/types.d.ts +2 -0
  289. package/dist/ai-service/types.d.ts.map +1 -1
  290. package/dist/ai-service/types.js.map +1 -1
  291. package/dist/ai-service/workspace-metrics.d.ts +1 -0
  292. package/dist/ai-service/workspace-metrics.d.ts.map +1 -1
  293. package/dist/ai-service/workspace-metrics.js +14 -1
  294. package/dist/ai-service/workspace-metrics.js.map +1 -1
  295. package/dist/attachment-artifacts.d.ts +4 -0
  296. package/dist/attachment-artifacts.d.ts.map +1 -0
  297. package/dist/attachment-artifacts.js +4 -0
  298. package/dist/attachment-artifacts.js.map +1 -0
  299. package/dist/dev-server-ws-smoke-client.d.ts.map +1 -1
  300. package/dist/dev-server-ws-smoke-client.js +1 -0
  301. package/dist/dev-server-ws-smoke-client.js.map +1 -1
  302. package/dist/file-sync-vite-plugin.d.ts.map +1 -1
  303. package/dist/file-sync-vite-plugin.js +51 -2
  304. package/dist/file-sync-vite-plugin.js.map +1 -1
  305. package/dist/git-service/credential-scope.d.ts +1 -0
  306. package/dist/git-service/credential-scope.d.ts.map +1 -1
  307. package/dist/git-service/credential-scope.js +56 -1
  308. package/dist/git-service/credential-scope.js.map +1 -1
  309. package/dist/index.d.ts +9 -0
  310. package/dist/index.d.ts.map +1 -1
  311. package/dist/index.js +5 -0
  312. package/dist/index.js.map +1 -1
  313. package/dist/inject-index-vite-plugin.d.ts.map +1 -1
  314. package/dist/inject-index-vite-plugin.js +2 -0
  315. package/dist/inject-index-vite-plugin.js.map +1 -1
  316. package/dist/injected-index.d.ts.map +1 -1
  317. package/dist/injected-index.js +2 -0
  318. package/dist/injected-index.js.map +1 -1
  319. package/dist/lock-service/branch-metrics.d.ts +3 -0
  320. package/dist/lock-service/branch-metrics.d.ts.map +1 -0
  321. package/dist/lock-service/branch-metrics.js +15 -0
  322. package/dist/lock-service/branch-metrics.js.map +1 -0
  323. package/dist/lock-service/index.d.ts +9 -0
  324. package/dist/lock-service/index.d.ts.map +1 -1
  325. package/dist/lock-service/index.js +55 -7
  326. package/dist/lock-service/index.js.map +1 -1
  327. package/dist/plugin-options.d.ts +7 -7
  328. package/dist/plugin-options.d.ts.map +1 -1
  329. package/dist/policy-gate-live-step.d.ts +25 -0
  330. package/dist/policy-gate-live-step.d.ts.map +1 -0
  331. package/dist/policy-gate-live-step.js +197 -0
  332. package/dist/policy-gate-live-step.js.map +1 -0
  333. package/dist/policy-gate-run-registry.d.ts +10 -0
  334. package/dist/policy-gate-run-registry.d.ts.map +1 -1
  335. package/dist/policy-gate-run-registry.js +28 -0
  336. package/dist/policy-gate-run-registry.js.map +1 -1
  337. package/dist/policy-gate-runner.d.ts +9 -1
  338. package/dist/policy-gate-runner.d.ts.map +1 -1
  339. package/dist/policy-gate-runner.js +100 -36
  340. package/dist/policy-gate-runner.js.map +1 -1
  341. package/dist/policy-gates/authorization.d.ts +9 -0
  342. package/dist/policy-gates/authorization.d.ts.map +1 -0
  343. package/dist/policy-gates/authorization.js +12 -0
  344. package/dist/policy-gates/authorization.js.map +1 -0
  345. package/dist/policy-gates/index.d.ts +5 -0
  346. package/dist/policy-gates/index.d.ts.map +1 -0
  347. package/dist/policy-gates/index.js +4 -0
  348. package/dist/policy-gates/index.js.map +1 -0
  349. package/dist/policy-gates/metrics.d.ts +23 -0
  350. package/dist/policy-gates/metrics.d.ts.map +1 -0
  351. package/dist/policy-gates/metrics.js +19 -0
  352. package/dist/policy-gates/metrics.js.map +1 -0
  353. package/dist/project-agent-tools.d.ts +23 -0
  354. package/dist/project-agent-tools.d.ts.map +1 -0
  355. package/dist/project-agent-tools.js +73 -0
  356. package/dist/project-agent-tools.js.map +1 -0
  357. package/dist/project-functions.d.ts +19 -0
  358. package/dist/project-functions.d.ts.map +1 -0
  359. package/dist/project-functions.js +70 -0
  360. package/dist/project-functions.js.map +1 -0
  361. package/dist/project-manifest.d.ts +150 -0
  362. package/dist/project-manifest.d.ts.map +1 -0
  363. package/dist/project-manifest.js +284 -0
  364. package/dist/project-manifest.js.map +1 -0
  365. package/dist/review-runner.d.ts.map +1 -1
  366. package/dist/review-runner.js +12 -14
  367. package/dist/review-runner.js.map +1 -1
  368. package/dist/socket-manager.d.ts +2 -1
  369. package/dist/socket-manager.d.ts.map +1 -1
  370. package/dist/socket-manager.js +162 -6
  371. package/dist/socket-manager.js.map +1 -1
  372. package/dist/sync-service/index.d.ts.map +1 -1
  373. package/dist/sync-service/index.js +2 -0
  374. package/dist/sync-service/index.js.map +1 -1
  375. package/dist/workspace-sync-methods.d.ts +21 -1
  376. package/dist/workspace-sync-methods.d.ts.map +1 -1
  377. package/package.json +17 -21
  378. package/dist/agent-tool-executor/claude-sandbox-placeholders.d.ts +0 -38
  379. package/dist/agent-tool-executor/claude-sandbox-placeholders.d.ts.map +0 -1
  380. package/dist/agent-tool-executor/claude-sandbox-placeholders.js +0 -132
  381. package/dist/agent-tool-executor/claude-sandbox-placeholders.js.map +0 -1
  382. package/dist/ai-service/skills/system/native.d.ts +0 -15
  383. package/dist/ai-service/skills/system/native.d.ts.map +0 -1
  384. package/dist/ai-service/skills/system/native.js +0 -32
  385. package/dist/ai-service/skills/system/native.js.map +0 -1
  386. package/dist/native-system-skills.d.ts +0 -2
  387. package/dist/native-system-skills.d.ts.map +0 -1
  388. package/dist/native-system-skills.js +0 -4
  389. package/dist/native-system-skills.js.map +0 -1
@@ -1,14 +1,16 @@
1
- import { randomUUID } from "node:crypto";
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdtemp, rm } from "node:fs/promises";
2
3
  import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { context as otelContext, metrics, propagation, SpanKind, SpanStatusCode, trace, } from "@opentelemetry/api";
5
6
  import { z } from "zod";
6
7
  import { AiGenerationState, AiMode, resolveAttachmentFileName, } from "@superblocksteam/library-shared/types";
7
8
  import { isToolPermissionClarification } from "@superblocksteam/library-shared/types/tool-permission-response";
8
- import { addTracingToMethods, BuilderCaller, AiSystemTriggerType, classifyAttachmentDelivery, FactAccessType, FactCreatedSource, FactEntityScope, isAiAbandonTurnState, TracedEventEmitter, getAiQuotaPaywallReasonFromMessage, } from "@superblocksteam/shared";
9
- import { HarnessTrace, npmRegistryEmitter } from "@superblocksteam/telemetry";
9
+ import { addTracingToMethods, BuilderCaller, AiSystemTriggerType, classifyAttachmentDelivery, FactAccessType, FactCreatedSource, FactEntityScope, isAiAbandonTurnState, TracedEventEmitter, getAiQuotaPaywallReasonFromMessage, isAiQuotaPaywallReason, CHAT_CHANGED_ELSEWHERE_MESSAGE, EDITOR_RESTART_REQUIRED_MESSAGE, isChatChangedElsewhereError, } from "@superblocksteam/shared";
10
+ import { AgentSessionTrace, HarnessTrace, npmRegistryEmitter, TraceCorrelation, } from "@superblocksteam/telemetry";
10
11
  import { applyTestApiDenialSideEffects, buildMigrationTestApiDenialContinuationPrompt, } from "../migration/mark-api-testing-denied.js";
11
12
  import { buildTranslationPrompt } from "../migration/translation-prompt.js";
13
+ import { recordAgentStepDelivery } from "../policy-gate-live-step.js";
12
14
  import { POLICY_GATE_RUN_IN_PROGRESS_ERROR, policyGateRunRegistry, } from "../policy-gate-run-registry.js";
13
15
  import { GenerationWaitTimeoutError } from "../util/generation-wait-timeout-error.js";
14
16
  import { escapeTagDelimiters } from "../util/log-sanitizer.js";
@@ -34,13 +36,17 @@ import { NpmRegistryClient, createDiskRegistryPolicyStore, } from "./app-interfa
34
36
  import { AppShell } from "./app-interface/shell.js";
35
37
  import { AppSkillsManager } from "./app-skills/manager.js";
36
38
  import { recordAttachmentLabelTruncated } from "./attachment-label-metrics.js";
39
+ import { NativeAttachmentPreparations } from "./attachments/native-attachment-preparations.js";
37
40
  import { parseDataUrl } from "./attachments/parse-data-url.js";
38
41
  import { isUploadedAttachment, toUploadedAttachmentContentPart, } from "./attachments/uploaded-content-part.js";
42
+ import { resolveAttachmentHistory, resolvePromptAttachments, } from "./attachments/validate-prompt-attachments.js";
39
43
  import { BuilderConversation } from "./builder-conversation.js";
40
44
  import { BuilderInferenceAuth } from "./builder-inference-auth.js";
45
+ import { BuilderRuntimeAuth } from "./builder-runtime-auth.js";
41
46
  import { BuilderRuntimeError, } from "./builder-runtime.js";
47
+ import { BuilderSkillsAuth } from "./builder-skills-auth.js";
42
48
  import { NativeBuilderToolHost } from "./builder-tools.js";
43
- import { WorkspaceRuntimeClient, } from "./builder-workspace.js";
49
+ import { WorkspaceDowngradedError, WorkspaceRuntimeClient, } from "./builder-workspace.js";
44
50
  import { recordChatSessionIdLookup } from "./chat/chat-session-store-metrics.js";
45
51
  import { ChatSessionStore } from "./chat/chat-session-store.js";
46
52
  import { seedMessagesFromTranscript } from "./chat/switch-chat-seed.js";
@@ -52,6 +58,8 @@ import { downloadContextFromBucketeer, downloadLatestContextFromBucketeer, resto
52
58
  import { restoreConversationToCheckpoint, } from "./context-restore.js";
53
59
  import { uploadContextToBucketeer } from "./context-upload.js";
54
60
  import { AppContextStore } from "./context/app-context.js";
61
+ import { projectAgentsEnabled } from "./demo-agents/enabled.js";
62
+ import { handleAgentList, handleAgentResetSession, handleAgentRun, handleAgentSetTool, handleRemoteAgentRun, } from "./demo-agents/handlers.js";
55
63
  import { createDevDatabaseHttpTransport, DevDatabaseClient, } from "./dev-database-client.js";
56
64
  import { buildEnsureDevDatabaseFilesSynced, } from "./dev-database-file-sync.js";
57
65
  import { EditAfterClarkTracker } from "./edit-after-clark.js";
@@ -87,7 +95,7 @@ import { buildServerMigrationLlmConfig, isMigrationAutoDispatchEnabled, } from "
87
95
  import { isMigrationSessionActive } from "./migration-session-active.js";
88
96
  import { hasSettledNormalMigrationTurn, recordMigrationTurnDispatched, recordMigrationTurnSettled, } from "./migration-turns-log.js";
89
97
  import { buildPolicyGateRemediationUsageMetadata } from "./policy-gate-remediation-usage.js";
90
- import { runPolicyGateReview, } from "./policy-gate-review.js";
98
+ import { createReviewAppShell, runPolicyGateReview, } from "./policy-gate-review.js";
91
99
  import { ClarkProfiler } from "./profiler/clark-profiler.js";
92
100
  import { buildSummarizeApiUsagePrompt } from "./prompts/summarize-api-usage.js";
93
101
  import { buildSummarizeDestructiveMigrationPrompt } from "./prompts/summarize-destructive-migration.js";
@@ -126,6 +134,7 @@ import { buildModelConfigAttributes, processOneShotLLMConfig, } from "./util/llm
126
134
  import { parseJwt } from "./util/parse-jwt.js";
127
135
  import { PERMISSION_PROMPT_DELIVERY_TIMEOUT_MS, PERMISSION_PROMPT_RESPONSE_TIMEOUT_MS, } from "./util/rpc-timeout.js";
128
136
  import { getToolCallSignature } from "./util/tool-signature.js";
137
+ import { readWorkspaceIngress } from "./workspace-edge-health.js";
129
138
  import { rpcWorkspaceMirrorSource, WorkspaceMirror, } from "./workspace-mirror.js";
130
139
  export { AiServiceFeatureFlags } from "./features.js";
131
140
  export { WorkspaceDowngradedError } from "./builder-workspace.js";
@@ -135,7 +144,6 @@ export { stripResolvedFromLockfile } from "./app-interface/npm-registry.js";
135
144
  export { isPeerUnavailableError } from "./state-machine/helpers/stable-peer.js";
136
145
  export { SnapshotManager } from "./recording/index.js";
137
146
  export { isSdkApiTemplate } from "./sdk-api-templates.js";
138
- export { NativeSystemSkills } from "./skills/system/native.js";
139
147
  /**
140
148
  * APPS-4370. Build the disk-backed `LastKnownRegistryPolicyStore` the
141
149
  * production `AiService` wires into its default `NpmRegistryClient`.
@@ -196,6 +204,31 @@ export function estimateSize(obj) {
196
204
  * not-configured rather than crashing the install path.
197
205
  */
198
206
  const NPM_REGISTRY_JWT_WAIT_MS = 5_000;
207
+ /** How long the AI process waits for a restarted sidecar to come back as the workspace edge, and how often it looks. */
208
+ const SIDECAR_RESTART_TIMEOUT_MS = 3 * 60_000;
209
+ const SIDECAR_RESTART_POLL_MS = 1_000;
210
+ /** The longest wait between attempts to open the workspace after a restart, while the restart deadline allows. */
211
+ const WORKSPACE_REOPEN_MAX_BACKOFF_MS = 30_000;
212
+ /** Refuses a harness, model, or chat switch while the sidecar has not finished the restart an earlier switch asked for. */
213
+ const EDITOR_STILL_RESTARTING_MESSAGE = "The editor is still restarting from your last switch. Try again in a moment.";
214
+ const STALE_BINDING_MESSAGE = "This editor lost track of the active chat. Reload the editor and try again.";
215
+ const STALE_BINDING_AUTH_MESSAGE = "This editor could not reach the dev server after it restarted. Reload the page and try again.";
216
+ /** True when an error, or any error in its cause chain, is a 401 or 403 from a service this process called. */
217
+ function isAuthFailure(error) {
218
+ for (let current = error, depth = 0; current && depth < 8; depth += 1) {
219
+ if (typeof current !== "object")
220
+ return false;
221
+ const { status, statusCode, response, message, cause } = current;
222
+ const code = status ?? statusCode ?? response?.status;
223
+ if (code === 401 || code === 403)
224
+ return true;
225
+ if (typeof message === "string" &&
226
+ /\b(401|403)\b|forbidden|unauthorized/i.test(message))
227
+ return true;
228
+ current = cause;
229
+ }
230
+ return false;
231
+ }
199
232
  /**
200
233
  * How long the npm-registry client will wait for a fresh `tokenUpdated`
201
234
  * event between an HTTP 401 and its retry.
@@ -317,6 +350,27 @@ function toolErrorResult(toolCallId, toolName, error) {
317
350
  ],
318
351
  };
319
352
  }
353
+ let bindingMismatchCounter;
354
+ function builderBindingMismatchCounter() {
355
+ bindingMismatchCounter ??= metrics
356
+ .getMeter("superblocks.ai_service")
357
+ .createCounter("superblocks.ai_service.builder_binding.mismatch", {
358
+ description: "Native prompts whose chat binding no longer matched what this pod selected, or that the server refused",
359
+ unit: "1",
360
+ });
361
+ return bindingMismatchCounter;
362
+ }
363
+ function bindingMatchesRuntime(binding, runtime) {
364
+ return (binding.harness === runtime.harness &&
365
+ (binding.model === undefined || binding.model === runtime.model));
366
+ }
367
+ /** The chat's server binding changed between the pre-turn check and the turn. */
368
+ export class BuilderBindingChangedError extends Error {
369
+ constructor(message = "This chat uses a different harness or model. Reconnect before sending a prompt.") {
370
+ super(message);
371
+ this.name = "BuilderBindingChangedError";
372
+ }
373
+ }
320
374
  export class AiService extends TracedEventEmitter {
321
375
  config;
322
376
  templateRenderer;
@@ -330,10 +384,28 @@ export class AiService extends TracedEventEmitter {
330
384
  _logger;
331
385
  clark;
332
386
  builderConversation;
387
+ nativeAttachmentPreparations;
388
+ nativeCancellationVersion;
333
389
  builderBinding;
390
+ /** See {@link builderRuntimeAccess}. */
391
+ runtimeAccess;
334
392
  activeBuilderRuntime;
393
+ /**
394
+ * A harness switch moved the server to a new chat but this pod did not follow it. The next prompt reselects first:
395
+ * a Clark pod otherwise never re-reads the binding, and would keep running Clark in a native chat.
396
+ */
397
+ builderBindingStale = false;
398
+ /** Set while a harness switch moves the server and this pod to a new chat; prompts wait for it to finish. */
399
+ builderSwitchInProgress = false;
400
+ /**
401
+ * Prompts past the switch check but whose turn has not started yet. They await a server round trip before the
402
+ * conversation reports busy, so a switch counts them as a running turn.
403
+ */
404
+ promptsBeingAdmitted = 0;
335
405
  /** The branch `builderBinding` was resolved for. */
336
406
  builderBranch;
407
+ /** The binding the pre-turn check resolved, which that request's turn uses instead of resolving again. */
408
+ checkedBinding;
337
409
  workspaceClient;
338
410
  workspaceMirror;
339
411
  /** The newest DBFS hash the VM reported for the current workspace. */
@@ -347,6 +419,7 @@ export class AiService extends TracedEventEmitter {
347
419
  */
348
420
  workspaceTurnFinish;
349
421
  nativeBuilderJwt;
422
+ nativeInferenceTurn;
350
423
  nativePromptAttempt;
351
424
  clarkProfiler;
352
425
  chatSessionStore;
@@ -357,6 +430,7 @@ export class AiService extends TracedEventEmitter {
357
430
  });
358
431
  }, () => this.chatSessionStore.getChatSessionId());
359
432
  contextManagerV2;
433
+ reviewAppShell;
360
434
  llmClient;
361
435
  stablePeer = new StablePeer({
362
436
  currentRequestKey: () => this.builderConversation
@@ -600,8 +674,15 @@ export class AiService extends TracedEventEmitter {
600
674
  return false;
601
675
  }
602
676
  getLogger().info("[ai-service] Accepted a new inference JWT");
677
+ const firstJwt = !this.nativeBuilderJwt;
678
+ // Kept in Clark mode too, so a native builder started later has the
679
+ // editor's JWT for its first workspace open without reading Clark's state.
680
+ this.nativeBuilderJwt = jwt;
603
681
  if (this.builderConversation) {
604
- this.nativeBuilderJwt = jwt;
682
+ // The background open at binding time needs a JWT to mint its runtime
683
+ // token; when none had arrived yet, start it now.
684
+ if (firstJwt && this.builderBinding)
685
+ this.openWorkspaceInBackground(this.builderBinding, this.builderBranch ?? "main");
605
686
  return true;
606
687
  }
607
688
  const hadUser = this.getContextId() !== null;
@@ -664,9 +745,53 @@ export class AiService extends TracedEventEmitter {
664
745
  hasConnectedPeer() {
665
746
  return this.stablePeer?.peerId != null;
666
747
  }
748
+ /** Pushes one live agent step to the open editor and reports whether it arrived. */
749
+ async pushPolicyAgentStep(step) {
750
+ let outcome = "dropped";
751
+ if (this.hasConnectedPeer()) {
752
+ try {
753
+ await this.stablePeer.call.aiPushPolicyAgentStep(step);
754
+ outcome = "forwarded";
755
+ }
756
+ catch (error) {
757
+ this.getLogger().warn("[ai-service] Failed to push policy agent step", getErrorMeta(error));
758
+ outcome = "failed";
759
+ }
760
+ }
761
+ recordAgentStepDelivery(outcome);
762
+ return outcome;
763
+ }
667
764
  get builderRuntime() {
668
765
  return this.activeBuilderRuntime ?? this.config.builderRuntime;
669
766
  }
767
+ /**
768
+ * The runtime whose native agent may call back into this pod's tools, or undefined while the chat runs on Clark. A
769
+ * pod that started on a native harness still holds that startup runtime after a switch to Clark, so its callback
770
+ * token and tool host must stop answering until a native chat is bound again.
771
+ */
772
+ get agentToolRuntime() {
773
+ return this.builderConversation ? this.builderRuntime : undefined;
774
+ }
775
+ /**
776
+ * The harnesses this pod can run, or undefined when its host did not say. Clark always runs; Codex and Claude need a
777
+ * split live-edit pod with their AgentCore runtime configured.
778
+ */
779
+ getRunnableHarnesses() {
780
+ const native = this.config.nativeHarnesses;
781
+ return native ? ["clark", ...native] : undefined;
782
+ }
783
+ /** A runtime for the native harness, or undefined when this pod cannot run it. */
784
+ runtimeForHarness(harness) {
785
+ if (this.builderRuntime?.harness === harness)
786
+ return this.builderRuntime;
787
+ try {
788
+ return this.config.builderRuntimeForHarness?.(harness);
789
+ }
790
+ catch (error) {
791
+ this.getLogger().info(`[builder-runtime] This pod cannot run ${harness}`, getErrorMeta(error));
792
+ return undefined;
793
+ }
794
+ }
670
795
  constructor(config) {
671
796
  super(config.tracer);
672
797
  this.config = config;
@@ -1005,21 +1130,39 @@ export class AiService extends TracedEventEmitter {
1005
1130
  : this.clark?.context.promptOutcomeDedupeKey);
1006
1131
  // TODO apply isocket error handling
1007
1132
  }
1008
- async selectBuilderSession() {
1009
- const branch = (await this._syncContextProvider?.getBranchName()) ?? "main";
1133
+ /**
1134
+ * `knownBranch` skips asking the dev server for the branch. A model change passes the branch this pod already
1135
+ * follows: the chat does not change, and the dev server may be unreachable while it restarts between placements.
1136
+ */
1137
+ async selectBuilderSession(knownBranch) {
1138
+ const branch = knownBranch ??
1139
+ (await this._syncContextProvider?.getBranchName()) ??
1140
+ "main";
1010
1141
  const binding = await this.chatSessionStore.resolveBuilderBinding(branch, this.config.builderRuntime?.harness ?? "clark");
1011
- if (binding.harness !== "clark" &&
1012
- binding.harness !== this.builderRuntime?.harness) {
1013
- const runtime = this.config.builderRuntimeForHarness?.(binding.harness);
1142
+ const replacesConversation = binding.harness === "clark"
1143
+ ? this.builderConversation !== undefined
1144
+ : binding.harness !== this.builderRuntime?.harness ||
1145
+ (binding.model !== undefined &&
1146
+ binding.model !== this.builderRuntime?.model);
1147
+ // A turn may have started during the lookup; replacing its conversation would orphan it. On a Clark pod that
1148
+ // turn is Clark's own, which the native conversation's busy flag does not see.
1149
+ const clarkTurnRunning = binding.harness !== "clark" &&
1150
+ !this.builderConversation &&
1151
+ this.builderBinding?.harness === "clark" &&
1152
+ (this.generationStarting || this.isClarkMidTurn());
1153
+ if (replacesConversation &&
1154
+ (this.builderConversation?.isBusy || clarkTurnRunning))
1155
+ throw new Error("Wait for the running turn to finish");
1156
+ if (binding.harness !== "clark") {
1157
+ // Resolve the runtime before changing anything: a lookup or model failure must leave this pod on the chat it
1158
+ // was running, not halfway off it with no native conversation, which callers read as Clark.
1159
+ let runtime = this.runtimeForHarness(binding.harness);
1014
1160
  if (!runtime)
1015
1161
  throw new Error("This chat's native builder runtime is unavailable.");
1016
- this.activeBuilderRuntime = runtime;
1017
- this.builderConversation = undefined;
1018
- }
1019
- if (binding.harness !== "clark" && binding.model !== undefined) {
1020
- const runtime = this.builderRuntime;
1021
- if (runtime.model !== binding.model) {
1022
- this.activeBuilderRuntime = runtime.withModel(binding.model);
1162
+ if (binding.model !== undefined && runtime.model !== binding.model)
1163
+ runtime = runtime.withModel(binding.model);
1164
+ if (runtime !== this.builderRuntime) {
1165
+ this.activeBuilderRuntime = runtime;
1023
1166
  this.builderConversation = undefined;
1024
1167
  }
1025
1168
  }
@@ -1031,7 +1174,7 @@ export class AiService extends TracedEventEmitter {
1031
1174
  // Start the VM as soon as placement is known so its cold start overlaps
1032
1175
  // the editor loading; the first turn awaits the same open.
1033
1176
  if (binding.workspace?.placement === "agentcore")
1034
- this.ensureWorkspace(binding, branch).catch((error) => this.getLogger().warn("[workspace] Background workspace open failed; the next turn retries", getErrorMeta(error)));
1177
+ this.openWorkspaceInBackground(binding, branch);
1035
1178
  else
1036
1179
  this.closeWorkspace();
1037
1180
  }
@@ -1041,6 +1184,59 @@ export class AiService extends TracedEventEmitter {
1041
1184
  this.builderConversation = undefined;
1042
1185
  this.initializeClark();
1043
1186
  }
1187
+ this.builderBindingStale = false;
1188
+ this.pushBuilderSelection();
1189
+ }
1190
+ /**
1191
+ * Follows a binding a failed chat change left behind, once no turn is running. Landing on Clark from a native
1192
+ * harness starts Clark from the active chat, as a successful change does, not from whatever Clark last held.
1193
+ */
1194
+ async recoverStaleBuilderBinding(knownBranch) {
1195
+ if (this.isBusy())
1196
+ return;
1197
+ const wasNative = this.builderConversation !== undefined;
1198
+ // A failed reselect leaves the binding on the previous chat, so a new chat id means Clark was never seeded for it.
1199
+ const previousChat = this.builderBinding?.chatSessionId;
1200
+ await this.selectBuilderSession(knownBranch);
1201
+ if (!this.builderConversation &&
1202
+ (wasNative || this.builderBinding?.chatSessionId !== previousChat)) {
1203
+ this.editAfterClark.reset();
1204
+ this.clearClarkInteractiveState();
1205
+ await this.seedClarkContextFromChat(this._syncContextProvider?.getLastCommitId() ??
1206
+ (await this.chatSessionStore.getLatestCommitId()));
1207
+ }
1208
+ }
1209
+ /** A turn is running, or a prompt is on its way to starting one; a switch now would move it to another chat. */
1210
+ isBusyForBuilderSwitch() {
1211
+ return this.isBusy() || this.promptsBeingAdmitted > 0;
1212
+ }
1213
+ /** A prompt sent while a harness switch is moving to a new chat would run on the old harness in the new chat. */
1214
+ assertNoBuilderSwitchInProgress() {
1215
+ if (this.builderSwitchInProgress)
1216
+ throw new Error("Switching the harness or model. Send your prompt again in a moment.");
1217
+ }
1218
+ /** Tells every editor which harness and model the active chat now runs on. */
1219
+ pushBuilderSelection() {
1220
+ const builderSelection = this.getBuilderSelection();
1221
+ if (!builderSelection)
1222
+ return;
1223
+ catchBackgroundPeerDisconnect(this.stablePeer.call.aiSetBuilderSelection({
1224
+ chatSessionId: this.builderBinding?.chatSessionId,
1225
+ builderSelection,
1226
+ runnableHarnesses: this.getRunnableHarnesses(),
1227
+ }), "builder selection push");
1228
+ }
1229
+ /**
1230
+ * Opens the binding's AgentCore workspace without waiting for it. Opening
1231
+ * needs a JWT to mint the runtime token, so without one it waits for
1232
+ * `updateClarkJwt`; the first turn joins the same open.
1233
+ */
1234
+ openWorkspaceInBackground(binding, branch) {
1235
+ if (binding.workspace?.placement !== "agentcore")
1236
+ return;
1237
+ if (!this.getInferenceJwt())
1238
+ return;
1239
+ this.ensureWorkspace(binding, branch).catch((error) => this.getLogger().warn("[workspace] Background workspace open failed; the next turn retries", getErrorMeta(error)));
1044
1240
  }
1045
1241
  initializeNativeBuilder() {
1046
1242
  const config = this.config;
@@ -1049,7 +1245,6 @@ export class AiService extends TracedEventEmitter {
1049
1245
  this.builderConversation = new BuilderConversation({
1050
1246
  runtime,
1051
1247
  tools: new NativeBuilderToolHost({
1052
- coreModel: runtime.model,
1053
1248
  getJwt: () => this.getClarkJwt(),
1054
1249
  getPackageServices: (request) => ({
1055
1250
  appContextStore: this.appContext,
@@ -1060,16 +1255,19 @@ export class AiService extends TracedEventEmitter {
1060
1255
  llmProvider: createLLMProvider(this.getLLMProviderSettings(request?.llmConfig), () => this.requireProviderInferenceAuthToken(), request?.llmConfig),
1061
1256
  }),
1062
1257
  appShell: this.appShell,
1258
+ assertLocalAppTreeWritable: (action) => this.assertLocalAppTreeWritable(action),
1063
1259
  ensureFilesSynced: async () => {
1064
1260
  const sync = this._runtimeSyncService;
1065
1261
  if (!sync?.syncCurrentDirectoryWithDraftsNow)
1066
1262
  throw new Error("Native builder DEV sync service is unavailable");
1067
1263
  const synced = await sync.syncCurrentDirectoryWithDraftsNow("requestedFilesSync");
1264
+ if (!synced?.directoryHash)
1265
+ throw new Error("Native builder file sync did not return a directory hash");
1068
1266
  // testApi reads the tree here: in agentcore placement, bring the
1069
1267
  // mirror up to what the VM just synced.
1070
- if (this.isWorkspacePlacement &&
1071
- typeof synced?.directoryHash === "string")
1072
- await this.mirrorWorkspaceHash(synced.directoryHash);
1268
+ if (this.isWorkspacePlacement)
1269
+ await this.refreshWorkspaceMirror(synced.directoryHash);
1270
+ return synced.directoryHash;
1073
1271
  },
1074
1272
  features: config.features,
1075
1273
  agentType: config.agentType,
@@ -1111,7 +1309,7 @@ export class AiService extends TracedEventEmitter {
1111
1309
  .aiSetDraftState({ hasDraft })
1112
1310
  .catch((error) => this.getLogger().warn("Failed to publish native draft state", getErrorMeta(error)));
1113
1311
  },
1114
- onSettled: (generationId, error) => {
1312
+ onSettled: (generationId, error, cancelled) => {
1115
1313
  const attempt = this.nativePromptAttempt;
1116
1314
  if (attempt?.generationId === generationId) {
1117
1315
  this.nativePromptAttempt = undefined;
@@ -1128,10 +1326,12 @@ export class AiService extends TracedEventEmitter {
1128
1326
  streakEligible: true,
1129
1327
  });
1130
1328
  }
1131
- this.activeGenerationTrace?.finish(error);
1329
+ this.endNativeInferenceTurn(generationId);
1330
+ this.activeGenerationTrace?.finish(cancelled ? "cancelled" : error ? "failed" : "completed", error);
1132
1331
  this.triggerGenerationComplete(generationId);
1133
1332
  },
1134
- onError: (error) => BuilderRuntimeError.log(error, this.getLogger()),
1333
+ onError: (error, attempt) => BuilderRuntimeError.log(error, this.getLogger(), attempt),
1334
+ checkPaywall: () => this.nativePaywallReason(),
1135
1335
  });
1136
1336
  }
1137
1337
  }
@@ -1459,12 +1659,20 @@ export class AiService extends TracedEventEmitter {
1459
1659
  // A span still open here means the previous run never reached a terminal
1460
1660
  // transition. Close it now so its listeners cannot fire on this run's
1461
1661
  // events.
1462
- this.activeGenerationTrace?.finish();
1662
+ this.activeGenerationTrace?.finish("abandoned");
1463
1663
  const runtime = this.builderConversation ? this.builderRuntime : undefined;
1464
- const parentContext = HarnessTrace.context(runtime?.harness ?? "clark");
1664
+ // Every span of the turn inherits this correlation; it is what joins the
1665
+ // session's turns, which are separate traces, into one history.
1666
+ const parentContext = AgentSessionTrace.context({
1667
+ sessionId: this.sessionId,
1668
+ turnId: promptId,
1669
+ ...(runtime && {
1670
+ conversationId: this.builderBinding?.runtimeSessionId,
1671
+ }),
1672
+ }, HarnessTrace.context(runtime?.harness ?? "clark"));
1465
1673
  const span = this.config.tracer.startSpan("AiService.generation", {
1466
1674
  attributes: {
1467
- ...HarnessTrace.attributes(parentContext),
1675
+ ...TraceCorrelation.attributes(parentContext),
1468
1676
  "ai.mode": request.mode,
1469
1677
  "ai.model": request.llmConfig?.coreModel,
1470
1678
  "ai.provider": runtime
@@ -1479,7 +1687,7 @@ export class AiService extends TracedEventEmitter {
1479
1687
  const traceHeaders = {};
1480
1688
  propagation.inject(spanContext, traceHeaders);
1481
1689
  let finished = false;
1482
- const finish = (error) => {
1690
+ const finish = (outcome, error) => {
1483
1691
  if (finished)
1484
1692
  return;
1485
1693
  finished = true;
@@ -1488,12 +1696,13 @@ export class AiService extends TracedEventEmitter {
1488
1696
  if (this.activeGenerationTrace === generationTrace) {
1489
1697
  this.activeGenerationTrace = undefined;
1490
1698
  }
1491
- if (error === undefined) {
1699
+ span.setAttribute("builder.turn.outcome", outcome);
1700
+ // A stop is the user's choice, not a fault, so it carries no error
1701
+ // status, as the runtime's builder.turn does.
1702
+ if (outcome === "completed")
1492
1703
  span.setStatus({ code: SpanStatusCode.OK });
1493
- }
1494
- else {
1704
+ if (outcome === "failed")
1495
1705
  setSpanError(span, error);
1496
- }
1497
1706
  span.end();
1498
1707
  };
1499
1708
  // Only end this span for its own run: generationCompleted carries the
@@ -1504,10 +1713,10 @@ export class AiService extends TracedEventEmitter {
1504
1713
  // starts.
1505
1714
  const onCompleted = (_producedDraft, generationId) => {
1506
1715
  if (generationId === promptId) {
1507
- finish();
1716
+ finish("completed");
1508
1717
  }
1509
1718
  };
1510
- const onFailed = (error) => finish(error);
1719
+ const onFailed = (error) => finish("failed", error);
1511
1720
  this.on("generationCompleted", onCompleted);
1512
1721
  this.on("generationFailed", onFailed);
1513
1722
  const generationTrace = {
@@ -1572,6 +1781,7 @@ export class AiService extends TracedEventEmitter {
1572
1781
  recordingManager: this.recordingManager,
1573
1782
  gitService: this._runtimeGitService,
1574
1783
  syncService: this._runtimeSyncService,
1784
+ getBranchName: () => this._syncContextProvider?.getBranchName(),
1575
1785
  gitOperationLock: this._runtimeGitOperationLock,
1576
1786
  onGitOperationComplete: this._onGitOperationComplete,
1577
1787
  taskStore: this.taskStore,
@@ -1727,6 +1937,19 @@ export class AiService extends TracedEventEmitter {
1727
1937
  getProviderInferenceAuthToken() {
1728
1938
  return this.config.inferenceAuthToken ?? this.getInferenceJwt();
1729
1939
  }
1940
+ // Best effort: after a failed call, the last token of the turn still expires in 15 minutes.
1941
+ endNativeInferenceTurn(generationId) {
1942
+ const turn = this.nativeInferenceTurn;
1943
+ if (turn?.generationId !== generationId)
1944
+ return;
1945
+ this.nativeInferenceTurn = undefined;
1946
+ const jwt = this.getInferenceJwt();
1947
+ if (!jwt)
1948
+ return;
1949
+ turn.auth
1950
+ .end(jwt)
1951
+ .catch((error) => this.getLogger().warn("[ai-service] Failed to end the native inference turn", getErrorMeta(error)));
1952
+ }
1730
1953
  requireInferenceJwt() {
1731
1954
  const jwt = this.getInferenceJwt();
1732
1955
  if (!jwt) {
@@ -1773,6 +1996,10 @@ export class AiService extends TracedEventEmitter {
1773
1996
  }
1774
1997
  return null;
1775
1998
  }
1999
+ let restoreFailed = false;
2000
+ const onFailure = () => {
2001
+ restoreFailed = true;
2002
+ };
1776
2003
  // Primary: server-resolved latest context for (app, branch), no commitId.
1777
2004
  const latest = await downloadLatestContextFromBucketeer({
1778
2005
  applicationId: this.config.applicationId,
@@ -1782,6 +2009,7 @@ export class AiService extends TracedEventEmitter {
1782
2009
  jwt,
1783
2010
  contextId: id,
1784
2011
  appRootDirPath: this.config.appRootDirPath,
2012
+ onFailure,
1785
2013
  });
1786
2014
  if (latest) {
1787
2015
  this.getLogger().info(`[context-restore] remoteRestoreFallback restored latest context applicationId=${this.config.applicationId} branch=${branchName}`);
@@ -1797,6 +2025,9 @@ export class AiService extends TracedEventEmitter {
1797
2025
  ? "chatSessionStore.getLatestCommitId"
1798
2026
  : "unavailable";
1799
2027
  if (!commitId) {
2028
+ if (!restoreFailed && (await this.chatSessionStore.isFirstTurn())) {
2029
+ return undefined;
2030
+ }
1800
2031
  this.getLogger().warn(`[context-restore] remoteRestoreFallback found no restore key: applicationId=${this.config.applicationId} source=${commitIdSource} branch=${branchName}`);
1801
2032
  return null;
1802
2033
  }
@@ -1805,7 +2036,7 @@ export class AiService extends TracedEventEmitter {
1805
2036
  // resolved one). The extra resolution is bounded to the rollout window: once
1806
2037
  // Bucketeer serves /context/latest, that call returns a record and this
1807
2038
  // fallback no longer runs.
1808
- return downloadContextFromBucketeer({
2039
+ const restored = await downloadContextFromBucketeer({
1809
2040
  applicationId: this.config.applicationId,
1810
2041
  commitId,
1811
2042
  branchName,
@@ -1814,7 +2045,14 @@ export class AiService extends TracedEventEmitter {
1814
2045
  jwt,
1815
2046
  contextId: id,
1816
2047
  appRootDirPath: this.config.appRootDirPath,
2048
+ onFailure,
1817
2049
  });
2050
+ if (restored) {
2051
+ return restored;
2052
+ }
2053
+ return !restoreFailed && (await this.chatSessionStore.isFirstTurn())
2054
+ ? undefined
2055
+ : null;
1818
2056
  }
1819
2057
  requireProvidedInferenceJwt(jwt, source) {
1820
2058
  if (!jwt) {
@@ -2038,6 +2276,15 @@ export class AiService extends TracedEventEmitter {
2038
2276
  logger: this.getLogger(),
2039
2277
  });
2040
2278
  }
2279
+ /** The paywall a native turn ran into, when the server says this AI quota ran out. */
2280
+ async nativePaywallReason() {
2281
+ const quota = await this.checkAiQuota(this.config.inferenceAuthToken ?? this.nativeBuilderJwt);
2282
+ if (quota.allowed)
2283
+ return undefined;
2284
+ return isAiQuotaPaywallReason(quota.reason)
2285
+ ? quota.reason
2286
+ : "token_limit_exceeded";
2287
+ }
2041
2288
  async ensureAiQuotaAvailable(jwt) {
2042
2289
  const quota = await this.checkAiQuota(jwt);
2043
2290
  if (!quota.allowed) {
@@ -2767,6 +3014,96 @@ export class AiService extends TracedEventEmitter {
2767
3014
  this.remediationAutoDispatch = undefined;
2768
3015
  }
2769
3016
  }
3017
+ resolveNativePromptAttachments(request) {
3018
+ this.nativeAttachmentPreparations ??= new NativeAttachmentPreparations({
3019
+ hasRequest: (requestId) => this.builderConversation?.hasRequest(requestId) ?? false,
3020
+ supportsFiles: () => this.nativeFileAttachmentsSupported(),
3021
+ resolveAttachments: (input, signal) => resolvePromptAttachments(input.promptContext?.attachments, input.jwt, this.config, signal),
3022
+ });
3023
+ return this.nativeAttachmentPreparations.resolve(request);
3024
+ }
3025
+ cancelPendingNativeRequests() {
3026
+ this.nativeCancellationVersion = (this.nativeCancellationVersion ?? 0) + 1;
3027
+ this.nativeAttachmentPreparations?.cancel();
3028
+ }
3029
+ assertNativeRequestActive(version) {
3030
+ if (version !== (this.nativeCancellationVersion ?? 0))
3031
+ throw new DOMException("Native request cancelled", "AbortError");
3032
+ }
3033
+ async nativeFileAttachmentsSupported() {
3034
+ const runtime = this.builderRuntime;
3035
+ if (!runtime)
3036
+ return false;
3037
+ const branch = (await this._syncContextProvider?.getBranchName()) ?? "main";
3038
+ const binding = await this.chatSessionStore.resolveBuilderBinding(branch, runtime.harness);
3039
+ return binding.workspace?.placement === "agentcore";
3040
+ }
3041
+ /**
3042
+ * Before an idle native builder starts a turn, follows the server's binding
3043
+ * for the chat the editor shows. Checking inside the turn would settle it as
3044
+ * failed and release the app lock first. The server refuses the prompt when
3045
+ * the editor's chat is no longer the active one; a prompt without a chat
3046
+ * (a gateway turn) follows whatever is active.
3047
+ */
3048
+ async followBuilderBinding(request) {
3049
+ const runtime = this.builderRuntime;
3050
+ if (!runtime)
3051
+ return;
3052
+ const { branch, binding } = await this.resolveEditorBinding(request, runtime.harness);
3053
+ // Another prompt may have started a turn during the round trip; its start() reports busy.
3054
+ if (this.builderConversation?.isBusy)
3055
+ return;
3056
+ const sameChat = binding.chatSessionId === this.builderBinding?.chatSessionId;
3057
+ if (sameChat && bindingMatchesRuntime(binding, runtime)) {
3058
+ if (request.requestId)
3059
+ this.checkedBinding = { requestId: request.requestId, branch, binding };
3060
+ return;
3061
+ }
3062
+ await this.selectBuilderSession();
3063
+ this.recordBindingMismatch(runtime.harness, binding.harness, "reselected");
3064
+ }
3065
+ /** Resolves the binding for the chat the editor shows; the server refuses a replaced chat. */
3066
+ async resolveEditorBinding(request, harness) {
3067
+ const branch = (await this._syncContextProvider?.getBranchName()) ?? "main";
3068
+ try {
3069
+ const binding = await this.chatSessionStore.resolveBuilderBinding(branch, harness, request.chatSessionId);
3070
+ return { branch, binding };
3071
+ }
3072
+ catch (error) {
3073
+ if (!isChatChangedElsewhereError(error))
3074
+ throw error;
3075
+ this.recordBindingMismatch(harness, undefined, "refused");
3076
+ throw new BuilderBindingChangedError(CHAT_CHANGED_ELSEWHERE_MESSAGE);
3077
+ }
3078
+ }
3079
+ /** A prompt the conversation already handled stays a no-op, as start()'s dedup makes it. */
3080
+ shouldFollowBuilderBinding(request) {
3081
+ return (this.builderConversation?.isBusy === false &&
3082
+ !this.builderConversation.hasRequest(request.requestId));
3083
+ }
3084
+ recordBindingMismatch(activeHarness, boundHarness, outcome) {
3085
+ const attributes = {
3086
+ "builder.harness.active": activeHarness,
3087
+ ...(boundHarness && { "builder.harness.bound": boundHarness }),
3088
+ "builder.binding.outcome": outcome,
3089
+ };
3090
+ this.getLogger().warn("[ai-service] The chat's builder binding no longer matches this pod's selection", attributes);
3091
+ builderBindingMismatchCounter().add(1, attributes);
3092
+ }
3093
+ /**
3094
+ * The server-side builder runtime for one chat and branch, minting its
3095
+ * tokens from the editor's current Superblocks token. Kept while the chat
3096
+ * and branch stay the same, so tokens are reused across turns and opens.
3097
+ */
3098
+ builderRuntimeAccess(chatSessionId, branchName) {
3099
+ const key = JSON.stringify([chatSessionId, branchName]);
3100
+ if (this.runtimeAccess?.key !== key)
3101
+ this.runtimeAccess = {
3102
+ key,
3103
+ auth: new BuilderRuntimeAuth(this.config.superblocksBaseUrl, this.config.applicationId, { chatSessionId, branchName }, () => this.requireInferenceJwt()),
3104
+ };
3105
+ return this.runtimeAccess.auth;
3106
+ }
2770
3107
  async prepareNativeBuilderRequest(request, signal, generationId) {
2771
3108
  this.assertNoActivePolicyGateRun();
2772
3109
  setPromptOrgClaims(orgClaimsFromJwt(request.jwt));
@@ -2784,24 +3121,39 @@ export class AiService extends TracedEventEmitter {
2784
3121
  const runtime = this.builderRuntime;
2785
3122
  if (!runtime)
2786
3123
  throw new Error("Native builder runtime is unavailable");
2787
- const binding = await this.chatSessionStore.resolveBuilderBinding(branch, runtime.harness);
2788
- if (binding.harness !== runtime.harness ||
2789
- (binding.model !== undefined && binding.model !== runtime.model))
2790
- throw new Error("This chat uses a different harness or model. Reconnect before sending a prompt.");
3124
+ const checked = this.checkedBinding;
3125
+ this.checkedBinding = undefined;
3126
+ const binding = checked &&
3127
+ checked.requestId === request.requestId &&
3128
+ checked.branch === branch
3129
+ ? checked.binding
3130
+ : await this.chatSessionStore.resolveBuilderBinding(branch, runtime.harness, request.chatSessionId);
3131
+ if (!bindingMatchesRuntime(binding, runtime))
3132
+ throw new BuilderBindingChangedError();
2791
3133
  this.builderBinding = binding;
2792
3134
  this.builderBranch = branch;
2793
3135
  signal.throwIfAborted();
2794
3136
  const workspaceLocal = binding.workspace?.placement === "agentcore";
3137
+ const userId = parseJwt(request.jwt)?.userId;
2795
3138
  const turnFinish = {
2796
3139
  finished: false,
2797
3140
  };
2798
3141
  this.workspaceTurnFinish = workspaceLocal ? turnFinish : undefined;
2799
- if (workspaceLocal) {
2800
- await this.ensureWorkspace(binding, branch);
2801
- signal.throwIfAborted();
2802
- }
2803
- const inferenceAuth = new BuilderInferenceAuth(this.config.superblocksBaseUrl, this.config.applicationId, runtime.providerFor(runtime.model), { chatSessionId: binding.chatSessionId, branchName: branch });
2804
- const inference = await inferenceAuth.issue(request.jwt, signal);
3142
+ const opened = workspaceLocal
3143
+ ? await this.ensureWorkspace(binding, branch)
3144
+ : undefined;
3145
+ signal.throwIfAborted();
3146
+ const inferenceAuth = new BuilderInferenceAuth(this.config.superblocksBaseUrl, this.config.applicationId, runtime.providerFor(runtime.model), {
3147
+ chatSessionId: binding.chatSessionId,
3148
+ branchName: branch,
3149
+ runId: generationId,
3150
+ });
3151
+ this.nativeInferenceTurn = { generationId, auth: inferenceAuth };
3152
+ const skillsAuth = new BuilderSkillsAuth(this.config.superblocksBaseUrl, this.config.applicationId, { chatSessionId: binding.chatSessionId, branchName: branch });
3153
+ const [inference, skills] = await Promise.all([
3154
+ inferenceAuth.issue(request.jwt, signal),
3155
+ skillsAuth.issue(request.jwt, signal),
3156
+ ]);
2805
3157
  const generationTrace = this.startGenerationTrace({
2806
3158
  ...request,
2807
3159
  llmConfig: { ...request.llmConfig, coreModel: runtime.model },
@@ -2817,6 +3169,14 @@ export class AiService extends TracedEventEmitter {
2817
3169
  this.emit("generationStarted", generationId);
2818
3170
  return {
2819
3171
  scope: binding.runtimeSessionId,
3172
+ restoreAttachments: async () => {
3173
+ signal.throwIfAborted();
3174
+ const references = await this.chatSessionStore.getAttachmentReferences(binding.chatSessionId, request.requestId);
3175
+ signal.throwIfAborted();
3176
+ if (!references.messageIds.length)
3177
+ return [];
3178
+ return resolveAttachmentHistory(await this.chatSessionStore.getAttachmentHistory(binding.chatSessionId, references.messageIds), request.jwt, this.config, signal);
3179
+ },
2820
3180
  conversationId: binding.runtimeSessionId,
2821
3181
  workspaceSessionKey: binding.workspace?.sessionKey,
2822
3182
  traceContext: generationTrace.context,
@@ -2831,6 +3191,12 @@ export class AiService extends TracedEventEmitter {
2831
3191
  },
2832
3192
  }),
2833
3193
  actorId: binding.actorId,
3194
+ ...(opened?.ownerScoped &&
3195
+ userId && {
3196
+ ownerId: createHash("sha256")
3197
+ .update(JSON.stringify([binding.actorId, userId]))
3198
+ .digest("hex"),
3199
+ }),
2834
3200
  nativeSessionId: binding.nativeSessionId,
2835
3201
  saveSession: (nativeSessionId) => this.chatSessionStore.saveBuilderSession({
2836
3202
  branchName: branch,
@@ -2844,13 +3210,38 @@ export class AiService extends TracedEventEmitter {
2844
3210
  sessionId: binding.chatSessionId,
2845
3211
  applicationId: this.config.applicationId,
2846
3212
  },
3213
+ skills,
3214
+ access: this.builderRuntimeAccess(binding.chatSessionId, branch),
2847
3215
  refreshInference: async (signal) => (await inferenceAuth.issue(this.requireInferenceJwt(), signal)).token,
3216
+ refreshSkills: async (signal) => (await skillsAuth.issue(this.requireInferenceJwt(), signal)).token,
2848
3217
  };
2849
3218
  }
2850
3219
  async handleAiGenerate(request, inputSource, remediationContinuationSignal, continuationCaller) {
2851
- if (this.builderConversation) {
2852
- await this.builderConversation.start(request);
2853
- return;
3220
+ this.assertNoBuilderSwitchInProgress();
3221
+ // Counted until the turn starts: Clark's path below reaches `generationStarting` without another await.
3222
+ this.promptsBeingAdmitted++;
3223
+ try {
3224
+ // Guarded so the common case adds no tick before the admission checks below.
3225
+ if (this.editorRestartRequired)
3226
+ await this.assertEditorNeedsNoRestart();
3227
+ // Only awaits when stale: an extra tick here would let a duplicate prompt past the admission check.
3228
+ if (this.builderBindingStale)
3229
+ await this.recoverStaleBuilderBinding();
3230
+ if (this.shouldFollowBuilderBinding(request))
3231
+ await this.followBuilderBinding(request);
3232
+ if (this.builderConversation) {
3233
+ const cancellationVersion = this.nativeCancellationVersion ?? 0;
3234
+ const attachments = await this.resolveNativePromptAttachments(request);
3235
+ this.assertNativeRequestActive(cancellationVersion);
3236
+ if (attachments)
3237
+ await this.builderConversation.start(request, attachments);
3238
+ else
3239
+ await this.builderConversation.start(request);
3240
+ return;
3241
+ }
3242
+ }
3243
+ finally {
3244
+ this.promptsBeingAdmitted--;
2854
3245
  }
2855
3246
  this.getLogger().info(`[ai-service] handleAiGenerate: peerId=${this.stablePeer.peerId ?? "unknown"}`);
2856
3247
  // Before the first rejection below: a rejected prompt is an attempt and an
@@ -3116,7 +3507,7 @@ export class AiService extends TracedEventEmitter {
3116
3507
  internal: remediationContinuationSignal ? true : undefined,
3117
3508
  })))
3118
3509
  .catch(async (error) => {
3119
- activeGenerationTrace.finish(error);
3510
+ activeGenerationTrace.finish("failed", error);
3120
3511
  this.emit("generationSettled", promptId);
3121
3512
  if (request.requestId) {
3122
3513
  this.requestDeduplicator.forget(request.requestId);
@@ -3139,7 +3530,7 @@ export class AiService extends TracedEventEmitter {
3139
3530
  generationStarted = true;
3140
3531
  }
3141
3532
  catch (error) {
3142
- generationTrace?.finish(error);
3533
+ generationTrace?.finish("failed", error);
3143
3534
  recordPromptOutcome({
3144
3535
  dedupeKey: resolvePromptRequestDedupeKey(request),
3145
3536
  outcome: "failure",
@@ -3752,8 +4143,10 @@ export class AiService extends TracedEventEmitter {
3752
4143
  : "User closed the integration setup form. The integration setup might not have been completed successfully.");
3753
4144
  }
3754
4145
  async handleUserCanceled(reason) {
3755
- if (this.builderConversation)
4146
+ if (this.builderConversation) {
4147
+ this.cancelPendingNativeRequests();
3756
4148
  return this.builderConversation.cancel();
4149
+ }
3757
4150
  if (this.remediationCancellation)
3758
4151
  return this.remediationCancellation;
3759
4152
  const busy = this.isBusy();
@@ -3899,14 +4292,50 @@ export class AiService extends TracedEventEmitter {
3899
4292
  * If not busy, starts immediately. Otherwise interrupts and continues.
3900
4293
  */
3901
4294
  async handleAiGenerateWithQueue(request, mode, inputSource) {
3902
- if (this.builderConversation) {
3903
- const interrupted = this.builderConversation.isBusy &&
3904
- !request.responseMetadata &&
3905
- !this.builderConversation.hasRequest(request.requestId);
3906
- if (interrupted)
3907
- await this.builderConversation.cancel();
3908
- const generationId = await this.builderConversation.start(request);
3909
- return { generationId, status: interrupted ? "interrupted" : "started" };
4295
+ this.assertNoBuilderSwitchInProgress();
4296
+ // Counted until the turn starts; Clark's path below hands off to handleAiGenerate, which counts it again.
4297
+ this.promptsBeingAdmitted++;
4298
+ try {
4299
+ // Guarded so the common case adds no tick before the admission checks below.
4300
+ if (this.editorRestartRequired)
4301
+ await this.assertEditorNeedsNoRestart();
4302
+ // Only awaits when stale: an extra tick here would let a duplicate prompt past the admission check.
4303
+ if (this.builderBindingStale)
4304
+ await this.recoverStaleBuilderBinding();
4305
+ let interrupted = false;
4306
+ let attachments;
4307
+ let cancellationVersion = 0;
4308
+ if (this.builderConversation) {
4309
+ // Attachments are validated before a running turn is interrupted.
4310
+ cancellationVersion = this.nativeCancellationVersion ?? 0;
4311
+ attachments = await this.resolveNativePromptAttachments(request);
4312
+ interrupted =
4313
+ this.builderConversation.isBusy &&
4314
+ !request.responseMetadata &&
4315
+ !this.builderConversation.hasRequest(request.requestId);
4316
+ if (interrupted) {
4317
+ // A prompt the server refuses must not cost the user their running turn.
4318
+ const runtime = this.builderRuntime;
4319
+ if (runtime && request.chatSessionId)
4320
+ await this.resolveEditorBinding(request, runtime.harness);
4321
+ await this.builderConversation?.cancel();
4322
+ }
4323
+ if (this.shouldFollowBuilderBinding(request))
4324
+ await this.followBuilderBinding(request);
4325
+ }
4326
+ if (this.builderConversation) {
4327
+ this.assertNativeRequestActive(cancellationVersion);
4328
+ const generationId = attachments
4329
+ ? await this.builderConversation.start(request, attachments)
4330
+ : await this.builderConversation.start(request);
4331
+ return {
4332
+ generationId,
4333
+ status: interrupted ? "interrupted" : "started",
4334
+ };
4335
+ }
4336
+ }
4337
+ finally {
4338
+ this.promptsBeingAdmitted--;
3910
4339
  }
3911
4340
  this.getLogger().info(`[ai-service] handleAiGenerateWithQueue: peerId=${this.stablePeer.peerId ?? "unknown"}, mode=${mode}`);
3912
4341
  // Covers the dead rejection here and the paywall rejection on the
@@ -4710,8 +5139,12 @@ export class AiService extends TracedEventEmitter {
4710
5139
  });
4711
5140
  }
4712
5141
  getChatStateSnapshot() {
5142
+ const builderSelection = this.getBuilderSelection();
5143
+ const runnableHarnesses = this.getRunnableHarnesses();
4713
5144
  if (this.builderConversation)
4714
5145
  return {
5146
+ builderSelection,
5147
+ runnableHarnesses,
4715
5148
  generationState: this.builderConversation.state,
4716
5149
  ...(this.builderConversation.activeInteractiveMessage
4717
5150
  ? {
@@ -4721,6 +5154,8 @@ export class AiService extends TracedEventEmitter {
4721
5154
  };
4722
5155
  const generationState = this.resolveGenerationStateForUi();
4723
5156
  return {
5157
+ builderSelection,
5158
+ runnableHarnesses,
4724
5159
  generationState,
4725
5160
  activeInteractiveMessage: generationState?.state === AiGenerationState.AWAITING_USER_INPUT
4726
5161
  ? this.clark.context.activeInteractiveMessage?.payload
@@ -5558,24 +5993,115 @@ export class AiService extends TracedEventEmitter {
5558
5993
  }
5559
5994
  }
5560
5995
  async handlePolicyGateExecution(request) {
5561
- if (this.builderConversation)
5562
- throw new Error("This helper is not available with the Codex builder yet");
5563
- return runPolicyGateReview({
5996
+ // Without a binding, an agentcore app's mirror may be empty: fail, never pass.
5997
+ if (!this.builderBinding)
5998
+ throw new Error("The app's builder placement is unknown, so the review cannot read the app");
5999
+ // In agentcore placement, scan the mirror at the VM's latest tree.
6000
+ await this.waitForWorkspaceFiles();
6001
+ // Native harness sessions have no Clark, so no context manager: use a
6002
+ // scratch one, as a review pod does.
6003
+ const scratchDir = this.contextManagerV2
6004
+ ? undefined
6005
+ : await mkdtemp(path.join(os.tmpdir(), "review-run-"));
6006
+ const contextManagerV2 = scratchDir
6007
+ ? new ContextManagerV2({
6008
+ rootDir: scratchDir,
6009
+ storage: new LocalContextStorageV2(scratchDir),
6010
+ })
6011
+ : this.contextManagerV2;
6012
+ this.reviewAppShell ??= createReviewAppShell({
6013
+ appRootDirPath: this.config.appRootDirPath,
6014
+ features: this.config.features,
6015
+ fsOperationQueue: this.config.fsOperationQueue,
6016
+ knowledgeManager: this.knowledgeManager,
6017
+ templateRenderer: this.templateRenderer,
6018
+ });
6019
+ try {
6020
+ return await runPolicyGateReview({
6021
+ appShell: this.reviewAppShell,
6022
+ chatSessionStore: this.chatSessionStore,
6023
+ contextManagerV2,
6024
+ defaultLlmConfig: this.clark?.context.llmConfig,
6025
+ ensureAiQuotaAvailable: (jwt) => this.ensureAiQuotaAvailable(jwt),
6026
+ features: this.config.features ?? {},
6027
+ getLLMProviderSettings: (llmConfig) => this.getLLMProviderSettings(llmConfig),
6028
+ // Unbound, a queued call would run in the next editor's session.
6029
+ getPeer: () => (this.stablePeer.peerId ? this.stablePeer : undefined),
6030
+ integrationStore: this.integrationStore,
6031
+ logger: this.getLogger(),
6032
+ organizationId: this.config.organizationId,
6033
+ reportAgentStep: (step) => void this.pushPolicyAgentStep(step),
6034
+ retryOptions: streamRetryOptionsFromConfig(this.config.retryOptions, this.config.features.streamTimeoutBudgets),
6035
+ sessionId: this.sessionId,
6036
+ }, request);
6037
+ }
6038
+ finally {
6039
+ if (scratchDir)
6040
+ await rm(scratchDir, { force: true, recursive: true }).catch((error) => this.getLogger().warn("[ai-service] Failed to remove policy review scratch dir", getErrorMeta(error)));
6041
+ }
6042
+ }
6043
+ getDemoAgentDeps() {
6044
+ if (!projectAgentsEnabled(this.config.features)) {
6045
+ throw new Error("Project agents are not enabled");
6046
+ }
6047
+ return {
5564
6048
  appShell: this.appShell,
5565
- chatSessionStore: this.chatSessionStore,
5566
6049
  contextManagerV2: this.contextManagerV2,
5567
- defaultLlmConfig: this.clark.context.llmConfig,
5568
- ensureAiQuotaAvailable: (jwt) => this.ensureAiQuotaAvailable(jwt),
5569
- features: this.config.features ?? {},
5570
- getConnectedPeer: () => this.hasConnectedPeer() ? this.clark.context.peer : undefined,
5571
- getLLMProviderSettings: (llmConfig) => this.getLLMProviderSettings(llmConfig),
5572
- getPeer: () => this.clark.context.peer,
5573
- integrationStore: this.integrationStore,
6050
+ features: this.config.features,
6051
+ getJwt: () => this.requireProviderInferenceAuthToken(),
6052
+ getLLMProviderSettings: () => this.getLLMProviderSettings(this.clark?.context?.llmConfig),
6053
+ getPeer: () => this.stablePeer,
5574
6054
  logger: this.getLogger(),
5575
6055
  organizationId: this.config.organizationId,
5576
- retryOptions: streamRetryOptionsFromConfig(this.config.retryOptions, this.config.features.streamTimeoutBudgets),
5577
- sessionId: this.sessionId,
5578
- }, request);
6056
+ applicationId: this.config.applicationId,
6057
+ retryOptions: this.config.retryOptions,
6058
+ };
6059
+ }
6060
+ async handleDemoAgentList() {
6061
+ return handleAgentList(this.getDemoAgentDeps());
6062
+ }
6063
+ handleDemoAgentRun(request, callerUserId) {
6064
+ const userId = this.requireEditorUser(callerUserId);
6065
+ return handleAgentRun(this.getDemoAgentDeps(), request, userId, (payload) => this.pushDemoAgentRunEvent(payload));
6066
+ }
6067
+ // An agent's tools run in the open editor's browser as that editor's user,
6068
+ // so only that user may start or reset a run.
6069
+ requireEditorUser(callerUserId) {
6070
+ if (!callerUserId || callerUserId !== this.getEditorUserId()) {
6071
+ throw new Error("The app is open in another user's editor");
6072
+ }
6073
+ return callerUserId;
6074
+ }
6075
+ /** The user of the bound editor, once it has proved who it is. */
6076
+ getEditorUserId() {
6077
+ return this.getAuthenticatedPeerUserId();
6078
+ }
6079
+ handleDemoAgentRemoteRun(request) {
6080
+ return handleRemoteAgentRun(this.getDemoAgentDeps(), request, (payload) => this.pushDemoAgentRunEvent(payload));
6081
+ }
6082
+ pushDemoAgentRunEvent(payload) {
6083
+ // ponytail: cast needed because ISocketClientMethodCall truncates at ~64 members
6084
+ void this.stablePeer.call
6085
+ .agentPushRunEvent(payload)
6086
+ .catch((err) => {
6087
+ this.getLogger().warn("[demo-agents] Failed to push run event", err instanceof Error ? err.message : String(err));
6088
+ });
6089
+ }
6090
+ // Changing an agent's tools edits the app's files, so only the user of the
6091
+ // open editor may do it, as with a run.
6092
+ handleDemoAgentSetTool(request, callerUserId) {
6093
+ this.requireEditorUser(callerUserId);
6094
+ // agent.json lists the APIs the agent may run. In an AgentCore workspace
6095
+ // this process only holds a mirror of it: a change here would not reach
6096
+ // the VM's copy, and the next mirror would bring the old list back.
6097
+ this.assertLocalAppTreeWritable("changing an agent's tools");
6098
+ return handleAgentSetTool(this.getDemoAgentDeps(), request);
6099
+ }
6100
+ handleDemoAgentResetSession(request, callerUserId) {
6101
+ if (!projectAgentsEnabled(this.config.features)) {
6102
+ throw new Error("Project agents are not enabled");
6103
+ }
6104
+ handleAgentResetSession(request, this.requireEditorUser(callerUserId));
5579
6105
  }
5580
6106
  handleUserChange(change) {
5581
6107
  this.getLogger().info(`[ai-service] User changed: ${change.type}`, change);
@@ -5584,11 +6110,187 @@ export class AiService extends TracedEventEmitter {
5584
6110
  userChanges: [...(context.userChanges ?? []), change],
5585
6111
  }));
5586
6112
  }
5587
- async handleNewChat() {
5588
- if (this.builderConversation) {
5589
- await this.builderConversation.reset();
5590
- await this.reselectBuilderSessionAfterChatChange("new chat");
6113
+ /**
6114
+ * Starts a new chat and returns its id, which the editor sends with later prompts. A `builderSelection` moves the app
6115
+ * to that harness: it reopens the app's most recent chat on it (`resumed`), which keeps that chat's own model, or
6116
+ * starts a new chat bound to it when there is none. A model-only change goes through `handleSetBuilderModel`.
6117
+ */
6118
+ async handleNewChat(builderSelection) {
6119
+ if (builderSelection) {
6120
+ if (this.isBusyForBuilderSwitch())
6121
+ throw new Error("Wait for the current turn to finish before switching the harness or model");
6122
+ if (this.builderSwitchInProgress)
6123
+ throw new Error("The harness or model is already being switched");
6124
+ // Set synchronously after the busy check, so no prompt starts between them.
6125
+ this.builderSwitchInProgress = true;
6126
+ }
6127
+ try {
6128
+ if (builderSelection)
6129
+ await this.assertEditorFinishedRestarting();
6130
+ return await this.switchOrStartNewChat(builderSelection);
6131
+ }
6132
+ finally {
6133
+ if (builderSelection)
6134
+ this.builderSwitchInProgress = false;
6135
+ }
6136
+ }
6137
+ async switchOrStartNewChat(builderSelection) {
6138
+ if (builderSelection) {
6139
+ // New chat discards uncommitted AI changes; a switch must not.
6140
+ if (await this.config.draftInterface?.hasLocalDraftChanges())
6141
+ throw new Error("Accept or reject the pending changes before switching the harness or model");
6142
+ // Refuse here, before the server archives the chat, a switch this editor could not run.
6143
+ this.assertCanRunSelection(builderSelection);
6144
+ }
6145
+ let resumed = false;
6146
+ try {
6147
+ ({ resumed } = await this.startNewChat(builderSelection));
6148
+ if (builderSelection)
6149
+ this.assertSelectionApplied(builderSelection);
6150
+ }
6151
+ catch (error) {
6152
+ if (builderSelection)
6153
+ this.builderBindingStale = true;
6154
+ throw error;
6155
+ }
6156
+ // A switch between Clark and a native harness can move the app between live-edit and agentcore placement.
6157
+ const restartRequired = builderSelection !== undefined &&
6158
+ (await this.refreshEditorRestartRequired());
6159
+ if (restartRequired) {
6160
+ this.editorRestartAskedAt = Date.now();
6161
+ this.openWorkspaceAfterRestart();
6162
+ }
6163
+ return {
6164
+ chatSessionId: this.chatSessionStore.getChatSessionId(),
6165
+ builderSelection: this.getBuilderSelection(),
6166
+ ...(resumed ? { resumed } : {}),
6167
+ ...(restartRequired ? { restartRequired } : {}),
6168
+ };
6169
+ }
6170
+ /**
6171
+ * Changes the model of the active native chat in place. The chat, its transcript, and its native Claude or Codex
6172
+ * session stay; the next turn resumes that session on the new model. Placement does not change, so no restart.
6173
+ */
6174
+ async handleSetBuilderModel(model) {
6175
+ if (this.isBusyForBuilderSwitch())
6176
+ throw new Error("Wait for the current turn to finish before changing the model");
6177
+ if (this.builderSwitchInProgress)
6178
+ throw new Error("The harness or model is already being switched");
6179
+ // Set synchronously after the busy check, so no prompt starts between them.
6180
+ this.builderSwitchInProgress = true;
6181
+ try {
6182
+ await this.assertEditorFinishedRestarting();
6183
+ // A failed switch left this pod off the active chat; follow it first, so the change lands on the chat it runs.
6184
+ if (this.builderBindingStale)
6185
+ await this.recoverStaleBindingForModelChange();
6186
+ const chatSessionId = this.builderBinding?.chatSessionId;
6187
+ const harness = this.builderBinding?.harness;
6188
+ if (!chatSessionId || !harness || harness === "clark")
6189
+ throw new Error("This chat does not run on a native harness");
6190
+ // Throws for a model the harness does not offer, before the server changes anything.
6191
+ this.assertCanRunSelection({ harness, model });
6192
+ const branch = this.builderBranch ??
6193
+ (await this._syncContextProvider?.getBranchName()) ??
6194
+ "main";
6195
+ try {
6196
+ await this.chatSessionStore.setBuilderModel(branch, model, chatSessionId);
6197
+ }
6198
+ catch (error) {
6199
+ if (!isChatChangedElsewhereError(error))
6200
+ throw error;
6201
+ this.recordBindingMismatch(harness, undefined, "refused");
6202
+ throw new BuilderBindingChangedError(CHAT_CHANGED_ELSEWHERE_MESSAGE);
6203
+ }
6204
+ try {
6205
+ await this.selectBuilderSession(branch);
6206
+ this.assertSelectionApplied({ harness, model });
6207
+ }
6208
+ catch (error) {
6209
+ // The next prompt re-follows the binding, which now carries the new model.
6210
+ this.builderBindingStale = true;
6211
+ this.getLogger().warn("[ai-service] Saved the chat's model, but this pod did not follow it", getErrorMeta(error));
6212
+ throw new Error("Saved the model. It takes effect on your next prompt.", { cause: error });
6213
+ }
6214
+ const builderSelection = this.getBuilderSelection();
6215
+ if (!builderSelection)
6216
+ throw new Error("Changed the model, but this editor lost the chat.");
6217
+ return { builderSelection };
6218
+ }
6219
+ finally {
6220
+ this.builderSwitchInProgress = false;
6221
+ }
6222
+ }
6223
+ async recoverStaleBindingForModelChange() {
6224
+ try {
6225
+ await this.recoverStaleBuilderBinding(this.builderBranch);
6226
+ }
6227
+ catch (error) {
6228
+ this.getLogger().warn("[ai-service] Could not follow the active chat before changing the model", getErrorMeta(error));
6229
+ throw new Error(isAuthFailure(error)
6230
+ ? STALE_BINDING_AUTH_MESSAGE
6231
+ : STALE_BINDING_MESSAGE, { cause: error });
6232
+ }
6233
+ if (this.builderBindingStale)
6234
+ throw new Error(STALE_BINDING_MESSAGE);
6235
+ }
6236
+ assertCanRunSelection(selection) {
6237
+ if (selection.harness === "clark")
5591
6238
  return;
6239
+ const runtime = this.runtimeForHarness(selection.harness);
6240
+ if (!runtime)
6241
+ throw new Error(`This editor cannot run ${selection.harness === "codex" ? "Codex" : "Claude"}.`);
6242
+ // Throws for a model the harness does not offer.
6243
+ if (selection.model !== undefined)
6244
+ runtime.withModel(selection.model);
6245
+ }
6246
+ /**
6247
+ * The server already moved to the new chat. If this pod did not follow it, say so instead of reporting a switch
6248
+ * that did not happen: the editor would otherwise show the old harness as if the user had picked it.
6249
+ */
6250
+ assertSelectionApplied(selection) {
6251
+ const applied = this.getBuilderSelection();
6252
+ const matches = applied?.harness === selection.harness &&
6253
+ (selection.harness === "clark" ||
6254
+ selection.model === undefined ||
6255
+ applied.model === selection.model);
6256
+ if (!matches)
6257
+ throw new Error("Changed the chat, but this editor could not switch to the selected harness or model. Try again.");
6258
+ }
6259
+ /** The harness and model of the active chat, as this pod last resolved it from the server. */
6260
+ getBuilderSelection() {
6261
+ const binding = this.builderBinding;
6262
+ if (!binding)
6263
+ return undefined;
6264
+ if (binding.harness === "clark")
6265
+ return { harness: "clark" };
6266
+ return {
6267
+ harness: binding.harness,
6268
+ model: binding.model ?? this.builderRuntime?.model,
6269
+ };
6270
+ }
6271
+ /** `resumed` when the server reopened the app's last chat on the picked harness instead of a new one. */
6272
+ async startNewChat(builderSelection) {
6273
+ if (this.builderConversation) {
6274
+ this.cancelPendingNativeRequests();
6275
+ // Read before reset() clears the session; only a switch to Clark needs it.
6276
+ const commitIdForUpload = builderSelection?.harness === "clark"
6277
+ ? (this._syncContextProvider?.getLastCommitId() ??
6278
+ (await this.chatSessionStore.getLatestCommitId()))
6279
+ : undefined;
6280
+ let resumed = false;
6281
+ await this.builderConversation.reset(async () => {
6282
+ ({ resumed } = await this.chatSessionStore.newChat(builderSelection));
6283
+ });
6284
+ await this.reselectBuilderSessionAfterChatChange("new chat", {
6285
+ rethrow: builderSelection !== undefined,
6286
+ });
6287
+ // Switched to Clark: seed it from the chat it now runs, empty or reopened, not whatever Clark last held.
6288
+ if (!this.builderConversation) {
6289
+ this.editAfterClark.reset();
6290
+ this.clearClarkInteractiveState();
6291
+ await this.seedClarkContextFromChat(commitIdForUpload);
6292
+ }
6293
+ return { resumed };
5592
6294
  }
5593
6295
  this.reportAbandonTurn("clear_chat");
5594
6296
  // Before newChat() switches the session id, so no report for a turn of
@@ -5600,7 +6302,19 @@ export class AiService extends TracedEventEmitter {
5600
6302
  const contextId = this.getContextId();
5601
6303
  const commitIdForUpload = this._syncContextProvider?.getLastCommitId() ??
5602
6304
  (await this.chatSessionStore.getLatestCommitId());
5603
- await this.chatSessionStore.newChat();
6305
+ const { resumed } = await this.chatSessionStore.newChat(builderSelection);
6306
+ if (resumed) {
6307
+ // Switched back to a harness the app already had a chat on: continue it, as a chat switch does.
6308
+ try {
6309
+ await this.resetInteractiveStateForChatChange("new chat", {
6310
+ rethrow: true,
6311
+ });
6312
+ }
6313
+ finally {
6314
+ await this.seedClarkContextIfStillOnClark(commitIdForUpload);
6315
+ }
6316
+ return { resumed };
6317
+ }
5604
6318
  try {
5605
6319
  await this.contextManagerV2.clearAllContexts("new_chat");
5606
6320
  // Persist an empty context locally and upload it to Bucketeer so
@@ -5614,26 +6328,84 @@ export class AiService extends TracedEventEmitter {
5614
6328
  catch (error) {
5615
6329
  this.getLogger().error("[ai-service] Failed to clear contexts on new chat", getErrorMeta(error));
5616
6330
  }
5617
- await this.resetInteractiveStateForChatChange("new chat");
6331
+ await this.resetInteractiveStateForChatChange("new chat", {
6332
+ rethrow: builderSelection !== undefined,
6333
+ });
6334
+ return { resumed: false };
5618
6335
  }
5619
6336
  /**
5620
6337
  * Continues an earlier chat of this branch. Clark's memory is rebuilt from that chat's saved text turns and latest
5621
6338
  * summary, so its tool calls and their results are not restored.
5622
6339
  */
5623
6340
  async handleSwitchChat(chatSessionId) {
6341
+ if (this.isBusyForBuilderSwitch()) {
6342
+ throw new Error("Wait for Clark to finish before switching chats");
6343
+ }
6344
+ if (this.builderSwitchInProgress)
6345
+ throw new Error("The harness or model is already being switched");
6346
+ // The earlier chat may run on another harness. Set synchronously after the busy check, so no prompt starts
6347
+ // between the new chat id reaching the editors and the restart check below.
6348
+ this.builderSwitchInProgress = true;
6349
+ let restartRequired;
6350
+ try {
6351
+ await this.assertEditorFinishedRestarting();
6352
+ await this.switchChat(chatSessionId);
6353
+ // The earlier chat may run on a harness with the other placement.
6354
+ restartRequired = await this.refreshEditorRestartRequired();
6355
+ }
6356
+ finally {
6357
+ this.builderSwitchInProgress = false;
6358
+ }
6359
+ if (!restartRequired)
6360
+ return undefined;
6361
+ this.editorRestartAskedAt = Date.now();
6362
+ this.openWorkspaceAfterRestart();
6363
+ return { restartRequired: true };
6364
+ }
6365
+ async switchChat(chatSessionId) {
5624
6366
  if (this.isBusy()) {
5625
6367
  throw new Error("Wait for Clark to finish before switching chats");
5626
6368
  }
5627
- const contextId = this.getContextId();
6369
+ if (this.builderConversation) {
6370
+ await this.builderConversation.reset(() => this.chatSessionStore.switchChat(chatSessionId));
6371
+ await this.reselectBuilderSessionAfterChatChange("switch chat");
6372
+ // The chosen chat ran on Clark: reset and seed Clark as a Clark pod's switch does.
6373
+ if (!this.builderConversation) {
6374
+ this.editAfterClark.reset();
6375
+ this.clearClarkInteractiveState();
6376
+ await this.seedClarkContextFromChat(this._syncContextProvider?.getLastCommitId() ??
6377
+ (await this.chatSessionStore.getLatestCommitId()));
6378
+ }
6379
+ return;
6380
+ }
5628
6381
  const commitIdForUpload = this._syncContextProvider?.getLastCommitId() ??
5629
6382
  (await this.chatSessionStore.getLatestCommitId());
5630
6383
  await this.chatSessionStore.switchChat(chatSessionId);
5631
6384
  this.editAfterClark.reset();
5632
- const [transcript, latestSummary] = await Promise.all([
5633
- this.chatSessionStore.getMessages({ force: true }),
5634
- this.chatSessionStore.getLatestSummary(),
5635
- ]);
6385
+ await this.resetInteractiveStateForChatChange("switch chat");
6386
+ await this.seedClarkContextIfStillOnClark(commitIdForUpload);
6387
+ }
6388
+ /**
6389
+ * Seeds Clark from the active chat after a chat change on a Clark pod, once the reselect has run: a chat that runs on
6390
+ * a native harness keeps its own memory, and its transcript must not become Clark's context or reach Bucketeer.
6391
+ * A pod without a binding runs only Clark. A stale binding defers the seed to recovery.
6392
+ */
6393
+ async seedClarkContextIfStillOnClark(commitIdForUpload) {
6394
+ if (this.builderBinding && this.builderBinding.harness !== "clark")
6395
+ return;
6396
+ if (this.builderBindingStale)
6397
+ return;
6398
+ await this.seedClarkContextFromChat(commitIdForUpload);
6399
+ }
6400
+ /** Rebuilds Clark's memory from the active chat's saved text turns and latest summary. */
6401
+ async seedClarkContextFromChat(commitIdForUpload) {
6402
+ const contextId = this.getContextId();
6403
+ // The chat already moved on the server, so a failed seed must not fail the switch.
5636
6404
  try {
6405
+ const [transcript, latestSummary] = await Promise.all([
6406
+ this.chatSessionStore.getMessages({ force: true }),
6407
+ this.chatSessionStore.getLatestSummary(),
6408
+ ]);
5637
6409
  await this.contextManagerV2.clearAllContexts("switch_chat");
5638
6410
  if (contextId) {
5639
6411
  await this.contextManagerV2.persistContextMessages(contextId, seedMessagesFromTranscript(transcript, latestSummary?.summary));
@@ -5643,12 +6415,8 @@ export class AiService extends TracedEventEmitter {
5643
6415
  catch (error) {
5644
6416
  this.getLogger().error("[ai-service] Failed to rebuild context on chat switch", getErrorMeta(error));
5645
6417
  }
5646
- await this.resetInteractiveStateForChatChange("switch chat");
5647
6418
  }
5648
- // Reset FSM state that gates the next chat's interactive prompts. Without this, an open interactive prompt
5649
- // (askMultiChoice card, exitPlanMode plan card, askSearchableDropdown) survives into the next chat and the
5650
- // channel guard silently rejects the next interactive tool call. See peer.ts for the channel-level recovery.
5651
- async resetInteractiveStateForChatChange(label) {
6419
+ clearClarkInteractiveState() {
5652
6420
  this.clark.updateContext({
5653
6421
  activeInteractiveMessage: undefined,
5654
6422
  pendingIntegrationActionPrompt: undefined,
@@ -5656,16 +6424,26 @@ export class AiService extends TracedEventEmitter {
5656
6424
  resumeAfterAuthFailure: undefined,
5657
6425
  });
5658
6426
  this.clark.clearLastContextUsage?.();
6427
+ }
6428
+ // Reset FSM state that gates the next chat's interactive prompts. Without this, an open interactive prompt
6429
+ // (askMultiChoice card, exitPlanMode plan card, askSearchableDropdown) survives into the next chat and the
6430
+ // channel guard silently rejects the next interactive tool call. See peer.ts for the channel-level recovery.
6431
+ async resetInteractiveStateForChatChange(label, options) {
6432
+ this.clearClarkInteractiveState();
5659
6433
  if (!this.isBusy()) {
5660
6434
  catchBackgroundPeerDisconnect(sendUserGenerationStateChannel(this.clark)({
5661
6435
  state: AiGenerationState.IDLE,
5662
6436
  chatSessionReset: true,
6437
+ chatSessionId: this.chatSessionStore.getChatSessionId(),
5663
6438
  }), `${label} generation state push`);
5664
6439
  }
5665
- await this.reselectBuilderSessionAfterChatChange(label);
6440
+ await this.reselectBuilderSessionAfterChatChange(label, options);
5666
6441
  }
5667
- // The server session already changed, so a failed select must not fail the chat change.
5668
- async reselectBuilderSessionAfterChatChange(label) {
6442
+ /**
6443
+ * The server session already changed, so a failed select must not fail a plain chat change. A harness switch
6444
+ * (`rethrow`) fails instead: the user picked a harness, and reporting success would leave them on the old one.
6445
+ */
6446
+ async reselectBuilderSessionAfterChatChange(label, options) {
5669
6447
  if (!this.builderBinding)
5670
6448
  return;
5671
6449
  try {
@@ -5673,6 +6451,10 @@ export class AiService extends TracedEventEmitter {
5673
6451
  }
5674
6452
  catch (error) {
5675
6453
  this.getLogger().error(`[ai-service] Failed to select the builder session after ${label}`, getErrorMeta(error));
6454
+ // The server already moved to the new chat; the next prompt follows it.
6455
+ this.builderBindingStale = true;
6456
+ if (options?.rethrow)
6457
+ throw error;
5676
6458
  }
5677
6459
  }
5678
6460
  reportAbandonTurn(action) {
@@ -6086,7 +6868,7 @@ export class AiService extends TracedEventEmitter {
6086
6868
  // completed or failed already ended it via the generation events; this
6087
6869
  // ends it on the paths that emit neither (user/agent cancel,
6088
6870
  // runtime-updated-without-edits, planning errors that park in Idle).
6089
- this.activeGenerationTrace?.finish();
6871
+ this.activeGenerationTrace?.finish("unclassified");
6090
6872
  if (generationId !== undefined) {
6091
6873
  this.emit("generationSettled", generationId);
6092
6874
  }
@@ -6119,6 +6901,115 @@ export class AiService extends TracedEventEmitter {
6119
6901
  get isWorkspacePlacement() {
6120
6902
  return this.builderBinding?.workspace?.placement === "agentcore";
6121
6903
  }
6904
+ /** Set when the active chat's placement differs from the mode the sidecar started in; see the refresh below. */
6905
+ editorRestartRequired = false;
6906
+ /** When a switch last asked the editor to restart the sidecar; cleared once a switch finds the restart finished. */
6907
+ editorRestartAskedAt;
6908
+ /**
6909
+ * Records whether the dev server must restart before the active chat can run. The sidecar runs Vite or the
6910
+ * workspace edge, chosen from the active chat's placement when it starts, so a chat change that moves the app between
6911
+ * live-edit and agentcore placement leaves it in the wrong mode until it restarts.
6912
+ */
6913
+ async refreshEditorRestartRequired() {
6914
+ const workspace = this.config.workspace;
6915
+ if (!workspace || !this.builderBinding) {
6916
+ this.editorRestartRequired = false;
6917
+ return false;
6918
+ }
6919
+ const ingress = await readWorkspaceIngress(workspace.edgeUrl);
6920
+ // An unreachable sidecar is starting or restarting, and resolves placement as it comes up.
6921
+ this.editorRestartRequired =
6922
+ ingress !== undefined && this.sidecarModeMismatch(ingress);
6923
+ return this.editorRestartRequired;
6924
+ }
6925
+ /** True when the sidecar runs the other mode than the active chat's placement needs. */
6926
+ sidecarModeMismatch(ingress) {
6927
+ return (ingress !== "live-edit") !== this.isWorkspacePlacement;
6928
+ }
6929
+ /**
6930
+ * Refuses a harness, model, or chat switch until the sidecar finishes the restart an earlier switch asked for. The
6931
+ * sidecar picks its mode when it starts, so a switch made while it still restarts from the previous one asks for a
6932
+ * restart that is lost, and leaves the chat on a placement the sidecar does not serve. While that restart is due, a
6933
+ * sidecar that does not answer is restarting too, so the switch waits for it. Checked before the server changes
6934
+ * anything, and only in split placement, where a switch can need a restart at all. A mismatch no switch asked to
6935
+ * fix does not block switching: the switch may fix it, and asks for its own restart when it does not.
6936
+ */
6937
+ async assertEditorFinishedRestarting() {
6938
+ const workspace = this.config.workspace;
6939
+ const askedAt = this.editorRestartAskedAt;
6940
+ if (!workspace || !this.builderBinding || askedAt === undefined)
6941
+ return;
6942
+ // The editor gave up on that restart; a later switch asks again.
6943
+ if (Date.now() - askedAt >= SIDECAR_RESTART_TIMEOUT_MS) {
6944
+ this.editorRestartAskedAt = undefined;
6945
+ return;
6946
+ }
6947
+ const ingress = await readWorkspaceIngress(workspace.edgeUrl);
6948
+ if (ingress !== undefined) {
6949
+ this.editorRestartRequired = this.sidecarModeMismatch(ingress);
6950
+ if (!this.editorRestartRequired) {
6951
+ this.editorRestartAskedAt = undefined;
6952
+ return;
6953
+ }
6954
+ }
6955
+ this.getLogger().info("[ai-service] Refused a switch while the editor restarts", { sidecarReachable: ingress !== undefined });
6956
+ throw new Error(EDITOR_STILL_RESTARTING_MESSAGE);
6957
+ }
6958
+ /**
6959
+ * After a restart into the workspace edge, opens the workspace as soon as the edge answers. The edge forwards the
6960
+ * editor's connection to the VM, so the editor cannot reconnect, and no turn can start, until this process opens it.
6961
+ * A restart into Vite needs nothing from here: Vite serves the editor itself.
6962
+ */
6963
+ openWorkspaceAfterRestart() {
6964
+ const binding = this.builderBinding;
6965
+ const workspace = this.config.workspace;
6966
+ const sessionKey = binding?.workspace?.sessionKey;
6967
+ if (!workspace ||
6968
+ binding?.workspace?.placement !== "agentcore" ||
6969
+ !sessionKey)
6970
+ return;
6971
+ const deadline = Date.now() + SIDECAR_RESTART_TIMEOUT_MS;
6972
+ let failedOpens = 0;
6973
+ const poll = async () => {
6974
+ const current = this.builderBinding;
6975
+ // The chat moved on; whatever it moved to handles its own placement.
6976
+ if (current?.workspace?.placement !== "agentcore" ||
6977
+ current.workspace.sessionKey !== sessionKey)
6978
+ return;
6979
+ const ingress = await readWorkspaceIngress(workspace.edgeUrl);
6980
+ if (ingress !== undefined && ingress !== "live-edit") {
6981
+ this.editorRestartRequired = false;
6982
+ try {
6983
+ await this.ensureWorkspace(current, this.builderBranch ?? "main");
6984
+ return;
6985
+ }
6986
+ catch (error) {
6987
+ // The runtime client forgets a failed open and watches only an open VM, so nothing else retries it, and
6988
+ // the editor cannot reconnect until this process opens it. An editor that can never open it stops here.
6989
+ if (error instanceof WorkspaceDowngradedError ||
6990
+ Date.now() >= deadline)
6991
+ throw error;
6992
+ this.getLogger().warn("[workspace] Opening the workspace after the editor restart failed; retrying", getErrorMeta(error));
6993
+ failedOpens += 1;
6994
+ const backoff = Math.min(SIDECAR_RESTART_POLL_MS * 2 ** failedOpens, WORKSPACE_REOPEN_MAX_BACKOFF_MS, Math.max(deadline - Date.now(), 0));
6995
+ setTimeout(() => void run(), backoff).unref?.();
6996
+ return;
6997
+ }
6998
+ }
6999
+ if (Date.now() >= deadline) {
7000
+ this.getLogger().warn("[workspace] The editor did not restart into the workspace edge; the next prompt asks again");
7001
+ return;
7002
+ }
7003
+ setTimeout(() => void run(), SIDECAR_RESTART_POLL_MS).unref?.();
7004
+ };
7005
+ const run = () => poll().catch((error) => this.getLogger().warn("[workspace] Opening the workspace after the editor restart failed; the next turn retries", getErrorMeta(error)));
7006
+ void run();
7007
+ }
7008
+ /** Refuses a prompt while the sidecar still runs the wrong mode; a restart since the last check clears the flag. */
7009
+ async assertEditorNeedsNoRestart() {
7010
+ if (await this.refreshEditorRestartRequired())
7011
+ throw new Error(EDITOR_RESTART_REQUIRED_MESSAGE);
7012
+ }
6122
7013
  /**
6123
7014
  * The credential this process presents on the sidecar's `/sb-dev-updates`.
6124
7015
  * In agentcore placement that socket is the VM's, which trusts only its
@@ -6163,6 +7054,18 @@ export class AiService extends TracedEventEmitter {
6163
7054
  throw new Error("This app's chat runs in an AgentCore workspace, which this editor cannot open.");
6164
7055
  this.workspaceClient ??= new WorkspaceRuntimeClient({
6165
7056
  runtime: () => this.builderRuntime,
7057
+ // The branch's current chat: a new chat on the same branch keeps the
7058
+ // workspace open, and the chat that opened it can no longer mint tokens.
7059
+ access: (request) => {
7060
+ const current = this.builderBinding;
7061
+ const chatSessionId = current?.workspace?.sessionKey ===
7062
+ request.binding.workspace?.sessionKey
7063
+ ? current?.chatSessionId
7064
+ : request.binding.chatSessionId;
7065
+ return chatSessionId
7066
+ ? this.builderRuntimeAccess(chatSessionId, request.branchName)
7067
+ : undefined;
7068
+ },
6166
7069
  npmRegistryClient: this.npmRegistryClient,
6167
7070
  serverUrl: this.config.superblocksBaseUrl,
6168
7071
  edgeUrl: workspace.edgeUrl,
@@ -6170,20 +7073,31 @@ export class AiService extends TracedEventEmitter {
6170
7073
  // Reopen a reclaimed VM only while someone is in the editor; otherwise
6171
7074
  // the next turn opens it, so AgentCore's idle reclaim still works.
6172
7075
  shouldReopen: () => this.hasConnectedPeer(),
7076
+ // A reloaded editor retries an open the watcher stopped retrying.
7077
+ editorGeneration: () => this.stablePeer.connectionGeneration,
6173
7078
  onReopened: async (result, reopenedKey) => {
6174
7079
  if (!this.adoptWorkspaceOpen(reopenedKey, result))
6175
7080
  return;
6176
7081
  await this.mirrorWorkspaceHash(result.dbfsHash);
6177
7082
  },
6178
7083
  });
6179
- const result = await this.workspaceClient.open({
6180
- binding,
6181
- applicationId: this.config.applicationId,
6182
- branchName,
6183
- templateName: workspace.templateName,
6184
- sdkApiEnabled: workspace.sdkApiEnabled,
6185
- publicHost: workspace.publicHost,
6186
- });
7084
+ let result;
7085
+ try {
7086
+ result = await this.workspaceClient.open({
7087
+ binding,
7088
+ applicationId: this.config.applicationId,
7089
+ branchName,
7090
+ templateName: workspace.templateName,
7091
+ sdkApiEnabled: workspace.sdkApiEnabled,
7092
+ publicHost: workspace.publicHost,
7093
+ });
7094
+ }
7095
+ catch (error) {
7096
+ // The dev server runs live-edit, which never accepts a VM's token; it takes the user's token instead.
7097
+ if (error instanceof WorkspaceDowngradedError)
7098
+ this.workspaceInternalToken = undefined;
7099
+ throw error;
7100
+ }
6187
7101
  if (!this.adoptWorkspaceOpen(sessionKey, result))
6188
7102
  throw new Error("The chat moved to another workspace while it opened");
6189
7103
  if (this.workspaceMirror?.sessionKey !== sessionKey)
@@ -6236,6 +7150,8 @@ export class AiService extends TracedEventEmitter {
6236
7150
  closeWorkspace() {
6237
7151
  this.workspaceClient?.close();
6238
7152
  this.workspaceClient = undefined;
7153
+ // A closed VM's token is never valid again; the next open brings its own.
7154
+ this.workspaceInternalToken = undefined;
6239
7155
  }
6240
7156
  async refreshFileModel() {
6241
7157
  if (!this.fileSystemManager) {