@superblocksteam/vite-plugin-file-sync 2.0.180-next.4 → 2.0.183-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 (295) hide show
  1. package/dist/agent-tool-executor/claude-file-tools.d.ts +72 -10
  2. package/dist/agent-tool-executor/claude-file-tools.d.ts.map +1 -1
  3. package/dist/agent-tool-executor/claude-sandbox.d.ts +15 -1
  4. package/dist/agent-tool-executor/claude-sandbox.d.ts.map +1 -1
  5. package/dist/agent-tool-executor/claude-shell.d.ts +36 -4
  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 +4 -6
  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 +2 -5
  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 +0 -2
  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 +2 -9
  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 +44 -13
  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 +0 -1
  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 +0 -3
  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 +0 -2
  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 +0 -7
  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 +1 -5
  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 +0 -1
  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 +0 -3
  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 +0 -1
  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 +0 -3
  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 +185 -39
  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 +13 -35
  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 +342 -47
  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/report-security-findings.d.ts +112 -25
  67. package/dist/ai-service/agent/tools/report-security-findings.d.ts.map +1 -1
  68. package/dist/ai-service/agent/tools.d.ts.map +1 -1
  69. package/dist/ai-service/agent/tools.js +0 -1
  70. package/dist/ai-service/agent/tools.js.map +1 -1
  71. package/dist/ai-service/agent/tools2/tools/bash.d.ts +2 -2
  72. package/dist/ai-service/agent/tools2/tools/list-tasks.d.ts +1 -1
  73. package/dist/ai-service/agent/tools2/types.d.ts +1 -1
  74. package/dist/ai-service/agent/tools2/types.d.ts.map +1 -1
  75. package/dist/ai-service/agent/tools2/types.js.map +1 -1
  76. package/dist/ai-service/app-interface/npm-registry.d.ts +10 -20
  77. package/dist/ai-service/app-interface/npm-registry.d.ts.map +1 -1
  78. package/dist/ai-service/app-interface/npm-registry.js +73 -109
  79. package/dist/ai-service/app-interface/npm-registry.js.map +1 -1
  80. package/dist/ai-service/app-interface/shell.d.ts +4 -14
  81. package/dist/ai-service/app-interface/shell.d.ts.map +1 -1
  82. package/dist/ai-service/app-interface/shell.js +30 -45
  83. package/dist/ai-service/app-interface/shell.js.map +1 -1
  84. package/dist/ai-service/builder-conversation.d.ts +3 -44
  85. package/dist/ai-service/builder-conversation.d.ts.map +1 -1
  86. package/dist/ai-service/builder-conversation.js +47 -353
  87. package/dist/ai-service/builder-conversation.js.map +1 -1
  88. package/dist/ai-service/builder-core-prompt.d.ts +1 -1
  89. package/dist/ai-service/builder-core-prompt.d.ts.map +1 -1
  90. package/dist/ai-service/builder-core-prompt.js +12 -7
  91. package/dist/ai-service/builder-core-prompt.js.map +1 -1
  92. package/dist/ai-service/builder-runtime-auth.d.ts.map +1 -1
  93. package/dist/ai-service/builder-runtime-auth.js +2 -6
  94. package/dist/ai-service/builder-runtime-auth.js.map +1 -1
  95. package/dist/ai-service/builder-runtime.d.ts +237 -103
  96. package/dist/ai-service/builder-runtime.d.ts.map +1 -1
  97. package/dist/ai-service/builder-runtime.js +62 -370
  98. package/dist/ai-service/builder-runtime.js.map +1 -1
  99. package/dist/ai-service/builder-session-store.d.ts +7 -1
  100. package/dist/ai-service/builder-session-store.d.ts.map +1 -1
  101. package/dist/ai-service/builder-session-store.js +1 -1
  102. package/dist/ai-service/builder-session-store.js.map +1 -1
  103. package/dist/ai-service/builder-tool-callbacks.d.ts +0 -5
  104. package/dist/ai-service/builder-tool-callbacks.d.ts.map +1 -1
  105. package/dist/ai-service/builder-tool-callbacks.js +2 -5
  106. package/dist/ai-service/builder-tool-callbacks.js.map +1 -1
  107. package/dist/ai-service/builder-tools.d.ts +4 -26
  108. package/dist/ai-service/builder-tools.d.ts.map +1 -1
  109. package/dist/ai-service/builder-tools.js +29 -156
  110. package/dist/ai-service/builder-tools.js.map +1 -1
  111. package/dist/ai-service/builder-workspace.d.ts +0 -1
  112. package/dist/ai-service/builder-workspace.d.ts.map +1 -1
  113. package/dist/ai-service/builder-workspace.js +6 -15
  114. package/dist/ai-service/builder-workspace.js.map +1 -1
  115. package/dist/ai-service/chat/chat-session-store.d.ts +2 -2
  116. package/dist/ai-service/chat/chat-session-store.d.ts.map +1 -1
  117. package/dist/ai-service/chat/chat-session-store.js +8 -25
  118. package/dist/ai-service/chat/chat-session-store.js.map +1 -1
  119. package/dist/ai-service/demo-agents/load-agents.d.ts +2 -5
  120. package/dist/ai-service/demo-agents/load-agents.d.ts.map +1 -1
  121. package/dist/ai-service/demo-agents/load-agents.js +49 -43
  122. package/dist/ai-service/demo-agents/load-agents.js.map +1 -1
  123. package/dist/ai-service/demo-agents/run-agent.js +2 -2
  124. package/dist/ai-service/demo-agents/run-agent.js.map +1 -1
  125. package/dist/ai-service/demo-agents/system-prompt.d.ts +5 -6
  126. package/dist/ai-service/demo-agents/system-prompt.d.ts.map +1 -1
  127. package/dist/ai-service/demo-agents/system-prompt.js +26 -18
  128. package/dist/ai-service/demo-agents/system-prompt.js.map +1 -1
  129. package/dist/ai-service/demo-agents/types.d.ts +56 -1
  130. package/dist/ai-service/demo-agents/types.d.ts.map +1 -1
  131. package/dist/ai-service/demo-agents/types.js +7 -0
  132. package/dist/ai-service/demo-agents/types.js.map +1 -1
  133. package/dist/ai-service/dev-database-file-sync.d.ts +1 -2
  134. package/dist/ai-service/dev-database-file-sync.d.ts.map +1 -1
  135. package/dist/ai-service/dev-database-file-sync.js.map +1 -1
  136. package/dist/ai-service/features.d.ts +8 -20
  137. package/dist/ai-service/features.d.ts.map +1 -1
  138. package/dist/ai-service/index.d.ts +7 -100
  139. package/dist/ai-service/index.d.ts.map +1 -1
  140. package/dist/ai-service/index.js +108 -549
  141. package/dist/ai-service/index.js.map +1 -1
  142. package/dist/ai-service/judge/tools/playwright-action.d.ts +5 -5
  143. package/dist/ai-service/judge/tools/playwright-action.d.ts.map +1 -1
  144. package/dist/ai-service/judge/tools/playwright-action.js +1 -4
  145. package/dist/ai-service/judge/tools/playwright-action.js.map +1 -1
  146. package/dist/ai-service/llm/context-v2/storage/event-types.d.ts +110 -45
  147. package/dist/ai-service/llm/context-v2/storage/event-types.d.ts.map +1 -1
  148. package/dist/ai-service/llm/context-v2/storage/event-types.js +3 -3
  149. package/dist/ai-service/llm/context-v2/storage/event-types.js.map +1 -1
  150. package/dist/ai-service/llm/interaction/adapters/vercel.d.ts.map +1 -1
  151. package/dist/ai-service/llm/interaction/adapters/vercel.js +1 -6
  152. package/dist/ai-service/llm/interaction/adapters/vercel.js.map +1 -1
  153. package/dist/ai-service/mcp/adapter/json-schema-to-zod.d.ts.map +1 -1
  154. package/dist/ai-service/mcp/adapter/json-schema-to-zod.js.map +1 -1
  155. package/dist/ai-service/mcp/embedded-playwright-mcp-server.d.ts +0 -2
  156. package/dist/ai-service/mcp/embedded-playwright-mcp-server.d.ts.map +1 -1
  157. package/dist/ai-service/mcp/embedded-playwright-mcp-server.js +0 -28
  158. package/dist/ai-service/mcp/embedded-playwright-mcp-server.js.map +1 -1
  159. package/dist/ai-service/mcp/playwright-server.d.ts +0 -2
  160. package/dist/ai-service/mcp/playwright-server.d.ts.map +1 -1
  161. package/dist/ai-service/mcp/playwright-server.js +0 -1
  162. package/dist/ai-service/mcp/playwright-server.js.map +1 -1
  163. package/dist/ai-service/migration-prompt-gating.d.ts +0 -2
  164. package/dist/ai-service/migration-prompt-gating.d.ts.map +1 -1
  165. package/dist/ai-service/migration-prompt-gating.js +0 -3
  166. package/dist/ai-service/migration-prompt-gating.js.map +1 -1
  167. package/dist/ai-service/prompt-builder-service/types.d.ts +1 -3
  168. package/dist/ai-service/prompt-builder-service/types.d.ts.map +1 -1
  169. package/dist/ai-service/security/vulnerability-triage.d.ts +30 -12
  170. package/dist/ai-service/security/vulnerability-triage.d.ts.map +1 -1
  171. package/dist/ai-service/skills/system/_registry.generated.d.ts.map +1 -1
  172. package/dist/ai-service/skills/system/_registry.generated.js +0 -6
  173. package/dist/ai-service/skills/system/_registry.generated.js.map +1 -1
  174. package/dist/ai-service/state-machine/handlers/llm-generating.d.ts.map +1 -1
  175. package/dist/ai-service/state-machine/handlers/llm-generating.js +7 -10
  176. package/dist/ai-service/state-machine/handlers/llm-generating.js.map +1 -1
  177. package/dist/ai-service/state-machine/helpers/stable-peer.d.ts +0 -2
  178. package/dist/ai-service/state-machine/helpers/stable-peer.d.ts.map +1 -1
  179. package/dist/ai-service/state-machine/helpers/stable-peer.js +2 -9
  180. package/dist/ai-service/state-machine/helpers/stable-peer.js.map +1 -1
  181. package/dist/ai-service/tasks/task-store.d.ts.map +1 -1
  182. package/dist/ai-service/tasks/task-store.js +1 -1
  183. package/dist/ai-service/tasks/task-store.js.map +1 -1
  184. package/dist/ai-service/tasks/types.d.ts +1 -5
  185. package/dist/ai-service/tasks/types.d.ts.map +1 -1
  186. package/dist/ai-service/util/inference-jwt.d.ts +0 -5
  187. package/dist/ai-service/util/inference-jwt.d.ts.map +1 -1
  188. package/dist/ai-service/util/inference-jwt.js +0 -17
  189. package/dist/ai-service/util/inference-jwt.js.map +1 -1
  190. package/dist/ai-service/workspace-mirror.d.ts +0 -2
  191. package/dist/ai-service/workspace-mirror.d.ts.map +1 -1
  192. package/dist/ai-service/workspace-mirror.js +0 -21
  193. package/dist/ai-service/workspace-mirror.js.map +1 -1
  194. package/dist/dev-server-ws-smoke-client.d.ts.map +1 -1
  195. package/dist/dev-server-ws-smoke-client.js +0 -1
  196. package/dist/dev-server-ws-smoke-client.js.map +1 -1
  197. package/dist/file-sync-vite-plugin.d.ts +1 -3
  198. package/dist/file-sync-vite-plugin.d.ts.map +1 -1
  199. package/dist/file-sync-vite-plugin.js +11 -19
  200. package/dist/file-sync-vite-plugin.js.map +1 -1
  201. package/dist/file-system-manager.d.ts.map +1 -1
  202. package/dist/file-system-manager.js +13 -11
  203. package/dist/file-system-manager.js.map +1 -1
  204. package/dist/index.d.ts +3 -5
  205. package/dist/index.d.ts.map +1 -1
  206. package/dist/index.js +1 -2
  207. package/dist/index.js.map +1 -1
  208. package/dist/lock-service/index.d.ts +0 -36
  209. package/dist/lock-service/index.d.ts.map +1 -1
  210. package/dist/lock-service/index.js +0 -59
  211. package/dist/lock-service/index.js.map +1 -1
  212. package/dist/plugin-options.d.ts +1 -9
  213. package/dist/plugin-options.d.ts.map +1 -1
  214. package/dist/plugin-options.js.map +1 -1
  215. package/dist/policy-gate-runner.d.ts +9 -1
  216. package/dist/policy-gate-runner.d.ts.map +1 -1
  217. package/dist/project-manifest.d.ts +108 -8
  218. package/dist/project-manifest.d.ts.map +1 -1
  219. package/dist/project-manifest.js +115 -28
  220. package/dist/project-manifest.js.map +1 -1
  221. package/dist/server-rpc/index.d.ts +0 -6
  222. package/dist/server-rpc/index.d.ts.map +1 -1
  223. package/dist/server-rpc/index.js +1 -13
  224. package/dist/server-rpc/index.js.map +1 -1
  225. package/dist/socket-manager.d.ts +1 -3
  226. package/dist/socket-manager.d.ts.map +1 -1
  227. package/dist/socket-manager.js +65 -115
  228. package/dist/socket-manager.js.map +1 -1
  229. package/dist/sync-service/draft-mutation.d.ts +2 -6
  230. package/dist/sync-service/draft-mutation.d.ts.map +1 -1
  231. package/dist/sync-service/draft-mutation.js +33 -20
  232. package/dist/sync-service/draft-mutation.js.map +1 -1
  233. package/dist/sync-service/index.d.ts +6 -6
  234. package/dist/sync-service/index.d.ts.map +1 -1
  235. package/dist/sync-service/index.js +61 -29
  236. package/dist/sync-service/index.js.map +1 -1
  237. package/dist/sync-service/native-draft-session.d.ts +3 -0
  238. package/dist/sync-service/native-draft-session.d.ts.map +1 -0
  239. package/dist/sync-service/native-draft-session.js +4 -0
  240. package/dist/sync-service/native-draft-session.js.map +1 -0
  241. package/dist/workspace-sync-methods.d.ts +20 -5
  242. package/dist/workspace-sync-methods.d.ts.map +1 -1
  243. package/package.json +13 -17
  244. package/dist/ai-service/agent/tools/project-agent-feedback.d.ts +0 -17
  245. package/dist/ai-service/agent/tools/project-agent-feedback.d.ts.map +0 -1
  246. package/dist/ai-service/agent/tools/project-agent-feedback.js +0 -87
  247. package/dist/ai-service/agent/tools/project-agent-feedback.js.map +0 -1
  248. package/dist/ai-service/app-interface/invalid-lockfile-error.d.ts +0 -11
  249. package/dist/ai-service/app-interface/invalid-lockfile-error.d.ts.map +0 -1
  250. package/dist/ai-service/app-interface/invalid-lockfile-error.js +0 -27
  251. package/dist/ai-service/app-interface/invalid-lockfile-error.js.map +0 -1
  252. package/dist/ai-service/app-interface/npm-lockfile-sources.d.ts +0 -13
  253. package/dist/ai-service/app-interface/npm-lockfile-sources.d.ts.map +0 -1
  254. package/dist/ai-service/app-interface/npm-lockfile-sources.js +0 -129
  255. package/dist/ai-service/app-interface/npm-lockfile-sources.js.map +0 -1
  256. package/dist/ai-service/app-interface/registry-lockfile-preparer.d.ts +0 -46
  257. package/dist/ai-service/app-interface/registry-lockfile-preparer.d.ts.map +0 -1
  258. package/dist/ai-service/app-interface/registry-lockfile-preparer.js +0 -88
  259. package/dist/ai-service/app-interface/registry-lockfile-preparer.js.map +0 -1
  260. package/dist/ai-service/builder-binding-error.d.ts +0 -5
  261. package/dist/ai-service/builder-binding-error.d.ts.map +0 -1
  262. package/dist/ai-service/builder-binding-error.js +0 -8
  263. package/dist/ai-service/builder-binding-error.js.map +0 -1
  264. package/dist/ai-service/skills/system/project-agents/references/errors.generated.d.ts +0 -2
  265. package/dist/ai-service/skills/system/project-agents/references/errors.generated.d.ts.map +0 -1
  266. package/dist/ai-service/skills/system/project-agents/references/errors.generated.js +0 -25
  267. package/dist/ai-service/skills/system/project-agents/references/errors.generated.js.map +0 -1
  268. package/dist/ai-service/skills/system/project-agents/references/fields.generated.d.ts +0 -2
  269. package/dist/ai-service/skills/system/project-agents/references/fields.generated.d.ts.map +0 -1
  270. package/dist/ai-service/skills/system/project-agents/references/fields.generated.js +0 -55
  271. package/dist/ai-service/skills/system/project-agents/references/fields.generated.js.map +0 -1
  272. package/dist/ai-service/skills/system/project-agents/skill.generated.d.ts +0 -2
  273. package/dist/ai-service/skills/system/project-agents/skill.generated.d.ts.map +0 -1
  274. package/dist/ai-service/skills/system/project-agents/skill.generated.js +0 -73
  275. package/dist/ai-service/skills/system/project-agents/skill.generated.js.map +0 -1
  276. package/dist/ai-service/tool-input-schema.d.ts +0 -14
  277. package/dist/ai-service/tool-input-schema.d.ts.map +0 -1
  278. package/dist/ai-service/tool-input-schema.js +0 -23
  279. package/dist/ai-service/tool-input-schema.js.map +0 -1
  280. package/dist/ai-service/workspace-package-registry.d.ts +0 -3
  281. package/dist/ai-service/workspace-package-registry.d.ts.map +0 -1
  282. package/dist/ai-service/workspace-package-registry.js +0 -87
  283. package/dist/ai-service/workspace-package-registry.js.map +0 -1
  284. package/dist/ai-service/workspace-package-state.d.ts +0 -12
  285. package/dist/ai-service/workspace-package-state.d.ts.map +0 -1
  286. package/dist/ai-service/workspace-package-state.js +0 -47
  287. package/dist/ai-service/workspace-package-state.js.map +0 -1
  288. package/dist/ai-service/workspace-packages.d.ts +0 -234
  289. package/dist/ai-service/workspace-packages.d.ts.map +0 -1
  290. package/dist/ai-service/workspace-packages.js +0 -466
  291. package/dist/ai-service/workspace-packages.js.map +0 -1
  292. package/dist/project-agents.d.ts +0 -31
  293. package/dist/project-agents.d.ts.map +0 -1
  294. package/dist/project-agents.js +0 -50
  295. package/dist/project-agents.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, SWITCH_ENDS_WAITING_TURN_MESSAGE, SWITCH_NEEDS_DRAFT_SETTLED_MESSAGE, SWITCH_STOPS_WORKING_TURN_MESSAGE, SocketErrorException, } 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, } 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, DevDatabaseTaskOwnerUnavailableError, wireDevDatabaseIntegrationPriming, } from "./agent/tools/databases/dev-database-tasks.js";
28
+ import { applyDevDatabaseMigrationsTaskMetadata, createDevDatabaseTaskTypes, 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,7 +40,6 @@ 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";
44
43
  import { BuilderConversation } from "./builder-conversation.js";
45
44
  import { BuilderInferenceAuth } from "./builder-inference-auth.js";
46
45
  import { BuilderRuntimeAuth } from "./builder-runtime-auth.js";
@@ -137,7 +136,6 @@ import { PERMISSION_PROMPT_DELIVERY_TIMEOUT_MS, PERMISSION_PROMPT_RESPONSE_TIMEO
137
136
  import { getToolCallSignature } from "./util/tool-signature.js";
138
137
  import { readWorkspaceIngress } from "./workspace-edge-health.js";
139
138
  import { rpcWorkspaceMirrorSource, WorkspaceMirror, } from "./workspace-mirror.js";
140
- import { workspacePackageShell, parseWorkspacePackagePolicyRequest, } from "./workspace-packages.js";
141
139
  export { AiServiceFeatureFlags } from "./features.js";
142
140
  export { WorkspaceDowngradedError } from "./builder-workspace.js";
143
141
  export { BuilderRuntime } from "./builder-runtime.js";
@@ -362,28 +360,17 @@ function builderBindingMismatchCounter() {
362
360
  });
363
361
  return bindingMismatchCounter;
364
362
  }
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
- }
381
363
  function bindingMatchesRuntime(binding, runtime) {
382
364
  return (binding.harness === runtime.harness &&
383
365
  (binding.model === undefined || binding.model === runtime.model));
384
366
  }
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;
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
+ }
387
374
  export class AiService extends TracedEventEmitter {
388
375
  config;
389
376
  templateRenderer;
@@ -409,19 +396,7 @@ export class AiService extends TracedEventEmitter {
409
396
  */
410
397
  builderBindingStale = false;
411
398
  /** Set while a harness switch moves the server and this pod to a new chat; prompts wait for it to finish. */
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;
399
+ builderSwitchInProgress = false;
425
400
  /**
426
401
  * Prompts past the switch check but whose turn has not started yet. They await a server round trip before the
427
402
  * conversation reports busy, so a switch counts them as a running turn.
@@ -432,106 +407,9 @@ export class AiService extends TracedEventEmitter {
432
407
  /** The binding the pre-turn check resolved, which that request's turn uses instead of resolving again. */
433
408
  checkedBinding;
434
409
  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
- }
529
410
  workspaceMirror;
530
411
  /** The newest DBFS hash the VM reported for the current workspace. */
531
412
  workspaceHash;
532
- /** The mirror changed on disk but reloading the file model has not succeeded. */
533
- workspaceFileModelStale = false;
534
- workspaceRefreshQueue = new OperationQueue();
535
413
  adoptedWorkspaceOpens = new WeakSet();
536
414
  /** The current VM boot's ai-service credential, from `workspace.open`. */
537
415
  workspaceInternalToken;
@@ -540,12 +418,6 @@ export class AiService extends TracedEventEmitter {
540
418
  * the VM's turn-end commit reported. Undefined for a live-edit turn.
541
419
  */
542
420
  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;
549
421
  nativeBuilderJwt;
550
422
  nativeInferenceTurn;
551
423
  nativePromptAttempt;
@@ -1137,7 +1009,7 @@ export class AiService extends TracedEventEmitter {
1137
1009
  // (LD flag + ONPREMISE + OPA edit lifecycle registration). When the
1138
1010
  // gate is off, `taskStore` stays undefined and `agent/tools.ts`
1139
1011
  // skips registering the start*/check*/wait*/cancel*/list* tools.
1140
- if (isBackgroundTaskFrameworkEnabled(config)) {
1012
+ if (!config.builderRuntime && isBackgroundTaskFrameworkEnabled(config)) {
1141
1013
  this.taskStore = new TaskStore();
1142
1014
  // Heterogeneous list of task types funneled into
1143
1015
  // `registerBackgroundTaskTypes` (which itself takes ReadonlyArray<TaskType<any, any, any>>),
@@ -1163,19 +1035,10 @@ export class AiService extends TracedEventEmitter {
1163
1035
  // AFTER this constructor runs, so the helper resolves it
1164
1036
  // lazily at task-start time.
1165
1037
  ensureFilesSynced: buildEnsureDevDatabaseFilesSynced(() => this._runtimeSyncService),
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();
1038
+ getClient: () => {
1039
+ const jwt = this.clark?.context?.jwt;
1174
1040
  if (!jwt) {
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");
1041
+ throw new Error("[devDatabase] cannot start background task: no JWT available on Clark context");
1179
1042
  }
1180
1043
  return new DevDatabaseClient({
1181
1044
  transport: createDevDatabaseHttpTransport({
@@ -1186,7 +1049,12 @@ export class AiService extends TracedEventEmitter {
1186
1049
  },
1187
1050
  // Same owner stamping as defineBackgroundTaskFactory so sibling
1188
1051
  // watch tasks are not world-readable inside the AiService session.
1189
- getCurrentOwnerId: () => this.getAuthenticatedTaskUserId(),
1052
+ getCurrentOwnerId: () => {
1053
+ const jwt = this.clark?.context?.jwt;
1054
+ if (!jwt)
1055
+ return undefined;
1056
+ return parseJwt(jwt)?.userId;
1057
+ },
1190
1058
  // Lazy: TaskStore exists on `this` but watch siblings only start
1191
1059
  // after types are registered below.
1192
1060
  getTaskStore: () => this.taskStore,
@@ -1342,143 +1210,6 @@ export class AiService extends TracedEventEmitter {
1342
1210
  isBusyForBuilderSwitch() {
1343
1211
  return this.isBusy() || this.promptsBeingAdmitted > 0;
1344
1212
  }
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
- }
1482
1213
  /** A prompt sent while a harness switch is moving to a new chat would run on the old harness in the new chat. */
1483
1214
  assertNoBuilderSwitchInProgress() {
1484
1215
  if (this.builderSwitchInProgress)
@@ -1499,36 +1230,13 @@ export class AiService extends TracedEventEmitter {
1499
1230
  * Opens the binding's AgentCore workspace without waiting for it. Opening
1500
1231
  * needs a JWT to mint the runtime token, so without one it waits for
1501
1232
  * `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`.
1508
1233
  */
1509
1234
  openWorkspaceInBackground(binding, branch) {
1510
1235
  if (binding.workspace?.placement !== "agentcore")
1511
1236
  return;
1512
1237
  if (!this.getInferenceJwt())
1513
1238
  return;
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
- }));
1239
+ this.ensureWorkspace(binding, branch).catch((error) => this.getLogger().warn("[workspace] Background workspace open failed; the next turn retries", getErrorMeta(error)));
1532
1240
  }
1533
1241
  initializeNativeBuilder() {
1534
1242
  const config = this.config;
@@ -1538,24 +1246,21 @@ export class AiService extends TracedEventEmitter {
1538
1246
  runtime,
1539
1247
  tools: new NativeBuilderToolHost({
1540
1248
  getJwt: () => this.getClarkJwt(),
1541
- taskStore: this.taskStore,
1542
- getCurrentOwnerId: () => this.getAuthenticatedTaskUserId(),
1543
- isWorkspacePlacement: () => this.isWorkspacePlacement,
1544
1249
  getPackageServices: (request) => ({
1545
1250
  appContextStore: this.appContext,
1546
- ...this.nativePackageServices(),
1251
+ appShell: this.appShell,
1252
+ draftInterface: config.draftInterface,
1547
1253
  chatSessionStore: this.chatSessionStore,
1548
1254
  llmClient: this.llmClient,
1549
1255
  llmProvider: createLLMProvider(this.getLLMProviderSettings(request?.llmConfig), () => this.requireProviderInferenceAuthToken(), request?.llmConfig),
1550
1256
  }),
1551
1257
  appShell: this.appShell,
1258
+ assertLocalAppTreeWritable: (action) => this.assertLocalAppTreeWritable(action),
1552
1259
  ensureFilesSynced: async () => {
1553
1260
  const sync = this._runtimeSyncService;
1554
1261
  if (!sync?.syncCurrentDirectoryWithDraftsNow)
1555
1262
  throw new Error("Native builder DEV sync service is unavailable");
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");
1263
+ const synced = await sync.syncCurrentDirectoryWithDraftsNow("requestedFilesSync");
1559
1264
  if (!synced?.directoryHash)
1560
1265
  throw new Error("Native builder file sync did not return a directory hash");
1561
1266
  // testApi reads the tree here: in agentcore placement, bring the
@@ -1580,40 +1285,29 @@ export class AiService extends TracedEventEmitter {
1580
1285
  chat: this.chatSessionStore,
1581
1286
  prepare: (request, signal, generationId) => this.prepareNativeBuilderRequest(request, signal, generationId),
1582
1287
  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.
1585
1288
  const workspaceFinish = this.workspaceTurnFinish;
1586
- let checkpointId;
1587
1289
  if (workspaceFinish) {
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.
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.
1592
1293
  await turn?.events();
1593
1294
  if (workspaceFinish.finished && !workspaceFinish.dbfsHash)
1594
1295
  throw new Error("The workspace did not report a committed hash for this turn; its changes may not be saved.");
1595
- checkpointId = workspaceFinish.commitId;
1596
1296
  }
1597
1297
  else {
1598
1298
  const sync = this._runtimeSyncService;
1599
1299
  if (!sync?.syncCurrentDirectoryWithDraftsNow)
1600
1300
  throw new Error("Native builder DEV sync service is unavailable");
1601
- const synced = await sync.syncCurrentDirectoryWithDraftsNow("ai:accept", { waitForNativeSession: true });
1301
+ const synced = await sync.syncCurrentDirectoryWithDraftsNow("ai:generate:post", { waitForNativeSession: true });
1602
1302
  // The binding moved to a workspace since the turn started.
1603
1303
  if (this.isWorkspacePlacement &&
1604
1304
  typeof synced?.directoryHash === "string")
1605
1305
  await this.mirrorWorkspaceHash(synced.directoryHash);
1606
- if (synced?.commitId && !synced.checkpointSkipped)
1607
- checkpointId = synced.commitId;
1608
1306
  }
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 };
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)));
1617
1311
  },
1618
1312
  onSettled: (generationId, error, cancelled) => {
1619
1313
  const attempt = this.nativePromptAttempt;
@@ -1636,7 +1330,7 @@ export class AiService extends TracedEventEmitter {
1636
1330
  this.activeGenerationTrace?.finish(cancelled ? "cancelled" : error ? "failed" : "completed", error);
1637
1331
  this.triggerGenerationComplete(generationId);
1638
1332
  },
1639
- onError: (error, attempt, context) => BuilderRuntimeError.log(error, this.getLogger(), attempt, context),
1333
+ onError: (error, attempt) => BuilderRuntimeError.log(error, this.getLogger(), attempt),
1640
1334
  checkPaywall: () => this.nativePaywallReason(),
1641
1335
  });
1642
1336
  }
@@ -1976,20 +1670,14 @@ export class AiService extends TracedEventEmitter {
1976
1670
  conversationId: this.builderBinding?.runtimeSessionId,
1977
1671
  }),
1978
1672
  }, 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;
1985
1673
  const span = this.config.tracer.startSpan("AiService.generation", {
1986
1674
  attributes: {
1987
1675
  ...TraceCorrelation.attributes(parentContext),
1988
1676
  "ai.mode": request.mode,
1989
- "ai.model": model,
1990
- "ai.provider": provider,
1991
- "gen_ai.provider.name": provider,
1992
- "gen_ai.request.model": model,
1677
+ "ai.model": request.llmConfig?.coreModel,
1678
+ "ai.provider": runtime
1679
+ ? runtime.providerFor(runtime.model)
1680
+ : request.llmConfig?.provider,
1993
1681
  "app.id": this.config.applicationId,
1994
1682
  "org.id": this.config.organizationId,
1995
1683
  },
@@ -2097,9 +1785,17 @@ export class AiService extends TracedEventEmitter {
2097
1785
  gitOperationLock: this._runtimeGitOperationLock,
2098
1786
  onGitOperationComplete: this._onGitOperationComplete,
2099
1787
  taskStore: this.taskStore,
2100
- // Task access follows the authenticated transport principal, not
2101
- // claims decoded from a separately supplied inference credential.
2102
- getCurrentOwnerId: () => this.getAuthenticatedTaskUserId(),
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
+ },
2103
1799
  };
2104
1800
  const clarkStateHandlers = Object.fromEntries(Object.entries(clarkStateHandlerFactories).map(([state, handlerFactory]) => [state, handlerFactory(clark, params)]));
2105
1801
  const { from, to, event } = transition;
@@ -3326,32 +3022,6 @@ export class AiService extends TracedEventEmitter {
3326
3022
  });
3327
3023
  return this.nativeAttachmentPreparations.resolve(request);
3328
3024
  }
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
- }
3355
3025
  cancelPendingNativeRequests() {
3356
3026
  this.nativeCancellationVersion = (this.nativeCancellationVersion ?? 0) + 1;
3357
3027
  this.nativeAttachmentPreparations?.cancel();
@@ -3464,9 +3134,10 @@ export class AiService extends TracedEventEmitter {
3464
3134
  this.builderBranch = branch;
3465
3135
  signal.throwIfAborted();
3466
3136
  const workspaceLocal = binding.workspace?.placement === "agentcore";
3467
- this.lastNativeCheckpointId = undefined;
3468
3137
  const userId = parseJwt(request.jwt)?.userId;
3469
- const turnFinish = { finished: false };
3138
+ const turnFinish = {
3139
+ finished: false,
3140
+ };
3470
3141
  this.workspaceTurnFinish = workspaceLocal ? turnFinish : undefined;
3471
3142
  const opened = workspaceLocal
3472
3143
  ? await this.ensureWorkspace(binding, branch)
@@ -3515,8 +3186,6 @@ export class AiService extends TracedEventEmitter {
3515
3186
  onWorkspaceFinish: async (workspace) => {
3516
3187
  turnFinish.finished = true;
3517
3188
  turnFinish.dbfsHash = workspace.dbfsHash;
3518
- // A retried attempt that changed nothing keeps the first one's.
3519
- turnFinish.commitId = workspace.commitId ?? turnFinish.commitId;
3520
3189
  if (workspace.dbfsHash)
3521
3190
  await this.mirrorWorkspaceHash(workspace.dbfsHash);
3522
3191
  },
@@ -3562,7 +3231,7 @@ export class AiService extends TracedEventEmitter {
3562
3231
  await this.followBuilderBinding(request);
3563
3232
  if (this.builderConversation) {
3564
3233
  const cancellationVersion = this.nativeCancellationVersion ?? 0;
3565
- const attachments = await this.prepareNativePromptAttachments(request);
3234
+ const attachments = await this.resolveNativePromptAttachments(request);
3566
3235
  this.assertNativeRequestActive(cancellationVersion);
3567
3236
  if (attachments)
3568
3237
  await this.builderConversation.start(request, attachments);
@@ -4417,45 +4086,11 @@ export class AiService extends TracedEventEmitter {
4417
4086
  type: "draftCommitted",
4418
4087
  }, inputSource);
4419
4088
  }
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
- }
4456
4089
  async handleUserAcceptedDraft(silently) {
4457
- if (this.builderConversation)
4090
+ if (this.builderConversation) {
4091
+ await this.chatSessionStore.recordUserAcceptance();
4458
4092
  return;
4093
+ }
4459
4094
  this.getLogger().info(`[ai-service] handleUserAcceptedDraft`);
4460
4095
  if (this.clark.state === ClarkStateNames.Idle) {
4461
4096
  return;
@@ -4468,14 +4103,13 @@ export class AiService extends TracedEventEmitter {
4468
4103
  void transitionTo({ type: USER_ACCEPTED_DRAFT, silently });
4469
4104
  }
4470
4105
  async handleUserRejectedDraft(silently) {
4471
- if (this.builderConversation)
4106
+ if (this.builderConversation) {
4107
+ await this.chatSessionStore.recordUserRejection();
4472
4108
  return;
4109
+ }
4473
4110
  this.getLogger().info(`[ai-service] handleUserRejectedDraft`);
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
4111
  this.submitAcceptanceEvaluation(false);
4112
+ this.editAfterClark.discardLastTurn();
4479
4113
  if (this.clark.state !== ClarkStateNames.AwaitingUser) {
4480
4114
  throw new Error("Service is not awaiting user input");
4481
4115
  }
@@ -4597,17 +4231,9 @@ export class AiService extends TracedEventEmitter {
4597
4231
  awaitingUserHandoffPromptId: undefined,
4598
4232
  awaitingUserHandoffRecorded: undefined,
4599
4233
  }));
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({
4234
+ void this.clark.send({
4602
4235
  type: USER_CANCELED,
4603
4236
  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;
4611
4237
  });
4612
4238
  }
4613
4239
  finally {
@@ -4682,7 +4308,7 @@ export class AiService extends TracedEventEmitter {
4682
4308
  if (this.builderConversation) {
4683
4309
  // Attachments are validated before a running turn is interrupted.
4684
4310
  cancellationVersion = this.nativeCancellationVersion ?? 0;
4685
- attachments = await this.prepareNativePromptAttachments(request);
4311
+ attachments = await this.resolveNativePromptAttachments(request);
4686
4312
  interrupted =
4687
4313
  this.builderConversation.isBusy &&
4688
4314
  !request.responseMetadata &&
@@ -5634,11 +5260,6 @@ export class AiService extends TracedEventEmitter {
5634
5260
  this.authenticatedPeerId = undefined;
5635
5261
  this.authenticatedPeerUserId = undefined;
5636
5262
  }
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
- }
5642
5263
  if (this.builderConversation) {
5643
5264
  void this.builderConversation.replay();
5644
5265
  return;
@@ -5680,7 +5301,18 @@ export class AiService extends TracedEventEmitter {
5680
5301
  this.getLogger().warn(`[ai-service] Failed to clear stale tool permission on reconnect`, error);
5681
5302
  });
5682
5303
  }
5683
- // 3. Close out tool calls the transcript still reports as running but
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
5684
5316
  // that no process is executing (ENG-6785). Does not gate the connect
5685
5317
  // handshake: the peer is already bound, and the reconcile is several
5686
5318
  // RPCs long. Reconnect `getMessages({ force })` joins this promise so
@@ -5798,18 +5430,6 @@ export class AiService extends TracedEventEmitter {
5798
5430
  * as auth is proven, but never before.
5799
5431
  */
5800
5432
  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
- }
5813
5433
  /**
5814
5434
  * The authenticated peer's identity, but only while that same peer is
5815
5435
  * still the bound `stablePeer`. `handleUserConnected` can swap in a
@@ -6494,64 +6114,31 @@ export class AiService extends TracedEventEmitter {
6494
6114
  * Starts a new chat and returns its id, which the editor sends with later prompts. A `builderSelection` moves the app
6495
6115
  * to that harness: it reopens the app's most recent chat on it (`resumed`), which keeps that chat's own model, or
6496
6116
  * 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.
6498
6117
  */
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;
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;
6509
6126
  }
6510
- const { mustStopTurn } = this.claimBuilderSwitch("harness", stopTurn);
6511
- // Recorded once, when the switch settles.
6512
- let outcome = "failed";
6513
6127
  try {
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;
6128
+ if (builderSelection)
6129
+ await this.assertEditorFinishedRestarting();
6130
+ return await this.switchOrStartNewChat(builderSelection);
6528
6131
  }
6529
6132
  finally {
6530
- recordBuilderSwitchClaim("harness", outcome);
6531
- this.builderSwitchInProgress = false;
6133
+ if (builderSelection)
6134
+ this.builderSwitchInProgress = false;
6532
6135
  }
6533
6136
  }
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
- }
6551
6137
  async switchOrStartNewChat(builderSelection) {
6552
6138
  if (builderSelection) {
6553
- // Again after any stop: the stopped turn may have left changes.
6554
- await this.assertNoPendingDraftForSwitch();
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");
6555
6142
  // Refuse here, before the server archives the chat, a switch this editor could not run.
6556
6143
  this.assertCanRunSelection(builderSelection);
6557
6144
  }
@@ -6584,41 +6171,29 @@ export class AiService extends TracedEventEmitter {
6584
6171
  * Changes the model of the active native chat in place. The chat, its transcript, and its native Claude or Codex
6585
6172
  * session stay; the next turn resumes that session on the new model. Placement does not change, so no restart.
6586
6173
  */
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";
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;
6591
6181
  try {
6592
6182
  await this.assertEditorFinishedRestarting();
6593
6183
  // A failed switch left this pod off the active chat; follow it first, so the change lands on the chat it runs.
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
- }
6184
+ if (this.builderBindingStale)
6604
6185
  await this.recoverStaleBindingForModelChange();
6605
- }
6606
6186
  const chatSessionId = this.builderBinding?.chatSessionId;
6607
6187
  const harness = this.builderBinding?.harness;
6608
6188
  if (!chatSessionId || !harness || harness === "clark")
6609
6189
  throw new Error("This chat does not run on a native harness");
6610
6190
  // Throws for a model the harness does not offer, before the server changes anything.
6611
6191
  this.assertCanRunSelection({ harness, model });
6612
- if (mustStopTurn && !turnStopped) {
6613
- outcome = "stop_failed";
6614
- stopped = await this.stopTurnForBuilderSwitch("model", onTurnStopped);
6615
- outcome = "failed";
6616
- }
6617
6192
  const branch = this.builderBranch ??
6618
6193
  (await this._syncContextProvider?.getBranchName()) ??
6619
6194
  "main";
6620
6195
  try {
6621
- await this.chatSessionStore.setBuilderModel(branch, model, chatSessionId, ...(effort === undefined ? [] : [effort]));
6196
+ await this.chatSessionStore.setBuilderModel(branch, model, chatSessionId);
6622
6197
  }
6623
6198
  catch (error) {
6624
6199
  if (!isChatChangedElsewhereError(error))
@@ -6639,11 +6214,9 @@ export class AiService extends TracedEventEmitter {
6639
6214
  const builderSelection = this.getBuilderSelection();
6640
6215
  if (!builderSelection)
6641
6216
  throw new Error("Changed the model, but this editor lost the chat.");
6642
- outcome = stopped ? "switched_after_stop" : "switched";
6643
6217
  return { builderSelection };
6644
6218
  }
6645
6219
  finally {
6646
- recordBuilderSwitchClaim("model", outcome);
6647
6220
  this.builderSwitchInProgress = false;
6648
6221
  }
6649
6222
  }
@@ -6693,7 +6266,6 @@ export class AiService extends TracedEventEmitter {
6693
6266
  return {
6694
6267
  harness: binding.harness,
6695
6268
  model: binding.model ?? this.builderRuntime?.model,
6696
- ...(binding.effort ? { effort: binding.effort } : {}),
6697
6269
  };
6698
6270
  }
6699
6271
  /** `resumed` when the server reopened the app's last chat on the picked harness instead of a new one. */
@@ -7054,9 +6626,6 @@ export class AiService extends TracedEventEmitter {
7054
6626
  }
7055
6627
  async handleRestoreToCommit(sinceTimestamp, commitId, applicationId, branchName) {
7056
6628
  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;
7060
6629
  await this.handleNewChat();
7061
6630
  return;
7062
6631
  }
@@ -7507,7 +7076,9 @@ export class AiService extends TracedEventEmitter {
7507
7076
  // A reloaded editor retries an open the watcher stopped retrying.
7508
7077
  editorGeneration: () => this.stablePeer.connectionGeneration,
7509
7078
  onReopened: async (result, reopenedKey) => {
7510
- await this.mirrorWorkspaceOpen(reopenedKey, this.builderBranch ?? "main", result);
7079
+ if (!this.adoptWorkspaceOpen(reopenedKey, result))
7080
+ return;
7081
+ await this.mirrorWorkspaceHash(result.dbfsHash);
7511
7082
  },
7512
7083
  });
7513
7084
  let result;
@@ -7527,14 +7098,8 @@ export class AiService extends TracedEventEmitter {
7527
7098
  this.workspaceInternalToken = undefined;
7528
7099
  throw error;
7529
7100
  }
7530
- if (!(await this.mirrorWorkspaceOpen(sessionKey, branchName, result)))
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
7101
  if (!this.adoptWorkspaceOpen(sessionKey, result))
7537
- return false;
7102
+ throw new Error("The chat moved to another workspace while it opened");
7538
7103
  if (this.workspaceMirror?.sessionKey !== sessionKey)
7539
7104
  this.workspaceMirror = {
7540
7105
  sessionKey,
@@ -7545,7 +7110,7 @@ export class AiService extends TracedEventEmitter {
7545
7110
  }),
7546
7111
  };
7547
7112
  await this.refreshWorkspaceMirror(this.workspaceHash ?? result.dbfsHash);
7548
- return true;
7113
+ return result;
7549
7114
  }
7550
7115
  /**
7551
7116
  * Takes a successful open's token and hash, once per open, and only while
@@ -7568,20 +7133,14 @@ export class AiService extends TracedEventEmitter {
7568
7133
  * reloads the file model: the VM's watcher cannot reach this process. The
7569
7134
  * hash is remembered first, so the next turn retries a failed refresh.
7570
7135
  */
7571
- refreshWorkspaceMirror(hash) {
7136
+ async refreshWorkspaceMirror(hash) {
7572
7137
  this.workspaceHash = hash;
7573
7138
  const mirror = this.workspaceMirror?.mirror;
7574
7139
  if (!mirror)
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;
7140
+ return;
7141
+ const { changed } = await mirror.refresh(hash);
7142
+ if (changed && this.fileSystemManager)
7582
7143
  await this.refreshFileModel();
7583
- this.workspaceFileModelStale = false;
7584
- });
7585
7144
  }
7586
7145
  /** Mirrors a hash the VM reported, logging rather than failing a turn. */
7587
7146
  mirrorWorkspaceHash(hash) {