@superblocksteam/vite-plugin-file-sync 2.0.183 → 2.0.185-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (366) hide show
  1. package/dist/agent-tool-executor/claude-file-tools.d.ts +10 -72
  2. package/dist/agent-tool-executor/claude-file-tools.d.ts.map +1 -1
  3. package/dist/agent-tool-executor/claude-sandbox.d.ts +1 -15
  4. package/dist/agent-tool-executor/claude-sandbox.d.ts.map +1 -1
  5. package/dist/agent-tool-executor/claude-shell.d.ts +4 -36
  6. package/dist/agent-tool-executor/claude-shell.d.ts.map +1 -1
  7. package/dist/agent-tool-executor/claude-tool-server.js +2 -2
  8. package/dist/agent-tool-executor/claude-tool-server.js.map +1 -1
  9. package/dist/agent-tool-executor/codex-exec-server.d.ts.map +1 -1
  10. package/dist/agent-tool-executor/codex-exec-server.js +6 -4
  11. package/dist/agent-tool-executor/codex-exec-server.js.map +1 -1
  12. package/dist/agent-tool-executor/codex-execution-policy.js +2 -2
  13. package/dist/agent-tool-executor/codex-execution-policy.js.map +1 -1
  14. package/dist/agent-tool-executor/native-draft-service.d.ts +5 -2
  15. package/dist/agent-tool-executor/native-draft-service.d.ts.map +1 -1
  16. package/dist/agent-tool-executor/native-tool-environment.js +1 -1
  17. package/dist/agent-tool-executor/native-tool-environment.js.map +1 -1
  18. package/dist/ai-service/agent/prompts/build-base-system-prompt.d.ts +2 -0
  19. package/dist/ai-service/agent/prompts/build-base-system-prompt.d.ts.map +1 -1
  20. package/dist/ai-service/agent/prompts/build-base-system-prompt.js +9 -2
  21. package/dist/ai-service/agent/prompts/build-base-system-prompt.js.map +1 -1
  22. package/dist/ai-service/agent/tools/apis/analysis.d.ts.map +1 -1
  23. package/dist/ai-service/agent/tools/apis/analysis.js +36 -67
  24. package/dist/ai-service/agent/tools/apis/analysis.js.map +1 -1
  25. package/dist/ai-service/agent/tools/apis/api-executor.d.ts +1 -0
  26. package/dist/ai-service/agent/tools/apis/api-executor.d.ts.map +1 -1
  27. package/dist/ai-service/agent/tools/apis/api-executor.js +1 -0
  28. package/dist/ai-service/agent/tools/apis/api-executor.js.map +1 -1
  29. package/dist/ai-service/agent/tools/apis/api-validation-orchestrator.d.ts +2 -0
  30. package/dist/ai-service/agent/tools/apis/api-validation-orchestrator.d.ts.map +1 -1
  31. package/dist/ai-service/agent/tools/apis/api-validation-orchestrator.js +1 -0
  32. package/dist/ai-service/agent/tools/apis/api-validation-orchestrator.js.map +1 -1
  33. package/dist/ai-service/agent/tools/apis/test-api.d.ts +22 -1
  34. package/dist/ai-service/agent/tools/apis/test-api.d.ts.map +1 -1
  35. package/dist/ai-service/agent/tools/apis/test-api.js +115 -65
  36. package/dist/ai-service/agent/tools/apis/test-api.js.map +1 -1
  37. package/dist/ai-service/agent/tools/branching/branch-tools.d.ts +2 -2
  38. package/dist/ai-service/agent/tools/branching/branch-tools.d.ts.map +1 -1
  39. package/dist/ai-service/agent/tools/branching/branch-tools.js +1 -1
  40. package/dist/ai-service/agent/tools/branching/branch-tools.js.map +1 -1
  41. package/dist/ai-service/agent/tools/build-copy-utils.d.ts +13 -44
  42. package/dist/ai-service/agent/tools/build-copy-utils.d.ts.map +1 -1
  43. package/dist/ai-service/agent/tools/build-debug.d.ts +1 -1
  44. package/dist/ai-service/agent/tools/build-debug.d.ts.map +1 -1
  45. package/dist/ai-service/agent/tools/build-delete-file.d.ts +1 -0
  46. package/dist/ai-service/agent/tools/build-delete-file.d.ts.map +1 -1
  47. package/dist/ai-service/agent/tools/build-delete-file.js +3 -0
  48. package/dist/ai-service/agent/tools/build-delete-file.js.map +1 -1
  49. package/dist/ai-service/agent/tools/build-edit-file.d.ts +2 -0
  50. package/dist/ai-service/agent/tools/build-edit-file.d.ts.map +1 -1
  51. package/dist/ai-service/agent/tools/build-edit-file.js +7 -0
  52. package/dist/ai-service/agent/tools/build-edit-file.js.map +1 -1
  53. package/dist/ai-service/agent/tools/build-install-packages.d.ts.map +1 -1
  54. package/dist/ai-service/agent/tools/build-install-packages.js +5 -1
  55. package/dist/ai-service/agent/tools/build-install-packages.js.map +1 -1
  56. package/dist/ai-service/agent/tools/build-list-files.d.ts +1 -1
  57. package/dist/ai-service/agent/tools/build-multi-edit-file.d.ts +1 -0
  58. package/dist/ai-service/agent/tools/build-multi-edit-file.d.ts.map +1 -1
  59. package/dist/ai-service/agent/tools/build-multi-edit-file.js +3 -0
  60. package/dist/ai-service/agent/tools/build-multi-edit-file.js.map +1 -1
  61. package/dist/ai-service/agent/tools/build-navigate-preview.js +2 -2
  62. package/dist/ai-service/agent/tools/build-navigate-preview.js.map +1 -1
  63. package/dist/ai-service/agent/tools/build-write-file.d.ts +1 -0
  64. package/dist/ai-service/agent/tools/build-write-file.d.ts.map +1 -1
  65. package/dist/ai-service/agent/tools/build-write-file.js +3 -0
  66. package/dist/ai-service/agent/tools/build-write-file.js.map +1 -1
  67. package/dist/ai-service/agent/tools/clear-error-cache.d.ts +1 -1
  68. package/dist/ai-service/agent/tools/databases/dev-database-tasks.d.ts +39 -185
  69. package/dist/ai-service/agent/tools/databases/dev-database-tasks.d.ts.map +1 -1
  70. package/dist/ai-service/agent/tools/databases/dev-database-tasks.js +35 -13
  71. package/dist/ai-service/agent/tools/databases/dev-database-tasks.js.map +1 -1
  72. package/dist/ai-service/agent/tools/databases/dev-database-tools.d.ts +2 -2
  73. package/dist/ai-service/agent/tools/get-security-findings.d.ts +1 -1
  74. package/dist/ai-service/agent/tools/integrations/execute-request.d.ts +71 -268
  75. package/dist/ai-service/agent/tools/integrations/execute-request.d.ts.map +1 -1
  76. package/dist/ai-service/agent/tools/integrations/execute-request.js +20 -11
  77. package/dist/ai-service/agent/tools/integrations/execute-request.js.map +1 -1
  78. package/dist/ai-service/agent/tools/integrations/index.d.ts +1 -1
  79. package/dist/ai-service/agent/tools/integrations/index.d.ts.map +1 -1
  80. package/dist/ai-service/agent/tools/integrations/index.js +1 -1
  81. package/dist/ai-service/agent/tools/integrations/index.js.map +1 -1
  82. package/dist/ai-service/agent/tools/integrations/integration-setup.d.ts +2 -2
  83. package/dist/ai-service/agent/tools/integrations/integration-setup.js +3 -3
  84. package/dist/ai-service/agent/tools/integrations/integration-setup.js.map +1 -1
  85. package/dist/ai-service/agent/tools/integrations/internal.d.ts +14 -2
  86. package/dist/ai-service/agent/tools/integrations/internal.d.ts.map +1 -1
  87. package/dist/ai-service/agent/tools/integrations/internal.js +5 -2
  88. package/dist/ai-service/agent/tools/integrations/internal.js.map +1 -1
  89. package/dist/ai-service/agent/tools/project-agent-feedback.d.ts +17 -0
  90. package/dist/ai-service/agent/tools/project-agent-feedback.d.ts.map +1 -0
  91. package/dist/ai-service/agent/tools/project-agent-feedback.js +87 -0
  92. package/dist/ai-service/agent/tools/project-agent-feedback.js.map +1 -0
  93. package/dist/ai-service/agent/tools/report-security-findings.d.ts +25 -112
  94. package/dist/ai-service/agent/tools/report-security-findings.d.ts.map +1 -1
  95. package/dist/ai-service/agent/tools.d.ts.map +1 -1
  96. package/dist/ai-service/agent/tools.js +1 -0
  97. package/dist/ai-service/agent/tools.js.map +1 -1
  98. package/dist/ai-service/agent/tools2/access-control.d.ts +6 -0
  99. package/dist/ai-service/agent/tools2/access-control.d.ts.map +1 -1
  100. package/dist/ai-service/agent/tools2/access-control.js +16 -10
  101. package/dist/ai-service/agent/tools2/access-control.js.map +1 -1
  102. package/dist/ai-service/agent/tools2/registry.d.ts +4 -2
  103. package/dist/ai-service/agent/tools2/registry.d.ts.map +1 -1
  104. package/dist/ai-service/agent/tools2/registry.js +21 -9
  105. package/dist/ai-service/agent/tools2/registry.js.map +1 -1
  106. package/dist/ai-service/agent/tools2/tool-execution-scope.d.ts +10 -0
  107. package/dist/ai-service/agent/tools2/tool-execution-scope.d.ts.map +1 -0
  108. package/dist/ai-service/agent/tools2/tool-execution-scope.js +21 -0
  109. package/dist/ai-service/agent/tools2/tool-execution-scope.js.map +1 -0
  110. package/dist/ai-service/agent/tools2/tools/end-test-run.d.ts +1 -1
  111. package/dist/ai-service/agent/tools2/tools/list-tasks.d.ts +1 -1
  112. package/dist/ai-service/agent/tools2/types.d.ts +1 -1
  113. package/dist/ai-service/agent/tools2/types.d.ts.map +1 -1
  114. package/dist/ai-service/agent/tools2/types.js.map +1 -1
  115. package/dist/ai-service/app-interface/invalid-lockfile-error.d.ts +11 -0
  116. package/dist/ai-service/app-interface/invalid-lockfile-error.d.ts.map +1 -0
  117. package/dist/ai-service/app-interface/invalid-lockfile-error.js +27 -0
  118. package/dist/ai-service/app-interface/invalid-lockfile-error.js.map +1 -0
  119. package/dist/ai-service/app-interface/npm-lockfile-sources.d.ts +13 -0
  120. package/dist/ai-service/app-interface/npm-lockfile-sources.d.ts.map +1 -0
  121. package/dist/ai-service/app-interface/npm-lockfile-sources.js +129 -0
  122. package/dist/ai-service/app-interface/npm-lockfile-sources.js.map +1 -0
  123. package/dist/ai-service/app-interface/npm-registry.d.ts +20 -10
  124. package/dist/ai-service/app-interface/npm-registry.d.ts.map +1 -1
  125. package/dist/ai-service/app-interface/npm-registry.js +109 -73
  126. package/dist/ai-service/app-interface/npm-registry.js.map +1 -1
  127. package/dist/ai-service/app-interface/registry-lockfile-preparer.d.ts +46 -0
  128. package/dist/ai-service/app-interface/registry-lockfile-preparer.d.ts.map +1 -0
  129. package/dist/ai-service/app-interface/registry-lockfile-preparer.js +88 -0
  130. package/dist/ai-service/app-interface/registry-lockfile-preparer.js.map +1 -0
  131. package/dist/ai-service/app-interface/shell.d.ts +14 -4
  132. package/dist/ai-service/app-interface/shell.d.ts.map +1 -1
  133. package/dist/ai-service/app-interface/shell.js +45 -30
  134. package/dist/ai-service/app-interface/shell.js.map +1 -1
  135. package/dist/ai-service/attachments/validate-prompt-attachments.d.ts.map +1 -1
  136. package/dist/ai-service/attachments/validate-prompt-attachments.js +12 -2
  137. package/dist/ai-service/attachments/validate-prompt-attachments.js.map +1 -1
  138. package/dist/ai-service/builder-binding-error.d.ts +5 -0
  139. package/dist/ai-service/builder-binding-error.d.ts.map +1 -0
  140. package/dist/ai-service/builder-binding-error.js +8 -0
  141. package/dist/ai-service/builder-binding-error.js.map +1 -0
  142. package/dist/ai-service/builder-conversation.d.ts +71 -6
  143. package/dist/ai-service/builder-conversation.d.ts.map +1 -1
  144. package/dist/ai-service/builder-conversation.js +549 -83
  145. package/dist/ai-service/builder-conversation.js.map +1 -1
  146. package/dist/ai-service/builder-core-prompt.d.ts +3 -3
  147. package/dist/ai-service/builder-core-prompt.d.ts.map +1 -1
  148. package/dist/ai-service/builder-core-prompt.js +22 -34
  149. package/dist/ai-service/builder-core-prompt.js.map +1 -1
  150. package/dist/ai-service/builder-runtime-auth.d.ts.map +1 -1
  151. package/dist/ai-service/builder-runtime-auth.js +6 -2
  152. package/dist/ai-service/builder-runtime-auth.js.map +1 -1
  153. package/dist/ai-service/builder-runtime.d.ts +105 -240
  154. package/dist/ai-service/builder-runtime.d.ts.map +1 -1
  155. package/dist/ai-service/builder-runtime.js +391 -77
  156. package/dist/ai-service/builder-runtime.js.map +1 -1
  157. package/dist/ai-service/builder-session-store.d.ts +1 -7
  158. package/dist/ai-service/builder-session-store.d.ts.map +1 -1
  159. package/dist/ai-service/builder-session-store.js +1 -1
  160. package/dist/ai-service/builder-session-store.js.map +1 -1
  161. package/dist/ai-service/builder-tool-callbacks.d.ts +19 -0
  162. package/dist/ai-service/builder-tool-callbacks.d.ts.map +1 -1
  163. package/dist/ai-service/builder-tool-callbacks.js +151 -31
  164. package/dist/ai-service/builder-tool-callbacks.js.map +1 -1
  165. package/dist/ai-service/builder-tools.d.ts +28 -5
  166. package/dist/ai-service/builder-tools.d.ts.map +1 -1
  167. package/dist/ai-service/builder-tools.js +214 -45
  168. package/dist/ai-service/builder-tools.js.map +1 -1
  169. package/dist/ai-service/builder-workspace.d.ts +1 -0
  170. package/dist/ai-service/builder-workspace.d.ts.map +1 -1
  171. package/dist/ai-service/builder-workspace.js +15 -6
  172. package/dist/ai-service/builder-workspace.js.map +1 -1
  173. package/dist/ai-service/chat/chat-session-store.d.ts +2 -2
  174. package/dist/ai-service/chat/chat-session-store.d.ts.map +1 -1
  175. package/dist/ai-service/chat/chat-session-store.js +25 -8
  176. package/dist/ai-service/chat/chat-session-store.js.map +1 -1
  177. package/dist/ai-service/demo-agents/handlers.d.ts +11 -24
  178. package/dist/ai-service/demo-agents/handlers.d.ts.map +1 -1
  179. package/dist/ai-service/demo-agents/handlers.js +19 -30
  180. package/dist/ai-service/demo-agents/handlers.js.map +1 -1
  181. package/dist/ai-service/demo-agents/load-agents.d.ts +9 -2
  182. package/dist/ai-service/demo-agents/load-agents.d.ts.map +1 -1
  183. package/dist/ai-service/demo-agents/load-agents.js +50 -49
  184. package/dist/ai-service/demo-agents/load-agents.js.map +1 -1
  185. package/dist/ai-service/demo-agents/run-agent.d.ts.map +1 -1
  186. package/dist/ai-service/demo-agents/run-agent.js +50 -5
  187. package/dist/ai-service/demo-agents/run-agent.js.map +1 -1
  188. package/dist/ai-service/demo-agents/system-prompt.d.ts +6 -5
  189. package/dist/ai-service/demo-agents/system-prompt.d.ts.map +1 -1
  190. package/dist/ai-service/demo-agents/system-prompt.js +18 -26
  191. package/dist/ai-service/demo-agents/system-prompt.js.map +1 -1
  192. package/dist/ai-service/demo-agents/types.d.ts +9 -56
  193. package/dist/ai-service/demo-agents/types.d.ts.map +1 -1
  194. package/dist/ai-service/demo-agents/types.js +0 -7
  195. package/dist/ai-service/demo-agents/types.js.map +1 -1
  196. package/dist/ai-service/dev-database-file-sync.d.ts +2 -1
  197. package/dist/ai-service/dev-database-file-sync.d.ts.map +1 -1
  198. package/dist/ai-service/dev-database-file-sync.js.map +1 -1
  199. package/dist/ai-service/features.d.ts +20 -8
  200. package/dist/ai-service/features.d.ts.map +1 -1
  201. package/dist/ai-service/index.d.ts +107 -15
  202. package/dist/ai-service/index.d.ts.map +1 -1
  203. package/dist/ai-service/index.js +588 -139
  204. package/dist/ai-service/index.js.map +1 -1
  205. package/dist/ai-service/judge/tools/playwright-action.d.ts +5 -5
  206. package/dist/ai-service/judge/tools/playwright-action.d.ts.map +1 -1
  207. package/dist/ai-service/judge/tools/playwright-action.js +4 -1
  208. package/dist/ai-service/judge/tools/playwright-action.js.map +1 -1
  209. package/dist/ai-service/llm/context-v2/context-metrics.js +2 -2
  210. package/dist/ai-service/llm/context-v2/storage/event-types.d.ts +45 -110
  211. package/dist/ai-service/llm/context-v2/storage/event-types.d.ts.map +1 -1
  212. package/dist/ai-service/llm/context-v2/storage/event-types.js +3 -3
  213. package/dist/ai-service/llm/context-v2/storage/event-types.js.map +1 -1
  214. package/dist/ai-service/llm/interaction/adapters/vercel.d.ts.map +1 -1
  215. package/dist/ai-service/llm/interaction/adapters/vercel.js +6 -1
  216. package/dist/ai-service/llm/interaction/adapters/vercel.js.map +1 -1
  217. package/dist/ai-service/mcp/adapter/json-schema-to-zod.d.ts.map +1 -1
  218. package/dist/ai-service/mcp/adapter/json-schema-to-zod.js.map +1 -1
  219. package/dist/ai-service/mcp/embedded-playwright-mcp-server.d.ts +2 -0
  220. package/dist/ai-service/mcp/embedded-playwright-mcp-server.d.ts.map +1 -1
  221. package/dist/ai-service/mcp/embedded-playwright-mcp-server.js +28 -0
  222. package/dist/ai-service/mcp/embedded-playwright-mcp-server.js.map +1 -1
  223. package/dist/ai-service/mcp/playwright-server.d.ts +2 -0
  224. package/dist/ai-service/mcp/playwright-server.d.ts.map +1 -1
  225. package/dist/ai-service/mcp/playwright-server.js +1 -0
  226. package/dist/ai-service/mcp/playwright-server.js.map +1 -1
  227. package/dist/ai-service/migration-prompt-gating.d.ts +2 -0
  228. package/dist/ai-service/migration-prompt-gating.d.ts.map +1 -1
  229. package/dist/ai-service/migration-prompt-gating.js +3 -0
  230. package/dist/ai-service/migration-prompt-gating.js.map +1 -1
  231. package/dist/ai-service/native-turn-failure.d.ts +13 -0
  232. package/dist/ai-service/native-turn-failure.d.ts.map +1 -1
  233. package/dist/ai-service/native-turn-failure.js +46 -1
  234. package/dist/ai-service/native-turn-failure.js.map +1 -1
  235. package/dist/ai-service/prompt-builder-service/types.d.ts +3 -1
  236. package/dist/ai-service/prompt-builder-service/types.d.ts.map +1 -1
  237. package/dist/ai-service/security/vulnerability-triage.d.ts +12 -30
  238. package/dist/ai-service/security/vulnerability-triage.d.ts.map +1 -1
  239. package/dist/ai-service/skills/system/_registry.generated.d.ts.map +1 -1
  240. package/dist/ai-service/skills/system/_registry.generated.js +6 -0
  241. package/dist/ai-service/skills/system/_registry.generated.js.map +1 -1
  242. package/dist/ai-service/skills/system/project-agents/references/errors.generated.d.ts +2 -0
  243. package/dist/ai-service/skills/system/project-agents/references/errors.generated.d.ts.map +1 -0
  244. package/dist/ai-service/skills/system/project-agents/references/errors.generated.js +26 -0
  245. package/dist/ai-service/skills/system/project-agents/references/errors.generated.js.map +1 -0
  246. package/dist/ai-service/skills/system/project-agents/references/fields.generated.d.ts +2 -0
  247. package/dist/ai-service/skills/system/project-agents/references/fields.generated.d.ts.map +1 -0
  248. package/dist/ai-service/skills/system/project-agents/references/fields.generated.js +55 -0
  249. package/dist/ai-service/skills/system/project-agents/references/fields.generated.js.map +1 -0
  250. package/dist/ai-service/skills/system/project-agents/skill.generated.d.ts +2 -0
  251. package/dist/ai-service/skills/system/project-agents/skill.generated.d.ts.map +1 -0
  252. package/dist/ai-service/skills/system/project-agents/skill.generated.js +74 -0
  253. package/dist/ai-service/skills/system/project-agents/skill.generated.js.map +1 -0
  254. package/dist/ai-service/state-machine/handlers/llm-generating.d.ts.map +1 -1
  255. package/dist/ai-service/state-machine/handlers/llm-generating.js +10 -7
  256. package/dist/ai-service/state-machine/handlers/llm-generating.js.map +1 -1
  257. package/dist/ai-service/state-machine/helpers/prompt-failure.d.ts +8 -0
  258. package/dist/ai-service/state-machine/helpers/prompt-failure.d.ts.map +1 -1
  259. package/dist/ai-service/state-machine/helpers/prompt-failure.js +25 -8
  260. package/dist/ai-service/state-machine/helpers/prompt-failure.js.map +1 -1
  261. package/dist/ai-service/state-machine/helpers/prompt-request-metrics.d.ts +4 -0
  262. package/dist/ai-service/state-machine/helpers/prompt-request-metrics.d.ts.map +1 -1
  263. package/dist/ai-service/state-machine/helpers/prompt-request-metrics.js +4 -0
  264. package/dist/ai-service/state-machine/helpers/prompt-request-metrics.js.map +1 -1
  265. package/dist/ai-service/state-machine/helpers/stable-peer.d.ts +2 -0
  266. package/dist/ai-service/state-machine/helpers/stable-peer.d.ts.map +1 -1
  267. package/dist/ai-service/state-machine/helpers/stable-peer.js +9 -2
  268. package/dist/ai-service/state-machine/helpers/stable-peer.js.map +1 -1
  269. package/dist/ai-service/tasks/task-store.d.ts.map +1 -1
  270. package/dist/ai-service/tasks/task-store.js +1 -1
  271. package/dist/ai-service/tasks/task-store.js.map +1 -1
  272. package/dist/ai-service/tasks/types.d.ts +5 -1
  273. package/dist/ai-service/tasks/types.d.ts.map +1 -1
  274. package/dist/ai-service/tool-input-schema.d.ts +14 -0
  275. package/dist/ai-service/tool-input-schema.d.ts.map +1 -0
  276. package/dist/ai-service/tool-input-schema.js +23 -0
  277. package/dist/ai-service/tool-input-schema.js.map +1 -0
  278. package/dist/ai-service/util/inference-jwt.d.ts +5 -0
  279. package/dist/ai-service/util/inference-jwt.d.ts.map +1 -1
  280. package/dist/ai-service/util/inference-jwt.js +17 -0
  281. package/dist/ai-service/util/inference-jwt.js.map +1 -1
  282. package/dist/ai-service/workspace-mirror.d.ts +2 -0
  283. package/dist/ai-service/workspace-mirror.d.ts.map +1 -1
  284. package/dist/ai-service/workspace-mirror.js +21 -0
  285. package/dist/ai-service/workspace-mirror.js.map +1 -1
  286. package/dist/ai-service/workspace-package-registry.d.ts +3 -0
  287. package/dist/ai-service/workspace-package-registry.d.ts.map +1 -0
  288. package/dist/ai-service/workspace-package-registry.js +87 -0
  289. package/dist/ai-service/workspace-package-registry.js.map +1 -0
  290. package/dist/ai-service/workspace-package-state.d.ts +12 -0
  291. package/dist/ai-service/workspace-package-state.d.ts.map +1 -0
  292. package/dist/ai-service/workspace-package-state.js +47 -0
  293. package/dist/ai-service/workspace-package-state.js.map +1 -0
  294. package/dist/ai-service/workspace-packages.d.ts +234 -0
  295. package/dist/ai-service/workspace-packages.d.ts.map +1 -0
  296. package/dist/ai-service/workspace-packages.js +466 -0
  297. package/dist/ai-service/workspace-packages.js.map +1 -0
  298. package/dist/dev-server-ws-smoke-client.d.ts.map +1 -1
  299. package/dist/dev-server-ws-smoke-client.js +1 -0
  300. package/dist/dev-server-ws-smoke-client.js.map +1 -1
  301. package/dist/file-sync-vite-plugin.d.ts +3 -1
  302. package/dist/file-sync-vite-plugin.d.ts.map +1 -1
  303. package/dist/file-sync-vite-plugin.js +28 -11
  304. package/dist/file-sync-vite-plugin.js.map +1 -1
  305. package/dist/file-system-manager.d.ts.map +1 -1
  306. package/dist/file-system-manager.js +11 -13
  307. package/dist/file-system-manager.js.map +1 -1
  308. package/dist/import-check.d.ts +16 -0
  309. package/dist/import-check.d.ts.map +1 -0
  310. package/dist/import-check.js +23 -0
  311. package/dist/import-check.js.map +1 -0
  312. package/dist/index.d.ts +5 -3
  313. package/dist/index.d.ts.map +1 -1
  314. package/dist/index.js +2 -1
  315. package/dist/index.js.map +1 -1
  316. package/dist/lock-service/branch-metrics.d.ts +1 -1
  317. package/dist/lock-service/branch-metrics.d.ts.map +1 -1
  318. package/dist/lock-service/branch-metrics.js.map +1 -1
  319. package/dist/lock-service/index.d.ts +51 -0
  320. package/dist/lock-service/index.d.ts.map +1 -1
  321. package/dist/lock-service/index.js +176 -0
  322. package/dist/lock-service/index.js.map +1 -1
  323. package/dist/plugin-options.d.ts +9 -1
  324. package/dist/plugin-options.d.ts.map +1 -1
  325. package/dist/plugin-options.js.map +1 -1
  326. package/dist/policy-gate-runner.d.ts +1 -9
  327. package/dist/policy-gate-runner.d.ts.map +1 -1
  328. package/dist/project-agent-update.d.ts +44 -0
  329. package/dist/project-agent-update.d.ts.map +1 -0
  330. package/dist/project-agent-update.js +125 -0
  331. package/dist/project-agent-update.js.map +1 -0
  332. package/dist/project-agents.d.ts +31 -0
  333. package/dist/project-agents.d.ts.map +1 -0
  334. package/dist/project-agents.js +50 -0
  335. package/dist/project-agents.js.map +1 -0
  336. package/dist/project-manifest.d.ts +8 -108
  337. package/dist/project-manifest.d.ts.map +1 -1
  338. package/dist/project-manifest.js +28 -115
  339. package/dist/project-manifest.js.map +1 -1
  340. package/dist/server-rpc/index.d.ts +6 -0
  341. package/dist/server-rpc/index.d.ts.map +1 -1
  342. package/dist/server-rpc/index.js +13 -1
  343. package/dist/server-rpc/index.js.map +1 -1
  344. package/dist/socket-manager.d.ts +3 -1
  345. package/dist/socket-manager.d.ts.map +1 -1
  346. package/dist/socket-manager.js +122 -72
  347. package/dist/socket-manager.js.map +1 -1
  348. package/dist/sync-service/draft-mutation.d.ts +6 -2
  349. package/dist/sync-service/draft-mutation.d.ts.map +1 -1
  350. package/dist/sync-service/draft-mutation.js +20 -33
  351. package/dist/sync-service/draft-mutation.js.map +1 -1
  352. package/dist/sync-service/index.d.ts +6 -6
  353. package/dist/sync-service/index.d.ts.map +1 -1
  354. package/dist/sync-service/index.js +29 -61
  355. package/dist/sync-service/index.js.map +1 -1
  356. package/dist/workspace-sync-methods.d.ts +5 -20
  357. package/dist/workspace-sync-methods.d.ts.map +1 -1
  358. package/package.json +17 -13
  359. package/dist/project-agent-tools.d.ts +0 -23
  360. package/dist/project-agent-tools.d.ts.map +0 -1
  361. package/dist/project-agent-tools.js +0 -73
  362. package/dist/project-agent-tools.js.map +0 -1
  363. package/dist/sync-service/native-draft-session.d.ts +0 -3
  364. package/dist/sync-service/native-draft-session.d.ts.map +0 -1
  365. package/dist/sync-service/native-draft-session.js +0 -4
  366. package/dist/sync-service/native-draft-session.js.map +0 -1
@@ -6,7 +6,7 @@ import { context as otelContext, metrics, propagation, SpanKind, SpanStatusCode,
6
6
  import { z } from "zod";
7
7
  import { AiGenerationState, AiMode, resolveAttachmentFileName, } from "@superblocksteam/library-shared/types";
8
8
  import { isToolPermissionClarification } from "@superblocksteam/library-shared/types/tool-permission-response";
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";
9
+ import { addTracingToMethods, BuilderCaller, AiSystemTriggerType, classifyAttachmentDelivery, FactAccessType, FactCreatedSource, FactEntityScope, isAiAbandonTurnState, TracedEventEmitter, getAiQuotaPaywallReasonFromMessage, isAiQuotaPaywallReason, CHAT_CHANGED_ELSEWHERE_MESSAGE, EDITOR_RESTART_REQUIRED_MESSAGE, isChatChangedElsewhereError, SWITCH_ENDS_WAITING_TURN_MESSAGE, SWITCH_NEEDS_DRAFT_SETTLED_MESSAGE, SWITCH_STOPS_WORKING_TURN_MESSAGE, SocketErrorException, } from "@superblocksteam/shared";
10
10
  import { AgentSessionTrace, HarnessTrace, npmRegistryEmitter, TraceCorrelation, } from "@superblocksteam/telemetry";
11
11
  import { applyTestApiDenialSideEffects, buildMigrationTestApiDenialContinuationPrompt, } from "../migration/mark-api-testing-denied.js";
12
12
  import { buildTranslationPrompt } from "../migration/translation-prompt.js";
@@ -25,7 +25,7 @@ import { isBackgroundTaskFrameworkEnabled } from "./agent/tools.js";
25
25
  import { hasPendingEscalations, flushPendingEscalations, } from "./agent/tools/apis/api-validation-orchestrator.js";
26
26
  import { safeSampleJson } from "./agent/tools/apis/sample-json.js";
27
27
  import { resolveSdkApiEntryPoint } from "./agent/tools/apis/sdk-registry.js";
28
- import { applyDevDatabaseMigrationsTaskMetadata, createDevDatabaseTaskTypes, wireDevDatabaseIntegrationPriming, } from "./agent/tools/databases/dev-database-tasks.js";
28
+ import { applyDevDatabaseMigrationsTaskMetadata, createDevDatabaseTaskTypes, DevDatabaseTaskOwnerUnavailableError, wireDevDatabaseIntegrationPriming, } from "./agent/tools/databases/dev-database-tasks.js";
29
29
  import { debugCache } from "./agent/tools/debug-cache.js";
30
30
  import { SessionEntityPermissionStore, } from "./agent/tools2/entity-permissions.js";
31
31
  import { ToolRegistry } from "./agent/tools2/registry.js";
@@ -40,6 +40,7 @@ import { NativeAttachmentPreparations } from "./attachments/native-attachment-pr
40
40
  import { parseDataUrl } from "./attachments/parse-data-url.js";
41
41
  import { isUploadedAttachment, toUploadedAttachmentContentPart, } from "./attachments/uploaded-content-part.js";
42
42
  import { resolveAttachmentHistory, resolvePromptAttachments, } from "./attachments/validate-prompt-attachments.js";
43
+ import { BuilderBindingChangedError } from "./builder-binding-error.js";
43
44
  import { BuilderConversation } from "./builder-conversation.js";
44
45
  import { BuilderInferenceAuth } from "./builder-inference-auth.js";
45
46
  import { BuilderRuntimeAuth } from "./builder-runtime-auth.js";
@@ -59,7 +60,7 @@ import { restoreConversationToCheckpoint, } from "./context-restore.js";
59
60
  import { uploadContextToBucketeer } from "./context-upload.js";
60
61
  import { AppContextStore } from "./context/app-context.js";
61
62
  import { projectAgentsEnabled } from "./demo-agents/enabled.js";
62
- import { handleAgentList, handleAgentResetSession, handleAgentRun, handleAgentSetTool, handleRemoteAgentRun, } from "./demo-agents/handlers.js";
63
+ import { handleAgentList, handleAgentUpdate, handleAgentResetSession, handleAgentRun, handleRemoteAgentRun, } from "./demo-agents/handlers.js";
63
64
  import { createDevDatabaseHttpTransport, DevDatabaseClient, } from "./dev-database-client.js";
64
65
  import { buildEnsureDevDatabaseFilesSynced, } from "./dev-database-file-sync.js";
65
66
  import { EditAfterClarkTracker } from "./edit-after-clark.js";
@@ -94,6 +95,7 @@ import { recordMigrationAutoDispatchOutcome } from "./migration-autodispatch-met
94
95
  import { buildServerMigrationLlmConfig, isMigrationAutoDispatchEnabled, } from "./migration-llm-config.js";
95
96
  import { isMigrationSessionActive } from "./migration-session-active.js";
96
97
  import { hasSettledNormalMigrationTurn, recordMigrationTurnDispatched, recordMigrationTurnSettled, } from "./migration-turns-log.js";
98
+ import { NativeTurnFailure } from "./native-turn-failure.js";
97
99
  import { buildPolicyGateRemediationUsageMetadata } from "./policy-gate-remediation-usage.js";
98
100
  import { createReviewAppShell, runPolicyGateReview, } from "./policy-gate-review.js";
99
101
  import { ClarkProfiler } from "./profiler/clark-profiler.js";
@@ -136,6 +138,7 @@ import { PERMISSION_PROMPT_DELIVERY_TIMEOUT_MS, PERMISSION_PROMPT_RESPONSE_TIMEO
136
138
  import { getToolCallSignature } from "./util/tool-signature.js";
137
139
  import { readWorkspaceIngress } from "./workspace-edge-health.js";
138
140
  import { rpcWorkspaceMirrorSource, WorkspaceMirror, } from "./workspace-mirror.js";
141
+ import { workspacePackageShell, parseWorkspacePackagePolicyRequest, } from "./workspace-packages.js";
139
142
  export { AiServiceFeatureFlags } from "./features.js";
140
143
  export { WorkspaceDowngradedError } from "./builder-workspace.js";
141
144
  export { BuilderRuntime } from "./builder-runtime.js";
@@ -360,17 +363,28 @@ function builderBindingMismatchCounter() {
360
363
  });
361
364
  return bindingMismatchCounter;
362
365
  }
366
+ let switchClaimCounter;
367
+ function builderSwitchClaimCounter() {
368
+ switchClaimCounter ??= metrics
369
+ .getMeter("superblocks.ai_service")
370
+ .createCounter("superblocks.ai_service.builder_switch.claims", {
371
+ description: "Harness or model switch requests, by whether a running turn refused, was stopped for, or did not stop for the switch",
372
+ unit: "1",
373
+ });
374
+ return switchClaimCounter;
375
+ }
376
+ function recordBuilderSwitchClaim(kind, outcome) {
377
+ builderSwitchClaimCounter().add(1, {
378
+ "switch.kind": kind,
379
+ "switch.outcome": outcome,
380
+ });
381
+ }
363
382
  function bindingMatchesRuntime(binding, runtime) {
364
383
  return (binding.harness === runtime.harness &&
365
384
  (binding.model === undefined || binding.model === runtime.model));
366
385
  }
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
- }
386
+ /** A server commit id. */
387
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
374
388
  export class AiService extends TracedEventEmitter {
375
389
  config;
376
390
  templateRenderer;
@@ -396,7 +410,19 @@ export class AiService extends TracedEventEmitter {
396
410
  */
397
411
  builderBindingStale = false;
398
412
  /** Set while a harness switch moves the server and this pod to a new chat; prompts wait for it to finish. */
399
- builderSwitchInProgress = false;
413
+ _builderSwitchInProgress = false;
414
+ /** Every editor must see a switch: prompts are refused while it runs, and its stop publishes CANCELLED to all of them. */
415
+ get builderSwitchInProgress() {
416
+ return this._builderSwitchInProgress;
417
+ }
418
+ set builderSwitchInProgress(switching) {
419
+ if (switching === this._builderSwitchInProgress)
420
+ return;
421
+ this._builderSwitchInProgress = switching;
422
+ catchBackgroundPeerDisconnect(this.stablePeer.call.aiSetBuilderSwitching({ switching }), "builder switching push");
423
+ }
424
+ /** Clark's USER_CANCELED handler, which keeps writing to the chat after the FSM reports Idle. */
425
+ clarkCancelHandler;
400
426
  /**
401
427
  * Prompts past the switch check but whose turn has not started yet. They await a server round trip before the
402
428
  * conversation reports busy, so a switch counts them as a running turn.
@@ -407,9 +433,106 @@ export class AiService extends TracedEventEmitter {
407
433
  /** The binding the pre-turn check resolved, which that request's turn uses instead of resolving again. */
408
434
  checkedBinding;
409
435
  workspaceClient;
436
+ workspacePackageTransport;
437
+ workspacePackageRecovery = { required: false };
438
+ setWorkspacePackageTransport(transport) {
439
+ this.workspacePackageTransport = transport;
440
+ }
441
+ async workspacePackagePolicy(request) {
442
+ request = parseWorkspacePackagePolicyRequest(request);
443
+ switch (request.kind) {
444
+ case "registry": {
445
+ const result = await this.npmRegistryClient.getConfig({
446
+ forceRefresh: true,
447
+ });
448
+ return {
449
+ source: result.source,
450
+ config: {
451
+ configured: result.config.configured,
452
+ allowInstallScripts: result.config.allowInstallScripts,
453
+ },
454
+ ...(result.source === "unreachable" && {
455
+ everConfigured: result.everConfigured,
456
+ }),
457
+ };
458
+ }
459
+ case "lookup":
460
+ return this.appShell.lookupPackageVulnerabilities(request.packages);
461
+ case "holdback":
462
+ return this.npmPackageLookup.pickQuarantineHoldback(request.name, request.version);
463
+ case "blocked_audit":
464
+ return this.config.rpcClient.call((client) => client.call.v1.audit.npmInstallBlocked(request.report));
465
+ case "outcome":
466
+ return this.config.rpcClient.call((client) => client.call.v1.audit.npmInstallOutcome(request.report));
467
+ }
468
+ }
469
+ nativePackageServices() {
470
+ if (!this.isWorkspacePlacement)
471
+ return {
472
+ appShell: this.appShell,
473
+ draftInterface: this.config.draftInterface,
474
+ };
475
+ const sessionKey = this.builderBinding?.workspace?.sessionKey;
476
+ const assertSession = () => {
477
+ if (!sessionKey ||
478
+ this.builderBinding?.workspace?.sessionKey !== sessionKey)
479
+ throw new Error("The application moved to another workspace during package management");
480
+ };
481
+ return {
482
+ appShell: workspacePackageShell({
483
+ recoveryState: this.workspacePackageRecovery,
484
+ local: this.appShell,
485
+ execute: async (operation, signal) => {
486
+ assertSession();
487
+ if (!this.workspacePackageTransport)
488
+ throw new Error("VM package transport is unavailable; reload the editor before retrying");
489
+ return this.workspacePackageTransport.packageOperation({
490
+ operation,
491
+ gateEnabled: this.config.features.packageInstallGateEnabled === true,
492
+ }, (request) => {
493
+ assertSession();
494
+ return this.workspacePackagePolicy(request);
495
+ }, signal);
496
+ },
497
+ recover: async ({ cancelled }) => {
498
+ assertSession();
499
+ if (cancelled) {
500
+ if (!this.workspacePackageTransport?.packageState ||
501
+ !this.workspaceMirror)
502
+ throw new Error("Read-only VM package recovery is unavailable");
503
+ const state = await this.workspacePackageTransport.packageState();
504
+ assertSession();
505
+ await this.workspaceMirror.mirror.refreshPackageState(state);
506
+ await this.refreshFileModel();
507
+ return;
508
+ }
509
+ const sync = this._runtimeSyncService;
510
+ if (!sync ||
511
+ !("syncCurrentDirectoryWithDraftsNow" in sync) ||
512
+ typeof sync.syncCurrentDirectoryWithDraftsNow !== "function")
513
+ throw new Error("VM state recovery is unavailable");
514
+ const result = z
515
+ .object({ directoryHash: z.string().min(1) })
516
+ .parse(await sync.syncCurrentDirectoryWithDraftsNow("requestedFilesSync"));
517
+ assertSession();
518
+ await this.refreshWorkspaceMirror(result.directoryHash);
519
+ },
520
+ refresh: async (hash) => {
521
+ assertSession();
522
+ await this.refreshWorkspaceMirror(hash);
523
+ },
524
+ }),
525
+ // The VM records package.json and both lockfiles in its active journal.
526
+ // Never write draft markers into the read-only mirror.
527
+ draftInterface: { createDraftMarkerOnly: async (_path) => { } },
528
+ };
529
+ }
410
530
  workspaceMirror;
411
531
  /** The newest DBFS hash the VM reported for the current workspace. */
412
532
  workspaceHash;
533
+ /** The mirror changed on disk but reloading the file model has not succeeded. */
534
+ workspaceFileModelStale = false;
535
+ workspaceRefreshQueue = new OperationQueue();
413
536
  adoptedWorkspaceOpens = new WeakSet();
414
537
  /** The current VM boot's ai-service credential, from `workspace.open`. */
415
538
  workspaceInternalToken;
@@ -418,6 +541,12 @@ export class AiService extends TracedEventEmitter {
418
541
  * the VM's turn-end commit reported. Undefined for a live-edit turn.
419
542
  */
420
543
  workspaceTurnFinish;
544
+ /**
545
+ * The AI checkpoint the last completed native turn created. Native turns
546
+ * commit at turn end instead of leaving a draft, so an accept after one
547
+ * (the gateway's checkpoint step) returns this commit.
548
+ */
549
+ lastNativeCheckpointId;
421
550
  nativeBuilderJwt;
422
551
  nativeInferenceTurn;
423
552
  nativePromptAttempt;
@@ -1009,7 +1138,7 @@ export class AiService extends TracedEventEmitter {
1009
1138
  // (LD flag + ONPREMISE + OPA edit lifecycle registration). When the
1010
1139
  // gate is off, `taskStore` stays undefined and `agent/tools.ts`
1011
1140
  // skips registering the start*/check*/wait*/cancel*/list* tools.
1012
- if (!config.builderRuntime && isBackgroundTaskFrameworkEnabled(config)) {
1141
+ if (isBackgroundTaskFrameworkEnabled(config)) {
1013
1142
  this.taskStore = new TaskStore();
1014
1143
  // Heterogeneous list of task types funneled into
1015
1144
  // `registerBackgroundTaskTypes` (which itself takes ReadonlyArray<TaskType<any, any, any>>),
@@ -1035,10 +1164,19 @@ export class AiService extends TracedEventEmitter {
1035
1164
  // AFTER this constructor runs, so the helper resolves it
1036
1165
  // lazily at task-start time.
1037
1166
  ensureFilesSynced: buildEnsureDevDatabaseFilesSynced(() => this._runtimeSyncService),
1038
- getClient: () => {
1039
- const jwt = this.clark?.context?.jwt;
1167
+ getClient: (ownerUserId) => {
1168
+ if (!ownerUserId) {
1169
+ throw new Error("[devDatabase] task starter is unavailable");
1170
+ }
1171
+ if (this.getAuthenticatedTaskUserId() !== ownerUserId) {
1172
+ throw new DevDatabaseTaskOwnerUnavailableError("[devDatabase] task owner does not match the authenticated peer; reconnect as the user who started the task");
1173
+ }
1174
+ const jwt = this.getInferenceJwt();
1040
1175
  if (!jwt) {
1041
- throw new Error("[devDatabase] cannot start background task: no JWT available on Clark context");
1176
+ throw new DevDatabaseTaskOwnerUnavailableError("[devDatabase] cannot start background task: no current JWT available");
1177
+ }
1178
+ if (parseJwt(jwt)?.userId !== ownerUserId) {
1179
+ throw new DevDatabaseTaskOwnerUnavailableError("[devDatabase] task owner does not match the current editor; reconnect as the user who started the task");
1042
1180
  }
1043
1181
  return new DevDatabaseClient({
1044
1182
  transport: createDevDatabaseHttpTransport({
@@ -1049,12 +1187,7 @@ export class AiService extends TracedEventEmitter {
1049
1187
  },
1050
1188
  // Same owner stamping as defineBackgroundTaskFactory so sibling
1051
1189
  // watch tasks are not world-readable inside the AiService session.
1052
- getCurrentOwnerId: () => {
1053
- const jwt = this.clark?.context?.jwt;
1054
- if (!jwt)
1055
- return undefined;
1056
- return parseJwt(jwt)?.userId;
1057
- },
1190
+ getCurrentOwnerId: () => this.getAuthenticatedTaskUserId(),
1058
1191
  // Lazy: TaskStore exists on `this` but watch siblings only start
1059
1192
  // after types are registered below.
1060
1193
  getTaskStore: () => this.taskStore,
@@ -1210,6 +1343,143 @@ export class AiService extends TracedEventEmitter {
1210
1343
  isBusyForBuilderSwitch() {
1211
1344
  return this.isBusy() || this.promptsBeingAdmitted > 0;
1212
1345
  }
1346
+ /**
1347
+ * Claims a harness or model switch without stopping anything. A running turn, or Clark waiting on a question or a
1348
+ * permission prompt, refuses it until the user confirms `stopTurn`. Returns whether the caller must stop the turn,
1349
+ * which it does with {@link stopTurnForBuilderSwitch} once the switch's own checks pass. The caller releases
1350
+ * `builderSwitchInProgress`.
1351
+ */
1352
+ claimBuilderSwitch(kind, stopTurn) {
1353
+ const record = (outcome) => recordBuilderSwitchClaim(kind, outcome);
1354
+ if (this.builderSwitchInProgress) {
1355
+ record("refused_in_progress");
1356
+ throw new Error("The harness or model is already being switched");
1357
+ }
1358
+ // Its turn has not started yet, so there is nothing to stop. Clark's cancel cannot stop a turn it is still starting
1359
+ // either, and waitUntilGenerationComplete does not wait for one. Checked on every click, ahead of the
1360
+ // turn-in-progress refusal: offering "Stop and switch" for a stop that would be refused loops the dialog.
1361
+ if (this.promptsBeingAdmitted > 0 ||
1362
+ (!this.builderConversation && this.generationStarting)) {
1363
+ record("refused_starting");
1364
+ throw new SocketErrorException(409, "A prompt is starting. Try the switch again in a moment.");
1365
+ }
1366
+ const busy = this.isTurnRunningForBuilderSwitch();
1367
+ // A plain Error crosses the socket as "Error: <message>"; the editor matches the exact message.
1368
+ if (busy && !stopTurn) {
1369
+ const waiting = this.isAwaitingInteractiveResponse();
1370
+ record(waiting ? "refused_waiting" : "refused_working");
1371
+ throw new SocketErrorException(409, waiting
1372
+ ? SWITCH_ENDS_WAITING_TURN_MESSAGE
1373
+ : SWITCH_STOPS_WORKING_TURN_MESSAGE);
1374
+ }
1375
+ // Set synchronously after the checks, so no prompt starts between them.
1376
+ this.builderSwitchInProgress = true;
1377
+ return { mustStopTurn: busy };
1378
+ }
1379
+ /**
1380
+ * Stops the turn a confirmed switch claimed, as the Stop button does, including its draft-state report. Runs only
1381
+ * after the switch's own checks pass, so a switch that cannot happen never costs the user the turn.
1382
+ */
1383
+ async stopTurnForBuilderSwitch(kind, onTurnStopped) {
1384
+ // The turn may have ended on its own during the checks; cancelling then would mark a finished turn cancelled.
1385
+ if (!this.isBusy() &&
1386
+ !(!this.builderConversation && this.isAwaitingInteractiveResponse()))
1387
+ return false;
1388
+ const startedAt = Date.now();
1389
+ try {
1390
+ await this.handleUserCanceled("stop");
1391
+ // A native cancel waits for its turn to settle; Clark's state machine settles after the cancel event.
1392
+ if (!this.builderConversation) {
1393
+ await this.waitForClarkCancelHandler();
1394
+ await this.waitUntilGenerationComplete();
1395
+ await this.waitForClarkToDropOpenQuestion();
1396
+ }
1397
+ if (this.isBusy())
1398
+ throw new Error("The current turn did not stop. Try the switch again.");
1399
+ }
1400
+ catch (error) {
1401
+ this.getLogger().warn("[ai-service] Could not stop the turn for a switch", {
1402
+ "switch.kind": kind,
1403
+ "switch.stop_ms": Date.now() - startedAt,
1404
+ ...getErrorMeta(error),
1405
+ });
1406
+ throw error;
1407
+ }
1408
+ this.getLogger().info("[ai-service] Stopped the turn for a switch", {
1409
+ "switch.kind": kind,
1410
+ "switch.stop_ms": Date.now() - startedAt,
1411
+ });
1412
+ const hasDraft = await this.showDraftLeftByStop();
1413
+ // The turn already stopped; a failed draft-state report must not also cost the user the switch.
1414
+ try {
1415
+ await onTurnStopped?.(hasDraft);
1416
+ }
1417
+ catch (error) {
1418
+ this.getLogger().warn("[ai-service] Could not report draft state after stopping the turn for a switch", { "switch.kind": kind, ...getErrorMeta(error) });
1419
+ }
1420
+ return true;
1421
+ }
1422
+ /** The FSM reports Idle before its cancel handler finishes writing to the chat; a switch must not change it first. */
1423
+ async waitForClarkCancelHandler() {
1424
+ const handler = this.clarkCancelHandler;
1425
+ if (!handler)
1426
+ return;
1427
+ let timer;
1428
+ const timedOut = new Promise((_, reject) => {
1429
+ timer = setTimeout(() => reject(new Error("The current turn did not stop. Try the switch again.")), GENERATION_COMPLETION_WAIT_TIMEOUT_MS);
1430
+ timer.unref();
1431
+ });
1432
+ try {
1433
+ await Promise.race([handler, timedOut]);
1434
+ }
1435
+ finally {
1436
+ clearTimeout(timer);
1437
+ }
1438
+ }
1439
+ /**
1440
+ * Clark's USER_CANCELED for an open question runs after handleUserCanceled returns, and waitUntilGenerationComplete
1441
+ * does not wait for a turn that is not generating. A switch that went on would start the new chat under that question.
1442
+ */
1443
+ async waitForClarkToDropOpenQuestion() {
1444
+ const deadline = Date.now() + GENERATION_COMPLETION_WAIT_TIMEOUT_MS;
1445
+ while (this.isAwaitingInteractiveResponse()) {
1446
+ if (Date.now() > deadline)
1447
+ throw new Error("The current turn did not stop. Try the switch again.");
1448
+ await new Promise((resolve) => setTimeout(resolve, 25));
1449
+ }
1450
+ }
1451
+ /** Clark's resting AwaitingUser state is not a turn to isBusy(), but switching would drop its open question. */
1452
+ isTurnRunningForBuilderSwitch() {
1453
+ return (this.isBusyForBuilderSwitch() ||
1454
+ (!this.builderConversation && this.isAwaitingInteractiveResponse()));
1455
+ }
1456
+ /**
1457
+ * After a stop by the Stop button or for a switch: the stop's CANCELLED hides Accept and Reject, so show them again
1458
+ * for any changes the turn left. Clark's cancel handler publishes that CANCELLED late, so it is awaited first.
1459
+ * Returns whether changes remain, in which case the server's draft flag must stay set, or undefined when the check
1460
+ * failed: then the flag stays set too, since clearing it could let unaccepted changes look clean to git.
1461
+ */
1462
+ async showDraftLeftByStop() {
1463
+ if (!this.builderConversation)
1464
+ await this.waitForClarkCancelHandler().catch((error) => {
1465
+ this.getLogger().warn("[ai-service] Clark's cancel handler did not finish before the draft check", getErrorMeta(error));
1466
+ });
1467
+ let hasDraft;
1468
+ try {
1469
+ hasDraft = Boolean(await this.config.draftInterface?.hasLocalDraftChanges());
1470
+ }
1471
+ catch (error) {
1472
+ // The stop already happened, so do not fail it; without an answer, leave the server's draft flag alone.
1473
+ this.getLogger().warn("[ai-service] Could not check for changes left by a stop", getErrorMeta(error));
1474
+ }
1475
+ if (hasDraft)
1476
+ catchBackgroundPeerDisconnect(this.stablePeer.call.aiSetDraftState({ hasDraft: true }), "draft state push");
1477
+ return hasDraft;
1478
+ }
1479
+ /** Sent to an editor when it connects, so a tab that reconnects mid-switch does not wait for a push it missed. */
1480
+ isBuilderSwitchInProgress() {
1481
+ return this.builderSwitchInProgress;
1482
+ }
1213
1483
  /** A prompt sent while a harness switch is moving to a new chat would run on the old harness in the new chat. */
1214
1484
  assertNoBuilderSwitchInProgress() {
1215
1485
  if (this.builderSwitchInProgress)
@@ -1230,13 +1500,36 @@ export class AiService extends TracedEventEmitter {
1230
1500
  * Opens the binding's AgentCore workspace without waiting for it. Opening
1231
1501
  * needs a JWT to mint the runtime token, so without one it waits for
1232
1502
  * `updateClarkJwt`; the first turn joins the same open.
1503
+ *
1504
+ * A switch from Clark applies the agentcore binding while the sidecar still
1505
+ * runs Vite, and only then asks the editor to restart it into the workspace
1506
+ * edge. Opening now would fail as sidecar_mismatch, so a sidecar still on
1507
+ * live-edit is left to `openWorkspaceAfterRestart`; a prompt sent before then
1508
+ * is refused by `assertEditorNeedsNoRestart`.
1233
1509
  */
1234
1510
  openWorkspaceInBackground(binding, branch) {
1235
1511
  if (binding.workspace?.placement !== "agentcore")
1236
1512
  return;
1237
1513
  if (!this.getInferenceJwt())
1238
1514
  return;
1239
- this.ensureWorkspace(binding, branch).catch((error) => this.getLogger().warn("[workspace] Background workspace open failed; the next turn retries", getErrorMeta(error)));
1515
+ void this.openWorkspaceUnlessSidecarOnLiveEdit(binding, branch);
1516
+ }
1517
+ async openWorkspaceUnlessSidecarOnLiveEdit(binding, branch) {
1518
+ const edgeUrl = this.config.workspace?.edgeUrl;
1519
+ if (edgeUrl && (await readWorkspaceIngress(edgeUrl)) === "live-edit") {
1520
+ this.getLogger().info("[workspace] The editor still runs live-edit; the workspace opens after it restarts", { harness: binding.harness });
1521
+ return;
1522
+ }
1523
+ await this.ensureWorkspace(binding, branch).catch((error) => this.getLogger().warn("[workspace] Background workspace open failed; the next turn retries", {
1524
+ ...getErrorMeta(error),
1525
+ harness: binding.harness,
1526
+ // A switch into agentcore restarts the sidecar; an open that runs before that restart lands fails as
1527
+ // sidecar_mismatch. These say whether one was due and how long ago it was asked for.
1528
+ editorRestartRequired: this.editorRestartRequired,
1529
+ editorRestartAskedAgoMs: this.editorRestartAskedAt === undefined
1530
+ ? undefined
1531
+ : Date.now() - this.editorRestartAskedAt,
1532
+ }));
1240
1533
  }
1241
1534
  initializeNativeBuilder() {
1242
1535
  const config = this.config;
@@ -1246,21 +1539,24 @@ export class AiService extends TracedEventEmitter {
1246
1539
  runtime,
1247
1540
  tools: new NativeBuilderToolHost({
1248
1541
  getJwt: () => this.getClarkJwt(),
1542
+ taskStore: this.taskStore,
1543
+ getCurrentOwnerId: () => this.getAuthenticatedTaskUserId(),
1544
+ isWorkspacePlacement: () => this.isWorkspacePlacement,
1249
1545
  getPackageServices: (request) => ({
1250
1546
  appContextStore: this.appContext,
1251
- appShell: this.appShell,
1252
- draftInterface: config.draftInterface,
1547
+ ...this.nativePackageServices(),
1253
1548
  chatSessionStore: this.chatSessionStore,
1254
1549
  llmClient: this.llmClient,
1255
1550
  llmProvider: createLLMProvider(this.getLLMProviderSettings(request?.llmConfig), () => this.requireProviderInferenceAuthToken(), request?.llmConfig),
1256
1551
  }),
1257
1552
  appShell: this.appShell,
1258
- assertLocalAppTreeWritable: (action) => this.assertLocalAppTreeWritable(action),
1259
1553
  ensureFilesSynced: async () => {
1260
1554
  const sync = this._runtimeSyncService;
1261
1555
  if (!sync?.syncCurrentDirectoryWithDraftsNow)
1262
1556
  throw new Error("Native builder DEV sync service is unavailable");
1263
- const synced = await sync.syncCurrentDirectoryWithDraftsNow("requestedFilesSync");
1557
+ // Interim: stores the tree for the read without a commit; the
1558
+ // turn end commits it.
1559
+ const synced = await sync.syncCurrentDirectoryWithDraftsNow("ai:generate:interim");
1264
1560
  if (!synced?.directoryHash)
1265
1561
  throw new Error("Native builder file sync did not return a directory hash");
1266
1562
  // testApi reads the tree here: in agentcore placement, bring the
@@ -1285,44 +1581,53 @@ export class AiService extends TracedEventEmitter {
1285
1581
  chat: this.chatSessionStore,
1286
1582
  prepare: (request, signal, generationId) => this.prepareNativeBuilderRequest(request, signal, generationId),
1287
1583
  afterRun: async (turn) => {
1584
+ // A native turn leaves no draft: its end commits the files as an
1585
+ // AI checkpoint, and an unchanged tree creates none.
1288
1586
  const workspaceFinish = this.workspaceTurnFinish;
1587
+ let checkpointId;
1289
1588
  if (workspaceFinish) {
1290
- // Agentcore placement: the runtime owns the turn in the VM and
1291
- // its finish carries the turn-end commit's hash, which the
1292
- // finish handler already mirrored. There is nothing to sync.
1589
+ // Agentcore placement: the runtime owns the turn in the VM, whose
1590
+ // turn end commits it. Its finish carries the commit's hash,
1591
+ // which the finish handler already mirrored, and the checkpoint
1592
+ // when one was created. There is nothing to sync.
1293
1593
  await turn?.events();
1294
1594
  if (workspaceFinish.finished && !workspaceFinish.dbfsHash)
1295
1595
  throw new Error("The workspace did not report a committed hash for this turn; its changes may not be saved.");
1596
+ checkpointId = workspaceFinish.commitId;
1296
1597
  }
1297
1598
  else {
1298
1599
  const sync = this._runtimeSyncService;
1299
1600
  if (!sync?.syncCurrentDirectoryWithDraftsNow)
1300
1601
  throw new Error("Native builder DEV sync service is unavailable");
1301
- const synced = await sync.syncCurrentDirectoryWithDraftsNow("ai:generate:post", { waitForNativeSession: true });
1602
+ const synced = await sync.syncCurrentDirectoryWithDraftsNow("ai:accept", { waitForNativeSession: true });
1302
1603
  // The binding moved to a workspace since the turn started.
1303
1604
  if (this.isWorkspacePlacement &&
1304
1605
  typeof synced?.directoryHash === "string")
1305
1606
  await this.mirrorWorkspaceHash(synced.directoryHash);
1607
+ if (synced?.commitId && !synced.checkpointSkipped)
1608
+ checkpointId = synced.commitId;
1306
1609
  }
1307
- const hasDraft = await config.draftInterface.hasLocalDraftChanges();
1308
- await this.stablePeer.call
1309
- .aiSetDraftState({ hasDraft })
1310
- .catch((error) => this.getLogger().warn("Failed to publish native draft state", getErrorMeta(error)));
1610
+ // The server records the card of an editor-token commit, but leaves
1611
+ // the VM's (its sync token's) to this service, so the card lands
1612
+ // after the turn's final message.
1613
+ if (checkpointId)
1614
+ await this.publishNativeCheckpoint(checkpointId, {
1615
+ record: Boolean(workspaceFinish),
1616
+ });
1617
+ return { checkpointId };
1311
1618
  },
1312
- onSettled: (generationId, error, cancelled) => {
1619
+ onSettled: (generationId, error, cancelled, paywallReason) => {
1313
1620
  const attempt = this.nativePromptAttempt;
1314
1621
  if (attempt?.generationId === generationId) {
1315
1622
  this.nativePromptAttempt = undefined;
1623
+ const failure = NativeTurnFailure.promptOutcome(error, cancelled, paywallReason);
1316
1624
  recordPromptOutcome({
1317
1625
  dedupeKey: attempt.dedupeKey,
1318
1626
  promptId: generationId,
1319
- coreModel: runtime.model,
1320
- outcome: error ? "failure" : "success",
1321
- failure: error
1322
- ? error instanceof Error && error.name === "AbortError"
1323
- ? promptFailureUserCanceled()
1324
- : promptFailurePlatform("handler_error")
1325
- : undefined,
1627
+ harness: attempt.harness,
1628
+ coreModel: attempt.coreModel,
1629
+ outcome: failure ? "failure" : "success",
1630
+ failure,
1326
1631
  streakEligible: true,
1327
1632
  });
1328
1633
  }
@@ -1330,7 +1635,7 @@ export class AiService extends TracedEventEmitter {
1330
1635
  this.activeGenerationTrace?.finish(cancelled ? "cancelled" : error ? "failed" : "completed", error);
1331
1636
  this.triggerGenerationComplete(generationId);
1332
1637
  },
1333
- onError: (error, attempt) => BuilderRuntimeError.log(error, this.getLogger(), attempt),
1638
+ onError: (error, attempt, context) => BuilderRuntimeError.log(error, this.getLogger(), attempt, context),
1334
1639
  checkPaywall: () => this.nativePaywallReason(),
1335
1640
  });
1336
1641
  }
@@ -1670,14 +1975,20 @@ export class AiService extends TracedEventEmitter {
1670
1975
  conversationId: this.builderBinding?.runtimeSessionId,
1671
1976
  }),
1672
1977
  }, HarnessTrace.context(runtime?.harness ?? "clark"));
1978
+ // A native turn runs on its runtime's model; the request's llmConfig is
1979
+ // the editor's Clark configuration and only describes a Clark turn.
1980
+ const model = runtime ? runtime.model : request.llmConfig?.coreModel;
1981
+ const provider = runtime
1982
+ ? runtime.providerFor(runtime.model)
1983
+ : request.llmConfig?.provider;
1673
1984
  const span = this.config.tracer.startSpan("AiService.generation", {
1674
1985
  attributes: {
1675
1986
  ...TraceCorrelation.attributes(parentContext),
1676
1987
  "ai.mode": request.mode,
1677
- "ai.model": request.llmConfig?.coreModel,
1678
- "ai.provider": runtime
1679
- ? runtime.providerFor(runtime.model)
1680
- : request.llmConfig?.provider,
1988
+ "ai.model": model,
1989
+ "ai.provider": provider,
1990
+ "gen_ai.provider.name": provider,
1991
+ "gen_ai.request.model": model,
1681
1992
  "app.id": this.config.applicationId,
1682
1993
  "org.id": this.config.organizationId,
1683
1994
  },
@@ -1785,17 +2096,9 @@ export class AiService extends TracedEventEmitter {
1785
2096
  gitOperationLock: this._runtimeGitOperationLock,
1786
2097
  onGitOperationComplete: this._onGitOperationComplete,
1787
2098
  taskStore: this.taskStore,
1788
- // Resolve `ownerUserId` from the *current* JWT at each call site
1789
- // (kickoff / read / cancel). Reading lazily — instead of capturing
1790
- // the JWT at handler construction — means the wired identity stays
1791
- // correct across `updateClarkJwt` refreshes that happen mid-turn
1792
- // when a user's token rotates. Tests pin this lazy contract.
1793
- getCurrentOwnerId: () => {
1794
- const jwt = clark.context.jwt;
1795
- if (!jwt)
1796
- return undefined;
1797
- return parseJwt(jwt)?.userId;
1798
- },
2099
+ // Task access follows the authenticated transport principal, not
2100
+ // claims decoded from a separately supplied inference credential.
2101
+ getCurrentOwnerId: () => this.getAuthenticatedTaskUserId(),
1799
2102
  };
1800
2103
  const clarkStateHandlers = Object.fromEntries(Object.entries(clarkStateHandlerFactories).map(([state, handlerFactory]) => [state, handlerFactory(clark, params)]));
1801
2104
  const { from, to, event } = transition;
@@ -3022,6 +3325,32 @@ export class AiService extends TracedEventEmitter {
3022
3325
  });
3023
3326
  return this.nativeAttachmentPreparations.resolve(request);
3024
3327
  }
3328
+ /** A prompt refused for its attachments stays in the chat with the reason. */
3329
+ async prepareNativePromptAttachments(request) {
3330
+ try {
3331
+ return await this.resolveNativePromptAttachments(request);
3332
+ }
3333
+ catch (error) {
3334
+ if (!this.builderConversation ||
3335
+ (error instanceof DOMException && error.name === "AbortError"))
3336
+ throw error;
3337
+ // The queue path reaches here before following the binding; the refusal must land in the editor's chat.
3338
+ if (this.shouldFollowBuilderBinding(request)) {
3339
+ try {
3340
+ await this.followBuilderBinding(request);
3341
+ }
3342
+ catch (bindingError) {
3343
+ if (bindingError instanceof BuilderBindingChangedError)
3344
+ throw bindingError;
3345
+ throw error;
3346
+ }
3347
+ }
3348
+ const conversation = this.builderConversation;
3349
+ if (!conversation)
3350
+ throw error;
3351
+ throw await conversation.rejectPrompt(request, error);
3352
+ }
3353
+ }
3025
3354
  cancelPendingNativeRequests() {
3026
3355
  this.nativeCancellationVersion = (this.nativeCancellationVersion ?? 0) + 1;
3027
3356
  this.nativeAttachmentPreparations?.cancel();
@@ -3105,8 +3434,24 @@ export class AiService extends TracedEventEmitter {
3105
3434
  return this.runtimeAccess.auth;
3106
3435
  }
3107
3436
  async prepareNativeBuilderRequest(request, signal, generationId) {
3437
+ // A refusal while a policy gate runs is not a prompt attempt, as on Clark's path.
3108
3438
  this.assertNoActivePolicyGateRun();
3439
+ const runtime = this.builderRuntime;
3440
+ if (!runtime)
3441
+ throw new Error("Native builder runtime is unavailable");
3109
3442
  setPromptOrgClaims(orgClaimsFromJwt(request.jwt));
3443
+ const dedupeKey = resolvePromptRequestDedupeKey(request);
3444
+ this.nativePromptAttempt = {
3445
+ generationId,
3446
+ dedupeKey,
3447
+ harness: runtime.harness,
3448
+ coreModel: runtime.model,
3449
+ };
3450
+ recordPromptAttempt({
3451
+ outcomeDedupeKey: dedupeKey,
3452
+ harness: runtime.harness,
3453
+ coreModel: runtime.model,
3454
+ });
3110
3455
  this.nativeBuilderJwt = request.jwt;
3111
3456
  this.nativeObservations = {
3112
3457
  ...this.nativeObservations,
@@ -3118,9 +3463,6 @@ export class AiService extends TracedEventEmitter {
3118
3463
  await this.ensureAiQuotaAvailable(this.config.inferenceAuthToken ?? request.jwt);
3119
3464
  signal.throwIfAborted();
3120
3465
  const branch = (await this._syncContextProvider?.getBranchName()) ?? "main";
3121
- const runtime = this.builderRuntime;
3122
- if (!runtime)
3123
- throw new Error("Native builder runtime is unavailable");
3124
3466
  const checked = this.checkedBinding;
3125
3467
  this.checkedBinding = undefined;
3126
3468
  const binding = checked &&
@@ -3134,10 +3476,9 @@ export class AiService extends TracedEventEmitter {
3134
3476
  this.builderBranch = branch;
3135
3477
  signal.throwIfAborted();
3136
3478
  const workspaceLocal = binding.workspace?.placement === "agentcore";
3479
+ this.lastNativeCheckpointId = undefined;
3137
3480
  const userId = parseJwt(request.jwt)?.userId;
3138
- const turnFinish = {
3139
- finished: false,
3140
- };
3481
+ const turnFinish = { finished: false };
3141
3482
  this.workspaceTurnFinish = workspaceLocal ? turnFinish : undefined;
3142
3483
  const opened = workspaceLocal
3143
3484
  ? await this.ensureWorkspace(binding, branch)
@@ -3158,14 +3499,6 @@ export class AiService extends TracedEventEmitter {
3158
3499
  ...request,
3159
3500
  llmConfig: { ...request.llmConfig, coreModel: runtime.model },
3160
3501
  }, generationId);
3161
- this.nativePromptAttempt = {
3162
- generationId,
3163
- dedupeKey: resolvePromptRequestDedupeKey(request),
3164
- };
3165
- recordPromptAttempt({
3166
- outcomeDedupeKey: this.nativePromptAttempt.dedupeKey,
3167
- coreModel: runtime.model,
3168
- });
3169
3502
  this.emit("generationStarted", generationId);
3170
3503
  return {
3171
3504
  scope: binding.runtimeSessionId,
@@ -3186,6 +3519,8 @@ export class AiService extends TracedEventEmitter {
3186
3519
  onWorkspaceFinish: async (workspace) => {
3187
3520
  turnFinish.finished = true;
3188
3521
  turnFinish.dbfsHash = workspace.dbfsHash;
3522
+ // A retried attempt that changed nothing keeps the first one's.
3523
+ turnFinish.commitId = workspace.commitId ?? turnFinish.commitId;
3189
3524
  if (workspace.dbfsHash)
3190
3525
  await this.mirrorWorkspaceHash(workspace.dbfsHash);
3191
3526
  },
@@ -3231,7 +3566,7 @@ export class AiService extends TracedEventEmitter {
3231
3566
  await this.followBuilderBinding(request);
3232
3567
  if (this.builderConversation) {
3233
3568
  const cancellationVersion = this.nativeCancellationVersion ?? 0;
3234
- const attachments = await this.resolveNativePromptAttachments(request);
3569
+ const attachments = await this.prepareNativePromptAttachments(request);
3235
3570
  this.assertNativeRequestActive(cancellationVersion);
3236
3571
  if (attachments)
3237
3572
  await this.builderConversation.start(request, attachments);
@@ -4086,11 +4421,45 @@ export class AiService extends TracedEventEmitter {
4086
4421
  type: "draftCommitted",
4087
4422
  }, inputSource);
4088
4423
  }
4424
+ /**
4425
+ * Shows a native turn's checkpoint card to the turn's peer and observers.
4426
+ * With `record`, it first records the card in the chat: the server records
4427
+ * it with an editor-token commit, but not with a workspace VM's, which
4428
+ * lands before the turn's final message.
4429
+ */
4430
+ async publishNativeCheckpoint(commitId, { record = false } = {}) {
4431
+ this.lastNativeCheckpointId = commitId;
4432
+ const card = {
4433
+ commitId,
4434
+ content: commitId,
4435
+ id: commitId,
4436
+ role: "assistant",
4437
+ timestamp: Date.now(),
4438
+ type: "draftCommitted",
4439
+ };
4440
+ // The id comes from the VM, so only a commit id's shape is recorded.
4441
+ if (record && UUID_PATTERN.test(commitId))
4442
+ await this.chatSessionStore.recordAssistant(card);
4443
+ else if (record)
4444
+ this.getLogger().warn("[ai-service] Not recording a native checkpoint card with a malformed commit id");
4445
+ await this.stablePeer.call
4446
+ .aiPushMessage(card)
4447
+ .catch((error) => this.getLogger().warn("[ai-service] Failed to push the native turn's checkpoint", getErrorMeta(error)));
4448
+ }
4449
+ /**
4450
+ * The accept result for a native builder, which commits at turn end and so
4451
+ * has no draft to accept: the last turn's checkpoint, or an empty commit id
4452
+ * when it created none. Undefined when Clark runs, whose accept commits a
4453
+ * draft.
4454
+ */
4455
+ get nativeAcceptResult() {
4456
+ if (!this.builderConversation)
4457
+ return undefined;
4458
+ return { commitId: this.lastNativeCheckpointId ?? "" };
4459
+ }
4089
4460
  async handleUserAcceptedDraft(silently) {
4090
- if (this.builderConversation) {
4091
- await this.chatSessionStore.recordUserAcceptance();
4461
+ if (this.builderConversation)
4092
4462
  return;
4093
- }
4094
4463
  this.getLogger().info(`[ai-service] handleUserAcceptedDraft`);
4095
4464
  if (this.clark.state === ClarkStateNames.Idle) {
4096
4465
  return;
@@ -4103,13 +4472,14 @@ export class AiService extends TracedEventEmitter {
4103
4472
  void transitionTo({ type: USER_ACCEPTED_DRAFT, silently });
4104
4473
  }
4105
4474
  async handleUserRejectedDraft(silently) {
4106
- if (this.builderConversation) {
4107
- await this.chatSessionStore.recordUserRejection();
4475
+ if (this.builderConversation)
4108
4476
  return;
4109
- }
4110
4477
  this.getLogger().info(`[ai-service] handleUserRejectedDraft`);
4111
- this.submitAcceptanceEvaluation(false);
4112
4478
  this.editAfterClark.discardLastTurn();
4479
+ // As for Accept: a Stop leaves Clark Idle with its changes still offered, and the files are already discarded.
4480
+ if (this.clark.state === ClarkStateNames.Idle)
4481
+ return;
4482
+ this.submitAcceptanceEvaluation(false);
4113
4483
  if (this.clark.state !== ClarkStateNames.AwaitingUser) {
4114
4484
  throw new Error("Service is not awaiting user input");
4115
4485
  }
@@ -4231,9 +4601,17 @@ export class AiService extends TracedEventEmitter {
4231
4601
  awaitingUserHandoffPromptId: undefined,
4232
4602
  awaitingUserHandoffRecorded: undefined,
4233
4603
  }));
4234
- void this.clark.send({
4604
+ // A switch awaits this before it changes the chat: the handler records "Canceled." and pushes CANCELLED.
4605
+ const cancelHandler = Promise.resolve(this.clark.send({
4235
4606
  type: USER_CANCELED,
4236
4607
  failure: promptFailureUserCanceled(),
4608
+ })).catch((error) => {
4609
+ this.getLogger().warn("[ai-service] Clark's cancel handler failed", getErrorMeta(error));
4610
+ });
4611
+ this.clarkCancelHandler = cancelHandler;
4612
+ void cancelHandler.finally(() => {
4613
+ if (this.clarkCancelHandler === cancelHandler)
4614
+ this.clarkCancelHandler = undefined;
4237
4615
  });
4238
4616
  }
4239
4617
  finally {
@@ -4308,7 +4686,7 @@ export class AiService extends TracedEventEmitter {
4308
4686
  if (this.builderConversation) {
4309
4687
  // Attachments are validated before a running turn is interrupted.
4310
4688
  cancellationVersion = this.nativeCancellationVersion ?? 0;
4311
- attachments = await this.resolveNativePromptAttachments(request);
4689
+ attachments = await this.prepareNativePromptAttachments(request);
4312
4690
  interrupted =
4313
4691
  this.builderConversation.isBusy &&
4314
4692
  !request.responseMetadata &&
@@ -5260,6 +5638,11 @@ export class AiService extends TracedEventEmitter {
5260
5638
  this.authenticatedPeerId = undefined;
5261
5639
  this.authenticatedPeerUserId = undefined;
5262
5640
  }
5641
+ // Task snapshots are shared by native and Clark sessions. Defer the
5642
+ // resync until RPC middleware proves the reconnecting peer's identity.
5643
+ if (this.taskStore) {
5644
+ this.pendingTaskResyncPeerIds.add(peerId);
5645
+ }
5263
5646
  if (this.builderConversation) {
5264
5647
  void this.builderConversation.replay();
5265
5648
  return;
@@ -5301,18 +5684,7 @@ export class AiService extends TracedEventEmitter {
5301
5684
  this.getLogger().warn(`[ai-service] Failed to clear stale tool permission on reconnect`, error);
5302
5685
  });
5303
5686
  }
5304
- // 3. Defer the background-task summary resync until the peer
5305
- // proves auth via its first authenticated RPC. The socket
5306
- // upgrade path only validates `applicationId`; auth is enforced
5307
- // by RPC middleware, which hasn't run yet at connect time. An
5308
- // unauthenticated client that manages to open the socket would
5309
- // otherwise receive the active task list. The resync drains
5310
- // inside `notifyAuthenticatedRpc(peerId)`, called by the
5311
- // auth middleware (see `socket-manager.ts`) on first success.
5312
- if (this.taskStore) {
5313
- this.pendingTaskResyncPeerIds.add(peerId);
5314
- }
5315
- // 4. Close out tool calls the transcript still reports as running but
5687
+ // 3. Close out tool calls the transcript still reports as running but
5316
5688
  // that no process is executing (ENG-6785). Does not gate the connect
5317
5689
  // handshake: the peer is already bound, and the reconcile is several
5318
5690
  // RPCs long. Reconnect `getMessages({ force })` joins this promise so
@@ -5430,6 +5802,18 @@ export class AiService extends TracedEventEmitter {
5430
5802
  * as auth is proven, but never before.
5431
5803
  */
5432
5804
  pendingTaskResyncPeerIds = new Set();
5805
+ authenticatedTaskUsers = new WeakMap();
5806
+ /** Called only after socket authorization succeeds for this physical client. */
5807
+ notifyAuthenticatedTaskRpc(peer, userId) {
5808
+ if (userId)
5809
+ this.authenticatedTaskUsers.set(peer, userId);
5810
+ else
5811
+ this.authenticatedTaskUsers.delete(peer);
5812
+ }
5813
+ getAuthenticatedTaskUserId() {
5814
+ const peer = this.stablePeer.activeRoutePeer;
5815
+ return peer ? this.authenticatedTaskUsers.get(peer) : undefined;
5816
+ }
5433
5817
  /**
5434
5818
  * The authenticated peer's identity, but only while that same peer is
5435
5819
  * still the bound `stablePeer`. `handleUserConnected` can swap in a
@@ -6060,6 +6444,20 @@ export class AiService extends TracedEventEmitter {
6060
6444
  async handleDemoAgentList() {
6061
6445
  return handleAgentList(this.getDemoAgentDeps());
6062
6446
  }
6447
+ /**
6448
+ * Changes an agent's definition or instructions from the editor's panel.
6449
+ * Only the user whose editor is open may, as for a run: the files are theirs
6450
+ * to change while they have the app open.
6451
+ */
6452
+ handleDemoAgentUpdate(request, callerUserId) {
6453
+ this.requireEditorUser(callerUserId);
6454
+ // agent.json and instructions.md are written here. In an AgentCore
6455
+ // workspace this process only holds a mirror of them: a change here would
6456
+ // not reach the VM's copy, and the next mirror would bring the old text
6457
+ // back after the panel reported it saved.
6458
+ this.assertLocalAppTreeWritable("changing an agent");
6459
+ return handleAgentUpdate(this.getDemoAgentDeps(), request);
6460
+ }
6063
6461
  handleDemoAgentRun(request, callerUserId) {
6064
6462
  const userId = this.requireEditorUser(callerUserId);
6065
6463
  return handleAgentRun(this.getDemoAgentDeps(), request, userId, (payload) => this.pushDemoAgentRunEvent(payload));
@@ -6087,16 +6485,6 @@ export class AiService extends TracedEventEmitter {
6087
6485
  this.getLogger().warn("[demo-agents] Failed to push run event", err instanceof Error ? err.message : String(err));
6088
6486
  });
6089
6487
  }
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
6488
  handleDemoAgentResetSession(request, callerUserId) {
6101
6489
  if (!projectAgentsEnabled(this.config.features)) {
6102
6490
  throw new Error("Project agents are not enabled");
@@ -6114,31 +6502,64 @@ export class AiService extends TracedEventEmitter {
6114
6502
  * Starts a new chat and returns its id, which the editor sends with later prompts. A `builderSelection` moves the app
6115
6503
  * to that harness: it reopens the app's most recent chat on it (`resumed`), which keeps that chat's own model, or
6116
6504
  * starts a new chat bound to it when there is none. A model-only change goes through `handleSetBuilderModel`.
6505
+ * `stopTurn` is the user's confirmation that a switch may stop the running turn.
6117
6506
  */
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;
6507
+ async handleNewChat(builderSelection, { stopTurn, onTurnStopped, } = {}) {
6508
+ if (!builderSelection)
6509
+ return this.switchOrStartNewChat(undefined);
6510
+ // Ahead of the turn-in-progress refusal: offering to stop a turn whose changes still block the switch would loop.
6511
+ try {
6512
+ await this.refuseSwitchOverRunningTurnsChanges();
6513
+ }
6514
+ catch (error) {
6515
+ recordBuilderSwitchClaim("harness", "refused_draft");
6516
+ throw error;
6126
6517
  }
6518
+ const { mustStopTurn } = this.claimBuilderSwitch("harness", stopTurn);
6519
+ // Recorded once, when the switch settles.
6520
+ let outcome = "failed";
6127
6521
  try {
6128
- if (builderSelection)
6129
- await this.assertEditorFinishedRestarting();
6130
- return await this.switchOrStartNewChat(builderSelection);
6522
+ await this.assertEditorFinishedRestarting();
6523
+ this.assertCanRunSelection(builderSelection);
6524
+ let stopped = false;
6525
+ if (mustStopTurn) {
6526
+ // Again right before the stop: the turn may have written files while the checks above awaited.
6527
+ outcome = "refused_draft";
6528
+ await this.refuseSwitchOverRunningTurnsChanges();
6529
+ outcome = "stop_failed";
6530
+ stopped = await this.stopTurnForBuilderSwitch("harness", onTurnStopped);
6531
+ outcome = "failed";
6532
+ }
6533
+ const result = await this.switchOrStartNewChat(builderSelection);
6534
+ outcome = stopped ? "switched_after_stop" : "switched";
6535
+ return result;
6131
6536
  }
6132
6537
  finally {
6133
- if (builderSelection)
6134
- this.builderSwitchInProgress = false;
6538
+ recordBuilderSwitchClaim("harness", outcome);
6539
+ this.builderSwitchInProgress = false;
6135
6540
  }
6136
6541
  }
6542
+ /** A harness switch cannot carry a running turn's changes to another chat, so stopping that turn would be for nothing. */
6543
+ async refuseSwitchOverRunningTurnsChanges() {
6544
+ if (!this.isTurnRunningForBuilderSwitch() ||
6545
+ !(await this.config.draftInterface?.hasLocalDraftChanges()))
6546
+ return;
6547
+ throw new SocketErrorException(409, SWITCH_NEEDS_DRAFT_SETTLED_MESSAGE);
6548
+ }
6549
+ /**
6550
+ * A new chat discards uncommitted AI changes; a switch must not. The draft's Accept and Reject controls are shown
6551
+ * again first: a turn the switch just stopped published CANCELLED, which hides them.
6552
+ */
6553
+ async assertNoPendingDraftForSwitch() {
6554
+ if (!(await this.config.draftInterface?.hasLocalDraftChanges()))
6555
+ return;
6556
+ catchBackgroundPeerDisconnect(this.stablePeer.call.aiSetDraftState({ hasDraft: true }), "draft state push");
6557
+ throw new Error("Accept or reject the pending changes before switching the harness or model");
6558
+ }
6137
6559
  async switchOrStartNewChat(builderSelection) {
6138
6560
  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");
6561
+ // Again after any stop: the stopped turn may have left changes.
6562
+ await this.assertNoPendingDraftForSwitch();
6142
6563
  // Refuse here, before the server archives the chat, a switch this editor could not run.
6143
6564
  this.assertCanRunSelection(builderSelection);
6144
6565
  }
@@ -6146,7 +6567,7 @@ export class AiService extends TracedEventEmitter {
6146
6567
  try {
6147
6568
  ({ resumed } = await this.startNewChat(builderSelection));
6148
6569
  if (builderSelection)
6149
- this.assertSelectionApplied(builderSelection);
6570
+ this.assertSelectionApplied(resumed ? { harness: builderSelection.harness } : builderSelection);
6150
6571
  }
6151
6572
  catch (error) {
6152
6573
  if (builderSelection)
@@ -6171,29 +6592,41 @@ export class AiService extends TracedEventEmitter {
6171
6592
  * Changes the model of the active native chat in place. The chat, its transcript, and its native Claude or Codex
6172
6593
  * session stay; the next turn resumes that session on the new model. Placement does not change, so no restart.
6173
6594
  */
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;
6595
+ async handleSetBuilderModel(model, { effort, stopTurn, onTurnStopped, } = {}) {
6596
+ const { mustStopTurn } = this.claimBuilderSwitch("model", stopTurn);
6597
+ // Recorded once, when the switch settles.
6598
+ let outcome = "failed";
6181
6599
  try {
6182
6600
  await this.assertEditorFinishedRestarting();
6183
6601
  // 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)
6602
+ // Following it needs an idle chat, so a stale pod stops the confirmed turn before the remaining checks.
6603
+ let turnStopped = false;
6604
+ let stopped = false;
6605
+ if (this.builderBindingStale) {
6606
+ if (mustStopTurn) {
6607
+ outcome = "stop_failed";
6608
+ stopped = await this.stopTurnForBuilderSwitch("model", onTurnStopped);
6609
+ outcome = "failed";
6610
+ turnStopped = true;
6611
+ }
6185
6612
  await this.recoverStaleBindingForModelChange();
6613
+ }
6186
6614
  const chatSessionId = this.builderBinding?.chatSessionId;
6187
6615
  const harness = this.builderBinding?.harness;
6188
6616
  if (!chatSessionId || !harness || harness === "clark")
6189
6617
  throw new Error("This chat does not run on a native harness");
6190
6618
  // Throws for a model the harness does not offer, before the server changes anything.
6191
6619
  this.assertCanRunSelection({ harness, model });
6620
+ if (mustStopTurn && !turnStopped) {
6621
+ outcome = "stop_failed";
6622
+ stopped = await this.stopTurnForBuilderSwitch("model", onTurnStopped);
6623
+ outcome = "failed";
6624
+ }
6192
6625
  const branch = this.builderBranch ??
6193
6626
  (await this._syncContextProvider?.getBranchName()) ??
6194
6627
  "main";
6195
6628
  try {
6196
- await this.chatSessionStore.setBuilderModel(branch, model, chatSessionId);
6629
+ await this.chatSessionStore.setBuilderModel(branch, model, chatSessionId, ...(effort === undefined ? [] : [effort]));
6197
6630
  }
6198
6631
  catch (error) {
6199
6632
  if (!isChatChangedElsewhereError(error))
@@ -6214,9 +6647,11 @@ export class AiService extends TracedEventEmitter {
6214
6647
  const builderSelection = this.getBuilderSelection();
6215
6648
  if (!builderSelection)
6216
6649
  throw new Error("Changed the model, but this editor lost the chat.");
6650
+ outcome = stopped ? "switched_after_stop" : "switched";
6217
6651
  return { builderSelection };
6218
6652
  }
6219
6653
  finally {
6654
+ recordBuilderSwitchClaim("model", outcome);
6220
6655
  this.builderSwitchInProgress = false;
6221
6656
  }
6222
6657
  }
@@ -6266,6 +6701,7 @@ export class AiService extends TracedEventEmitter {
6266
6701
  return {
6267
6702
  harness: binding.harness,
6268
6703
  model: binding.model ?? this.builderRuntime?.model,
6704
+ ...(binding.effort ? { effort: binding.effort } : {}),
6269
6705
  };
6270
6706
  }
6271
6707
  /** `resumed` when the server reopened the app's last chat on the picked harness instead of a new one. */
@@ -6626,6 +7062,9 @@ export class AiService extends TracedEventEmitter {
6626
7062
  }
6627
7063
  async handleRestoreToCommit(sinceTimestamp, commitId, applicationId, branchName) {
6628
7064
  if (this.builderConversation) {
7065
+ // The restore moved the server tree: the next ensureWorkspace mirrors
7066
+ // the hash the VM reports rather than this cached one.
7067
+ this.workspaceHash = undefined;
6629
7068
  await this.handleNewChat();
6630
7069
  return;
6631
7070
  }
@@ -7076,9 +7515,7 @@ export class AiService extends TracedEventEmitter {
7076
7515
  // A reloaded editor retries an open the watcher stopped retrying.
7077
7516
  editorGeneration: () => this.stablePeer.connectionGeneration,
7078
7517
  onReopened: async (result, reopenedKey) => {
7079
- if (!this.adoptWorkspaceOpen(reopenedKey, result))
7080
- return;
7081
- await this.mirrorWorkspaceHash(result.dbfsHash);
7518
+ await this.mirrorWorkspaceOpen(reopenedKey, this.builderBranch ?? "main", result);
7082
7519
  },
7083
7520
  });
7084
7521
  let result;
@@ -7098,8 +7535,14 @@ export class AiService extends TracedEventEmitter {
7098
7535
  this.workspaceInternalToken = undefined;
7099
7536
  throw error;
7100
7537
  }
7101
- if (!this.adoptWorkspaceOpen(sessionKey, result))
7538
+ if (!(await this.mirrorWorkspaceOpen(sessionKey, branchName, result)))
7102
7539
  throw new Error("The chat moved to another workspace while it opened");
7540
+ return result;
7541
+ }
7542
+ /** Initializes the read-only tree for both caller opens and watcher recovery. */
7543
+ async mirrorWorkspaceOpen(sessionKey, branchName, result) {
7544
+ if (!this.adoptWorkspaceOpen(sessionKey, result))
7545
+ return false;
7103
7546
  if (this.workspaceMirror?.sessionKey !== sessionKey)
7104
7547
  this.workspaceMirror = {
7105
7548
  sessionKey,
@@ -7110,7 +7553,7 @@ export class AiService extends TracedEventEmitter {
7110
7553
  }),
7111
7554
  };
7112
7555
  await this.refreshWorkspaceMirror(this.workspaceHash ?? result.dbfsHash);
7113
- return result;
7556
+ return true;
7114
7557
  }
7115
7558
  /**
7116
7559
  * Takes a successful open's token and hash, once per open, and only while
@@ -7133,14 +7576,20 @@ export class AiService extends TracedEventEmitter {
7133
7576
  * reloads the file model: the VM's watcher cannot reach this process. The
7134
7577
  * hash is remembered first, so the next turn retries a failed refresh.
7135
7578
  */
7136
- async refreshWorkspaceMirror(hash) {
7579
+ refreshWorkspaceMirror(hash) {
7137
7580
  this.workspaceHash = hash;
7138
7581
  const mirror = this.workspaceMirror?.mirror;
7139
7582
  if (!mirror)
7140
- return;
7141
- const { changed } = await mirror.refresh(hash);
7142
- if (changed && this.fileSystemManager)
7583
+ return Promise.resolve();
7584
+ return this.workspaceRefreshQueue.enqueue(async () => {
7585
+ const { changed } = await mirror.refresh(hash);
7586
+ if (changed)
7587
+ this.workspaceFileModelStale = true;
7588
+ if (!this.workspaceFileModelStale || !this.fileSystemManager)
7589
+ return;
7143
7590
  await this.refreshFileModel();
7591
+ this.workspaceFileModelStale = false;
7592
+ });
7144
7593
  }
7145
7594
  /** Mirrors a hash the VM reported, logging rather than failing a turn. */
7146
7595
  mirrorWorkspaceHash(hash) {