@superblocksteam/vite-plugin-file-sync 2.0.179-next.3 → 2.0.180-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 (289) 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 +5 -37
  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/branching/branch-tools.d.ts +2 -2
  23. package/dist/ai-service/agent/tools/branching/branch-tools.d.ts.map +1 -1
  24. package/dist/ai-service/agent/tools/branching/branch-tools.js +1 -1
  25. package/dist/ai-service/agent/tools/branching/branch-tools.js.map +1 -1
  26. package/dist/ai-service/agent/tools/build-copy-utils.d.ts +13 -44
  27. package/dist/ai-service/agent/tools/build-copy-utils.d.ts.map +1 -1
  28. package/dist/ai-service/agent/tools/build-debug.d.ts +1 -1
  29. package/dist/ai-service/agent/tools/build-debug.d.ts.map +1 -1
  30. package/dist/ai-service/agent/tools/build-delete-file.d.ts +1 -0
  31. package/dist/ai-service/agent/tools/build-delete-file.d.ts.map +1 -1
  32. package/dist/ai-service/agent/tools/build-delete-file.js +3 -0
  33. package/dist/ai-service/agent/tools/build-delete-file.js.map +1 -1
  34. package/dist/ai-service/agent/tools/build-edit-file.d.ts +2 -0
  35. package/dist/ai-service/agent/tools/build-edit-file.d.ts.map +1 -1
  36. package/dist/ai-service/agent/tools/build-edit-file.js +7 -0
  37. package/dist/ai-service/agent/tools/build-edit-file.js.map +1 -1
  38. package/dist/ai-service/agent/tools/build-install-packages.d.ts.map +1 -1
  39. package/dist/ai-service/agent/tools/build-install-packages.js +5 -1
  40. package/dist/ai-service/agent/tools/build-install-packages.js.map +1 -1
  41. package/dist/ai-service/agent/tools/build-list-files.d.ts +1 -1
  42. package/dist/ai-service/agent/tools/build-multi-edit-file.d.ts +1 -0
  43. package/dist/ai-service/agent/tools/build-multi-edit-file.d.ts.map +1 -1
  44. package/dist/ai-service/agent/tools/build-multi-edit-file.js +3 -0
  45. package/dist/ai-service/agent/tools/build-multi-edit-file.js.map +1 -1
  46. package/dist/ai-service/agent/tools/build-navigate-preview.js +2 -2
  47. package/dist/ai-service/agent/tools/build-navigate-preview.js.map +1 -1
  48. package/dist/ai-service/agent/tools/build-write-file.d.ts +1 -0
  49. package/dist/ai-service/agent/tools/build-write-file.d.ts.map +1 -1
  50. package/dist/ai-service/agent/tools/build-write-file.js +3 -0
  51. package/dist/ai-service/agent/tools/build-write-file.js.map +1 -1
  52. package/dist/ai-service/agent/tools/clear-error-cache.d.ts +1 -1
  53. package/dist/ai-service/agent/tools/databases/dev-database-tasks.d.ts +39 -185
  54. package/dist/ai-service/agent/tools/databases/dev-database-tasks.d.ts.map +1 -1
  55. package/dist/ai-service/agent/tools/databases/dev-database-tasks.js +35 -13
  56. package/dist/ai-service/agent/tools/databases/dev-database-tasks.js.map +1 -1
  57. package/dist/ai-service/agent/tools/databases/dev-database-tools.d.ts +2 -2
  58. package/dist/ai-service/agent/tools/get-security-findings.d.ts +1 -1
  59. package/dist/ai-service/agent/tools/integrations/execute-request.d.ts +47 -342
  60. package/dist/ai-service/agent/tools/integrations/execute-request.d.ts.map +1 -1
  61. package/dist/ai-service/agent/tools/integrations/execute-request.js +4 -4
  62. package/dist/ai-service/agent/tools/integrations/execute-request.js.map +1 -1
  63. package/dist/ai-service/agent/tools/integrations/integration-setup.d.ts +2 -2
  64. package/dist/ai-service/agent/tools/integrations/integration-setup.js +3 -3
  65. package/dist/ai-service/agent/tools/integrations/integration-setup.js.map +1 -1
  66. package/dist/ai-service/agent/tools/project-agent-feedback.d.ts +17 -0
  67. package/dist/ai-service/agent/tools/project-agent-feedback.d.ts.map +1 -0
  68. package/dist/ai-service/agent/tools/project-agent-feedback.js +87 -0
  69. package/dist/ai-service/agent/tools/project-agent-feedback.js.map +1 -0
  70. package/dist/ai-service/agent/tools/report-security-findings.d.ts +25 -112
  71. package/dist/ai-service/agent/tools/report-security-findings.d.ts.map +1 -1
  72. package/dist/ai-service/agent/tools.d.ts.map +1 -1
  73. package/dist/ai-service/agent/tools.js +1 -0
  74. package/dist/ai-service/agent/tools.js.map +1 -1
  75. package/dist/ai-service/agent/tools2/tools/bash.d.ts +2 -2
  76. package/dist/ai-service/agent/tools2/tools/end-test-run.d.ts +2 -2
  77. package/dist/ai-service/agent/tools2/tools/list-tasks.d.ts +1 -1
  78. package/dist/ai-service/agent/tools2/types.d.ts +1 -1
  79. package/dist/ai-service/agent/tools2/types.d.ts.map +1 -1
  80. package/dist/ai-service/agent/tools2/types.js.map +1 -1
  81. package/dist/ai-service/app-interface/invalid-lockfile-error.d.ts +11 -0
  82. package/dist/ai-service/app-interface/invalid-lockfile-error.d.ts.map +1 -0
  83. package/dist/ai-service/app-interface/invalid-lockfile-error.js +27 -0
  84. package/dist/ai-service/app-interface/invalid-lockfile-error.js.map +1 -0
  85. package/dist/ai-service/app-interface/npm-lockfile-sources.d.ts +13 -0
  86. package/dist/ai-service/app-interface/npm-lockfile-sources.d.ts.map +1 -0
  87. package/dist/ai-service/app-interface/npm-lockfile-sources.js +129 -0
  88. package/dist/ai-service/app-interface/npm-lockfile-sources.js.map +1 -0
  89. package/dist/ai-service/app-interface/npm-registry.d.ts +20 -10
  90. package/dist/ai-service/app-interface/npm-registry.d.ts.map +1 -1
  91. package/dist/ai-service/app-interface/npm-registry.js +109 -73
  92. package/dist/ai-service/app-interface/npm-registry.js.map +1 -1
  93. package/dist/ai-service/app-interface/registry-lockfile-preparer.d.ts +46 -0
  94. package/dist/ai-service/app-interface/registry-lockfile-preparer.d.ts.map +1 -0
  95. package/dist/ai-service/app-interface/registry-lockfile-preparer.js +88 -0
  96. package/dist/ai-service/app-interface/registry-lockfile-preparer.js.map +1 -0
  97. package/dist/ai-service/app-interface/shell.d.ts +14 -4
  98. package/dist/ai-service/app-interface/shell.d.ts.map +1 -1
  99. package/dist/ai-service/app-interface/shell.js +45 -30
  100. package/dist/ai-service/app-interface/shell.js.map +1 -1
  101. package/dist/ai-service/builder-binding-error.d.ts +5 -0
  102. package/dist/ai-service/builder-binding-error.d.ts.map +1 -0
  103. package/dist/ai-service/builder-binding-error.js +8 -0
  104. package/dist/ai-service/builder-binding-error.js.map +1 -0
  105. package/dist/ai-service/builder-conversation.d.ts +44 -3
  106. package/dist/ai-service/builder-conversation.d.ts.map +1 -1
  107. package/dist/ai-service/builder-conversation.js +353 -47
  108. package/dist/ai-service/builder-conversation.js.map +1 -1
  109. package/dist/ai-service/builder-core-prompt.d.ts +1 -1
  110. package/dist/ai-service/builder-core-prompt.d.ts.map +1 -1
  111. package/dist/ai-service/builder-core-prompt.js +7 -12
  112. package/dist/ai-service/builder-core-prompt.js.map +1 -1
  113. package/dist/ai-service/builder-runtime-auth.d.ts.map +1 -1
  114. package/dist/ai-service/builder-runtime-auth.js +6 -2
  115. package/dist/ai-service/builder-runtime-auth.js.map +1 -1
  116. package/dist/ai-service/builder-runtime.d.ts +103 -237
  117. package/dist/ai-service/builder-runtime.d.ts.map +1 -1
  118. package/dist/ai-service/builder-runtime.js +367 -61
  119. package/dist/ai-service/builder-runtime.js.map +1 -1
  120. package/dist/ai-service/builder-session-store.d.ts +1 -7
  121. package/dist/ai-service/builder-session-store.d.ts.map +1 -1
  122. package/dist/ai-service/builder-session-store.js +1 -1
  123. package/dist/ai-service/builder-session-store.js.map +1 -1
  124. package/dist/ai-service/builder-tool-callbacks.d.ts +5 -0
  125. package/dist/ai-service/builder-tool-callbacks.d.ts.map +1 -1
  126. package/dist/ai-service/builder-tool-callbacks.js +5 -2
  127. package/dist/ai-service/builder-tool-callbacks.js.map +1 -1
  128. package/dist/ai-service/builder-tools.d.ts +26 -4
  129. package/dist/ai-service/builder-tools.d.ts.map +1 -1
  130. package/dist/ai-service/builder-tools.js +156 -29
  131. package/dist/ai-service/builder-tools.js.map +1 -1
  132. package/dist/ai-service/builder-workspace.d.ts +1 -0
  133. package/dist/ai-service/builder-workspace.d.ts.map +1 -1
  134. package/dist/ai-service/builder-workspace.js +15 -6
  135. package/dist/ai-service/builder-workspace.js.map +1 -1
  136. package/dist/ai-service/chat/chat-session-store.d.ts +2 -2
  137. package/dist/ai-service/chat/chat-session-store.d.ts.map +1 -1
  138. package/dist/ai-service/chat/chat-session-store.js +25 -8
  139. package/dist/ai-service/chat/chat-session-store.js.map +1 -1
  140. package/dist/ai-service/demo-agents/load-agents.d.ts +5 -2
  141. package/dist/ai-service/demo-agents/load-agents.d.ts.map +1 -1
  142. package/dist/ai-service/demo-agents/load-agents.js +43 -49
  143. package/dist/ai-service/demo-agents/load-agents.js.map +1 -1
  144. package/dist/ai-service/demo-agents/run-agent.js +2 -2
  145. package/dist/ai-service/demo-agents/run-agent.js.map +1 -1
  146. package/dist/ai-service/demo-agents/system-prompt.d.ts +6 -5
  147. package/dist/ai-service/demo-agents/system-prompt.d.ts.map +1 -1
  148. package/dist/ai-service/demo-agents/system-prompt.js +18 -26
  149. package/dist/ai-service/demo-agents/system-prompt.js.map +1 -1
  150. package/dist/ai-service/demo-agents/types.d.ts +1 -56
  151. package/dist/ai-service/demo-agents/types.d.ts.map +1 -1
  152. package/dist/ai-service/demo-agents/types.js +0 -7
  153. package/dist/ai-service/demo-agents/types.js.map +1 -1
  154. package/dist/ai-service/dev-database-file-sync.d.ts +2 -1
  155. package/dist/ai-service/dev-database-file-sync.d.ts.map +1 -1
  156. package/dist/ai-service/dev-database-file-sync.js.map +1 -1
  157. package/dist/ai-service/features.d.ts +20 -8
  158. package/dist/ai-service/features.d.ts.map +1 -1
  159. package/dist/ai-service/index.d.ts +100 -7
  160. package/dist/ai-service/index.d.ts.map +1 -1
  161. package/dist/ai-service/index.js +549 -108
  162. package/dist/ai-service/index.js.map +1 -1
  163. package/dist/ai-service/judge/tools/playwright-action.d.ts +5 -5
  164. package/dist/ai-service/judge/tools/playwright-action.d.ts.map +1 -1
  165. package/dist/ai-service/judge/tools/playwright-action.js +4 -1
  166. package/dist/ai-service/judge/tools/playwright-action.js.map +1 -1
  167. package/dist/ai-service/llm/context-v2/storage/event-types.d.ts +45 -110
  168. package/dist/ai-service/llm/context-v2/storage/event-types.d.ts.map +1 -1
  169. package/dist/ai-service/llm/context-v2/storage/event-types.js +3 -3
  170. package/dist/ai-service/llm/context-v2/storage/event-types.js.map +1 -1
  171. package/dist/ai-service/mcp/adapter/json-schema-to-zod.d.ts.map +1 -1
  172. package/dist/ai-service/mcp/adapter/json-schema-to-zod.js.map +1 -1
  173. package/dist/ai-service/mcp/embedded-playwright-mcp-server.d.ts +2 -0
  174. package/dist/ai-service/mcp/embedded-playwright-mcp-server.d.ts.map +1 -1
  175. package/dist/ai-service/mcp/embedded-playwright-mcp-server.js +28 -0
  176. package/dist/ai-service/mcp/embedded-playwright-mcp-server.js.map +1 -1
  177. package/dist/ai-service/mcp/playwright-server.d.ts +2 -0
  178. package/dist/ai-service/mcp/playwright-server.d.ts.map +1 -1
  179. package/dist/ai-service/mcp/playwright-server.js +1 -0
  180. package/dist/ai-service/mcp/playwright-server.js.map +1 -1
  181. package/dist/ai-service/migration-prompt-gating.d.ts +2 -0
  182. package/dist/ai-service/migration-prompt-gating.d.ts.map +1 -1
  183. package/dist/ai-service/migration-prompt-gating.js +3 -0
  184. package/dist/ai-service/migration-prompt-gating.js.map +1 -1
  185. package/dist/ai-service/prompt-builder-service/types.d.ts +3 -1
  186. package/dist/ai-service/prompt-builder-service/types.d.ts.map +1 -1
  187. package/dist/ai-service/security/vulnerability-triage.d.ts +12 -30
  188. package/dist/ai-service/security/vulnerability-triage.d.ts.map +1 -1
  189. package/dist/ai-service/skills/system/_registry.generated.d.ts.map +1 -1
  190. package/dist/ai-service/skills/system/_registry.generated.js +6 -0
  191. package/dist/ai-service/skills/system/_registry.generated.js.map +1 -1
  192. package/dist/ai-service/skills/system/project-agents/references/errors.generated.d.ts +2 -0
  193. package/dist/ai-service/skills/system/project-agents/references/errors.generated.d.ts.map +1 -0
  194. package/dist/ai-service/skills/system/project-agents/references/errors.generated.js +25 -0
  195. package/dist/ai-service/skills/system/project-agents/references/errors.generated.js.map +1 -0
  196. package/dist/ai-service/skills/system/project-agents/references/fields.generated.d.ts +2 -0
  197. package/dist/ai-service/skills/system/project-agents/references/fields.generated.d.ts.map +1 -0
  198. package/dist/ai-service/skills/system/project-agents/references/fields.generated.js +55 -0
  199. package/dist/ai-service/skills/system/project-agents/references/fields.generated.js.map +1 -0
  200. package/dist/ai-service/skills/system/project-agents/skill.generated.d.ts +2 -0
  201. package/dist/ai-service/skills/system/project-agents/skill.generated.d.ts.map +1 -0
  202. package/dist/ai-service/skills/system/project-agents/skill.generated.js +73 -0
  203. package/dist/ai-service/skills/system/project-agents/skill.generated.js.map +1 -0
  204. package/dist/ai-service/state-machine/handlers/llm-generating.d.ts.map +1 -1
  205. package/dist/ai-service/state-machine/handlers/llm-generating.js +10 -7
  206. package/dist/ai-service/state-machine/handlers/llm-generating.js.map +1 -1
  207. package/dist/ai-service/state-machine/helpers/stable-peer.d.ts +2 -0
  208. package/dist/ai-service/state-machine/helpers/stable-peer.d.ts.map +1 -1
  209. package/dist/ai-service/state-machine/helpers/stable-peer.js +9 -2
  210. package/dist/ai-service/state-machine/helpers/stable-peer.js.map +1 -1
  211. package/dist/ai-service/tasks/task-store.d.ts.map +1 -1
  212. package/dist/ai-service/tasks/task-store.js +1 -1
  213. package/dist/ai-service/tasks/task-store.js.map +1 -1
  214. package/dist/ai-service/tasks/types.d.ts +5 -1
  215. package/dist/ai-service/tasks/types.d.ts.map +1 -1
  216. package/dist/ai-service/util/inference-jwt.d.ts +5 -0
  217. package/dist/ai-service/util/inference-jwt.d.ts.map +1 -1
  218. package/dist/ai-service/util/inference-jwt.js +17 -0
  219. package/dist/ai-service/util/inference-jwt.js.map +1 -1
  220. package/dist/ai-service/workspace-mirror.d.ts +2 -0
  221. package/dist/ai-service/workspace-mirror.d.ts.map +1 -1
  222. package/dist/ai-service/workspace-mirror.js +21 -0
  223. package/dist/ai-service/workspace-mirror.js.map +1 -1
  224. package/dist/ai-service/workspace-package-registry.d.ts +3 -0
  225. package/dist/ai-service/workspace-package-registry.d.ts.map +1 -0
  226. package/dist/ai-service/workspace-package-registry.js +87 -0
  227. package/dist/ai-service/workspace-package-registry.js.map +1 -0
  228. package/dist/ai-service/workspace-package-state.d.ts +12 -0
  229. package/dist/ai-service/workspace-package-state.d.ts.map +1 -0
  230. package/dist/ai-service/workspace-package-state.js +47 -0
  231. package/dist/ai-service/workspace-package-state.js.map +1 -0
  232. package/dist/ai-service/workspace-packages.d.ts +234 -0
  233. package/dist/ai-service/workspace-packages.d.ts.map +1 -0
  234. package/dist/ai-service/workspace-packages.js +466 -0
  235. package/dist/ai-service/workspace-packages.js.map +1 -0
  236. package/dist/dev-server-ws-smoke-client.d.ts.map +1 -1
  237. package/dist/dev-server-ws-smoke-client.js +1 -0
  238. package/dist/dev-server-ws-smoke-client.js.map +1 -1
  239. package/dist/file-sync-vite-plugin.d.ts +3 -1
  240. package/dist/file-sync-vite-plugin.d.ts.map +1 -1
  241. package/dist/file-sync-vite-plugin.js +19 -11
  242. package/dist/file-sync-vite-plugin.js.map +1 -1
  243. package/dist/file-system-manager.d.ts.map +1 -1
  244. package/dist/file-system-manager.js +11 -13
  245. package/dist/file-system-manager.js.map +1 -1
  246. package/dist/index.d.ts +5 -3
  247. package/dist/index.d.ts.map +1 -1
  248. package/dist/index.js +2 -1
  249. package/dist/index.js.map +1 -1
  250. package/dist/lock-service/index.d.ts +36 -0
  251. package/dist/lock-service/index.d.ts.map +1 -1
  252. package/dist/lock-service/index.js +59 -0
  253. package/dist/lock-service/index.js.map +1 -1
  254. package/dist/plugin-options.d.ts +9 -1
  255. package/dist/plugin-options.d.ts.map +1 -1
  256. package/dist/plugin-options.js.map +1 -1
  257. package/dist/policy-gate-runner.d.ts +1 -9
  258. package/dist/policy-gate-runner.d.ts.map +1 -1
  259. package/dist/project-agents.d.ts +31 -0
  260. package/dist/project-agents.d.ts.map +1 -0
  261. package/dist/project-agents.js +50 -0
  262. package/dist/project-agents.js.map +1 -0
  263. package/dist/project-manifest.d.ts +8 -108
  264. package/dist/project-manifest.d.ts.map +1 -1
  265. package/dist/project-manifest.js +28 -115
  266. package/dist/project-manifest.js.map +1 -1
  267. package/dist/server-rpc/index.d.ts +6 -0
  268. package/dist/server-rpc/index.d.ts.map +1 -1
  269. package/dist/server-rpc/index.js +13 -1
  270. package/dist/server-rpc/index.js.map +1 -1
  271. package/dist/socket-manager.d.ts +3 -1
  272. package/dist/socket-manager.d.ts.map +1 -1
  273. package/dist/socket-manager.js +115 -65
  274. package/dist/socket-manager.js.map +1 -1
  275. package/dist/sync-service/draft-mutation.d.ts +6 -2
  276. package/dist/sync-service/draft-mutation.d.ts.map +1 -1
  277. package/dist/sync-service/draft-mutation.js +20 -33
  278. package/dist/sync-service/draft-mutation.js.map +1 -1
  279. package/dist/sync-service/index.d.ts +6 -6
  280. package/dist/sync-service/index.d.ts.map +1 -1
  281. package/dist/sync-service/index.js +29 -61
  282. package/dist/sync-service/index.js.map +1 -1
  283. package/dist/workspace-sync-methods.d.ts +5 -20
  284. package/dist/workspace-sync-methods.d.ts.map +1 -1
  285. package/package.json +17 -13
  286. package/dist/sync-service/native-draft-session.d.ts +0 -3
  287. package/dist/sync-service/native-draft-session.d.ts.map +0 -1
  288. package/dist/sync-service/native-draft-session.js +0 -4
  289. 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";
@@ -136,6 +137,7 @@ import { PERMISSION_PROMPT_DELIVERY_TIMEOUT_MS, PERMISSION_PROMPT_RESPONSE_TIMEO
136
137
  import { getToolCallSignature } from "./util/tool-signature.js";
137
138
  import { readWorkspaceIngress } from "./workspace-edge-health.js";
138
139
  import { rpcWorkspaceMirrorSource, WorkspaceMirror, } from "./workspace-mirror.js";
140
+ import { workspacePackageShell, parseWorkspacePackagePolicyRequest, } from "./workspace-packages.js";
139
141
  export { AiServiceFeatureFlags } from "./features.js";
140
142
  export { WorkspaceDowngradedError } from "./builder-workspace.js";
141
143
  export { BuilderRuntime } from "./builder-runtime.js";
@@ -360,17 +362,28 @@ function builderBindingMismatchCounter() {
360
362
  });
361
363
  return bindingMismatchCounter;
362
364
  }
365
+ let switchClaimCounter;
366
+ function builderSwitchClaimCounter() {
367
+ switchClaimCounter ??= metrics
368
+ .getMeter("superblocks.ai_service")
369
+ .createCounter("superblocks.ai_service.builder_switch.claims", {
370
+ description: "Harness or model switch requests, by whether a running turn refused, was stopped for, or did not stop for the switch",
371
+ unit: "1",
372
+ });
373
+ return switchClaimCounter;
374
+ }
375
+ function recordBuilderSwitchClaim(kind, outcome) {
376
+ builderSwitchClaimCounter().add(1, {
377
+ "switch.kind": kind,
378
+ "switch.outcome": outcome,
379
+ });
380
+ }
363
381
  function bindingMatchesRuntime(binding, runtime) {
364
382
  return (binding.harness === runtime.harness &&
365
383
  (binding.model === undefined || binding.model === runtime.model));
366
384
  }
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
- }
385
+ /** A server commit id. */
386
+ 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
387
  export class AiService extends TracedEventEmitter {
375
388
  config;
376
389
  templateRenderer;
@@ -396,7 +409,19 @@ export class AiService extends TracedEventEmitter {
396
409
  */
397
410
  builderBindingStale = false;
398
411
  /** Set while a harness switch moves the server and this pod to a new chat; prompts wait for it to finish. */
399
- builderSwitchInProgress = false;
412
+ _builderSwitchInProgress = false;
413
+ /** Every editor must see a switch: prompts are refused while it runs, and its stop publishes CANCELLED to all of them. */
414
+ get builderSwitchInProgress() {
415
+ return this._builderSwitchInProgress;
416
+ }
417
+ set builderSwitchInProgress(switching) {
418
+ if (switching === this._builderSwitchInProgress)
419
+ return;
420
+ this._builderSwitchInProgress = switching;
421
+ catchBackgroundPeerDisconnect(this.stablePeer.call.aiSetBuilderSwitching({ switching }), "builder switching push");
422
+ }
423
+ /** Clark's USER_CANCELED handler, which keeps writing to the chat after the FSM reports Idle. */
424
+ clarkCancelHandler;
400
425
  /**
401
426
  * Prompts past the switch check but whose turn has not started yet. They await a server round trip before the
402
427
  * conversation reports busy, so a switch counts them as a running turn.
@@ -407,9 +432,106 @@ export class AiService extends TracedEventEmitter {
407
432
  /** The binding the pre-turn check resolved, which that request's turn uses instead of resolving again. */
408
433
  checkedBinding;
409
434
  workspaceClient;
435
+ workspacePackageTransport;
436
+ workspacePackageRecovery = { required: false };
437
+ setWorkspacePackageTransport(transport) {
438
+ this.workspacePackageTransport = transport;
439
+ }
440
+ async workspacePackagePolicy(request) {
441
+ request = parseWorkspacePackagePolicyRequest(request);
442
+ switch (request.kind) {
443
+ case "registry": {
444
+ const result = await this.npmRegistryClient.getConfig({
445
+ forceRefresh: true,
446
+ });
447
+ return {
448
+ source: result.source,
449
+ config: {
450
+ configured: result.config.configured,
451
+ allowInstallScripts: result.config.allowInstallScripts,
452
+ },
453
+ ...(result.source === "unreachable" && {
454
+ everConfigured: result.everConfigured,
455
+ }),
456
+ };
457
+ }
458
+ case "lookup":
459
+ return this.appShell.lookupPackageVulnerabilities(request.packages);
460
+ case "holdback":
461
+ return this.npmPackageLookup.pickQuarantineHoldback(request.name, request.version);
462
+ case "blocked_audit":
463
+ return this.config.rpcClient.call((client) => client.call.v1.audit.npmInstallBlocked(request.report));
464
+ case "outcome":
465
+ return this.config.rpcClient.call((client) => client.call.v1.audit.npmInstallOutcome(request.report));
466
+ }
467
+ }
468
+ nativePackageServices() {
469
+ if (!this.isWorkspacePlacement)
470
+ return {
471
+ appShell: this.appShell,
472
+ draftInterface: this.config.draftInterface,
473
+ };
474
+ const sessionKey = this.builderBinding?.workspace?.sessionKey;
475
+ const assertSession = () => {
476
+ if (!sessionKey ||
477
+ this.builderBinding?.workspace?.sessionKey !== sessionKey)
478
+ throw new Error("The application moved to another workspace during package management");
479
+ };
480
+ return {
481
+ appShell: workspacePackageShell({
482
+ recoveryState: this.workspacePackageRecovery,
483
+ local: this.appShell,
484
+ execute: async (operation, signal) => {
485
+ assertSession();
486
+ if (!this.workspacePackageTransport)
487
+ throw new Error("VM package transport is unavailable; reload the editor before retrying");
488
+ return this.workspacePackageTransport.packageOperation({
489
+ operation,
490
+ gateEnabled: this.config.features.packageInstallGateEnabled === true,
491
+ }, (request) => {
492
+ assertSession();
493
+ return this.workspacePackagePolicy(request);
494
+ }, signal);
495
+ },
496
+ recover: async ({ cancelled }) => {
497
+ assertSession();
498
+ if (cancelled) {
499
+ if (!this.workspacePackageTransport?.packageState ||
500
+ !this.workspaceMirror)
501
+ throw new Error("Read-only VM package recovery is unavailable");
502
+ const state = await this.workspacePackageTransport.packageState();
503
+ assertSession();
504
+ await this.workspaceMirror.mirror.refreshPackageState(state);
505
+ await this.refreshFileModel();
506
+ return;
507
+ }
508
+ const sync = this._runtimeSyncService;
509
+ if (!sync ||
510
+ !("syncCurrentDirectoryWithDraftsNow" in sync) ||
511
+ typeof sync.syncCurrentDirectoryWithDraftsNow !== "function")
512
+ throw new Error("VM state recovery is unavailable");
513
+ const result = z
514
+ .object({ directoryHash: z.string().min(1) })
515
+ .parse(await sync.syncCurrentDirectoryWithDraftsNow("requestedFilesSync"));
516
+ assertSession();
517
+ await this.refreshWorkspaceMirror(result.directoryHash);
518
+ },
519
+ refresh: async (hash) => {
520
+ assertSession();
521
+ await this.refreshWorkspaceMirror(hash);
522
+ },
523
+ }),
524
+ // The VM records package.json and both lockfiles in its active journal.
525
+ // Never write draft markers into the read-only mirror.
526
+ draftInterface: { createDraftMarkerOnly: async (_path) => { } },
527
+ };
528
+ }
410
529
  workspaceMirror;
411
530
  /** The newest DBFS hash the VM reported for the current workspace. */
412
531
  workspaceHash;
532
+ /** The mirror changed on disk but reloading the file model has not succeeded. */
533
+ workspaceFileModelStale = false;
534
+ workspaceRefreshQueue = new OperationQueue();
413
535
  adoptedWorkspaceOpens = new WeakSet();
414
536
  /** The current VM boot's ai-service credential, from `workspace.open`. */
415
537
  workspaceInternalToken;
@@ -418,6 +540,12 @@ export class AiService extends TracedEventEmitter {
418
540
  * the VM's turn-end commit reported. Undefined for a live-edit turn.
419
541
  */
420
542
  workspaceTurnFinish;
543
+ /**
544
+ * The AI checkpoint the last completed native turn created. Native turns
545
+ * commit at turn end instead of leaving a draft, so an accept after one
546
+ * (the gateway's checkpoint step) returns this commit.
547
+ */
548
+ lastNativeCheckpointId;
421
549
  nativeBuilderJwt;
422
550
  nativeInferenceTurn;
423
551
  nativePromptAttempt;
@@ -1009,7 +1137,7 @@ export class AiService extends TracedEventEmitter {
1009
1137
  // (LD flag + ONPREMISE + OPA edit lifecycle registration). When the
1010
1138
  // gate is off, `taskStore` stays undefined and `agent/tools.ts`
1011
1139
  // skips registering the start*/check*/wait*/cancel*/list* tools.
1012
- if (!config.builderRuntime && isBackgroundTaskFrameworkEnabled(config)) {
1140
+ if (isBackgroundTaskFrameworkEnabled(config)) {
1013
1141
  this.taskStore = new TaskStore();
1014
1142
  // Heterogeneous list of task types funneled into
1015
1143
  // `registerBackgroundTaskTypes` (which itself takes ReadonlyArray<TaskType<any, any, any>>),
@@ -1035,10 +1163,19 @@ export class AiService extends TracedEventEmitter {
1035
1163
  // AFTER this constructor runs, so the helper resolves it
1036
1164
  // lazily at task-start time.
1037
1165
  ensureFilesSynced: buildEnsureDevDatabaseFilesSynced(() => this._runtimeSyncService),
1038
- getClient: () => {
1039
- const jwt = this.clark?.context?.jwt;
1166
+ getClient: (ownerUserId) => {
1167
+ if (!ownerUserId) {
1168
+ throw new Error("[devDatabase] task starter is unavailable");
1169
+ }
1170
+ if (this.getAuthenticatedTaskUserId() !== ownerUserId) {
1171
+ throw new DevDatabaseTaskOwnerUnavailableError("[devDatabase] task owner does not match the authenticated peer; reconnect as the user who started the task");
1172
+ }
1173
+ const jwt = this.getInferenceJwt();
1040
1174
  if (!jwt) {
1041
- throw new Error("[devDatabase] cannot start background task: no JWT available on Clark context");
1175
+ throw new DevDatabaseTaskOwnerUnavailableError("[devDatabase] cannot start background task: no current JWT available");
1176
+ }
1177
+ if (parseJwt(jwt)?.userId !== ownerUserId) {
1178
+ throw new DevDatabaseTaskOwnerUnavailableError("[devDatabase] task owner does not match the current editor; reconnect as the user who started the task");
1042
1179
  }
1043
1180
  return new DevDatabaseClient({
1044
1181
  transport: createDevDatabaseHttpTransport({
@@ -1049,12 +1186,7 @@ export class AiService extends TracedEventEmitter {
1049
1186
  },
1050
1187
  // Same owner stamping as defineBackgroundTaskFactory so sibling
1051
1188
  // 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
- },
1189
+ getCurrentOwnerId: () => this.getAuthenticatedTaskUserId(),
1058
1190
  // Lazy: TaskStore exists on `this` but watch siblings only start
1059
1191
  // after types are registered below.
1060
1192
  getTaskStore: () => this.taskStore,
@@ -1210,6 +1342,143 @@ export class AiService extends TracedEventEmitter {
1210
1342
  isBusyForBuilderSwitch() {
1211
1343
  return this.isBusy() || this.promptsBeingAdmitted > 0;
1212
1344
  }
1345
+ /**
1346
+ * Claims a harness or model switch without stopping anything. A running turn, or Clark waiting on a question or a
1347
+ * permission prompt, refuses it until the user confirms `stopTurn`. Returns whether the caller must stop the turn,
1348
+ * which it does with {@link stopTurnForBuilderSwitch} once the switch's own checks pass. The caller releases
1349
+ * `builderSwitchInProgress`.
1350
+ */
1351
+ claimBuilderSwitch(kind, stopTurn) {
1352
+ const record = (outcome) => recordBuilderSwitchClaim(kind, outcome);
1353
+ if (this.builderSwitchInProgress) {
1354
+ record("refused_in_progress");
1355
+ throw new Error("The harness or model is already being switched");
1356
+ }
1357
+ // Its turn has not started yet, so there is nothing to stop. Clark's cancel cannot stop a turn it is still starting
1358
+ // either, and waitUntilGenerationComplete does not wait for one. Checked on every click, ahead of the
1359
+ // turn-in-progress refusal: offering "Stop and switch" for a stop that would be refused loops the dialog.
1360
+ if (this.promptsBeingAdmitted > 0 ||
1361
+ (!this.builderConversation && this.generationStarting)) {
1362
+ record("refused_starting");
1363
+ throw new SocketErrorException(409, "A prompt is starting. Try the switch again in a moment.");
1364
+ }
1365
+ const busy = this.isTurnRunningForBuilderSwitch();
1366
+ // A plain Error crosses the socket as "Error: <message>"; the editor matches the exact message.
1367
+ if (busy && !stopTurn) {
1368
+ const waiting = this.isAwaitingInteractiveResponse();
1369
+ record(waiting ? "refused_waiting" : "refused_working");
1370
+ throw new SocketErrorException(409, waiting
1371
+ ? SWITCH_ENDS_WAITING_TURN_MESSAGE
1372
+ : SWITCH_STOPS_WORKING_TURN_MESSAGE);
1373
+ }
1374
+ // Set synchronously after the checks, so no prompt starts between them.
1375
+ this.builderSwitchInProgress = true;
1376
+ return { mustStopTurn: busy };
1377
+ }
1378
+ /**
1379
+ * Stops the turn a confirmed switch claimed, as the Stop button does, including its draft-state report. Runs only
1380
+ * after the switch's own checks pass, so a switch that cannot happen never costs the user the turn.
1381
+ */
1382
+ async stopTurnForBuilderSwitch(kind, onTurnStopped) {
1383
+ // The turn may have ended on its own during the checks; cancelling then would mark a finished turn cancelled.
1384
+ if (!this.isBusy() &&
1385
+ !(!this.builderConversation && this.isAwaitingInteractiveResponse()))
1386
+ return false;
1387
+ const startedAt = Date.now();
1388
+ try {
1389
+ await this.handleUserCanceled("stop");
1390
+ // A native cancel waits for its turn to settle; Clark's state machine settles after the cancel event.
1391
+ if (!this.builderConversation) {
1392
+ await this.waitForClarkCancelHandler();
1393
+ await this.waitUntilGenerationComplete();
1394
+ await this.waitForClarkToDropOpenQuestion();
1395
+ }
1396
+ if (this.isBusy())
1397
+ throw new Error("The current turn did not stop. Try the switch again.");
1398
+ }
1399
+ catch (error) {
1400
+ this.getLogger().warn("[ai-service] Could not stop the turn for a switch", {
1401
+ "switch.kind": kind,
1402
+ "switch.stop_ms": Date.now() - startedAt,
1403
+ ...getErrorMeta(error),
1404
+ });
1405
+ throw error;
1406
+ }
1407
+ this.getLogger().info("[ai-service] Stopped the turn for a switch", {
1408
+ "switch.kind": kind,
1409
+ "switch.stop_ms": Date.now() - startedAt,
1410
+ });
1411
+ const hasDraft = await this.showDraftLeftByStop();
1412
+ // The turn already stopped; a failed draft-state report must not also cost the user the switch.
1413
+ try {
1414
+ await onTurnStopped?.(hasDraft);
1415
+ }
1416
+ catch (error) {
1417
+ this.getLogger().warn("[ai-service] Could not report draft state after stopping the turn for a switch", { "switch.kind": kind, ...getErrorMeta(error) });
1418
+ }
1419
+ return true;
1420
+ }
1421
+ /** The FSM reports Idle before its cancel handler finishes writing to the chat; a switch must not change it first. */
1422
+ async waitForClarkCancelHandler() {
1423
+ const handler = this.clarkCancelHandler;
1424
+ if (!handler)
1425
+ return;
1426
+ let timer;
1427
+ const timedOut = new Promise((_, reject) => {
1428
+ timer = setTimeout(() => reject(new Error("The current turn did not stop. Try the switch again.")), GENERATION_COMPLETION_WAIT_TIMEOUT_MS);
1429
+ timer.unref();
1430
+ });
1431
+ try {
1432
+ await Promise.race([handler, timedOut]);
1433
+ }
1434
+ finally {
1435
+ clearTimeout(timer);
1436
+ }
1437
+ }
1438
+ /**
1439
+ * Clark's USER_CANCELED for an open question runs after handleUserCanceled returns, and waitUntilGenerationComplete
1440
+ * does not wait for a turn that is not generating. A switch that went on would start the new chat under that question.
1441
+ */
1442
+ async waitForClarkToDropOpenQuestion() {
1443
+ const deadline = Date.now() + GENERATION_COMPLETION_WAIT_TIMEOUT_MS;
1444
+ while (this.isAwaitingInteractiveResponse()) {
1445
+ if (Date.now() > deadline)
1446
+ throw new Error("The current turn did not stop. Try the switch again.");
1447
+ await new Promise((resolve) => setTimeout(resolve, 25));
1448
+ }
1449
+ }
1450
+ /** Clark's resting AwaitingUser state is not a turn to isBusy(), but switching would drop its open question. */
1451
+ isTurnRunningForBuilderSwitch() {
1452
+ return (this.isBusyForBuilderSwitch() ||
1453
+ (!this.builderConversation && this.isAwaitingInteractiveResponse()));
1454
+ }
1455
+ /**
1456
+ * After a stop by the Stop button or for a switch: the stop's CANCELLED hides Accept and Reject, so show them again
1457
+ * for any changes the turn left. Clark's cancel handler publishes that CANCELLED late, so it is awaited first.
1458
+ * Returns whether changes remain, in which case the server's draft flag must stay set, or undefined when the check
1459
+ * failed: then the flag stays set too, since clearing it could let unaccepted changes look clean to git.
1460
+ */
1461
+ async showDraftLeftByStop() {
1462
+ if (!this.builderConversation)
1463
+ await this.waitForClarkCancelHandler().catch((error) => {
1464
+ this.getLogger().warn("[ai-service] Clark's cancel handler did not finish before the draft check", getErrorMeta(error));
1465
+ });
1466
+ let hasDraft;
1467
+ try {
1468
+ hasDraft = Boolean(await this.config.draftInterface?.hasLocalDraftChanges());
1469
+ }
1470
+ catch (error) {
1471
+ // The stop already happened, so do not fail it; without an answer, leave the server's draft flag alone.
1472
+ this.getLogger().warn("[ai-service] Could not check for changes left by a stop", getErrorMeta(error));
1473
+ }
1474
+ if (hasDraft)
1475
+ catchBackgroundPeerDisconnect(this.stablePeer.call.aiSetDraftState({ hasDraft: true }), "draft state push");
1476
+ return hasDraft;
1477
+ }
1478
+ /** Sent to an editor when it connects, so a tab that reconnects mid-switch does not wait for a push it missed. */
1479
+ isBuilderSwitchInProgress() {
1480
+ return this.builderSwitchInProgress;
1481
+ }
1213
1482
  /** A prompt sent while a harness switch is moving to a new chat would run on the old harness in the new chat. */
1214
1483
  assertNoBuilderSwitchInProgress() {
1215
1484
  if (this.builderSwitchInProgress)
@@ -1230,13 +1499,36 @@ export class AiService extends TracedEventEmitter {
1230
1499
  * Opens the binding's AgentCore workspace without waiting for it. Opening
1231
1500
  * needs a JWT to mint the runtime token, so without one it waits for
1232
1501
  * `updateClarkJwt`; the first turn joins the same open.
1502
+ *
1503
+ * A switch from Clark applies the agentcore binding while the sidecar still
1504
+ * runs Vite, and only then asks the editor to restart it into the workspace
1505
+ * edge. Opening now would fail as sidecar_mismatch, so a sidecar still on
1506
+ * live-edit is left to `openWorkspaceAfterRestart`; a prompt sent before then
1507
+ * is refused by `assertEditorNeedsNoRestart`.
1233
1508
  */
1234
1509
  openWorkspaceInBackground(binding, branch) {
1235
1510
  if (binding.workspace?.placement !== "agentcore")
1236
1511
  return;
1237
1512
  if (!this.getInferenceJwt())
1238
1513
  return;
1239
- this.ensureWorkspace(binding, branch).catch((error) => this.getLogger().warn("[workspace] Background workspace open failed; the next turn retries", getErrorMeta(error)));
1514
+ void this.openWorkspaceUnlessSidecarOnLiveEdit(binding, branch);
1515
+ }
1516
+ async openWorkspaceUnlessSidecarOnLiveEdit(binding, branch) {
1517
+ const edgeUrl = this.config.workspace?.edgeUrl;
1518
+ if (edgeUrl && (await readWorkspaceIngress(edgeUrl)) === "live-edit") {
1519
+ this.getLogger().info("[workspace] The editor still runs live-edit; the workspace opens after it restarts", { harness: binding.harness });
1520
+ return;
1521
+ }
1522
+ await this.ensureWorkspace(binding, branch).catch((error) => this.getLogger().warn("[workspace] Background workspace open failed; the next turn retries", {
1523
+ ...getErrorMeta(error),
1524
+ harness: binding.harness,
1525
+ // A switch into agentcore restarts the sidecar; an open that runs before that restart lands fails as
1526
+ // sidecar_mismatch. These say whether one was due and how long ago it was asked for.
1527
+ editorRestartRequired: this.editorRestartRequired,
1528
+ editorRestartAskedAgoMs: this.editorRestartAskedAt === undefined
1529
+ ? undefined
1530
+ : Date.now() - this.editorRestartAskedAt,
1531
+ }));
1240
1532
  }
1241
1533
  initializeNativeBuilder() {
1242
1534
  const config = this.config;
@@ -1246,21 +1538,24 @@ export class AiService extends TracedEventEmitter {
1246
1538
  runtime,
1247
1539
  tools: new NativeBuilderToolHost({
1248
1540
  getJwt: () => this.getClarkJwt(),
1541
+ taskStore: this.taskStore,
1542
+ getCurrentOwnerId: () => this.getAuthenticatedTaskUserId(),
1543
+ isWorkspacePlacement: () => this.isWorkspacePlacement,
1249
1544
  getPackageServices: (request) => ({
1250
1545
  appContextStore: this.appContext,
1251
- appShell: this.appShell,
1252
- draftInterface: config.draftInterface,
1546
+ ...this.nativePackageServices(),
1253
1547
  chatSessionStore: this.chatSessionStore,
1254
1548
  llmClient: this.llmClient,
1255
1549
  llmProvider: createLLMProvider(this.getLLMProviderSettings(request?.llmConfig), () => this.requireProviderInferenceAuthToken(), request?.llmConfig),
1256
1550
  }),
1257
1551
  appShell: this.appShell,
1258
- assertLocalAppTreeWritable: (action) => this.assertLocalAppTreeWritable(action),
1259
1552
  ensureFilesSynced: async () => {
1260
1553
  const sync = this._runtimeSyncService;
1261
1554
  if (!sync?.syncCurrentDirectoryWithDraftsNow)
1262
1555
  throw new Error("Native builder DEV sync service is unavailable");
1263
- const synced = await sync.syncCurrentDirectoryWithDraftsNow("requestedFilesSync");
1556
+ // Interim: stores the tree for the read without a commit; the
1557
+ // turn end commits it.
1558
+ const synced = await sync.syncCurrentDirectoryWithDraftsNow("ai:generate:interim");
1264
1559
  if (!synced?.directoryHash)
1265
1560
  throw new Error("Native builder file sync did not return a directory hash");
1266
1561
  // testApi reads the tree here: in agentcore placement, bring the
@@ -1285,29 +1580,40 @@ export class AiService extends TracedEventEmitter {
1285
1580
  chat: this.chatSessionStore,
1286
1581
  prepare: (request, signal, generationId) => this.prepareNativeBuilderRequest(request, signal, generationId),
1287
1582
  afterRun: async (turn) => {
1583
+ // A native turn leaves no draft: its end commits the files as an
1584
+ // AI checkpoint, and an unchanged tree creates none.
1288
1585
  const workspaceFinish = this.workspaceTurnFinish;
1586
+ let checkpointId;
1289
1587
  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.
1588
+ // Agentcore placement: the runtime owns the turn in the VM, whose
1589
+ // turn end commits it. Its finish carries the commit's hash,
1590
+ // which the finish handler already mirrored, and the checkpoint
1591
+ // when one was created. There is nothing to sync.
1293
1592
  await turn?.events();
1294
1593
  if (workspaceFinish.finished && !workspaceFinish.dbfsHash)
1295
1594
  throw new Error("The workspace did not report a committed hash for this turn; its changes may not be saved.");
1595
+ checkpointId = workspaceFinish.commitId;
1296
1596
  }
1297
1597
  else {
1298
1598
  const sync = this._runtimeSyncService;
1299
1599
  if (!sync?.syncCurrentDirectoryWithDraftsNow)
1300
1600
  throw new Error("Native builder DEV sync service is unavailable");
1301
- const synced = await sync.syncCurrentDirectoryWithDraftsNow("ai:generate:post", { waitForNativeSession: true });
1601
+ const synced = await sync.syncCurrentDirectoryWithDraftsNow("ai:accept", { waitForNativeSession: true });
1302
1602
  // The binding moved to a workspace since the turn started.
1303
1603
  if (this.isWorkspacePlacement &&
1304
1604
  typeof synced?.directoryHash === "string")
1305
1605
  await this.mirrorWorkspaceHash(synced.directoryHash);
1606
+ if (synced?.commitId && !synced.checkpointSkipped)
1607
+ checkpointId = synced.commitId;
1306
1608
  }
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)));
1609
+ // The server records the card of an editor-token commit, but leaves
1610
+ // the VM's (its sync token's) to this service, so the card lands
1611
+ // after the turn's final message.
1612
+ if (checkpointId)
1613
+ await this.publishNativeCheckpoint(checkpointId, {
1614
+ record: Boolean(workspaceFinish),
1615
+ });
1616
+ return { checkpointId };
1311
1617
  },
1312
1618
  onSettled: (generationId, error, cancelled) => {
1313
1619
  const attempt = this.nativePromptAttempt;
@@ -1330,7 +1636,7 @@ export class AiService extends TracedEventEmitter {
1330
1636
  this.activeGenerationTrace?.finish(cancelled ? "cancelled" : error ? "failed" : "completed", error);
1331
1637
  this.triggerGenerationComplete(generationId);
1332
1638
  },
1333
- onError: (error, attempt) => BuilderRuntimeError.log(error, this.getLogger(), attempt),
1639
+ onError: (error, attempt, context) => BuilderRuntimeError.log(error, this.getLogger(), attempt, context),
1334
1640
  checkPaywall: () => this.nativePaywallReason(),
1335
1641
  });
1336
1642
  }
@@ -1670,14 +1976,20 @@ export class AiService extends TracedEventEmitter {
1670
1976
  conversationId: this.builderBinding?.runtimeSessionId,
1671
1977
  }),
1672
1978
  }, HarnessTrace.context(runtime?.harness ?? "clark"));
1979
+ // A native turn runs on its runtime's model; the request's llmConfig is
1980
+ // the editor's Clark configuration and only describes a Clark turn.
1981
+ const model = runtime ? runtime.model : request.llmConfig?.coreModel;
1982
+ const provider = runtime
1983
+ ? runtime.providerFor(runtime.model)
1984
+ : request.llmConfig?.provider;
1673
1985
  const span = this.config.tracer.startSpan("AiService.generation", {
1674
1986
  attributes: {
1675
1987
  ...TraceCorrelation.attributes(parentContext),
1676
1988
  "ai.mode": request.mode,
1677
- "ai.model": request.llmConfig?.coreModel,
1678
- "ai.provider": runtime
1679
- ? runtime.providerFor(runtime.model)
1680
- : request.llmConfig?.provider,
1989
+ "ai.model": model,
1990
+ "ai.provider": provider,
1991
+ "gen_ai.provider.name": provider,
1992
+ "gen_ai.request.model": model,
1681
1993
  "app.id": this.config.applicationId,
1682
1994
  "org.id": this.config.organizationId,
1683
1995
  },
@@ -1785,17 +2097,9 @@ export class AiService extends TracedEventEmitter {
1785
2097
  gitOperationLock: this._runtimeGitOperationLock,
1786
2098
  onGitOperationComplete: this._onGitOperationComplete,
1787
2099
  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
- },
2100
+ // Task access follows the authenticated transport principal, not
2101
+ // claims decoded from a separately supplied inference credential.
2102
+ getCurrentOwnerId: () => this.getAuthenticatedTaskUserId(),
1799
2103
  };
1800
2104
  const clarkStateHandlers = Object.fromEntries(Object.entries(clarkStateHandlerFactories).map(([state, handlerFactory]) => [state, handlerFactory(clark, params)]));
1801
2105
  const { from, to, event } = transition;
@@ -3022,6 +3326,32 @@ export class AiService extends TracedEventEmitter {
3022
3326
  });
3023
3327
  return this.nativeAttachmentPreparations.resolve(request);
3024
3328
  }
3329
+ /** A prompt refused for its attachments stays in the chat with the reason. */
3330
+ async prepareNativePromptAttachments(request) {
3331
+ try {
3332
+ return await this.resolveNativePromptAttachments(request);
3333
+ }
3334
+ catch (error) {
3335
+ if (!this.builderConversation ||
3336
+ (error instanceof DOMException && error.name === "AbortError"))
3337
+ throw error;
3338
+ // The queue path reaches here before following the binding; the refusal must land in the editor's chat.
3339
+ if (this.shouldFollowBuilderBinding(request)) {
3340
+ try {
3341
+ await this.followBuilderBinding(request);
3342
+ }
3343
+ catch (bindingError) {
3344
+ if (bindingError instanceof BuilderBindingChangedError)
3345
+ throw bindingError;
3346
+ throw error;
3347
+ }
3348
+ }
3349
+ const conversation = this.builderConversation;
3350
+ if (!conversation)
3351
+ throw error;
3352
+ throw await conversation.rejectPrompt(request, error);
3353
+ }
3354
+ }
3025
3355
  cancelPendingNativeRequests() {
3026
3356
  this.nativeCancellationVersion = (this.nativeCancellationVersion ?? 0) + 1;
3027
3357
  this.nativeAttachmentPreparations?.cancel();
@@ -3134,10 +3464,9 @@ export class AiService extends TracedEventEmitter {
3134
3464
  this.builderBranch = branch;
3135
3465
  signal.throwIfAborted();
3136
3466
  const workspaceLocal = binding.workspace?.placement === "agentcore";
3467
+ this.lastNativeCheckpointId = undefined;
3137
3468
  const userId = parseJwt(request.jwt)?.userId;
3138
- const turnFinish = {
3139
- finished: false,
3140
- };
3469
+ const turnFinish = { finished: false };
3141
3470
  this.workspaceTurnFinish = workspaceLocal ? turnFinish : undefined;
3142
3471
  const opened = workspaceLocal
3143
3472
  ? await this.ensureWorkspace(binding, branch)
@@ -3186,6 +3515,8 @@ export class AiService extends TracedEventEmitter {
3186
3515
  onWorkspaceFinish: async (workspace) => {
3187
3516
  turnFinish.finished = true;
3188
3517
  turnFinish.dbfsHash = workspace.dbfsHash;
3518
+ // A retried attempt that changed nothing keeps the first one's.
3519
+ turnFinish.commitId = workspace.commitId ?? turnFinish.commitId;
3189
3520
  if (workspace.dbfsHash)
3190
3521
  await this.mirrorWorkspaceHash(workspace.dbfsHash);
3191
3522
  },
@@ -3231,7 +3562,7 @@ export class AiService extends TracedEventEmitter {
3231
3562
  await this.followBuilderBinding(request);
3232
3563
  if (this.builderConversation) {
3233
3564
  const cancellationVersion = this.nativeCancellationVersion ?? 0;
3234
- const attachments = await this.resolveNativePromptAttachments(request);
3565
+ const attachments = await this.prepareNativePromptAttachments(request);
3235
3566
  this.assertNativeRequestActive(cancellationVersion);
3236
3567
  if (attachments)
3237
3568
  await this.builderConversation.start(request, attachments);
@@ -4086,11 +4417,45 @@ export class AiService extends TracedEventEmitter {
4086
4417
  type: "draftCommitted",
4087
4418
  }, inputSource);
4088
4419
  }
4420
+ /**
4421
+ * Shows a native turn's checkpoint card to the turn's peer and observers.
4422
+ * With `record`, it first records the card in the chat: the server records
4423
+ * it with an editor-token commit, but not with a workspace VM's, which
4424
+ * lands before the turn's final message.
4425
+ */
4426
+ async publishNativeCheckpoint(commitId, { record = false } = {}) {
4427
+ this.lastNativeCheckpointId = commitId;
4428
+ const card = {
4429
+ commitId,
4430
+ content: commitId,
4431
+ id: commitId,
4432
+ role: "assistant",
4433
+ timestamp: Date.now(),
4434
+ type: "draftCommitted",
4435
+ };
4436
+ // The id comes from the VM, so only a commit id's shape is recorded.
4437
+ if (record && UUID_PATTERN.test(commitId))
4438
+ await this.chatSessionStore.recordAssistant(card);
4439
+ else if (record)
4440
+ this.getLogger().warn("[ai-service] Not recording a native checkpoint card with a malformed commit id");
4441
+ await this.stablePeer.call
4442
+ .aiPushMessage(card)
4443
+ .catch((error) => this.getLogger().warn("[ai-service] Failed to push the native turn's checkpoint", getErrorMeta(error)));
4444
+ }
4445
+ /**
4446
+ * The accept result for a native builder, which commits at turn end and so
4447
+ * has no draft to accept: the last turn's checkpoint, or an empty commit id
4448
+ * when it created none. Undefined when Clark runs, whose accept commits a
4449
+ * draft.
4450
+ */
4451
+ get nativeAcceptResult() {
4452
+ if (!this.builderConversation)
4453
+ return undefined;
4454
+ return { commitId: this.lastNativeCheckpointId ?? "" };
4455
+ }
4089
4456
  async handleUserAcceptedDraft(silently) {
4090
- if (this.builderConversation) {
4091
- await this.chatSessionStore.recordUserAcceptance();
4457
+ if (this.builderConversation)
4092
4458
  return;
4093
- }
4094
4459
  this.getLogger().info(`[ai-service] handleUserAcceptedDraft`);
4095
4460
  if (this.clark.state === ClarkStateNames.Idle) {
4096
4461
  return;
@@ -4103,13 +4468,14 @@ export class AiService extends TracedEventEmitter {
4103
4468
  void transitionTo({ type: USER_ACCEPTED_DRAFT, silently });
4104
4469
  }
4105
4470
  async handleUserRejectedDraft(silently) {
4106
- if (this.builderConversation) {
4107
- await this.chatSessionStore.recordUserRejection();
4471
+ if (this.builderConversation)
4108
4472
  return;
4109
- }
4110
4473
  this.getLogger().info(`[ai-service] handleUserRejectedDraft`);
4111
- this.submitAcceptanceEvaluation(false);
4112
4474
  this.editAfterClark.discardLastTurn();
4475
+ // As for Accept: a Stop leaves Clark Idle with its changes still offered, and the files are already discarded.
4476
+ if (this.clark.state === ClarkStateNames.Idle)
4477
+ return;
4478
+ this.submitAcceptanceEvaluation(false);
4113
4479
  if (this.clark.state !== ClarkStateNames.AwaitingUser) {
4114
4480
  throw new Error("Service is not awaiting user input");
4115
4481
  }
@@ -4231,9 +4597,17 @@ export class AiService extends TracedEventEmitter {
4231
4597
  awaitingUserHandoffPromptId: undefined,
4232
4598
  awaitingUserHandoffRecorded: undefined,
4233
4599
  }));
4234
- void this.clark.send({
4600
+ // A switch awaits this before it changes the chat: the handler records "Canceled." and pushes CANCELLED.
4601
+ const cancelHandler = Promise.resolve(this.clark.send({
4235
4602
  type: USER_CANCELED,
4236
4603
  failure: promptFailureUserCanceled(),
4604
+ })).catch((error) => {
4605
+ this.getLogger().warn("[ai-service] Clark's cancel handler failed", getErrorMeta(error));
4606
+ });
4607
+ this.clarkCancelHandler = cancelHandler;
4608
+ void cancelHandler.finally(() => {
4609
+ if (this.clarkCancelHandler === cancelHandler)
4610
+ this.clarkCancelHandler = undefined;
4237
4611
  });
4238
4612
  }
4239
4613
  finally {
@@ -4308,7 +4682,7 @@ export class AiService extends TracedEventEmitter {
4308
4682
  if (this.builderConversation) {
4309
4683
  // Attachments are validated before a running turn is interrupted.
4310
4684
  cancellationVersion = this.nativeCancellationVersion ?? 0;
4311
- attachments = await this.resolveNativePromptAttachments(request);
4685
+ attachments = await this.prepareNativePromptAttachments(request);
4312
4686
  interrupted =
4313
4687
  this.builderConversation.isBusy &&
4314
4688
  !request.responseMetadata &&
@@ -5260,6 +5634,11 @@ export class AiService extends TracedEventEmitter {
5260
5634
  this.authenticatedPeerId = undefined;
5261
5635
  this.authenticatedPeerUserId = undefined;
5262
5636
  }
5637
+ // Task snapshots are shared by native and Clark sessions. Defer the
5638
+ // resync until RPC middleware proves the reconnecting peer's identity.
5639
+ if (this.taskStore) {
5640
+ this.pendingTaskResyncPeerIds.add(peerId);
5641
+ }
5263
5642
  if (this.builderConversation) {
5264
5643
  void this.builderConversation.replay();
5265
5644
  return;
@@ -5301,18 +5680,7 @@ export class AiService extends TracedEventEmitter {
5301
5680
  this.getLogger().warn(`[ai-service] Failed to clear stale tool permission on reconnect`, error);
5302
5681
  });
5303
5682
  }
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
5683
+ // 3. Close out tool calls the transcript still reports as running but
5316
5684
  // that no process is executing (ENG-6785). Does not gate the connect
5317
5685
  // handshake: the peer is already bound, and the reconcile is several
5318
5686
  // RPCs long. Reconnect `getMessages({ force })` joins this promise so
@@ -5430,6 +5798,18 @@ export class AiService extends TracedEventEmitter {
5430
5798
  * as auth is proven, but never before.
5431
5799
  */
5432
5800
  pendingTaskResyncPeerIds = new Set();
5801
+ authenticatedTaskUsers = new WeakMap();
5802
+ /** Called only after socket authorization succeeds for this physical client. */
5803
+ notifyAuthenticatedTaskRpc(peer, userId) {
5804
+ if (userId)
5805
+ this.authenticatedTaskUsers.set(peer, userId);
5806
+ else
5807
+ this.authenticatedTaskUsers.delete(peer);
5808
+ }
5809
+ getAuthenticatedTaskUserId() {
5810
+ const peer = this.stablePeer.activeRoutePeer;
5811
+ return peer ? this.authenticatedTaskUsers.get(peer) : undefined;
5812
+ }
5433
5813
  /**
5434
5814
  * The authenticated peer's identity, but only while that same peer is
5435
5815
  * still the bound `stablePeer`. `handleUserConnected` can swap in a
@@ -6114,31 +6494,64 @@ export class AiService extends TracedEventEmitter {
6114
6494
  * Starts a new chat and returns its id, which the editor sends with later prompts. A `builderSelection` moves the app
6115
6495
  * to that harness: it reopens the app's most recent chat on it (`resumed`), which keeps that chat's own model, or
6116
6496
  * starts a new chat bound to it when there is none. A model-only change goes through `handleSetBuilderModel`.
6497
+ * `stopTurn` is the user's confirmation that a switch may stop the running turn.
6117
6498
  */
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;
6499
+ async handleNewChat(builderSelection, { stopTurn, onTurnStopped, } = {}) {
6500
+ if (!builderSelection)
6501
+ return this.switchOrStartNewChat(undefined);
6502
+ // Ahead of the turn-in-progress refusal: offering to stop a turn whose changes still block the switch would loop.
6503
+ try {
6504
+ await this.refuseSwitchOverRunningTurnsChanges();
6505
+ }
6506
+ catch (error) {
6507
+ recordBuilderSwitchClaim("harness", "refused_draft");
6508
+ throw error;
6126
6509
  }
6510
+ const { mustStopTurn } = this.claimBuilderSwitch("harness", stopTurn);
6511
+ // Recorded once, when the switch settles.
6512
+ let outcome = "failed";
6127
6513
  try {
6128
- if (builderSelection)
6129
- await this.assertEditorFinishedRestarting();
6130
- return await this.switchOrStartNewChat(builderSelection);
6514
+ await this.assertEditorFinishedRestarting();
6515
+ this.assertCanRunSelection(builderSelection);
6516
+ let stopped = false;
6517
+ if (mustStopTurn) {
6518
+ // Again right before the stop: the turn may have written files while the checks above awaited.
6519
+ outcome = "refused_draft";
6520
+ await this.refuseSwitchOverRunningTurnsChanges();
6521
+ outcome = "stop_failed";
6522
+ stopped = await this.stopTurnForBuilderSwitch("harness", onTurnStopped);
6523
+ outcome = "failed";
6524
+ }
6525
+ const result = await this.switchOrStartNewChat(builderSelection);
6526
+ outcome = stopped ? "switched_after_stop" : "switched";
6527
+ return result;
6131
6528
  }
6132
6529
  finally {
6133
- if (builderSelection)
6134
- this.builderSwitchInProgress = false;
6530
+ recordBuilderSwitchClaim("harness", outcome);
6531
+ this.builderSwitchInProgress = false;
6135
6532
  }
6136
6533
  }
6534
+ /** A harness switch cannot carry a running turn's changes to another chat, so stopping that turn would be for nothing. */
6535
+ async refuseSwitchOverRunningTurnsChanges() {
6536
+ if (!this.isTurnRunningForBuilderSwitch() ||
6537
+ !(await this.config.draftInterface?.hasLocalDraftChanges()))
6538
+ return;
6539
+ throw new SocketErrorException(409, SWITCH_NEEDS_DRAFT_SETTLED_MESSAGE);
6540
+ }
6541
+ /**
6542
+ * A new chat discards uncommitted AI changes; a switch must not. The draft's Accept and Reject controls are shown
6543
+ * again first: a turn the switch just stopped published CANCELLED, which hides them.
6544
+ */
6545
+ async assertNoPendingDraftForSwitch() {
6546
+ if (!(await this.config.draftInterface?.hasLocalDraftChanges()))
6547
+ return;
6548
+ catchBackgroundPeerDisconnect(this.stablePeer.call.aiSetDraftState({ hasDraft: true }), "draft state push");
6549
+ throw new Error("Accept or reject the pending changes before switching the harness or model");
6550
+ }
6137
6551
  async switchOrStartNewChat(builderSelection) {
6138
6552
  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");
6553
+ // Again after any stop: the stopped turn may have left changes.
6554
+ await this.assertNoPendingDraftForSwitch();
6142
6555
  // Refuse here, before the server archives the chat, a switch this editor could not run.
6143
6556
  this.assertCanRunSelection(builderSelection);
6144
6557
  }
@@ -6171,29 +6584,41 @@ export class AiService extends TracedEventEmitter {
6171
6584
  * Changes the model of the active native chat in place. The chat, its transcript, and its native Claude or Codex
6172
6585
  * session stay; the next turn resumes that session on the new model. Placement does not change, so no restart.
6173
6586
  */
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;
6587
+ async handleSetBuilderModel(model, { effort, stopTurn, onTurnStopped, } = {}) {
6588
+ const { mustStopTurn } = this.claimBuilderSwitch("model", stopTurn);
6589
+ // Recorded once, when the switch settles.
6590
+ let outcome = "failed";
6181
6591
  try {
6182
6592
  await this.assertEditorFinishedRestarting();
6183
6593
  // 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)
6594
+ // Following it needs an idle chat, so a stale pod stops the confirmed turn before the remaining checks.
6595
+ let turnStopped = false;
6596
+ let stopped = false;
6597
+ if (this.builderBindingStale) {
6598
+ if (mustStopTurn) {
6599
+ outcome = "stop_failed";
6600
+ stopped = await this.stopTurnForBuilderSwitch("model", onTurnStopped);
6601
+ outcome = "failed";
6602
+ turnStopped = true;
6603
+ }
6185
6604
  await this.recoverStaleBindingForModelChange();
6605
+ }
6186
6606
  const chatSessionId = this.builderBinding?.chatSessionId;
6187
6607
  const harness = this.builderBinding?.harness;
6188
6608
  if (!chatSessionId || !harness || harness === "clark")
6189
6609
  throw new Error("This chat does not run on a native harness");
6190
6610
  // Throws for a model the harness does not offer, before the server changes anything.
6191
6611
  this.assertCanRunSelection({ harness, model });
6612
+ if (mustStopTurn && !turnStopped) {
6613
+ outcome = "stop_failed";
6614
+ stopped = await this.stopTurnForBuilderSwitch("model", onTurnStopped);
6615
+ outcome = "failed";
6616
+ }
6192
6617
  const branch = this.builderBranch ??
6193
6618
  (await this._syncContextProvider?.getBranchName()) ??
6194
6619
  "main";
6195
6620
  try {
6196
- await this.chatSessionStore.setBuilderModel(branch, model, chatSessionId);
6621
+ await this.chatSessionStore.setBuilderModel(branch, model, chatSessionId, ...(effort === undefined ? [] : [effort]));
6197
6622
  }
6198
6623
  catch (error) {
6199
6624
  if (!isChatChangedElsewhereError(error))
@@ -6214,9 +6639,11 @@ export class AiService extends TracedEventEmitter {
6214
6639
  const builderSelection = this.getBuilderSelection();
6215
6640
  if (!builderSelection)
6216
6641
  throw new Error("Changed the model, but this editor lost the chat.");
6642
+ outcome = stopped ? "switched_after_stop" : "switched";
6217
6643
  return { builderSelection };
6218
6644
  }
6219
6645
  finally {
6646
+ recordBuilderSwitchClaim("model", outcome);
6220
6647
  this.builderSwitchInProgress = false;
6221
6648
  }
6222
6649
  }
@@ -6266,6 +6693,7 @@ export class AiService extends TracedEventEmitter {
6266
6693
  return {
6267
6694
  harness: binding.harness,
6268
6695
  model: binding.model ?? this.builderRuntime?.model,
6696
+ ...(binding.effort ? { effort: binding.effort } : {}),
6269
6697
  };
6270
6698
  }
6271
6699
  /** `resumed` when the server reopened the app's last chat on the picked harness instead of a new one. */
@@ -6626,6 +7054,9 @@ export class AiService extends TracedEventEmitter {
6626
7054
  }
6627
7055
  async handleRestoreToCommit(sinceTimestamp, commitId, applicationId, branchName) {
6628
7056
  if (this.builderConversation) {
7057
+ // The restore moved the server tree: the next ensureWorkspace mirrors
7058
+ // the hash the VM reports rather than this cached one.
7059
+ this.workspaceHash = undefined;
6629
7060
  await this.handleNewChat();
6630
7061
  return;
6631
7062
  }
@@ -7076,9 +7507,7 @@ export class AiService extends TracedEventEmitter {
7076
7507
  // A reloaded editor retries an open the watcher stopped retrying.
7077
7508
  editorGeneration: () => this.stablePeer.connectionGeneration,
7078
7509
  onReopened: async (result, reopenedKey) => {
7079
- if (!this.adoptWorkspaceOpen(reopenedKey, result))
7080
- return;
7081
- await this.mirrorWorkspaceHash(result.dbfsHash);
7510
+ await this.mirrorWorkspaceOpen(reopenedKey, this.builderBranch ?? "main", result);
7082
7511
  },
7083
7512
  });
7084
7513
  let result;
@@ -7098,8 +7527,14 @@ export class AiService extends TracedEventEmitter {
7098
7527
  this.workspaceInternalToken = undefined;
7099
7528
  throw error;
7100
7529
  }
7101
- if (!this.adoptWorkspaceOpen(sessionKey, result))
7530
+ if (!(await this.mirrorWorkspaceOpen(sessionKey, branchName, result)))
7102
7531
  throw new Error("The chat moved to another workspace while it opened");
7532
+ return result;
7533
+ }
7534
+ /** Initializes the read-only tree for both caller opens and watcher recovery. */
7535
+ async mirrorWorkspaceOpen(sessionKey, branchName, result) {
7536
+ if (!this.adoptWorkspaceOpen(sessionKey, result))
7537
+ return false;
7103
7538
  if (this.workspaceMirror?.sessionKey !== sessionKey)
7104
7539
  this.workspaceMirror = {
7105
7540
  sessionKey,
@@ -7110,7 +7545,7 @@ export class AiService extends TracedEventEmitter {
7110
7545
  }),
7111
7546
  };
7112
7547
  await this.refreshWorkspaceMirror(this.workspaceHash ?? result.dbfsHash);
7113
- return result;
7548
+ return true;
7114
7549
  }
7115
7550
  /**
7116
7551
  * Takes a successful open's token and hash, once per open, and only while
@@ -7133,14 +7568,20 @@ export class AiService extends TracedEventEmitter {
7133
7568
  * reloads the file model: the VM's watcher cannot reach this process. The
7134
7569
  * hash is remembered first, so the next turn retries a failed refresh.
7135
7570
  */
7136
- async refreshWorkspaceMirror(hash) {
7571
+ refreshWorkspaceMirror(hash) {
7137
7572
  this.workspaceHash = hash;
7138
7573
  const mirror = this.workspaceMirror?.mirror;
7139
7574
  if (!mirror)
7140
- return;
7141
- const { changed } = await mirror.refresh(hash);
7142
- if (changed && this.fileSystemManager)
7575
+ return Promise.resolve();
7576
+ return this.workspaceRefreshQueue.enqueue(async () => {
7577
+ const { changed } = await mirror.refresh(hash);
7578
+ if (changed)
7579
+ this.workspaceFileModelStale = true;
7580
+ if (!this.workspaceFileModelStale || !this.fileSystemManager)
7581
+ return;
7143
7582
  await this.refreshFileModel();
7583
+ this.workspaceFileModelStale = false;
7584
+ });
7144
7585
  }
7145
7586
  /** Mirrors a hash the VM reported, logging rather than failing a turn. */
7146
7587
  mirrorWorkspaceHash(hash) {