@orion-agents/orion-code 0.3.65 → 0.4.3

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 (370) hide show
  1. package/CHANGELOG.md +128 -2
  2. package/README.md +78 -361
  3. package/README.zh-CN.md +71 -263
  4. package/bin/orion +4 -1
  5. package/dist/acp/session-updates.d.ts +34 -0
  6. package/dist/acp/session-updates.js +162 -0
  7. package/dist/acp/sessions.d.ts +32 -0
  8. package/dist/acp/sessions.js +315 -0
  9. package/dist/acp/stdio.d.ts +3 -0
  10. package/dist/acp/stdio.js +59 -0
  11. package/dist/cli.js +136 -185
  12. package/dist/commands/context-tool-command-handlers.d.ts +1 -1
  13. package/dist/commands/context-tool-command-handlers.js +24 -3
  14. package/dist/commands/core-command-handlers.js +5 -1
  15. package/dist/commands/diagnostic-command-handlers.js +20 -6
  16. package/dist/commands/diagnostic-commands.js +0 -12
  17. package/dist/commands/init-command.d.ts +3 -0
  18. package/dist/commands/init-command.js +131 -0
  19. package/dist/commands/model-command-handlers.d.ts +1 -2
  20. package/dist/commands/model-command-handlers.js +15 -100
  21. package/dist/commands/model-commands.js +0 -11
  22. package/dist/commands/registry.js +0 -18
  23. package/dist/commands/rsi-command.d.ts +2 -0
  24. package/dist/commands/rsi-command.js +180 -0
  25. package/dist/commands/session-command-handlers.js +28 -19
  26. package/dist/commands/system-commands.js +0 -1
  27. package/dist/commands/tool-commands.js +1 -1
  28. package/dist/commands/types.d.ts +4 -10
  29. package/dist/commands/types.js +1 -21
  30. package/dist/commands/workflow-command-handlers.js +13 -4
  31. package/dist/framework/loop-budget-contract.d.ts +7 -2
  32. package/dist/framework/loop-budget-contract.js +4 -1
  33. package/dist/framework/loop-progress.d.ts +22 -0
  34. package/dist/framework/loop-progress.js +79 -0
  35. package/dist/framework/prompt.d.ts +0 -2
  36. package/dist/framework/prompt.js +9 -27
  37. package/dist/framework/query.d.ts +27 -20
  38. package/dist/framework/query.js +453 -153
  39. package/dist/framework/store.d.ts +6 -10
  40. package/dist/framework/store.js +2 -21
  41. package/dist/framework/tool-call-orchestrator.d.ts +7 -0
  42. package/dist/framework/tool-call-orchestrator.js +8 -3
  43. package/dist/framework/tool-state.d.ts +2 -0
  44. package/dist/framework/tool.d.ts +0 -23
  45. package/dist/framework/verification-command.d.ts +15 -0
  46. package/dist/framework/verification-command.js +32 -0
  47. package/dist/harness/assembler.d.ts +1 -0
  48. package/dist/harness/assembler.js +24 -0
  49. package/dist/harness/capsule.d.ts +1 -1
  50. package/dist/harness/capsule.js +33 -14
  51. package/dist/harness/context-harness.d.ts +31 -12
  52. package/dist/harness/context-harness.js +491 -35
  53. package/dist/harness/contract.js +1 -1
  54. package/dist/harness/drift-guard.d.ts +4 -0
  55. package/dist/harness/drift-guard.js +68 -16
  56. package/dist/harness/intent.js +21 -0
  57. package/dist/harness/ledger.d.ts +6 -11
  58. package/dist/harness/ledger.js +39 -9
  59. package/dist/harness/progress-controller.d.ts +12 -7
  60. package/dist/harness/progress-controller.js +66 -21
  61. package/dist/harness/state.js +9 -1
  62. package/dist/harness/task-checklist.d.ts +16 -0
  63. package/dist/harness/task-checklist.js +95 -0
  64. package/dist/harness/types.d.ts +73 -1
  65. package/dist/harness/verification.d.ts +19 -1
  66. package/dist/harness/verification.js +116 -29
  67. package/dist/index.d.ts +1 -1
  68. package/dist/index.js +1 -3
  69. package/dist/print-ui/event-stream.d.ts +38 -0
  70. package/dist/print-ui/event-stream.js +187 -0
  71. package/dist/print-ui/launch.d.ts +12 -1
  72. package/dist/print-ui/launch.js +173 -11
  73. package/dist/product/environment.d.ts +1 -1
  74. package/dist/product/environment.js +1 -1
  75. package/dist/product/identity.d.ts +1 -1
  76. package/dist/product/identity.js +1 -1
  77. package/dist/product/paths.d.ts +3 -2
  78. package/dist/product/paths.js +6 -2
  79. package/dist/runtime/agent-loop.d.ts +11 -2
  80. package/dist/runtime/agent-loop.js +165 -25
  81. package/dist/runtime/agent-runtime-controller.d.ts +13 -3
  82. package/dist/runtime/agent-runtime-controller.js +347 -183
  83. package/dist/runtime/agent-runtime-protocol.d.ts +10 -18
  84. package/dist/runtime/agent-runtime-runner.d.ts +10 -0
  85. package/dist/runtime/builtin-tool-provider.js +5 -1
  86. package/dist/runtime/capability-receipt-journal.js +1 -0
  87. package/dist/runtime/durable-tool-receipt-reader.js +2 -1
  88. package/dist/runtime/first-party-tool-services.d.ts +1 -0
  89. package/dist/runtime/first-party-tool-services.js +2 -12
  90. package/dist/runtime/first-party-tool-universe.d.ts +1 -0
  91. package/dist/runtime/first-party-tool-universe.js +1 -1
  92. package/dist/runtime/followup-queue-store.d.ts +16 -0
  93. package/dist/runtime/followup-queue-store.js +75 -0
  94. package/dist/runtime/goal-lifecycle-v2.d.ts +11 -1
  95. package/dist/runtime/goal-lifecycle-v2.js +85 -15
  96. package/dist/runtime/goal-runtime-coordinator.d.ts +10 -1
  97. package/dist/runtime/goal-runtime-coordinator.js +81 -24
  98. package/dist/runtime/loop-budget.js +7 -5
  99. package/dist/runtime/mcp/first-party-mcp-adapter.d.ts +2 -0
  100. package/dist/runtime/mcp/first-party-mcp-adapter.js +23 -19
  101. package/dist/runtime/model-coordinator.js +2 -5
  102. package/dist/runtime/orion-runtime-v1.d.ts +18 -2
  103. package/dist/runtime/orion-runtime-v1.js +135 -39
  104. package/dist/runtime/orion-session-runner.d.ts +7 -0
  105. package/dist/runtime/orion-session-runner.js +82 -0
  106. package/dist/runtime/plan-review.d.ts +1 -0
  107. package/dist/runtime/plan-review.js +8 -4
  108. package/dist/runtime/product-bootstrap.d.ts +6 -0
  109. package/dist/runtime/product-bootstrap.js +41 -51
  110. package/dist/runtime/product-orion-runtime.js +128 -52
  111. package/dist/runtime/release-receipts.d.ts +24 -124
  112. package/dist/runtime/release-receipts.js +129 -683
  113. package/dist/runtime/rich-text/layout.js +108 -65
  114. package/dist/runtime/rsi/contracts.d.ts +50 -0
  115. package/dist/runtime/rsi/contracts.js +17 -0
  116. package/dist/runtime/rsi/diagnosis.d.ts +46 -0
  117. package/dist/runtime/rsi/diagnosis.js +98 -0
  118. package/dist/runtime/rsi/evaluation-suite.d.ts +25 -0
  119. package/dist/runtime/rsi/evaluation-suite.js +141 -0
  120. package/dist/runtime/rsi/evaluation-worker.d.ts +19 -0
  121. package/dist/runtime/rsi/evaluation-worker.js +64 -0
  122. package/dist/runtime/rsi/evaluation.d.ts +49 -0
  123. package/dist/runtime/rsi/evaluation.js +351 -0
  124. package/dist/runtime/rsi/lifecycle.d.ts +54 -0
  125. package/dist/runtime/rsi/lifecycle.js +279 -0
  126. package/dist/runtime/rsi/proposal.d.ts +39 -0
  127. package/dist/runtime/rsi/proposal.js +312 -0
  128. package/dist/runtime/rsi/receipt.d.ts +28 -0
  129. package/dist/runtime/rsi/receipt.js +138 -0
  130. package/dist/runtime/rsi/skill-state.d.ts +7 -0
  131. package/dist/runtime/rsi/skill-state.js +50 -0
  132. package/dist/runtime/rsi/trajectory.d.ts +19 -0
  133. package/dist/runtime/rsi/trajectory.js +314 -0
  134. package/dist/runtime/rsi/triage.d.ts +274 -0
  135. package/dist/runtime/rsi/triage.js +58 -0
  136. package/dist/runtime/session-composer-control.d.ts +5 -24
  137. package/dist/runtime/session-composer-control.js +27 -189
  138. package/dist/runtime/step-snapshot.d.ts +1 -0
  139. package/dist/runtime/subagents/policy.js +0 -1
  140. package/dist/runtime/subagents/production.js +1 -1
  141. package/dist/runtime/subagents/runtime-integration.js +2 -4
  142. package/dist/runtime/subagents/types.d.ts +0 -5
  143. package/dist/runtime/subagents/types.js +0 -2
  144. package/dist/runtime/task-context-recovery.d.ts +55 -0
  145. package/dist/runtime/task-context-recovery.js +342 -0
  146. package/dist/runtime/task-context-service.d.ts +16 -10
  147. package/dist/runtime/task-context-service.js +35 -4
  148. package/dist/runtime/thread-admission.d.ts +1 -1
  149. package/dist/runtime/thread-admission.js +12 -6
  150. package/dist/runtime/thread-event-store.d.ts +2 -2
  151. package/dist/runtime/thread-event-store.js +7 -2
  152. package/dist/runtime/thread-projection.js +4 -2
  153. package/dist/runtime/thread-runtime.d.ts +7 -0
  154. package/dist/runtime/thread-runtime.js +43 -0
  155. package/dist/runtime/thread-session-index.d.ts +8 -0
  156. package/dist/runtime/thread-session-index.js +50 -1
  157. package/dist/runtime/thread-session-view.d.ts +2 -1
  158. package/dist/runtime/thread-session-view.js +4 -0
  159. package/dist/runtime/thread-tool-journal.d.ts +1 -0
  160. package/dist/runtime/thread-tool-journal.js +6 -2
  161. package/dist/runtime/thread-ui-adapter.d.ts +1 -0
  162. package/dist/runtime/thread-ui-adapter.js +88 -11
  163. package/dist/runtime/tool-gateway.d.ts +7 -0
  164. package/dist/runtime/tool-gateway.js +20 -0
  165. package/dist/runtime/tool-transcript-entry.d.ts +16 -0
  166. package/dist/runtime/tool-transcript-entry.js +73 -0
  167. package/dist/runtime/turn-commit.d.ts +4 -1
  168. package/dist/runtime/turn-commit.js +19 -15
  169. package/dist/runtime/ui-events.d.ts +12 -0
  170. package/dist/runtime/ui-view-model.d.ts +6 -5
  171. package/dist/runtime/ui-view-model.js +33 -19
  172. package/dist/runtime/workspace-runtime-kernel.js +0 -1
  173. package/dist/services/atomic-write.d.ts +2 -0
  174. package/dist/services/atomic-write.js +12 -1
  175. package/dist/services/code-review/format.d.ts +4 -1
  176. package/dist/services/code-review/format.js +5 -1
  177. package/dist/services/code-review/runner.d.ts +2 -2
  178. package/dist/services/code-review/runner.js +86 -64
  179. package/dist/services/code-review/snapshot.d.ts +9 -9
  180. package/dist/services/code-review/snapshot.js +182 -166
  181. package/dist/services/compact/auto-compact.d.ts +21 -6
  182. package/dist/services/compact/auto-compact.js +148 -22
  183. package/dist/services/compact/background-candidate.d.ts +33 -0
  184. package/dist/services/compact/background-candidate.js +184 -0
  185. package/dist/services/compact/compact.d.ts +4 -1
  186. package/dist/services/compact/compact.js +30 -3
  187. package/dist/services/compact/coordinator.d.ts +10 -4
  188. package/dist/services/compact/coordinator.js +17 -7
  189. package/dist/services/compact/summary-generator.d.ts +4 -2
  190. package/dist/services/compact/summary-generator.js +17 -3
  191. package/dist/services/config.d.ts +5 -5
  192. package/dist/services/config.js +30 -45
  193. package/dist/services/doctor.js +85 -13
  194. package/dist/services/effort.d.ts +5 -5
  195. package/dist/services/effort.js +5 -11
  196. package/dist/services/file-lock.d.ts +9 -3
  197. package/dist/services/file-lock.js +92 -26
  198. package/dist/services/global-config.d.ts +26 -56
  199. package/dist/services/global-config.js +213 -183
  200. package/dist/services/llm.d.ts +40 -4
  201. package/dist/services/llm.js +164 -45
  202. package/dist/services/model-client-pool.d.ts +15 -9
  203. package/dist/services/model-client-pool.js +62 -33
  204. package/dist/services/model-context.d.ts +2 -1
  205. package/dist/services/model-context.js +15 -9
  206. package/dist/services/model-registry.d.ts +4 -15
  207. package/dist/services/model-registry.js +32 -101
  208. package/dist/services/provider-diagnostics.d.ts +7 -0
  209. package/dist/services/provider-diagnostics.js +9 -10
  210. package/dist/services/provider-resilience/coordinator.d.ts +1 -1
  211. package/dist/services/provider-resilience/coordinator.js +10 -6
  212. package/dist/services/provider-resilience/request-gate.d.ts +3 -0
  213. package/dist/services/provider-resilience/request-gate.js +29 -18
  214. package/dist/services/provider-resilience/types.d.ts +2 -0
  215. package/dist/services/session-storage.d.ts +7 -10
  216. package/dist/services/session-storage.js +57 -30
  217. package/dist/services/settings-coordinator.d.ts +0 -6
  218. package/dist/services/settings-coordinator.js +19 -56
  219. package/dist/services/settings-document-repository.d.ts +3 -10
  220. package/dist/services/settings-document-repository.js +7 -85
  221. package/dist/services/usage-state.d.ts +3 -3
  222. package/dist/services/usage-state.js +11 -42
  223. package/dist/terminal-ui/answer-format.d.ts +14 -0
  224. package/dist/terminal-ui/answer-format.js +119 -0
  225. package/dist/terminal-ui/launch.d.ts +7 -6
  226. package/dist/terminal-ui/launch.js +160 -70
  227. package/dist/terminal-ui/output-queue.d.ts +2 -1
  228. package/dist/terminal-ui/output-queue.js +1 -1
  229. package/dist/terminal-ui/raw-editor.d.ts +2 -1
  230. package/dist/terminal-ui/raw-editor.js +56 -15
  231. package/dist/tools/core/edit-file.js +2 -0
  232. package/dist/tools/core/write-file.js +5 -0
  233. package/dist/tools/lsp.d.ts +16 -1
  234. package/dist/tools/lsp.js +60 -19
  235. package/dist/tools/sandbox.d.ts +1 -1
  236. package/dist/tools/sandbox.js +3 -16
  237. package/dist/tools/todo.d.ts +4 -2
  238. package/dist/tools/todo.js +76 -31
  239. package/dist/tui-core/input-parser.d.ts +1 -0
  240. package/dist/tui-core/input-parser.js +6 -0
  241. package/dist/tui-core/style.d.ts +1 -8
  242. package/dist/tui-core/style.js +3 -110
  243. package/dist/tui-ui/chrome-view-model.d.ts +1 -1
  244. package/dist/tui-ui/chrome-view-model.js +22 -27
  245. package/dist/tui-ui/launch.js +14 -14
  246. package/dist/tui-ui/layout.d.ts +5 -7
  247. package/dist/tui-ui/layout.js +129 -124
  248. package/dist/tui-ui/runner.d.ts +11 -12
  249. package/dist/tui-ui/runner.js +88 -67
  250. package/dist/tui-ui/state.d.ts +0 -11
  251. package/dist/tui-ui/state.js +22 -33
  252. package/dist/tui-ui/terminal-image.js +22 -4
  253. package/dist/tui-ui/transcript-inspector-layout.js +6 -3
  254. package/dist/tui-ui/transcript-inspector.d.ts +1 -0
  255. package/dist/tui-ui/transcript-inspector.js +7 -1
  256. package/dist/tui-ui/transcript-layout.js +42 -6
  257. package/dist/utils/terminal-text.d.ts +11 -0
  258. package/dist/utils/terminal-text.js +114 -0
  259. package/docs/cli-guide.md +562 -0
  260. package/docs/orion.example.yaml +42 -0
  261. package/docs/readme.md +12 -57
  262. package/npm-shrinkwrap.json +484 -1855
  263. package/package.json +13 -63
  264. package/dist/migration/command.d.ts +0 -9
  265. package/dist/migration/command.js +0 -100
  266. package/dist/migration/index.d.ts +0 -7
  267. package/dist/migration/index.js +0 -14
  268. package/dist/migration/migrate.d.ts +0 -19
  269. package/dist/migration/migrate.js +0 -406
  270. package/dist/migration/types.d.ts +0 -55
  271. package/dist/migration/types.js +0 -6
  272. package/dist/services/tool-allowlist.d.ts +0 -110
  273. package/dist/services/tool-allowlist.js +0 -299
  274. package/dist/services/yaml-config.d.ts +0 -57
  275. package/dist/services/yaml-config.js +0 -178
  276. package/dist/web/cli-options.d.ts +0 -17
  277. package/dist/web/cli-options.js +0 -51
  278. package/dist/web/code-review-run-service.d.ts +0 -68
  279. package/dist/web/code-review-run-service.js +0 -228
  280. package/dist/web/context-text.d.ts +0 -17
  281. package/dist/web/context-text.js +0 -40
  282. package/dist/web/errors.d.ts +0 -6
  283. package/dist/web/errors.js +0 -13
  284. package/dist/web/event-hub.d.ts +0 -45
  285. package/dist/web/event-hub.js +0 -370
  286. package/dist/web/file-read-service.d.ts +0 -101
  287. package/dist/web/file-read-service.js +0 -593
  288. package/dist/web/file-write-service.d.ts +0 -16
  289. package/dist/web/file-write-service.js +0 -103
  290. package/dist/web/git-compare-service.d.ts +0 -45
  291. package/dist/web/git-compare-service.js +0 -160
  292. package/dist/web/git-diff-document.d.ts +0 -102
  293. package/dist/web/git-diff-document.js +0 -258
  294. package/dist/web/git-file-source.d.ts +0 -25
  295. package/dist/web/git-file-source.js +0 -21
  296. package/dist/web/git-history-service.d.ts +0 -151
  297. package/dist/web/git-history-service.js +0 -619
  298. package/dist/web/git-index-transaction.d.ts +0 -45
  299. package/dist/web/git-index-transaction.js +0 -174
  300. package/dist/web/git-patch-builder.d.ts +0 -30
  301. package/dist/web/git-patch-builder.js +0 -138
  302. package/dist/web/git-read-model-service.d.ts +0 -452
  303. package/dist/web/git-read-model-service.js +0 -1833
  304. package/dist/web/git-version-service.d.ts +0 -79
  305. package/dist/web/git-version-service.js +0 -279
  306. package/dist/web/host-daemon.d.ts +0 -70
  307. package/dist/web/host-daemon.js +0 -237
  308. package/dist/web/index.d.ts +0 -6
  309. package/dist/web/index.js +0 -28
  310. package/dist/web/launch.d.ts +0 -12
  311. package/dist/web/launch.js +0 -89
  312. package/dist/web/native-directory-picker.d.ts +0 -63
  313. package/dist/web/native-directory-picker.js +0 -169
  314. package/dist/web/protocol.d.ts +0 -705
  315. package/dist/web/protocol.js +0 -639
  316. package/dist/web/review-service.d.ts +0 -22
  317. package/dist/web/review-service.js +0 -68
  318. package/dist/web/server.d.ts +0 -20
  319. package/dist/web/server.js +0 -1453
  320. package/dist/web/session-runtime-registry.d.ts +0 -138
  321. package/dist/web/session-runtime-registry.js +0 -471
  322. package/dist/web/terminal-manager.d.ts +0 -156
  323. package/dist/web/terminal-manager.js +0 -779
  324. package/dist/web/terminal-server.d.ts +0 -8
  325. package/dist/web/terminal-server.js +0 -304
  326. package/dist/web/workbench-controller.d.ts +0 -395
  327. package/dist/web/workbench-controller.js +0 -3077
  328. package/dist/web/workspace-discovery.d.ts +0 -92
  329. package/dist/web/workspace-discovery.js +0 -324
  330. package/dist/web/workspace-mutation-arbiter.d.ts +0 -54
  331. package/dist/web/workspace-mutation-arbiter.js +0 -267
  332. package/dist/web/workspace-open-telemetry.d.ts +0 -55
  333. package/dist/web/workspace-open-telemetry.js +0 -73
  334. package/dist/web-client/assets/FilesPanel-iBYj9ZRf.js +0 -1
  335. package/dist/web-client/assets/GitPanel-D33R_bZr.js +0 -4
  336. package/dist/web-client/assets/ReviewPanel-C_0upsDk.js +0 -6
  337. package/dist/web-client/assets/TerminalPanel-C7A8dMNf.js +0 -23
  338. package/dist/web-client/assets/TerminalPanel-DLuoa74B.css +0 -1
  339. package/dist/web-client/assets/index-BaOxrwGB.css +0 -1
  340. package/dist/web-client/assets/index-CqCgJ2ov.js +0 -20
  341. package/dist/web-client/assets/useAutoNotice-C1qM-_Sg.js +0 -1
  342. package/dist/web-client/favicon.svg +0 -9
  343. package/dist/web-client/index.html +0 -17
  344. package/docs/architecture/agent-mode-permission-contract.md +0 -87
  345. package/docs/architecture/v0.3.0-web-api.yaml +0 -1340
  346. package/docs/architecture/v0.3.1-web-api.yaml +0 -2338
  347. package/docs/architecture/v0.3.2-web-api.yaml +0 -3029
  348. package/docs/architecture/v0.3.3-web-api.yaml +0 -3205
  349. package/docs/architecture/v0.3.4-stabilization-contract.md +0 -32
  350. package/docs/migration/v0.1.9-to-v0.2.0.md +0 -98
  351. package/docs/migration/v0.2.2-to-v0.3.0-settings.md +0 -114
  352. package/docs/migration/v0.2.2-to-v0.3.0.md +0 -55
  353. package/docs/migration/v0.3.0-to-v0.3.1.md +0 -88
  354. package/docs/migration/v0.3.1-to-v0.3.2.md +0 -94
  355. package/docs/migration/v0.3.2-to-v0.3.3.md +0 -62
  356. package/docs/migration/v0.3.3-to-v0.3.4.md +0 -36
  357. package/docs/orion.example.json +0 -86
  358. package/docs/plan/v0.2.0-dsh-harness-redesign-plan.md +0 -1234
  359. package/docs/plan/v0.2.0-release-checklist.md +0 -91
  360. package/docs/plan/v0.3.0-node-runtime-compatibility-plan.md +0 -57
  361. package/docs/plan/v0.3.0-settings-integration-plan.md +0 -740
  362. package/docs/plan/v0.3.0-web-workbench-plan.md +0 -376
  363. package/docs/plan/v0.3.1-web-workbench-professional-shell-plan.md +0 -848
  364. package/docs/plan/v0.3.2-web-workbench-layout-and-composer-plan.md +0 -869
  365. package/docs/plan/v0.3.3-plan.md +0 -1113
  366. package/docs/plan/v0.3.4-stabilization-plan.md +0 -89
  367. package/docs/test/v0.3.1-web-workbench-e2e-plan.md +0 -140
  368. package/docs/test/v0.3.2-web-workbench-e2e-plan.md +0 -100
  369. package/docs/test/v0.3.3-web-workbench-e2e-plan.md +0 -79
  370. package/docs/test/v0.3.4-stabilization-e2e-plan.md +0 -54
@@ -1,3077 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WebWorkbenchController = exports.WebWorkbenchError = void 0;
4
- exports.pageItems = pageItems;
5
- exports.pageCollectionItems = pageCollectionItems;
6
- exports.hasProjectSignal = hasProjectSignal;
7
- const crypto_1 = require("crypto");
8
- const child_process_1 = require("child_process");
9
- const fs_1 = require("fs");
10
- const paths_1 = require("../product/paths");
11
- const promises_1 = require("fs/promises");
12
- const path_1 = require("path");
13
- const agent_runtime_controller_1 = require("../runtime/agent-runtime-controller");
14
- const mcp_1 = require("../runtime/mcp");
15
- const product_bootstrap_1 = require("../runtime/product-bootstrap");
16
- const canonical_1 = require("../runtime/protocol/canonical");
17
- const plan_review_1 = require("../runtime/plan-review");
18
- const thread_event_store_1 = require("../runtime/thread-event-store");
19
- const thread_session_index_1 = require("../runtime/thread-session-index");
20
- const thread_session_view_1 = require("../runtime/thread-session-view");
21
- const tool_detail_repository_1 = require("../runtime/tool-detail-repository");
22
- const turn_commit_1 = require("../runtime/turn-commit");
23
- const session_composer_control_1 = require("../runtime/session-composer-control");
24
- const global_config_1 = require("../services/global-config");
25
- const redaction_1 = require("../services/redaction");
26
- const settings_coordinator_1 = require("../services/settings-coordinator");
27
- const session_storage_1 = require("../services/session-storage");
28
- const workspace_registry_1 = require("../services/workspace-registry");
29
- const errors_1 = require("./errors");
30
- const context_text_1 = require("./context-text");
31
- const event_hub_1 = require("./event-hub");
32
- const file_read_service_1 = require("./file-read-service");
33
- const file_write_service_1 = require("./file-write-service");
34
- const git_read_model_service_1 = require("./git-read-model-service");
35
- const workspace_mutation_arbiter_1 = require("./workspace-mutation-arbiter");
36
- const protocol_1 = require("./protocol");
37
- const native_directory_picker_1 = require("./native-directory-picker");
38
- const workspace_open_telemetry_1 = require("./workspace-open-telemetry");
39
- const workspace_discovery_1 = require("./workspace-discovery");
40
- const workspace_roots_registry_1 = require("../services/workspace-roots-registry");
41
- const review_service_1 = require("./review-service");
42
- const code_review_run_service_1 = require("./code-review-run-service");
43
- const session_runtime_registry_1 = require("./session-runtime-registry");
44
- const terminal_manager_1 = require("./terminal-manager");
45
- var errors_2 = require("./errors");
46
- Object.defineProperty(exports, "WebWorkbenchError", { enumerable: true, get: function () { return errors_2.WebWorkbenchError; } });
47
- const SESSION_VIEW_CACHE_BYTES = 16 * 1024 * 1024;
48
- const MAX_MUTATION_RESULTS = 4096;
49
- const MAX_CONTEXT_REFERENCE_BYTES = 64 * 1024;
50
- const MAX_CONTEXT_MANIFEST_BYTES = 256 * 1024;
51
- const CONTEXT_TRANSITION_MUTATIONS = new Set(['context.activate', 'workspace.activate']);
52
- /** Owns the Workspace surface plus the bounded Web Session actor registry. */
53
- class WebWorkbenchController {
54
- constructor(options) {
55
- this.activeOrionRuntimes = new Map();
56
- /**
57
- * Workspace-scoped shared kernels owned by this Host. Control planes and
58
- * Session actors both borrow from this pool, so a Workspace Context switch
59
- * never tears down kernels that resident actors still reference. The pool is
60
- * released only during Host shutdown.
61
- */
62
- this.workspaceKernels = new Map();
63
- this.pickerInFlight = false;
64
- /** v0.3.17 — bounded, path-free open-path traces exposed through diagnostics(). */
65
- this.openTelemetry = new workspace_open_telemetry_1.WorkspaceOpenTelemetryV1();
66
- /**
67
- * v0.3.21 — global discovery single-flight: at most one scan runs per Host;
68
- * a new discover request aborts the previous one (scan_cancelled) and wins.
69
- */
70
- this.discoveryInflight = new Map();
71
- this.mutationResults = new Map();
72
- this.sessionViews = new Map();
73
- this.sessionViewBytes = 0;
74
- this.toolDetails = new tool_detail_repository_1.FileToolDetailRepository();
75
- this.workspaceMutationOwners = new Map();
76
- this.pendingWorkspaceMutationStates = new Map();
77
- /** v0.3.29 — shared code-review run history for the Review panel. */
78
- this.codeReviewRuns = new code_review_run_service_1.WebCodeReviewRunServiceV1({
79
- adapterProvider: () => createReviewModelAdapter(this.runtimeValue?.llm ?? null),
80
- cwdProvider: () => this.workspaceValue,
81
- repositoryRevisionProvider: async () => {
82
- const status = await this.gitService.status({ pageSize: 1 });
83
- return status.repositoryRevision;
84
- },
85
- });
86
- this.contextRevisionValue = (0, crypto_1.randomUUID)();
87
- this.composerRevisionValue = (0, crypto_1.randomUUID)();
88
- this.suppressComposerEdges = 0;
89
- this.suppressContextEdges = 0;
90
- this.latestStatus = 'Ready';
91
- this.activeMutationCount = 0;
92
- this.contextTransitionReserved = false;
93
- this.closed = false;
94
- /**
95
- * Host-observed Web activity counters. Exposed through diagnostics() so E2E
96
- * and the diagnostics panel can prove that a pure Session selection issues
97
- * no control-plane reinstall (controlPlaneInstalls delta 0) and that
98
- * snapshots stay bounded and fast (snapshotTotalMs / snapshotLastMs).
99
- */
100
- this.sessionActivity = {
101
- snapshotRequests: 0,
102
- snapshotFailures: 0,
103
- snapshotTotalMs: 0,
104
- snapshotLastMs: 0,
105
- controlPlaneInstalls: 0,
106
- controlPlaneShutdowns: 0,
107
- };
108
- this.workspaceWatchers = [];
109
- this.workspaceValue = canonicalDirectory(options.cwd);
110
- this.eventHub = options.eventHub ?? new event_hub_1.WebEventHub();
111
- this.workspaceMutations = new workspace_mutation_arbiter_1.WorkspaceMutationArbiterV1({
112
- onStateChanged: state => this.emitWorkspaceMutationState(state),
113
- });
114
- this.workspaceRegistry = options.workspaceRegistry ?? new workspace_registry_1.WorkspaceRegistryV1();
115
- this.workspaceRootsRegistry = options.workspaceRootsRegistry ?? new workspace_roots_registry_1.WorkspaceRootsRegistryV1();
116
- this.discoveryTelemetry = options.discoveryTelemetry ?? new workspace_discovery_1.WorkspaceDiscoveryTelemetryV1();
117
- this.discoveryService = new workspace_discovery_1.WorkspaceDiscoveryServiceV1({
118
- telemetry: this.discoveryTelemetry,
119
- });
120
- this.directoryPicker = options.nativeDirectoryPicker ?? (0, native_directory_picker_1.createNativeDirectoryPicker)();
121
- this.terminalManager = new terminal_manager_1.TerminalManagerV1({
122
- resolveWorkspace: workspaceId => this.workspaceRegistry.find(workspaceId)?.canonicalPath,
123
- getActiveContext: () => ({
124
- workspaceId: this.activeWorkspaceEntry().id,
125
- contextRevision: this.contextRevisionValue,
126
- }),
127
- onWorkspaceMutationHint: workspaceId => {
128
- if (workspaceId === this.activeWorkspaceEntry().id) {
129
- this.scheduleWorkspaceResourceInvalidation('terminal-command');
130
- }
131
- },
132
- });
133
- this.createRuntime =
134
- options.createRuntime ??
135
- (cwd => (0, product_bootstrap_1.createProductUiRuntime)({
136
- cwd,
137
- // Borrow the workspace kernel from the Host-owned pool so the
138
- // control plane shares config/Tool/MCP/Settings services with the
139
- // resident Session actors of the same Workspace.
140
- workspaceRuntimeKernel: this.workspaceKernelFor(cwd),
141
- workspaceMutationCoordinator: this.workspaceMutations,
142
- shutdownReason: 'Orion Web Workbench shutdown',
143
- onActiveSessionRuntime: (runtime, sessionId, activation) => this.observeThreadRuntime(runtime, sessionId, activation),
144
- onSettingsInvalidated: event => {
145
- if (this.suppressContextEdges > 0)
146
- return;
147
- this.eventHub.emit({
148
- type: 'settings_invalidated',
149
- revision: event.revision,
150
- reason: event.reason,
151
- state: event.state,
152
- }, false);
153
- },
154
- }));
155
- this.createSessionRuntime =
156
- options.createSessionRuntime ??
157
- options.createRuntime ??
158
- (cwd => (0, product_bootstrap_1.createProductUiRuntime)({
159
- cwd,
160
- // Session actors must keep the kernel of the Workspace they were
161
- // created for, never the currently active control plane's kernel.
162
- workspaceRuntimeKernel: this.workspaceKernelFor(cwd),
163
- workspaceMutationCoordinator: this.workspaceMutations,
164
- shutdownReason: 'Orion Web Session actor shutdown',
165
- onActiveSessionRuntime: (runtime, sessionId, activation) => this.observeThreadRuntime(runtime, sessionId, activation),
166
- }));
167
- this.sessionRegistry = this.createSessionRegistry();
168
- }
169
- static async create(options) {
170
- const workbench = new WebWorkbenchController(options);
171
- await (0, paths_1.resolveProjectStoragePathAsync)(workbench.workspaceValue);
172
- await (0, session_storage_1.prepareSessionCatalogAsync)();
173
- workbench.initializeWorkspaceRegistry();
174
- await workbench.installRuntime(workbench.workspaceValue);
175
- return workbench;
176
- }
177
- get workspace() {
178
- return this.workspaceValue;
179
- }
180
- get runtime() {
181
- return this.runtimeValue;
182
- }
183
- get controller() {
184
- return this.controllerValue;
185
- }
186
- get contextRevision() {
187
- return this.contextRevisionValue;
188
- }
189
- bootstrap(nonce) {
190
- return Object.freeze({
191
- apiVersion: protocol_1.WEB_API_VERSION,
192
- productVersion: this.runtimeValue.version,
193
- nonce,
194
- contextRevision: this.contextRevisionValue,
195
- workspaceId: this.activeWorkspaceEntry().id,
196
- workspace: this.workspaceValue,
197
- configured: this.runtimeValue.isConfigured,
198
- activeSessionId: this.runtimeValue.getSession()?.id ?? null,
199
- eventCursor: this.eventHub.snapshot().latest,
200
- settings: this.settings(),
201
- capabilities: {
202
- goal: true,
203
- plan: true,
204
- skills: true,
205
- mcp: true,
206
- diagnostics: true,
207
- review: true,
208
- files: true,
209
- git: true,
210
- terminal: this.terminalManager.available,
211
- },
212
- });
213
- }
214
- settings() {
215
- this.assertSettingsAvailable();
216
- const describe = this.runtimeValue.describeSettings;
217
- if (!describe) {
218
- throw new errors_1.WebWorkbenchError(503, 'The product Settings coordinator is unavailable.', 'settings_document_unavailable');
219
- }
220
- try {
221
- return describe();
222
- }
223
- catch (error) {
224
- throw mapSettingsError(error);
225
- }
226
- }
227
- listWorkspaces(context) {
228
- if (context)
229
- this.assertContextGuard(context);
230
- // Session metadata is canonicalized before it enters the catalog. The
231
- // summary read model deliberately avoids sorting Sessions or re-running
232
- // realpath/stat for every historical entry. Availability is checked once
233
- // per registered Workspace below.
234
- const counts = (0, session_storage_1.countSessionsByProject)();
235
- const result = Object.freeze(this.workspaceRegistry.list().map(entry => {
236
- let available = false;
237
- try {
238
- available = canonicalDirectory(entry.canonicalPath) === entry.canonicalPath;
239
- }
240
- catch {
241
- available = false;
242
- }
243
- return Object.freeze({
244
- id: entry.id,
245
- path: entry.canonicalPath,
246
- label: entry.label || (0, path_1.basename)(entry.canonicalPath) || entry.canonicalPath,
247
- active: entry.canonicalPath === this.workspaceValue,
248
- available,
249
- sessionCount: counts.get(entry.canonicalPath) ?? 0,
250
- lastActivatedAt: entry.lastActivatedAt,
251
- registeredAt: entry.registeredAt,
252
- ...(entry.pinnedOrder !== undefined ? { pinnedOrder: entry.pinnedOrder } : {}),
253
- });
254
- }));
255
- if (context)
256
- this.assertContextGuard(context);
257
- return result;
258
- }
259
- /**
260
- * v0.3.16 — Ask the Host to run the OS directory picker.
261
- *
262
- * This is a *browse* action: it never registers, activates or reads a
263
- * workspace. Only one picker may be open at a time so a stuck native dialog
264
- * cannot be stacked, and the result is a plain path the caller must still
265
- * confirm through the normal activation flow.
266
- */
267
- async pickDirectory(input) {
268
- if (this.closed) {
269
- throw new errors_1.WebWorkbenchError(503, 'The local Web Host is shutting down.', 'host_closed');
270
- }
271
- if (this.pickerInFlight) {
272
- throw new errors_1.WebWorkbenchError(429, 'A directory picker is already open.', 'picker_busy');
273
- }
274
- const span = input.requestId
275
- ? this.openTelemetry.start(input.requestId, 'pick-directory')
276
- : undefined;
277
- this.pickerInFlight = true;
278
- try {
279
- span?.mark('picker_launch');
280
- const result = await this.directoryPicker.pickDirectory(input);
281
- span?.mark('picker_result');
282
- if (span) {
283
- const outcome = result.kind === 'selected'
284
- ? 'success'
285
- : result.kind === 'cancelled'
286
- ? 'cancelled'
287
- : 'failed';
288
- this.openTelemetry.record(span.finish(outcome, result.kind === 'unavailable' ? result.reason : undefined));
289
- }
290
- return result;
291
- }
292
- catch (error) {
293
- if (span)
294
- this.openTelemetry.record(span.finish('failed', 'picker_error'));
295
- throw error;
296
- }
297
- finally {
298
- this.pickerInFlight = false;
299
- }
300
- }
301
- /**
302
- * v0.3.17 — Read-only, bounded preview of a candidate directory.
303
- *
304
- * Probes with asynchronous fs so a hung network mount or a broken symlink
305
- * cannot freeze the Node event loop, and races the whole probe against a
306
- * short budget. It never registers a workspace, activates a Context, reads
307
- * file contents, or touches the session catalog beyond a warm-cache peek.
308
- */
309
- async inspectWorkspaceFast(path, source = 'manual', requestId) {
310
- if (this.closed) {
311
- throw new errors_1.WebWorkbenchError(503, 'The local Web Host is shutting down.', 'host_closed');
312
- }
313
- const span = requestId ? this.openTelemetry.start(requestId, 'inspect') : undefined;
314
- const inspected = await inspectDirectory(requireCandidatePath(path));
315
- span?.mark('inspect_fs');
316
- const existing = this.workspaceRegistry
317
- .list()
318
- .find(entry => entry.canonicalPath === inspected.canonicalPath);
319
- // The preview must never wait on the session catalog: rebuilding it can
320
- // take a file lock for up to 10s. Use the warm cache when it is already
321
- // valid, otherwise report the count as deferred rather than blocking the
322
- // confirmation card.
323
- const counts = inspected.availability === 'available' ? (0, session_storage_1.peekCachedSessionCounts)() : null;
324
- span?.mark('inspect_session_count');
325
- const candidate = Object.freeze({
326
- canonicalPath: inspected.canonicalPath,
327
- label: (0, path_1.basename)(inspected.canonicalPath) || inspected.canonicalPath,
328
- availability: inspected.availability,
329
- kind: inspected.kind,
330
- source,
331
- ...(existing ? { existingWorkspaceId: existing.id } : {}),
332
- ...(existing?.pinnedOrder !== undefined ? { pinnedOrder: existing.pinnedOrder } : {}),
333
- ...(inspected.availability === 'available'
334
- ? counts
335
- ? {
336
- sessionCount: counts.get(inspected.canonicalPath) ?? 0,
337
- sessionCountStatus: 'ready',
338
- }
339
- : { sessionCountStatus: 'deferred' }
340
- : {}),
341
- isActive: inspected.canonicalPath === this.workspaceValue,
342
- });
343
- if (span) {
344
- this.openTelemetry.record(span.finish('success', inspected.timedOut ? 'inspect_budget_exceeded' : undefined));
345
- }
346
- return candidate;
347
- }
348
- // ---------------------------------------------------------------------
349
- // v0.3.21 — user-authorized project roots and bounded discovery.
350
- //
351
- // Roots are scan boundaries, not workspaces: nothing here registers a
352
- // workspace, activates a Context, installs a Runtime, or reads file
353
- // contents. A discovered candidate is a hint; the client must still run the
354
- // existing POST /workspaces/inspect → confirm → activate flow.
355
- // ---------------------------------------------------------------------
356
- listWorkspaceRoots() {
357
- return this.workspaceRootsRegistry.list().map(entry => {
358
- const cached = this.discoveryService.cached(entry.id);
359
- return Object.freeze({
360
- ...entry,
361
- discovery: cached
362
- ? Object.freeze({
363
- status: cached.status,
364
- candidateCount: cached.candidates.length,
365
- durationMs: cached.durationMs,
366
- ...(cached.errorCode ? { errorCode: cached.errorCode } : {}),
367
- cached: true,
368
- })
369
- : null,
370
- });
371
- });
372
- }
373
- async addWorkspaceRoot(path, requestId) {
374
- if (this.closed) {
375
- throw new errors_1.WebWorkbenchError(503, 'The local Web Host is shutting down.', 'host_closed');
376
- }
377
- const entry = this.workspaceRootsRegistry.add(path);
378
- void requestId;
379
- const view = this.listWorkspaceRoots().find(root => root.id === entry.id);
380
- if (!view)
381
- throw new errors_1.WebWorkbenchError(500, 'Workspace root vanished after add.', 'scan_failed');
382
- return view;
383
- }
384
- removeWorkspaceRoot(rootId) {
385
- // Cancelling first: a removed root must never receive a late scan result.
386
- const inflight = this.discoveryInflight.get(rootId);
387
- if (inflight) {
388
- inflight.controller.abort();
389
- this.discoveryInflight.delete(rootId);
390
- }
391
- this.discoveryService.invalidate(rootId);
392
- return this.workspaceRootsRegistry.remove(rootId);
393
- }
394
- async discoverWorkspaceRoot(rootId, requestId, options = {}) {
395
- if (this.closed) {
396
- throw new errors_1.WebWorkbenchError(503, 'The local Web Host is shutting down.', 'host_closed');
397
- }
398
- const entry = this.workspaceRootsRegistry.find(rootId);
399
- if (!entry) {
400
- throw new errors_1.WebWorkbenchError(404, 'Workspace root is not registered.', 'root_missing');
401
- }
402
- // Global single-flight: the newest discover request wins; the previous
403
- // scan is aborted and reports scan_cancelled.
404
- for (const [id, inflight] of this.discoveryInflight) {
405
- inflight.controller.abort();
406
- this.discoveryInflight.delete(id);
407
- }
408
- if (!options.refresh) {
409
- const cached = this.discoveryService.cached(rootId);
410
- if (cached)
411
- return this.toDiscoverOutcome(cached, entry.lastScannedAt, requestId);
412
- }
413
- const controller = new AbortController();
414
- const promise = this.discoveryService.discover({ root: entry, signal: controller.signal });
415
- this.discoveryInflight.set(rootId, { controller, promise });
416
- let outcome;
417
- try {
418
- outcome = await promise;
419
- }
420
- finally {
421
- const current = this.discoveryInflight.get(rootId);
422
- if (current && current.promise === promise)
423
- this.discoveryInflight.delete(rootId);
424
- }
425
- const scanned = this.workspaceRootsRegistry.markScanned(rootId);
426
- return this.toDiscoverOutcome(outcome, scanned?.lastScannedAt, requestId);
427
- }
428
- toDiscoverOutcome(outcome, lastScannedAt, requestId) {
429
- return Object.freeze({
430
- ...(requestId ? { requestId } : {}),
431
- rootId: outcome.rootId,
432
- status: outcome.status,
433
- candidates: outcome.candidates,
434
- ...(outcome.errorCode ? { errorCode: outcome.errorCode } : {}),
435
- durationMs: outcome.durationMs,
436
- scannedEntries: outcome.scannedEntries,
437
- ...(lastScannedAt ? { lastScannedAt } : {}),
438
- });
439
- }
440
- listWorkspaceSessions(workspaceId, context) {
441
- if (context)
442
- this.assertContextGuard(context);
443
- const entry = this.workspaceRegistry.find(workspaceId);
444
- if (!entry) {
445
- throw new errors_1.WebWorkbenchError(404, 'Workspace was not found.', 'workspace_not_found');
446
- }
447
- try {
448
- canonicalDirectory(entry.canonicalPath);
449
- }
450
- catch {
451
- throw new errors_1.WebWorkbenchError(409, 'Workspace is unavailable.', 'workspace_unavailable');
452
- }
453
- const result = Object.freeze((0, session_storage_1.listProjectSessions)(entry.canonicalPath).map(protocol_1.projectSessionSummary));
454
- if (context)
455
- this.assertContextGuard(context);
456
- return result;
457
- }
458
- /** Archived sessions of a Workspace (v0.3.7), newest archive first. */
459
- listArchivedWorkspaceSessions(workspaceId, context) {
460
- if (context)
461
- this.assertContextGuard(context);
462
- const entry = this.workspaceRegistry.find(workspaceId);
463
- if (!entry) {
464
- throw new errors_1.WebWorkbenchError(404, 'Workspace was not found.', 'workspace_not_found');
465
- }
466
- try {
467
- canonicalDirectory(entry.canonicalPath);
468
- }
469
- catch {
470
- throw new errors_1.WebWorkbenchError(409, 'Workspace is unavailable.', 'workspace_unavailable');
471
- }
472
- const result = Object.freeze((0, session_storage_1.listArchivedProjectSessions)(entry.canonicalPath).map(protocol_1.projectSessionSummary));
473
- if (context)
474
- this.assertContextGuard(context);
475
- return result;
476
- }
477
- async workspaceProjectSummary(workspaceId, context) {
478
- if (context)
479
- this.assertContextGuard(context);
480
- const entry = this.workspaceRegistry.find(workspaceId);
481
- if (!entry) {
482
- throw new errors_1.WebWorkbenchError(404, 'Workspace was not found.', 'workspace_not_found');
483
- }
484
- let workspace;
485
- try {
486
- workspace = canonicalDirectory(entry.canonicalPath);
487
- }
488
- catch {
489
- throw new errors_1.WebWorkbenchError(409, 'Workspace is unavailable.', 'workspace_unavailable');
490
- }
491
- const status = await new git_read_model_service_1.GitReadModelServiceV1(workspace).status({ pageSize: 2000 });
492
- const result = Object.freeze({
493
- workspaceId,
494
- repositoryRevision: status.repositoryRevision,
495
- isRepository: status.isRepository,
496
- branch: status.branch,
497
- detached: status.detached,
498
- head: status.head,
499
- dirtyCount: status.totalFiles,
500
- conflictCount: status.conflicted.length,
501
- });
502
- if (context)
503
- this.assertContextGuard(context);
504
- return result;
505
- }
506
- setWorkspacePinned(workspaceId, pinned, context) {
507
- this.assertContextGuard(context);
508
- try {
509
- this.workspaceRegistry.setPinned(workspaceId, pinned);
510
- }
511
- catch (error) {
512
- throw mapWorkspaceRegistryError(error);
513
- }
514
- const updated = this.listWorkspaces().find(workspace => workspace.id === workspaceId);
515
- if (!updated) {
516
- throw new errors_1.WebWorkbenchError(404, 'Workspace was not found.', 'workspace_not_found');
517
- }
518
- return updated;
519
- }
520
- removeWorkspace(workspaceId, context) {
521
- this.assertContextGuard(context);
522
- const entry = this.workspaceRegistry.find(workspaceId);
523
- if (!entry) {
524
- throw new errors_1.WebWorkbenchError(404, 'Workspace was not found.', 'workspace_not_found');
525
- }
526
- if (entry.canonicalPath === this.workspaceValue) {
527
- throw new errors_1.WebWorkbenchError(409, 'The active Workspace cannot be removed.', 'workspace_active');
528
- }
529
- this.terminalManager.closeWorkspace(workspaceId);
530
- if (!this.workspaceRegistry.remove(workspaceId)) {
531
- throw new errors_1.WebWorkbenchError(404, 'Workspace was not found.', 'workspace_not_found');
532
- }
533
- }
534
- listSessions(context) {
535
- if (context)
536
- this.assertContextGuard(context);
537
- const result = Object.freeze((0, session_storage_1.listProjectSessions)(this.workspaceValue).map(protocol_1.projectSessionSummary));
538
- if (context)
539
- this.assertContextGuard(context);
540
- return result;
541
- }
542
- sessionSnapshot(sessionId, cursor, pageSize = 50, tail = false, context) {
543
- const startedAt = Date.now();
544
- try {
545
- const snapshot = this.snapshotSessionV1(sessionId, cursor, pageSize, tail, context);
546
- this.recordSessionSnapshotActivity(startedAt);
547
- return snapshot;
548
- }
549
- catch (error) {
550
- this.recordSessionSnapshotActivity(startedAt, true);
551
- throw error;
552
- }
553
- }
554
- snapshotSessionV1(sessionId, cursor, pageSize = 50, tail = false, context) {
555
- if (context)
556
- this.assertContextGuard(context);
557
- const session = requireSession(sessionId);
558
- if (canonicalDirectory(session.projectPath) !== this.workspaceValue) {
559
- throw new errors_1.WebWorkbenchError(409, 'Session belongs to another workspace.');
560
- }
561
- const key = this.sessionActorKey(session);
562
- const resident = this.sessionRegistry.residentActor(key);
563
- const actor = resident?.actor;
564
- const baseSessionRuntime = resident?.runtime ?? this.sessionRegistry.summary(key);
565
- const active = actor !== undefined;
566
- const activeProjection = this.activeOrionRuntimes.get(session.id)?.thread.getProjection();
567
- let indexedPage;
568
- if (tail) {
569
- try {
570
- indexedPage = (0, thread_session_view_1.loadThreadSessionSnapshotPageV1)(this.workspaceValue, session.id, cursor, pageSize);
571
- }
572
- catch (error) {
573
- if (error instanceof thread_session_index_1.ThreadSessionIndexError) {
574
- throw new errors_1.WebWorkbenchError(error.code === 'ORION_THREAD_SESSION_CURSOR_STALE' ? 409 : 400, error.message, error.code === 'ORION_THREAD_SESSION_CURSOR_STALE'
575
- ? 'transcript_cursor_stale'
576
- : 'page_cursor_invalid');
577
- }
578
- throw error;
579
- }
580
- }
581
- if (indexedPage &&
582
- activeProjection &&
583
- (indexedPage.cursor !== activeProjection.cursor ||
584
- indexedPage.projectionDigest !== activeProjection.digest)) {
585
- if (cursor) {
586
- throw new errors_1.WebWorkbenchError(409, 'Active Thread changed after this transcript cursor was issued.', 'transcript_cursor_stale');
587
- }
588
- // Another process may have advanced the durable Thread before the active
589
- // Runtime has adopted that head. Never combine the newer page with the
590
- // older in-memory cursor/digest in one snapshot.
591
- indexedPage = undefined;
592
- }
593
- let view;
594
- if (!indexedPage && !activeProjection) {
595
- try {
596
- view = this.loadSessionView(session, activeProjection);
597
- }
598
- catch (error) {
599
- if (!activeProjection)
600
- throw error;
601
- view = undefined;
602
- }
603
- }
604
- const transcriptSource = indexedPage
605
- ? indexedPage.transcript.items
606
- : view
607
- ? view.transcriptMessages
608
- : activeProjection
609
- ? Object.values(activeProjection.items)
610
- .filter(item => item.kind === 'message' &&
611
- item.status !== 'started' &&
612
- ['system', 'user', 'assistant', 'tool'].includes(item.role ?? ''))
613
- .sort((left, right) => left.startedSeq - right.startedSeq)
614
- .map(item => ({
615
- role: item.role,
616
- content: item.content ?? item.summary ?? item.error ?? '',
617
- timestamp: item.terminalSeq ?? item.startedSeq,
618
- }))
619
- : (0, session_storage_1.readSessionMessages)(session.id).map(message => ({
620
- role: message.role,
621
- content: message.content,
622
- timestamp: message.timestamp,
623
- ...(message.toolCallId ? { toolCallId: message.toolCallId } : {}),
624
- ...(message.tool_calls ? { tool_calls: message.tool_calls } : {}),
625
- ...(message.modelVisibleContent
626
- ? { modelVisibleContent: message.modelVisibleContent }
627
- : {}),
628
- ...(message.appliedSkills ? { appliedSkills: message.appliedSkills } : {}),
629
- }));
630
- const tailPage = tail && !indexedPage ? pageTranscriptTail(transcriptSource, cursor, pageSize) : undefined;
631
- const transcriptPage = indexedPage
632
- ? {
633
- items: indexedPage.transcript.items,
634
- nextCursor: indexedPage.transcript.nextCursor,
635
- }
636
- : (tailPage ?? pageItems(transcriptSource, cursor, pageSize));
637
- const transcriptOffset = indexedPage
638
- ? indexedPage.transcript.offset
639
- : (tailPage?.offset ?? (cursor ? decodePageCursor(cursor) : 0));
640
- const transcript = Object.freeze({
641
- items: Object.freeze(transcriptPage.items.map((message, index) => ({
642
- ...message,
643
- id: `${session.id}:message:${transcriptOffset + index + 1}`,
644
- }))),
645
- nextCursor: indexedPage?.transcript.nextCursor ?? transcriptPage.nextCursor,
646
- });
647
- const commitProjections = indexedPage
648
- ? uniqueCommitProjections([indexedPage.latestPlanTurnCommit, indexedPage.latestTurnCommit])
649
- : view
650
- ? uniqueCommitProjections([view.latestPlanTurnCommit, view.latestTurnCommit])
651
- : activeProjection
652
- ? latestAuthorityCommits(activeProjection)
653
- : [];
654
- const commits = commitProjections.map(commit => (0, turn_commit_1.parseTurnCommitV1)(commit.receipt));
655
- const latestCommit = commits.at(-1);
656
- const latestProjectedTurn = activeProjection
657
- ? Object.values(activeProjection.turns)
658
- .sort((left, right) => left.startedSeq - right.startedSeq)
659
- .at(-1)
660
- : undefined;
661
- const durableTerminal = latestProjectedTurn?.status ?? indexedPage?.latestTurn?.status ?? latestCommit?.terminal;
662
- const recoverableTerminalPhase = durableTerminal === 'interrupted' || durableTerminal === 'failed'
663
- ? durableTerminal
664
- : undefined;
665
- const sessionRuntime = recoverableTerminalPhase &&
666
- ['cold', 'idle', 'interrupted', 'failed'].includes(baseSessionRuntime.phase)
667
- ? Object.freeze({ ...baseSessionRuntime, phase: recoverableTerminalPhase })
668
- : baseSessionRuntime;
669
- const planCommit = [...commits].reverse().find(commit => commit.planReceipt);
670
- const plan = planCommit?.planReceipt
671
- ? pickPlanReceipt((0, turn_commit_1.parsePlanReceiptV1)(planCommit.planReceipt))
672
- : null;
673
- const state = (actor?.runtime ?? this.runtimeValue).store.getSnapshot();
674
- const pendingPermissions = active
675
- ? actor.controller.getPendingPermissions().map(request => ({
676
- id: request.id,
677
- toolName: request.name,
678
- ...(request.reason ? { reason: request.reason } : {}),
679
- sanitizedArguments: request.args,
680
- allowedScopes: ['once', 'project', 'global'],
681
- }))
682
- : [];
683
- const projectionStatus = activeProjection?.status ?? (indexedPage || view ? 'idle' : 'legacy');
684
- const goal = latestCommit?.goalState && latestCommit.goalStateDigest
685
- ? {
686
- authority: 'turn_commit',
687
- digest: latestCommit.goalStateDigest,
688
- state: JSON.parse(latestCommit.goalState),
689
- }
690
- : null;
691
- const projectedComposer = actor
692
- ? this.projectActorComposerState(actor, session)
693
- : this.projectComposerStateValue(session, undefined, indexedPage?.planReview);
694
- const composer = projectedComposer.sessionRuntime.phase === sessionRuntime.phase
695
- ? projectedComposer
696
- : Object.freeze({ ...projectedComposer, sessionRuntime });
697
- const snapshot = Object.freeze({
698
- apiVersion: protocol_1.WEB_API_VERSION,
699
- session: (0, protocol_1.projectSessionSummary)(session),
700
- sessionRuntime,
701
- threadId: activeProjection?.threadId ?? indexedPage?.threadId ?? view?.threadId ?? null,
702
- threadCursor: activeProjection?.cursor ?? indexedPage?.cursor ?? view?.cursor ?? 0,
703
- eventCursor: this.eventHub.snapshot().latest,
704
- ...(activeProjection?.digest || indexedPage?.projectionDigest || view?.projectionDigest
705
- ? {
706
- projectionDigest: activeProjection?.digest ?? indexedPage?.projectionDigest ?? view?.projectionDigest,
707
- }
708
- : {}),
709
- threadStatus: projectionStatus,
710
- ...(activeProjection?.activeTurnId ? { activeTurnId: activeProjection.activeTurnId } : {}),
711
- transcript,
712
- runtime: {
713
- active,
714
- processing: active ? state.isProcessing : false,
715
- agentMode: state.agentMode,
716
- permissionMode: state.permissionMode,
717
- status: actor?.latestStatus ?? 'Ready',
718
- followups: active ? Object.freeze([...actor.controller.getFollowupQueue()]) : [],
719
- followupLimit: 16,
720
- contextUsage: active ? state.contextUsage : null,
721
- tokenUsage: active ? state.tokenUsage : null,
722
- },
723
- pendingApprovals: Object.freeze(pendingPermissions),
724
- goal,
725
- plan,
726
- composer,
727
- recoveryDiagnostics: indexedPage ? [] : (view?.diagnostics ?? []),
728
- });
729
- if (context)
730
- this.assertContextGuard(context);
731
- return snapshot;
732
- }
733
- recordSessionSnapshotActivity(startedAt, failed = false) {
734
- const elapsedMs = Date.now() - startedAt;
735
- this.sessionActivity.snapshotRequests += 1;
736
- if (failed)
737
- this.sessionActivity.snapshotFailures += 1;
738
- this.sessionActivity.snapshotTotalMs += elapsedMs;
739
- this.sessionActivity.snapshotLastMs = elapsedMs;
740
- }
741
- composerState(sessionId, context) {
742
- if (context)
743
- this.assertContextGuard(context);
744
- const session = requireSession(sessionId);
745
- this.assertSessionWorkspace(session);
746
- const actor = this.sessionRegistry.residentActor(this.sessionActorKey(session))?.actor;
747
- const state = actor
748
- ? this.projectActorComposerState(actor, session)
749
- : this.projectComposerStateValue(session);
750
- if (context)
751
- this.assertContextGuard(context);
752
- return state;
753
- }
754
- sessionRuntimeSummary(sessionId) {
755
- const session = requireSession(sessionId);
756
- this.assertSessionWorkspace(session);
757
- return this.sessionRegistry.summary(this.sessionActorKey(session));
758
- }
759
- async waitForSessionIdle(sessionId) {
760
- const session = requireSession(sessionId);
761
- this.assertSessionWorkspace(session);
762
- const actor = this.sessionRegistry.residentActor(this.sessionActorKey(session))?.actor;
763
- await actor?.controller.waitForIdle();
764
- }
765
- projectActorComposerState(actor, session) {
766
- const state = this.projectComposerStateValue(session, actor);
767
- // Durable Thread and Store authority can advance before the debounced SSE
768
- // observer runs. Keep every projected control state and its CAS token in
769
- // the same synchronous boundary so the UI never receives new controls
770
- // paired with an older revision.
771
- const authorityDigest = composerAuthorityDigest(state);
772
- if (actor.composerAuthorityDigest === undefined) {
773
- actor.composerAuthorityDigest = authorityDigest;
774
- return state;
775
- }
776
- if (authorityDigest === actor.composerAuthorityDigest)
777
- return state;
778
- actor.composerRevision = (0, crypto_1.randomUUID)();
779
- actor.composerAuthorityDigest = authorityDigest;
780
- return Object.freeze({ ...state, controlRevision: actor.composerRevision });
781
- }
782
- projectComposerStateValue(session, actor, indexedPlanReview) {
783
- const runtimeOwner = actor?.runtime ?? this.runtimeValue;
784
- const controller = actor?.controller;
785
- const controls = runtimeOwner.sessionComposerControls;
786
- if (!controls) {
787
- throw new errors_1.WebWorkbenchError(503, 'Session Composer controls are unavailable.', 'composer_controls_unavailable');
788
- }
789
- const runtime = controls.describeSession(session);
790
- const queue = actor
791
- ? actor.controller.getFollowupQueueSnapshot()
792
- : { items: [], limit: 16 };
793
- const projection = actor
794
- ? this.activeOrionRuntimes.get(session.id)?.thread.getProjection()
795
- : undefined;
796
- const review = projection?.planReview ?? indexedPlanReview;
797
- const workspaceId = this.workspaceRegistry
798
- .list()
799
- .find(entry => entry.canonicalPath === canonicalDirectory(session.projectPath))?.id;
800
- if (!workspaceId) {
801
- throw new errors_1.WebWorkbenchError(404, 'Workspace was not found.', 'workspace_not_found');
802
- }
803
- const sessionRuntime = this.sessionRegistry.summary({ workspaceId, sessionId: session.id });
804
- return Object.freeze({
805
- apiVersion: protocol_1.WEB_API_VERSION,
806
- workspaceId,
807
- sessionId: session.id,
808
- contextRevision: this.contextRevisionValue,
809
- controlRevision: actor?.composerRevision ?? sessionRuntime.runtimeRevision,
810
- sessionRuntime,
811
- processing: Boolean(actor) &&
812
- (runtimeOwner.store.getSnapshot().isProcessing || Boolean(projection?.activeTurnId)),
813
- mode: controller
814
- ? Object.freeze({ ...controller.getAgentModeSnapshot() })
815
- : Object.freeze({ baseMode: 'interactive', pendingBaseMode: null }),
816
- model: runtime.model,
817
- permission: runtime.permission,
818
- contextUsage: runtime.contextUsage,
819
- compactAvailable: controller?.canCompactContext() ?? false,
820
- pending: runtime.pending,
821
- lastError: runtime.lastError,
822
- planReview: review
823
- ? Object.freeze({
824
- planDigest: review.planDigest,
825
- revision: review.revision,
826
- status: review.status,
827
- createdAt: review.createdAt,
828
- createdModel: review.createdModel,
829
- returnMode: review.returnMode,
830
- ...(review.resolvedAt === undefined ? {} : { resolvedAt: review.resolvedAt }),
831
- })
832
- : null,
833
- queue: Object.freeze({
834
- items: Object.freeze(queue.items.map(item => Object.freeze({ ...item }))),
835
- limit: queue.limit,
836
- }),
837
- });
838
- }
839
- modelCatalog(sessionId, context) {
840
- if (context)
841
- this.assertContextGuard(context);
842
- const session = requireSession(sessionId);
843
- this.assertSessionWorkspace(session);
844
- const actor = this.sessionRegistry.residentActor(this.sessionActorKey(session))?.actor;
845
- const controls = (actor?.runtime ?? this.runtimeValue).sessionComposerControls;
846
- if (!controls) {
847
- throw new errors_1.WebWorkbenchError(503, 'Session model catalog is unavailable.', 'composer_controls_unavailable');
848
- }
849
- const catalog = controls.catalog();
850
- if (context)
851
- this.assertContextGuard(context);
852
- return catalog;
853
- }
854
- async applyComposerAction(input) {
855
- this.assertContextGuard(input);
856
- const session = requireSession(input.expectedSessionId);
857
- this.assertSessionWorkspace(session);
858
- const key = this.sessionActorKey(session);
859
- const wasResident = this.sessionRegistry.summary(key).resident;
860
- let actor;
861
- try {
862
- actor = (await this.sessionRegistry.ensureResident(key, input.expectedSessionRuntimeRevision))
863
- .actor;
864
- }
865
- catch (error) {
866
- throw mapSessionRuntimeError(error);
867
- }
868
- const actorSession = actor.runtime.getSession();
869
- if (!actorSession || actorSession.id !== input.expectedSessionId) {
870
- throw new errors_1.WebWorkbenchError(503, 'Session actor is not bound to the expected Session.', 'session_unavailable');
871
- }
872
- if (!wasResident)
873
- actor.composerRevision = input.expectedControlRevision;
874
- const admittedState = this.projectActorComposerState(actor, actorSession);
875
- if (input.expectedControlRevision !== admittedState.controlRevision) {
876
- throw new errors_1.WebWorkbenchError(409, 'Composer controls changed before the action was admitted.', 'composer_control_conflict');
877
- }
878
- const controls = actor.runtime.sessionComposerControls;
879
- if (!controls) {
880
- throw new errors_1.WebWorkbenchError(503, 'Session Composer controls are unavailable.', 'composer_controls_unavailable');
881
- }
882
- let outcome = 'applied';
883
- let detail;
884
- let modelReceipt;
885
- let permissionReceipt;
886
- let planReviewReceipt;
887
- actor.suppressComposerEdges += 1;
888
- try {
889
- switch (input.type) {
890
- case 'set_agent_mode': {
891
- const result = actor.controller.setAgentMode(input.mode);
892
- outcome =
893
- result.type === 'agent_mode_changed' && result.appliesFrom === 'next-logical-request'
894
- ? 'deferred'
895
- : 'applied';
896
- detail = JSON.stringify(result);
897
- break;
898
- }
899
- case 'set_permission_override':
900
- permissionReceipt = await controls.setPermissionOverride(input.value);
901
- outcome = permissionReceipt.appliesFrom === 'immediate' ? 'applied' : 'deferred';
902
- break;
903
- case 'clear_permission_override':
904
- permissionReceipt = await controls.setPermissionOverride(null);
905
- outcome = permissionReceipt.appliesFrom === 'immediate' ? 'applied' : 'deferred';
906
- break;
907
- case 'select_model':
908
- modelReceipt = await controls.selectModel({
909
- modelId: input.modelId,
910
- ...(input.effort ? { effort: input.effort } : {}),
911
- });
912
- outcome = modelReceipt.appliesFrom === 'next-logical-request' ? 'deferred' : 'applied';
913
- break;
914
- case 'compact_context': {
915
- const result = await actor.controller.compactContext();
916
- if (result.status === 'rejected') {
917
- throw new errors_1.WebWorkbenchError(409, 'Context compact was rejected.', 'runtime_busy');
918
- }
919
- detail = JSON.stringify(result);
920
- break;
921
- }
922
- case 'edit_queue_item':
923
- detail = JSON.stringify(actor.controller.editFollowupQueueItem(input.itemId, input.expectedItemRevision, input.text));
924
- break;
925
- case 'move_queue_item':
926
- detail = JSON.stringify(actor.controller.moveFollowupQueueItem(input.itemId, input.expectedItemRevision, input.targetIndex));
927
- break;
928
- case 'remove_queue_item':
929
- detail = JSON.stringify(actor.controller.removeFollowupQueueItem(input.itemId, input.expectedItemRevision));
930
- break;
931
- case 'review_plan': {
932
- planReviewReceipt = await actor.controller.reviewPlan({
933
- planDigest: input.planDigest,
934
- action: input.action,
935
- ...(input.feedback ? { feedback: input.feedback } : {}),
936
- });
937
- if (input.action === 'approve')
938
- actor.controller.setAgentMode('interactive');
939
- else if (input.action === 'continue')
940
- actor.controller.setAgentMode('plan');
941
- detail = JSON.stringify(planReviewReceipt.admission);
942
- break;
943
- }
944
- }
945
- }
946
- catch (error) {
947
- throw mapComposerControlError(error);
948
- }
949
- finally {
950
- actor.suppressComposerEdges -= 1;
951
- }
952
- actor.composerRevision = (0, crypto_1.randomUUID)();
953
- const state = this.projectComposerStateValue(actorSession, actor);
954
- actor.composerAuthorityDigest = composerAuthorityDigest(state);
955
- this.eventHub.emit({ type: 'composer_state_changed', state }, true, {
956
- sessionId: input.expectedSessionId,
957
- });
958
- return Object.freeze({
959
- requestId: input.requestId,
960
- outcome,
961
- controlRevision: actor.composerRevision,
962
- state,
963
- ...(modelReceipt ? { modelReceipt } : {}),
964
- ...(permissionReceipt ? { permissionReceipt } : {}),
965
- ...(planReviewReceipt ? { planReviewReceipt } : {}),
966
- ...(detail ? { detail } : {}),
967
- });
968
- }
969
- async skills(context) {
970
- if (context)
971
- this.assertContextGuard(context);
972
- const descriptors = (await this.runtimeValue.inspectSkills?.()) ?? [];
973
- const result = Object.freeze(descriptors.map(descriptor => Object.freeze({
974
- id: descriptor.id,
975
- name: descriptor.name,
976
- description: descriptor.description,
977
- providerId: descriptor.providerId,
978
- sourceScope: descriptor.sourceScope,
979
- modelInvocable: descriptor.modelInvocable,
980
- userInvocable: descriptor.userInvocable,
981
- requestedCapabilities: Object.freeze([...descriptor.requestedCapabilities]),
982
- digest: descriptor.digest,
983
- })));
984
- if (context)
985
- this.assertContextGuard(context);
986
- return result;
987
- }
988
- mcp(context) {
989
- if (context)
990
- this.assertContextGuard(context);
991
- const descriptors = this.runtimeValue.inspectMcp?.() ?? [];
992
- let runtimeServers = new Map();
993
- try {
994
- runtimeServers = new Map((this.activeOrionRuntime?.runtime.diagnostics().mcp.servers ?? []).map(server => [
995
- server.serverId,
996
- server,
997
- ]));
998
- }
999
- catch {
1000
- // A concurrent session transition may close the previous diagnostics graph.
1001
- }
1002
- const result = Object.freeze(descriptors.map(descriptor => {
1003
- const runtime = runtimeServers.get(descriptor.id);
1004
- return Object.freeze({
1005
- id: descriptor.id,
1006
- name: descriptor.name,
1007
- ...(descriptor.description ? { description: descriptor.description } : {}),
1008
- transport: descriptor.transport,
1009
- tags: Object.freeze([...(descriptor.tags ?? [])]),
1010
- disabled: descriptor.disabled ?? false,
1011
- state: runtime?.state ?? 'dormant',
1012
- generation: runtime?.generation ?? 0,
1013
- toolCount: runtime?.toolCount ?? 0,
1014
- activeCallCount: runtime?.activeCallCount ?? 0,
1015
- ...(runtime?.failure
1016
- ? { failure: 'Runtime transport failure. See local Host diagnostics for details.' }
1017
- : {}),
1018
- });
1019
- }));
1020
- if (context)
1021
- this.assertContextGuard(context);
1022
- return result;
1023
- }
1024
- async listToolDetails(context) {
1025
- if (context)
1026
- this.assertContextGuard(context);
1027
- const result = Object.freeze(await this.toolDetails.list(this.workspaceValue));
1028
- if (context)
1029
- this.assertContextGuard(context);
1030
- return result;
1031
- }
1032
- async readToolDetail(callId, offsetBytes, limitBytes, context) {
1033
- if (context)
1034
- this.assertContextGuard(context);
1035
- const entry = (await this.toolDetails.list(this.workspaceValue)).find(detail => detail.callId === callId || detail.artifactId === callId);
1036
- if (!entry?.artifactId)
1037
- throw new errors_1.WebWorkbenchError(404, 'Tool detail was not found.');
1038
- const result = await this.toolDetails.read({
1039
- callId: entry.callId,
1040
- sequence: entry.sequence,
1041
- artifactId: entry.artifactId,
1042
- outputBytes: entry.outputBytes,
1043
- }, { offsetBytes, limitBytes }, this.workspaceValue);
1044
- if (context)
1045
- this.assertContextGuard(context);
1046
- return result;
1047
- }
1048
- listFiles(context, input) {
1049
- this.assertContextGuard(context);
1050
- const result = this.fileService.list(input);
1051
- this.assertContextGuard(context);
1052
- return result;
1053
- }
1054
- readFileContent(context, input) {
1055
- this.assertContextGuard(context);
1056
- const result = this.fileService.readContent(input);
1057
- this.assertContextGuard(context);
1058
- return result;
1059
- }
1060
- /** v0.3.14 — guarded CAS write for an existing in-root text file. */
1061
- writeFileContent(context, input) {
1062
- this.assertContextGuard(context);
1063
- const result = this.fileWriteService.writeContent(input);
1064
- this.assertContextGuard(context);
1065
- return result;
1066
- }
1067
- async gitStatus(context, input) {
1068
- this.assertContextGuard(context);
1069
- const result = await this.gitService.status(input);
1070
- this.assertContextGuard(context);
1071
- return result;
1072
- }
1073
- searchFiles(context, input) {
1074
- this.assertContextGuard(context);
1075
- const result = this.fileService.search(input);
1076
- return Object.freeze({
1077
- revision: this.fileContextRevision(),
1078
- items: Object.freeze(result.items.map(item => Object.freeze({
1079
- id: item.id,
1080
- name: item.name,
1081
- path: item.path,
1082
- }))),
1083
- truncated: result.truncated,
1084
- });
1085
- }
1086
- /** v0.3.12 S3 — guarded stage/unstage/commit with repository revision CAS. */
1087
- async gitStage(context, input) {
1088
- this.assertContextGuard(context);
1089
- const paths = this.gitService.resolveMutationPaths('stage', input.fileIds);
1090
- await this.assertGitRepositoryRevision(input.expectedRepositoryRevision);
1091
- return this.gitService.stagePaths(paths);
1092
- }
1093
- async gitUnstage(context, input) {
1094
- this.assertContextGuard(context);
1095
- const paths = this.gitService.resolveMutationPaths('unstage', input.fileIds);
1096
- await this.assertGitRepositoryRevision(input.expectedRepositoryRevision);
1097
- return this.gitService.unstagePaths(paths);
1098
- }
1099
- /**
1100
- * v0.3.17 S4 — history reads.
1101
- *
1102
- * Read-only by construction: they are registered as queries, so none of them can reach the
1103
- * mutation path (`assertMutation` / `executeMutation` are never involved). That is what
1104
- * makes "browsing history never writes to the workspace" a structural property rather than
1105
- * a promise.
1106
- */
1107
- /**
1108
- * v0.3.17 S6 — translate a Git file token into a Files token (plan G7).
1109
- *
1110
- * The browser never derives one token from the other: the Git token is resolved to a
1111
- * workspace-relative path here, and only the FileReadService mints the Files-side id.
1112
- * That keeps the two id spaces from leaking into each other.
1113
- */
1114
- async gitFilesTarget(context, gitFileToken) {
1115
- this.assertContextGuard(context);
1116
- const target = this.gitService.resolveTarget(gitFileToken);
1117
- const filesToken = this.fileService.identifyRelativePath(target.path);
1118
- this.assertContextGuard(context);
1119
- return Object.freeze({
1120
- path: target.path,
1121
- source: target.source,
1122
- filesToken,
1123
- });
1124
- }
1125
- async gitRefs(context) {
1126
- this.assertContextGuard(context);
1127
- const result = await this.gitService.refs();
1128
- this.assertContextGuard(context);
1129
- return result;
1130
- }
1131
- async gitHistory(context, query) {
1132
- this.assertContextGuard(context);
1133
- const result = await this.gitService.history(query);
1134
- this.assertContextGuard(context);
1135
- return result;
1136
- }
1137
- async gitCommitDetail(context, oid, parentIndex = 0) {
1138
- this.assertContextGuard(context);
1139
- const result = await this.gitService.commitDetail(oid, parentIndex);
1140
- this.assertContextGuard(context);
1141
- return result;
1142
- }
1143
- async gitCommitFiles(context, oid, parentIndex = 0) {
1144
- this.assertContextGuard(context);
1145
- const result = await this.gitService.commitFiles(oid, parentIndex);
1146
- this.assertContextGuard(context);
1147
- return result;
1148
- }
1149
- async gitCommitDiff(context, input) {
1150
- this.assertContextGuard(context);
1151
- const result = await this.gitService.commitDiffDocument(input);
1152
- this.assertContextGuard(context);
1153
- return result;
1154
- }
1155
- /**
1156
- * v0.3.17 S5 — branch/version comparison. Registered as a query: the compare view can
1157
- * never reach the mutation path.
1158
- */
1159
- async gitCompare(context, input) {
1160
- this.assertContextGuard(context);
1161
- const result = await this.gitService.compare(input);
1162
- this.assertContextGuard(context);
1163
- return result;
1164
- }
1165
- async gitCompareFileDiff(context, input) {
1166
- this.assertContextGuard(context);
1167
- const result = await this.gitService.compareFileDiffDocument(input);
1168
- this.assertContextGuard(context);
1169
- return result;
1170
- }
1171
- /** v0.3.17 S5 — the commit graph, as git itself drew it. Read-only. */
1172
- async gitGraph(context, input) {
1173
- this.assertContextGuard(context);
1174
- const result = await this.gitService.graph(input);
1175
- this.assertContextGuard(context);
1176
- return result;
1177
- }
1178
- async gitBlame(context, input) {
1179
- this.assertContextGuard(context);
1180
- const result = await this.gitService.blame(input);
1181
- this.assertContextGuard(context);
1182
- return result;
1183
- }
1184
- /**
1185
- * v0.3.17 S5 — conflict stages, historical blobs and gitlink entries. All query-only.
1186
- */
1187
- async gitConflictVersions(context, path) {
1188
- this.assertContextGuard(context);
1189
- const result = await this.gitService.conflictVersions(path);
1190
- this.assertContextGuard(context);
1191
- return result;
1192
- }
1193
- async gitBlob(context, input) {
1194
- this.assertContextGuard(context);
1195
- const result = await this.gitService.fileBlob(input);
1196
- this.assertContextGuard(context);
1197
- return result;
1198
- }
1199
- async gitSubmodules(context) {
1200
- this.assertContextGuard(context);
1201
- const result = await this.gitService.submodules();
1202
- this.assertContextGuard(context);
1203
- return result;
1204
- }
1205
- async gitFileHistory(context, input) {
1206
- this.assertContextGuard(context);
1207
- const result = await this.gitService.fileHistory(input);
1208
- this.assertContextGuard(context);
1209
- return result;
1210
- }
1211
- /** v0.3.17 S3 — preview of what the index would commit, independent of list filters. */
1212
- async gitCommitPreview(context) {
1213
- this.assertContextGuard(context);
1214
- const result = await this.gitService.commitPreview();
1215
- this.assertContextGuard(context);
1216
- return result;
1217
- }
1218
- /**
1219
- * v0.3.17 S3 — commit against the frozen revision the form showed. Identity, signing and
1220
- * hooks come from the repository's own configuration (plan §7.9).
1221
- */
1222
- async gitCommit(context, input) {
1223
- this.assertContextGuard(context);
1224
- const result = await this.gitService.commit(input);
1225
- this.assertContextGuard(context);
1226
- return result;
1227
- }
1228
- /** v0.3.17 S3 — Host-rebuilt hunk or line selection applied to the index only. */
1229
- async gitApplyPatch(context, input) {
1230
- this.assertContextGuard(context);
1231
- await this.assertGitRepositoryRevision(input.expectedRepositoryRevision);
1232
- const result = await this.gitService.applySelection(input);
1233
- this.assertContextGuard(context);
1234
- return result;
1235
- }
1236
- /** v0.3.17 S2 — structured diff document for the selected comparison source. */
1237
- async gitDiffDocument(context, input) {
1238
- this.assertContextGuard(context);
1239
- const result = await this.gitService.diffDocument(input);
1240
- this.assertContextGuard(context);
1241
- return result;
1242
- }
1243
- async assertGitRepositoryRevision(expected) {
1244
- if (typeof expected !== 'string' || !/^[0-9a-f]{40,64}$/u.test(expected)) {
1245
- throw new errors_1.WebWorkbenchError(400, 'expectedRepositoryRevision is invalid.');
1246
- }
1247
- const status = await this.gitService.status({ pageSize: 1 });
1248
- if (status.repositoryRevision !== expected) {
1249
- throw new errors_1.WebWorkbenchError(409, 'The repository changed before the operation could run.', 'git_revision_conflict');
1250
- }
1251
- }
1252
- fileContextRevision() {
1253
- const node = this.fileService;
1254
- return typeof node.rootRevision === 'function' ? node.rootRevision() : '';
1255
- }
1256
- async gitLog(context, input) {
1257
- this.assertContextGuard(context);
1258
- const result = await this.gitService.log(input);
1259
- this.assertContextGuard(context);
1260
- return result;
1261
- }
1262
- async gitDiff(context, input) {
1263
- this.assertContextGuard(context);
1264
- const result = await this.gitService.diff(input);
1265
- this.assertContextGuard(context);
1266
- return result;
1267
- }
1268
- async review(context) {
1269
- this.assertContextGuard(context);
1270
- const result = await this.reviewService.snapshot();
1271
- this.assertContextGuard(context);
1272
- return result;
1273
- }
1274
- /** v0.3.29 — starts a shared code review run (fast admission, background run). */
1275
- async reviewRunStart(selector, context) {
1276
- this.assertContextGuard(context);
1277
- const started = await this.codeReviewRuns.start(selector);
1278
- this.assertContextGuard(context);
1279
- return started;
1280
- }
1281
- /** v0.3.29 — bounded list of review runs with freshness flags. */
1282
- async reviewRunList(context) {
1283
- this.assertContextGuard(context);
1284
- const runs = await this.codeReviewRuns.list();
1285
- this.assertContextGuard(context);
1286
- return runs;
1287
- }
1288
- /** v0.3.29 — one review run record with digest re-verification. */
1289
- async reviewRunGet(runId, context) {
1290
- this.assertContextGuard(context);
1291
- const run = await this.codeReviewRuns.get(runId);
1292
- this.assertContextGuard(context);
1293
- return run;
1294
- }
1295
- /** v0.3.29 — cancels a running review to release the single in-flight slot. */
1296
- reviewRunCancel(runId, context) {
1297
- this.assertContextGuard(context);
1298
- this.codeReviewRuns.cancel(runId);
1299
- this.assertContextGuard(context);
1300
- return { cancelled: true };
1301
- }
1302
- listTerminals(context) {
1303
- this.assertContextGuard(context);
1304
- const result = this.terminalManager.list(this.activeWorkspaceEntry().id);
1305
- this.assertContextGuard(context);
1306
- return result;
1307
- }
1308
- async createSession(name, context) {
1309
- if (context)
1310
- this.assertContextGuard(context);
1311
- // A new Session inherits the durable default; an override on another
1312
- // Session actor must never leak into it. Creation does not activate or
1313
- // close any actor; foreground selection belongs to the browser tab.
1314
- const workspace = this.workspaceValue;
1315
- const creationContext = context ?? {
1316
- workspaceId: this.activeWorkspaceEntry().id,
1317
- expectedContextRevision: this.contextRevisionValue,
1318
- };
1319
- const gitBranch = await probeSessionGitBranch(workspace);
1320
- // Git is optional metadata, but its asynchronous boundary must not allow a
1321
- // stale browser to create a Session in a newly selected Workspace.
1322
- this.assertContextGuard(creationContext);
1323
- let named;
1324
- try {
1325
- await (0, paths_1.resolveProjectStoragePathAsync)(workspace);
1326
- this.assertContextGuard(creationContext);
1327
- named = await (0, session_storage_1.createSessionAsync)(workspace, this.settings().sections.defaults.model.effectiveValue, {
1328
- gitBranch,
1329
- name,
1330
- beforeCommit: () => this.assertContextGuard(creationContext),
1331
- });
1332
- }
1333
- catch (error) {
1334
- if (error instanceof paths_1.ProjectStorageIdentityUnavailableError) {
1335
- throw new errors_1.WebWorkbenchError(503, error.message, error.code);
1336
- }
1337
- throw error;
1338
- }
1339
- (0, global_config_1.incrementSessionCount)();
1340
- this.sessionRegistry.summary(this.sessionActorKey(named));
1341
- return (0, protocol_1.projectSessionSummary)(named);
1342
- }
1343
- async activateSession(sessionId, context) {
1344
- if (context)
1345
- this.assertContextGuard(context);
1346
- const session = requireSession(sessionId);
1347
- this.assertSessionWorkspace(session);
1348
- const sessionRuntime = this.sessionRegistry.summary(this.sessionActorKey(session));
1349
- return {
1350
- requestId: `activate:${session.id}`,
1351
- result: 'foreground_session_selected',
1352
- sessionRuntime,
1353
- };
1354
- }
1355
- renameSession(sessionId, name, context) {
1356
- if (context)
1357
- this.assertContextGuard(context);
1358
- const session = requireSession(sessionId);
1359
- if (canonicalDirectory(session.projectPath) !== this.workspaceValue) {
1360
- throw new errors_1.WebWorkbenchError(409, 'Session belongs to another workspace.');
1361
- }
1362
- const normalizedName = name.trim();
1363
- if (!normalizedName)
1364
- throw new errors_1.WebWorkbenchError(400, 'Session name is required.');
1365
- if (normalizedName.length > 120)
1366
- throw new errors_1.WebWorkbenchError(400, 'Session name is too long.');
1367
- const updated = (0, session_storage_1.renameSession)(session.id, normalizedName);
1368
- if (!updated)
1369
- throw new errors_1.WebWorkbenchError(404, 'Session no longer exists.');
1370
- return (0, protocol_1.projectSessionSummary)(updated);
1371
- }
1372
- setSessionTags(sessionId, tags, context) {
1373
- if (context)
1374
- this.assertContextGuard(context);
1375
- const session = requireSession(sessionId);
1376
- this.assertSessionWorkspace(session);
1377
- if (!Array.isArray(tags)) {
1378
- throw new errors_1.WebWorkbenchError(400, 'Tags must be an array of strings.', 'invalid_tags');
1379
- }
1380
- if (tags.length > session_storage_1.SESSION_TAG_LIMIT) {
1381
- throw new errors_1.WebWorkbenchError(400, `A session can have at most ${session_storage_1.SESSION_TAG_LIMIT} tags.`, 'invalid_tags');
1382
- }
1383
- for (const raw of tags) {
1384
- if (typeof raw !== 'string' || !raw.trim()) {
1385
- throw new errors_1.WebWorkbenchError(400, 'Every tag must be a non-empty string.', 'invalid_tags');
1386
- }
1387
- if (raw.trim().length > session_storage_1.SESSION_TAG_MAX_LENGTH) {
1388
- throw new errors_1.WebWorkbenchError(400, `Each tag is limited to ${session_storage_1.SESSION_TAG_MAX_LENGTH} characters.`, 'invalid_tags');
1389
- }
1390
- }
1391
- const updated = (0, session_storage_1.setSessionTags)(session.id, (0, session_storage_1.normalizeSessionTags)(tags));
1392
- if (!updated)
1393
- throw new errors_1.WebWorkbenchError(404, 'Session no longer exists.');
1394
- return (0, protocol_1.projectSessionSummary)(updated);
1395
- }
1396
- archiveSession(sessionId, context) {
1397
- if (context)
1398
- this.assertContextGuard(context);
1399
- const session = requireSession(sessionId);
1400
- this.assertSessionWorkspace(session);
1401
- this.assertSessionNotBusy(session);
1402
- const updated = (0, session_storage_1.archiveSession)(session.id);
1403
- if (!updated)
1404
- throw new errors_1.WebWorkbenchError(404, 'Session no longer exists.');
1405
- return (0, protocol_1.projectSessionSummary)(updated);
1406
- }
1407
- restoreSession(sessionId, context) {
1408
- if (context)
1409
- this.assertContextGuard(context);
1410
- const session = requireSession(sessionId);
1411
- this.assertSessionWorkspace(session);
1412
- const updated = (0, session_storage_1.restoreSession)(session.id);
1413
- if (!updated)
1414
- throw new errors_1.WebWorkbenchError(404, 'Session no longer exists.');
1415
- return (0, protocol_1.projectSessionSummary)(updated);
1416
- }
1417
- deleteSession(sessionId, context) {
1418
- if (context)
1419
- this.assertContextGuard(context);
1420
- const session = requireSession(sessionId);
1421
- this.assertSessionWorkspace(session);
1422
- this.assertSessionHasNoActor(session);
1423
- const removed = (0, session_storage_1.deleteSession)(session.id);
1424
- if (!removed) {
1425
- throw new errors_1.WebWorkbenchError(409, 'Session files could not be fully removed; nothing was deleted.', 'session_delete_failed');
1426
- }
1427
- return { deleted: true };
1428
- }
1429
- /**
1430
- * A busy Session (starting / queued / running / waiting approval / stopping)
1431
- * must not be archived or deleted while its actor is doing work.
1432
- */
1433
- assertSessionNotBusy(session) {
1434
- const runtime = this.sessionRegistry.summary(this.sessionActorKey(session));
1435
- const busy = new Set(['starting', 'queued', 'running', 'waiting_approval', 'stopping']);
1436
- if (busy.has(runtime.phase)) {
1437
- throw new errors_1.WebWorkbenchError(409, 'Session is busy; stop it before archiving or deleting.', 'session_busy');
1438
- }
1439
- }
1440
- /**
1441
- * Deletion removes files under the Session while a resident actor may still
1442
- * hold them open — require that no actor exists at all (phase 'cold').
1443
- */
1444
- assertSessionHasNoActor(session) {
1445
- const resident = this.sessionRegistry.residentActor(this.sessionActorKey(session));
1446
- if (resident) {
1447
- throw new errors_1.WebWorkbenchError(409, 'Session has an active runtime; stop it before deleting.', 'session_busy');
1448
- }
1449
- }
1450
- async switchWorkspace(path, context, requestId) {
1451
- this.assertContextGuard(context);
1452
- const next = canonicalDirectory(path);
1453
- if (next === this.workspaceValue)
1454
- return;
1455
- let entry;
1456
- try {
1457
- entry = this.workspaceRegistry.register(next);
1458
- }
1459
- catch (error) {
1460
- throw mapWorkspaceRegistryError(error);
1461
- }
1462
- await this.activateContext({
1463
- expectedContextRevision: context.expectedContextRevision,
1464
- workspaceId: entry.id,
1465
- sessionId: null,
1466
- ...(requestId ? { requestId } : {}),
1467
- });
1468
- }
1469
- async activateContext(input) {
1470
- if (input.expectedContextRevision !== this.contextRevisionValue) {
1471
- throw new errors_1.WebWorkbenchError(409, 'The active Context changed before activation was admitted.', 'context_revision_conflict');
1472
- }
1473
- const entry = this.workspaceRegistry.find(input.workspaceId);
1474
- if (!entry)
1475
- throw new errors_1.WebWorkbenchError(404, 'Workspace was not found.', 'workspace_not_found');
1476
- const targetWorkspace = canonicalDirectory(entry.canonicalPath);
1477
- const targetSession = input.sessionId ? requireSession(input.sessionId) : null;
1478
- if (targetSession && canonicalDirectory(targetSession.projectPath) !== targetWorkspace) {
1479
- throw new errors_1.WebWorkbenchError(409, 'Session does not belong to the requested Workspace.', 'context_session_mismatch');
1480
- }
1481
- const currentSessionId = this.runtimeValue.getSession()?.id ?? null;
1482
- if (targetWorkspace === this.workspaceValue) {
1483
- if (targetSession)
1484
- this.sessionRegistry.summary(this.sessionActorKey(targetSession));
1485
- // Session foreground selection is browser-local. A same-Workspace
1486
- // selection never mutates the Host Context or any Session actor.
1487
- return;
1488
- }
1489
- // v0.3.17 — trace the transition so "confirm → usable" can be attributed
1490
- // to a stage instead of guessed at.
1491
- const span = input.requestId
1492
- ? this.openTelemetry.start(input.requestId, 'activate')
1493
- : undefined;
1494
- span?.mark('activate_admitted');
1495
- this.assertReadyForTransition('activate a Context');
1496
- const previousWorkspace = this.workspaceValue;
1497
- const previousSessionId = currentSessionId;
1498
- const previousRuntime = this.runtimeValue;
1499
- const previousController = this.controllerValue;
1500
- const transition = (async () => {
1501
- this.suppressContextEdges += 1;
1502
- try {
1503
- await previousController.stopActiveTurn();
1504
- await previousController.waitForIdle();
1505
- if (targetWorkspace !== previousWorkspace) {
1506
- // Detach the control-plane foreground first: releasing the previous
1507
- // control plane must not end a Session that a resident actor of that
1508
- // Workspace is still driving.
1509
- await this.restoreContextSession(null);
1510
- // P1-A runtime ownership: the Host-level Session registry and its
1511
- // resident actors are preserved across a Workspace Context switch.
1512
- // Only the active control plane is swapped. Both control planes
1513
- // borrowed their Workspace kernel from the shared pool, so releasing
1514
- // the previous one never tears down kernels that running Session
1515
- // actors of that Workspace still reference. Install the target
1516
- // control plane first, then release the previous one's mutable state.
1517
- await this.installRuntime(targetWorkspace, false);
1518
- span?.mark('runtime_install');
1519
- await previousRuntime.shutdown();
1520
- span?.mark('previous_runtime_shutdown');
1521
- }
1522
- this.workspaceRegistry.register(targetWorkspace, { activated: true });
1523
- }
1524
- catch (activationError) {
1525
- try {
1526
- if (this.runtimeValue !== previousRuntime) {
1527
- // The target control plane installed but a later step failed; tear
1528
- // it down and reinstall the previous Workspace's control plane.
1529
- await this.runtimeValue.shutdown();
1530
- await this.installRuntime(previousWorkspace, false);
1531
- }
1532
- await this.restoreContextSession(previousSessionId);
1533
- }
1534
- catch {
1535
- throw new errors_1.WebWorkbenchError(503, 'Context activation failed and the previous Context could not be restored.', 'context_recovery_required');
1536
- }
1537
- throw activationError;
1538
- }
1539
- finally {
1540
- this.suppressContextEdges -= 1;
1541
- }
1542
- this.emitState();
1543
- this.emitWorkspaceResourceInvalidation('context-change');
1544
- if (targetWorkspace !== previousWorkspace)
1545
- this.emitSettingsWorkspaceChange();
1546
- })()
1547
- .then(() => {
1548
- if (span)
1549
- this.openTelemetry.record(span.finish('success'));
1550
- })
1551
- .catch(error => {
1552
- if (span) {
1553
- this.openTelemetry.record(span.finish('failed', error instanceof errors_1.WebWorkbenchError ? error.code : 'activate_error'));
1554
- }
1555
- throw error;
1556
- })
1557
- .finally(() => {
1558
- if (this.transition === transition)
1559
- this.transition = undefined;
1560
- });
1561
- this.transition = transition;
1562
- return transition;
1563
- }
1564
- dispatch(raw) {
1565
- const command = (0, protocol_1.parseWebCommand)(raw);
1566
- return this.executeMutation(command.requestId, 'command', command, async () => {
1567
- this.assertContextGuard(command);
1568
- const session = requireSession(command.expectedSessionId);
1569
- this.assertSessionWorkspace(session);
1570
- const key = this.sessionActorKey(session);
1571
- if (command.type === 'cancel_queued_turn') {
1572
- try {
1573
- const sessionRuntime = this.sessionRegistry.cancelQueued(key, command.queueId, command.expectedSessionRuntimeRevision);
1574
- return Object.freeze({
1575
- requestId: command.requestId,
1576
- result: 'session_turn_queue_cancelled',
1577
- sessionRuntime,
1578
- });
1579
- }
1580
- catch (error) {
1581
- throw mapSessionRuntimeError(error);
1582
- }
1583
- }
1584
- const resolved = await this.resolveCommandContext(command);
1585
- const runtimeInput = resolved && command.type === 'queue_followup'
1586
- ? {
1587
- type: 'queue_followup',
1588
- text: command.text,
1589
- resolvedText: resolved.text,
1590
- source: 'programmatic',
1591
- }
1592
- : (0, protocol_1.toAgentRuntimeInput)({ ...command, ...(resolved ? { text: resolved.text } : {}) });
1593
- try {
1594
- if (command.type === 'submit') {
1595
- const currentRuntime = this.sessionRegistry.summary(key);
1596
- if (['running', 'waiting_approval'].includes(currentRuntime.phase)) {
1597
- const routed = await this.sessionRegistry.withActor(key, command.expectedSessionRuntimeRevision, actor => {
1598
- if (!actor.controller.hasActiveTurn()) {
1599
- throw new session_runtime_registry_1.WebSessionRuntimeRegistryError(409, 'session_runtime_revision_conflict', 'The Session turn ended before steering was admitted.');
1600
- }
1601
- return actor.controller.handle(runtimeInput);
1602
- });
1603
- return Object.freeze({
1604
- requestId: command.requestId,
1605
- result: routed.result.type,
1606
- detail: JSON.stringify(routed.result),
1607
- sessionRuntime: routed.runtime,
1608
- ...(resolved ? { contextReceipt: resolved.receipt } : {}),
1609
- });
1610
- }
1611
- const admission = await this.sessionRegistry.admitTurn({
1612
- key,
1613
- expectedRuntimeRevision: command.expectedSessionRuntimeRevision,
1614
- start: async (actor) => {
1615
- const runtimeResult = actor.controller.handle(runtimeInput);
1616
- return {
1617
- accepted: runtimeResult,
1618
- settled: actor.controller.waitForIdle(),
1619
- };
1620
- },
1621
- });
1622
- if (admission.status === 'queued') {
1623
- return Object.freeze({
1624
- requestId: command.requestId,
1625
- result: 'session_turn_queued',
1626
- queueId: admission.queueId,
1627
- queuePosition: admission.queuePosition,
1628
- sessionRuntime: admission.runtime,
1629
- ...(resolved ? { contextReceipt: resolved.receipt } : {}),
1630
- });
1631
- }
1632
- return Object.freeze({
1633
- requestId: command.requestId,
1634
- result: admission.accepted.type,
1635
- detail: JSON.stringify(admission.accepted),
1636
- sessionRuntime: admission.runtime,
1637
- ...(resolved ? { contextReceipt: resolved.receipt } : {}),
1638
- });
1639
- }
1640
- const routed = await this.sessionRegistry.withActor(key, command.expectedSessionRuntimeRevision, actor => {
1641
- const runtimeResult = actor.controller.handle(runtimeInput);
1642
- if (command.type === 'permission_decision') {
1643
- this.sessionRegistry.setPendingApprovalCount(key, actor.controller.getPendingPermissions().length);
1644
- }
1645
- return runtimeResult;
1646
- });
1647
- return Object.freeze({
1648
- requestId: command.requestId,
1649
- result: routed.result.type,
1650
- detail: JSON.stringify(routed.result),
1651
- sessionRuntime: routed.runtime,
1652
- ...(resolved ? { contextReceipt: resolved.receipt } : {}),
1653
- });
1654
- }
1655
- catch (error) {
1656
- throw mapSessionRuntimeError(error);
1657
- }
1658
- });
1659
- }
1660
- async resolveCommandContext(command) {
1661
- const references = command.contextReferences ?? [];
1662
- if (references.length === 0)
1663
- return undefined;
1664
- if (command.type !== 'submit' && command.type !== 'queue_followup') {
1665
- throw new errors_1.WebWorkbenchError(400, 'Context references are valid only for submitted or queued messages.', 'context_reference_invalid');
1666
- }
1667
- const resolved = [];
1668
- let totalBytes = 0;
1669
- for (const reference of references) {
1670
- let entry;
1671
- try {
1672
- entry = await this.resolveContextReference(reference);
1673
- }
1674
- catch (error) {
1675
- throw mapContextReferenceError(error);
1676
- }
1677
- const bytes = Buffer.byteLength(JSON.stringify(entry), 'utf8');
1678
- if (bytes > MAX_CONTEXT_REFERENCE_BYTES) {
1679
- throw new errors_1.WebWorkbenchError(413, 'A Context reference exceeds the per-reference byte budget.', 'context_reference_too_large');
1680
- }
1681
- totalBytes += bytes;
1682
- if (totalBytes > MAX_CONTEXT_MANIFEST_BYTES) {
1683
- throw new errors_1.WebWorkbenchError(413, 'Context references exceed the request byte budget.', 'context_reference_too_large');
1684
- }
1685
- resolved.push(Object.freeze(entry));
1686
- }
1687
- const manifestContent = Object.freeze({
1688
- version: 1,
1689
- references: Object.freeze(resolved),
1690
- });
1691
- const manifestDigest = (0, canonical_1.digestRuntimeValue)(manifestContent);
1692
- const manifest = Object.freeze({ ...manifestContent, manifestDigest });
1693
- return Object.freeze({
1694
- text: [
1695
- command.text.trim(),
1696
- '',
1697
- '[Orion Context Manifest V1]',
1698
- JSON.stringify(manifest),
1699
- ].join('\n'),
1700
- receipt: Object.freeze({
1701
- manifestDigest,
1702
- referenceCount: resolved.length,
1703
- totalBytes,
1704
- }),
1705
- });
1706
- }
1707
- async resolveContextReference(reference) {
1708
- switch (reference.kind) {
1709
- case 'file': {
1710
- const page = this.fileService.readContent({
1711
- fileId: reference.id,
1712
- limitBytes: MAX_CONTEXT_REFERENCE_BYTES,
1713
- });
1714
- if (page.revision !== reference.revision) {
1715
- throw new errors_1.WebWorkbenchError(409, 'Referenced file changed.', 'context_reference_stale');
1716
- }
1717
- if (page.binary || page.content === undefined) {
1718
- throw new errors_1.WebWorkbenchError(403, 'Binary files cannot be added to model Context.', 'context_reference_forbidden');
1719
- }
1720
- return {
1721
- kind: 'file',
1722
- id: reference.id,
1723
- label: this.sanitizeContextText(page.name),
1724
- revision: page.revision,
1725
- content: this.sanitizeContextText(page.content),
1726
- truncated: page.nextCursor !== null,
1727
- };
1728
- }
1729
- case 'file_range': {
1730
- const page = this.fileService.readContent({
1731
- fileId: reference.id,
1732
- limitBytes: MAX_CONTEXT_REFERENCE_BYTES,
1733
- });
1734
- if (page.revision !== reference.revision) {
1735
- throw new errors_1.WebWorkbenchError(409, 'Referenced file changed.', 'context_reference_stale');
1736
- }
1737
- if (page.binary || page.content === undefined) {
1738
- throw new errors_1.WebWorkbenchError(403, 'Binary files cannot be added to model Context.', 'context_reference_forbidden');
1739
- }
1740
- const extracted = (0, context_text_1.extractLineRange)(page.content, reference.startLine, reference.endLine);
1741
- const budgeted = (0, context_text_1.enforceContextBudget)(extracted.text, MAX_CONTEXT_REFERENCE_BYTES);
1742
- return {
1743
- kind: 'file_range',
1744
- id: reference.id,
1745
- label: `${this.sanitizeContextText(page.name)}:${reference.startLine}-${reference.endLine}`,
1746
- revision: page.revision,
1747
- startLine: reference.startLine,
1748
- endLine: reference.endLine,
1749
- content: this.sanitizeContextText(budgeted.text),
1750
- truncated: budgeted.truncated || page.nextCursor !== null || extracted.clampedAtEnd,
1751
- };
1752
- }
1753
- case 'folder': {
1754
- const page = this.fileService.list({ parentId: reference.id, pageSize: 100 });
1755
- if (page.revision !== reference.revision) {
1756
- throw new errors_1.WebWorkbenchError(409, 'Referenced folder changed.', 'context_reference_stale');
1757
- }
1758
- return {
1759
- kind: 'folder',
1760
- id: reference.id,
1761
- label: this.sanitizeContextText(reference.label),
1762
- revision: page.revision,
1763
- entries: page.items
1764
- .filter(item => !item.sensitive)
1765
- .map(item => ({
1766
- name: this.sanitizeContextText(item.name),
1767
- kind: item.kind,
1768
- sizeBytes: item.sizeBytes ?? null,
1769
- })),
1770
- truncated: page.nextCursor !== null,
1771
- };
1772
- }
1773
- case 'review': {
1774
- const snapshot = await this.reviewService.snapshot();
1775
- if (snapshot.repositoryRevision !== reference.gitRevision) {
1776
- throw new errors_1.WebWorkbenchError(409, 'Referenced Review changed.', 'context_reference_stale');
1777
- }
1778
- return {
1779
- kind: 'review',
1780
- id: reference.id,
1781
- revision: snapshot.repositoryRevision,
1782
- clean: snapshot.clean,
1783
- files: snapshot.changedFiles.slice(0, 100).map(file => ({
1784
- id: file.fileId,
1785
- path: this.sanitizeContextText(file.path),
1786
- indexStatus: file.indexStatus,
1787
- worktreeStatus: file.worktreeStatus,
1788
- })),
1789
- truncated: snapshot.truncated || snapshot.changedFiles.length > 100,
1790
- };
1791
- }
1792
- case 'session': {
1793
- const session = requireSession(reference.id);
1794
- if (canonicalDirectory(session.projectPath) !== this.workspaceValue) {
1795
- throw new errors_1.WebWorkbenchError(403, 'Referenced Session belongs to another Workspace.', 'context_reference_forbidden');
1796
- }
1797
- const summary = (0, protocol_1.projectSessionSummary)(session);
1798
- if (summary.contextDigest !== reference.digest) {
1799
- throw new errors_1.WebWorkbenchError(409, 'Referenced Session changed.', 'context_reference_stale');
1800
- }
1801
- const page = (0, thread_session_view_1.loadThreadSessionSnapshotPageV1)(this.workspaceValue, session.id, undefined, 8);
1802
- return {
1803
- kind: 'session',
1804
- id: session.id,
1805
- label: this.sanitizeContextText(session.name?.trim() || `Session ${session.id.slice(0, 8)}`),
1806
- digest: summary.contextDigest,
1807
- messages: (page?.transcript.items ?? []).map(message => ({
1808
- role: message.role,
1809
- content: this.sanitizeContextText(message.content),
1810
- })),
1811
- truncated: Boolean(page?.transcript.nextCursor),
1812
- };
1813
- }
1814
- case 'skill': {
1815
- const descriptor = ((await this.runtimeValue.inspectSkills?.()) ?? []).find(skill => skill.id === reference.id);
1816
- if (!descriptor || descriptor.digest !== reference.digest) {
1817
- throw new errors_1.WebWorkbenchError(409, 'Referenced Skill changed.', 'context_reference_stale');
1818
- }
1819
- if (!descriptor.userInvocable) {
1820
- throw new errors_1.WebWorkbenchError(403, 'Referenced Skill is not user-invocable.', 'context_reference_forbidden');
1821
- }
1822
- return {
1823
- kind: 'skill',
1824
- id: descriptor.id,
1825
- label: this.sanitizeContextText(descriptor.name),
1826
- digest: descriptor.digest,
1827
- invocation: `$${descriptor.id}`,
1828
- description: this.sanitizeContextText(descriptor.description),
1829
- };
1830
- }
1831
- }
1832
- }
1833
- sanitizeContextText(value) {
1834
- return (0, redaction_1.redactTraceText)(value).split(this.workspaceValue).join('<workspace>');
1835
- }
1836
- async updateSettings(input) {
1837
- this.assertContextGuard(input);
1838
- this.assertSettingsAvailable();
1839
- const update = this.runtimeValue.updateSettings;
1840
- if (!update) {
1841
- throw new errors_1.WebWorkbenchError(503, 'The product Settings coordinator is unavailable.', 'settings_document_unavailable');
1842
- }
1843
- try {
1844
- const result = await update({
1845
- requestId: input.requestId,
1846
- expectedRevision: input.expectedRevision,
1847
- operations: input.operations,
1848
- });
1849
- return Object.freeze({
1850
- revision: result.revision,
1851
- appliedKeys: result.appliedKeys,
1852
- settings: result.document,
1853
- });
1854
- }
1855
- catch (error) {
1856
- throw mapSettingsError(error);
1857
- }
1858
- }
1859
- async openSettingsDocument() {
1860
- this.assertSettingsAvailable();
1861
- const coordinator = this.runtimeValue.settingsCoordinator;
1862
- if (!coordinator) {
1863
- throw new errors_1.WebWorkbenchError(503, 'The product Settings coordinator is unavailable.', 'settings_document_unavailable');
1864
- }
1865
- try {
1866
- await coordinator.openDocument();
1867
- return true;
1868
- }
1869
- catch (error) {
1870
- throw mapSettingsError(error);
1871
- }
1872
- }
1873
- executeMutation(requestId, operation, payload, action) {
1874
- if (!requestId.trim() || requestId.length > 128) {
1875
- throw new errors_1.WebWorkbenchError(400, 'requestId must be a non-empty string up to 128 characters.');
1876
- }
1877
- const fingerprint = (0, canonical_1.digestRuntimeValue)({ operation, payload });
1878
- const cached = this.mutationResults.get(requestId);
1879
- if (cached) {
1880
- if (cached.fingerprint !== fingerprint) {
1881
- throw new errors_1.WebWorkbenchError(409, 'requestId was already used for another mutation.', 'request_id_conflict');
1882
- }
1883
- return cached.result;
1884
- }
1885
- if (this.mutationResults.size >= MAX_MUTATION_RESULTS) {
1886
- throw new errors_1.WebWorkbenchError(503, 'The mutation idempotency ledger is full; restart the local Web Host before retrying.', 'mutation_capacity_exhausted');
1887
- }
1888
- const contextTransition = CONTEXT_TRANSITION_MUTATIONS.has(operation);
1889
- let result;
1890
- try {
1891
- this.reserveMutation(contextTransition);
1892
- result = Promise.resolve()
1893
- .then(() => {
1894
- this.assertMutationAdmission();
1895
- return action();
1896
- })
1897
- .finally(() => this.releaseMutation(contextTransition));
1898
- }
1899
- catch (error) {
1900
- // Mutation admission is part of the idempotent result contract. Cache a
1901
- // rejected Promise just like failures raised by the action so a retry of
1902
- // the same requestId cannot observe a different outcome.
1903
- result = Promise.reject(error);
1904
- }
1905
- this.mutationResults.set(requestId, { fingerprint, result });
1906
- return result;
1907
- }
1908
- async diagnostics(context) {
1909
- if (context)
1910
- this.assertContextGuard(context);
1911
- const state = this.runtimeValue.store.getSnapshot();
1912
- const mcp = (0, mcp_1.loadFirstPartyMcpConfigurationV1)();
1913
- const activeSessionId = this.runtimeValue.getSession()?.id ?? null;
1914
- // Harness diagnostics may need the lazy Session runtime. A read-only Web
1915
- // baseline must not manufacture a Session merely by opening the page.
1916
- const harness = activeSessionId
1917
- ? ((await this.runtimeValue.getHarnessDiagnostics?.()) ?? null)
1918
- : null;
1919
- const result = {
1920
- workspace: this.workspaceValue,
1921
- activeSessionId,
1922
- configured: this.runtimeValue.isConfigured,
1923
- processing: state.isProcessing,
1924
- agentMode: state.agentMode,
1925
- permissionMode: state.permissionMode,
1926
- contextUsage: state.contextUsage,
1927
- tokenUsage: state.tokenUsage,
1928
- plan: state.currentPlan,
1929
- todos: state.todos,
1930
- skills: {
1931
- configuredPaths: this.runtimeValue.config.skills?.paths ?? [],
1932
- loadedFromPrompt: state.skillsContent.length > 0,
1933
- },
1934
- mcp: { servers: mcpServerIds(mcp) },
1935
- harness,
1936
- eventStream: this.eventHub.snapshot(),
1937
- workspaceKernel: this.runtimeValue.workspaceRuntimeKernel?.diagnostics() ?? null,
1938
- // v0.3.17 — bounded, path-free open-path traces (picker / inspect / activate).
1939
- workspaceOpen: this.openTelemetry.snapshot(),
1940
- // v0.3.21 — bounded, path-free discovery traces (scan duration, counts,
1941
- // error codes). Never a root path, a label, a marker name, or content.
1942
- workspaceDiscovery: this.discoveryTelemetry.snapshot(),
1943
- session: {
1944
- ...this.sessionActivity,
1945
- actors: this.sessionRegistry.stats(),
1946
- },
1947
- performance: {
1948
- files: this.fileService.performanceCounters(),
1949
- git: this.gitService.performanceCounters(),
1950
- thread: {
1951
- eventStore: (0, thread_event_store_1.threadEventStorePerformanceCountersV1)(),
1952
- sessionIndex: (0, thread_session_index_1.threadSessionIndexPerformanceCountersV1)(),
1953
- },
1954
- },
1955
- };
1956
- if (context)
1957
- this.assertContextGuard(context);
1958
- return result;
1959
- }
1960
- async shutdown() {
1961
- if (this.shutdownResult)
1962
- return this.shutdownResult;
1963
- this.closed = true;
1964
- this.shutdownResult = this.shutdownOwnedResources();
1965
- return this.shutdownResult;
1966
- }
1967
- async shutdownOwnedResources() {
1968
- const failures = [];
1969
- this.sessionActivity.controlPlaneShutdowns += 1;
1970
- this.workspaceMutations.close('Orion Web Workbench shutdown');
1971
- try {
1972
- await this.sessionRegistry.shutdown('Orion Web Workbench shutdown');
1973
- }
1974
- catch {
1975
- // The registry retains failed actor handles. Retry once after every
1976
- // actor received its first close attempt; a persistent failure remains
1977
- // an explicit Host shutdown error rather than an orphan hidden as GO.
1978
- try {
1979
- await this.sessionRegistry.shutdown('Orion Web Workbench shutdown retry');
1980
- }
1981
- catch (retryError) {
1982
- failures.push(retryError);
1983
- }
1984
- }
1985
- await captureShutdownFailure(failures, () => this.controllerValue.stopActiveTurn());
1986
- await captureShutdownFailure(failures, () => this.controllerValue.waitForIdle());
1987
- try {
1988
- this.closeWorkspaceWatchers();
1989
- this.closeComposerObserver();
1990
- }
1991
- catch (error) {
1992
- failures.push(error);
1993
- }
1994
- await captureShutdownFailure(failures, () => this.terminalManager.shutdown());
1995
- await captureShutdownFailure(failures, () => this.runtimeValue.shutdown());
1996
- try {
1997
- this.eventHub.close();
1998
- }
1999
- catch (error) {
2000
- failures.push(error);
2001
- }
2002
- this.workspaceMutationOwners.clear();
2003
- this.pendingWorkspaceMutationStates.clear();
2004
- this.releaseWorkspaceKernels();
2005
- if (failures.length > 0) {
2006
- throw new errors_1.WebWorkbenchError(503, `${failures.length} Web Workbench resource(s) could not be closed safely.`, 'workbench_shutdown_incomplete');
2007
- }
2008
- }
2009
- /**
2010
- * Return the workspace kernel for `cwd`, creating and pooling one on first
2011
- * use. Control planes and Session actors borrow the same kernel instance per
2012
- * canonical Workspace; the pool is released only when the Host shuts down.
2013
- */
2014
- workspaceKernelFor(cwd) {
2015
- const canonical = canonicalDirectory(cwd);
2016
- const existing = this.workspaceKernels.get(canonical);
2017
- if (existing && !existing.diagnostics().closed)
2018
- return existing;
2019
- if (existing)
2020
- this.workspaceKernels.delete(canonical);
2021
- const kernel = (0, product_bootstrap_1.createWorkspaceRuntimeKernelV1)({
2022
- cwd: canonical,
2023
- onSettingsInvalidated: event => this.onWorkspaceKernelSettingsInvalidated(canonical, event),
2024
- });
2025
- this.workspaceKernels.set(canonical, kernel);
2026
- return kernel;
2027
- }
2028
- /**
2029
- * Settings invalidations from pooled kernels are only forwarded while their
2030
- * Workspace is the active Context. A background Workspace's coordinator
2031
- * keeps watching its own durable file; its next activation publishes a fresh
2032
- * Settings document through `emitSettingsWorkspaceChange()`.
2033
- */
2034
- onWorkspaceKernelSettingsInvalidated(kernelWorkspace, event) {
2035
- if (this.suppressContextEdges > 0)
2036
- return;
2037
- if (kernelWorkspace !== this.workspaceValue)
2038
- return;
2039
- this.eventHub.emit({
2040
- type: 'settings_invalidated',
2041
- revision: event.revision,
2042
- reason: event.reason,
2043
- state: event.state,
2044
- }, false);
2045
- }
2046
- /**
2047
- * Release the Host owner seat on every pooled kernel. Runtime shutdowns have
2048
- * already disposed their Settings participants (actors first, then the
2049
- * active control plane), so an unowned kernel with zero participants closes
2050
- * its Settings coordinator here. A kernel that still has a running actor
2051
- * participant survives until that actor actually terminates.
2052
- */
2053
- releaseWorkspaceKernels() {
2054
- for (const kernel of this.workspaceKernels.values()) {
2055
- kernel.releaseOwner();
2056
- }
2057
- this.workspaceKernels.clear();
2058
- }
2059
- createSessionRegistry() {
2060
- return new session_runtime_registry_1.WebSessionRuntimeRegistryV1({
2061
- maxRunningSessions: 3,
2062
- maxResidentSessionActors: 4,
2063
- createActor: key => this.createSessionActor(key),
2064
- initializeActor: actor => actor.runtime.rebindSessionRuntime?.() ?? Promise.resolve(),
2065
- closeActor: (actor, reason) => this.closeSessionActor(actor, reason),
2066
- estimateActorBytes: actor => estimateSessionActorBytes(actor),
2067
- onSummaryChanged: runtime => {
2068
- if (this.closed || this.suppressContextEdges > 0)
2069
- return;
2070
- this.eventHub.emit({ type: 'session_runtime_changed', runtime }, true, {
2071
- sessionId: runtime.sessionId,
2072
- });
2073
- },
2074
- });
2075
- }
2076
- async createSessionActor(key) {
2077
- const workspace = this.workspaceRegistry.find(key.workspaceId);
2078
- if (!workspace) {
2079
- throw new errors_1.WebWorkbenchError(404, 'Workspace was not found.', 'workspace_not_found');
2080
- }
2081
- const session = requireSession(key.sessionId);
2082
- if (canonicalDirectory(session.projectPath) !== workspace.canonicalPath) {
2083
- throw new errors_1.WebWorkbenchError(409, 'Session belongs to another Workspace.', 'session_workspace_conflict');
2084
- }
2085
- const runtime = await this.createSessionRuntime(workspace.canonicalPath);
2086
- runtime.setSession(session);
2087
- const actorRef = {};
2088
- const eventSink = {
2089
- emit: (event) => this.emitSessionActorRuntimeEvent(key, runtime, actorRef.current, event),
2090
- };
2091
- const controller = new agent_runtime_controller_1.AgentRuntimeController({
2092
- runtime,
2093
- eventSink,
2094
- uiRenderer: 'web',
2095
- echoSubmittedInput: false,
2096
- useRuntimeToolPermissions: true,
2097
- uiCapabilities: {
2098
- structuredPickers: true,
2099
- inlineProgress: true,
2100
- suppressLegacyTokenMeta: true,
2101
- extraAssistantSpacing: true,
2102
- suppressAbortNotice: true,
2103
- },
2104
- });
2105
- const actor = {
2106
- key: Object.freeze({ ...key }),
2107
- runtime,
2108
- controller,
2109
- composerRevision: (0, crypto_1.randomUUID)(),
2110
- latestStatus: 'Ready',
2111
- suppressComposerEdges: 0,
2112
- };
2113
- actorRef.current = actor;
2114
- actor.composerStoreUnsubscribe = runtime.store.subscribe(() => this.scheduleActorComposerStateChanged(actor));
2115
- actor.composerControlsUnsubscribe = runtime.sessionComposerControls?.subscribe(() => this.scheduleActorComposerStateChanged(actor));
2116
- return actor;
2117
- }
2118
- async closeSessionActor(actor, _reason) {
2119
- if (actor.composerChangeTimer)
2120
- clearTimeout(actor.composerChangeTimer);
2121
- actor.composerChangeTimer = undefined;
2122
- actor.composerStoreUnsubscribe?.();
2123
- actor.composerControlsUnsubscribe?.();
2124
- actor.composerStoreUnsubscribe = undefined;
2125
- actor.composerControlsUnsubscribe = undefined;
2126
- await actor.controller.stopActiveTurn();
2127
- await actor.controller.waitForIdle();
2128
- await actor.runtime.shutdown();
2129
- this.activeOrionRuntimes.delete(actor.key.sessionId);
2130
- for (const [invocationId, owner] of this.workspaceMutationOwners) {
2131
- if (owner.sessionId === actor.key.sessionId && owner.workspaceId === actor.key.workspaceId) {
2132
- this.workspaceMutationOwners.delete(invocationId);
2133
- this.pendingWorkspaceMutationStates.delete(invocationId);
2134
- }
2135
- }
2136
- }
2137
- emitSessionActorRuntimeEvent(key, runtime, actor, event) {
2138
- if (event.type === 'status_changed' && actor)
2139
- actor.latestStatus = event.message;
2140
- if (event.type === 'followup_queue_changed') {
2141
- if (actor && actor.suppressComposerEdges === 0) {
2142
- this.publishActorComposerState(actor);
2143
- }
2144
- return undefined;
2145
- }
2146
- if (event.type === 'tool_started') {
2147
- this.workspaceMutationOwners.set(event.event.callId, Object.freeze({ ...key }));
2148
- }
2149
- const thread = this.activeOrionRuntimes.get(key.sessionId)?.thread.getProjection().threadId;
2150
- const envelope = this.eventHub.emitRuntime(event, {
2151
- sessionId: key.sessionId,
2152
- ...(thread ? { threadId: thread } : {}),
2153
- });
2154
- if (event.type === 'tool_started') {
2155
- const pendingMutation = this.pendingWorkspaceMutationStates.get(event.event.callId);
2156
- if (pendingMutation) {
2157
- this.pendingWorkspaceMutationStates.delete(event.event.callId);
2158
- this.emitWorkspaceMutationState(pendingMutation);
2159
- }
2160
- }
2161
- if (event.type === 'permission_requested' && actor) {
2162
- this.sessionRegistry.setPendingApprovalCount(key, actor.controller.getPendingPermissions().length);
2163
- }
2164
- if (event.type === 'tool_finished' && key.workspaceId === this.activeWorkspaceEntry().id) {
2165
- this.scheduleWorkspaceResourceInvalidation('tool-finished');
2166
- }
2167
- if (event.type === 'tool_finished') {
2168
- this.workspaceMutationOwners.delete(event.event.callId);
2169
- this.pendingWorkspaceMutationStates.delete(event.event.callId);
2170
- }
2171
- return event.type === 'transcript_append' ? `web-entry-${envelope.cursor}` : undefined;
2172
- }
2173
- emitWorkspaceMutationState(state) {
2174
- if (this.closed || this.suppressContextEdges > 0)
2175
- return;
2176
- const owner = this.workspaceMutationOwners.get(state.invocationId);
2177
- if (!owner) {
2178
- if (state.phase === 'queued' || state.phase === 'running') {
2179
- this.pendingWorkspaceMutationStates.set(state.invocationId, Object.freeze({ ...state }));
2180
- }
2181
- else {
2182
- this.pendingWorkspaceMutationStates.delete(state.invocationId);
2183
- }
2184
- return;
2185
- }
2186
- this.eventHub.emit({
2187
- type: 'workspace_mutation_changed',
2188
- state: {
2189
- callId: state.invocationId,
2190
- phase: state.phase,
2191
- ...(state.queuePosition === undefined ? {} : { queuePosition: state.queuePosition }),
2192
- },
2193
- }, false, { sessionId: owner.sessionId });
2194
- if (['completed', 'failed', 'cancelled'].includes(state.phase)) {
2195
- this.workspaceMutationOwners.delete(state.invocationId);
2196
- this.pendingWorkspaceMutationStates.delete(state.invocationId);
2197
- }
2198
- }
2199
- scheduleActorComposerStateChanged(actor) {
2200
- if (this.closed || actor.suppressComposerEdges > 0)
2201
- return;
2202
- if (actor.composerChangeTimer)
2203
- clearTimeout(actor.composerChangeTimer);
2204
- actor.composerChangeTimer = setTimeout(() => {
2205
- actor.composerChangeTimer = undefined;
2206
- if (this.closed || actor.suppressComposerEdges > 0)
2207
- return;
2208
- this.publishActorComposerState(actor);
2209
- }, 100);
2210
- actor.composerChangeTimer.unref();
2211
- }
2212
- publishActorComposerState(actor) {
2213
- try {
2214
- const state = this.projectActorComposerState(actor, requireSession(actor.key.sessionId));
2215
- this.eventHub.emit({ type: 'composer_state_changed', state }, true, {
2216
- sessionId: actor.key.sessionId,
2217
- });
2218
- }
2219
- catch {
2220
- // A concurrent actor teardown publishes its final Runtime summary.
2221
- }
2222
- }
2223
- async installRuntime(workspace, publishState = true) {
2224
- const storageRoot = await (0, paths_1.resolveProjectStoragePathAsync)(workspace);
2225
- if (storageRoot !== workspace)
2226
- await (0, paths_1.resolveProjectStoragePathAsync)(storageRoot);
2227
- // Every control-plane install reloads the Workspace catalog, provider
2228
- // wiring, Skills and MCP adapters, so this counter proxies "catalog
2229
- // reload" for the runtime-ownership diagnostics matrix.
2230
- this.sessionActivity.controlPlaneInstalls += 1;
2231
- this.closeComposerObserver();
2232
- const runtime = await this.createRuntime(workspace);
2233
- this.closeWorkspaceWatchers();
2234
- this.activeOrionRuntime = undefined;
2235
- this.sessionViews.clear();
2236
- this.sessionViewBytes = 0;
2237
- this.latestStatus = 'Ready';
2238
- this.workspaceValue = workspace;
2239
- this.runtimeValue = runtime;
2240
- this.fileService = new file_read_service_1.FileReadServiceV1(workspace);
2241
- this.fileWriteService = new file_write_service_1.FileWriteServiceV1(this.fileService);
2242
- this.gitService = new git_read_model_service_1.GitReadModelServiceV1(workspace);
2243
- this.reviewService = new review_service_1.ReviewServiceV1(this.gitService);
2244
- const eventSink = {
2245
- emit: (event) => {
2246
- if (event.type === 'status_changed')
2247
- this.latestStatus = event.message;
2248
- if (this.suppressContextEdges > 0)
2249
- return undefined;
2250
- const activeSessionId = this.runtimeValue.getSession()?.id;
2251
- if (event.type === 'followup_queue_changed') {
2252
- // The queue is part of the Composer CAS authority. Publishing the
2253
- // Runtime queue event on its own lets the browser observe new items
2254
- // with an older controlRevision and guarantees a 409 on its next
2255
- // edit/move/remove action. Project one complete Composer state in
2256
- // this same synchronous boundary instead. Composer actions suppress
2257
- // their intermediate queue edge and publish their final state below.
2258
- if (activeSessionId && this.suppressComposerEdges === 0) {
2259
- const state = this.composerState(activeSessionId);
2260
- this.eventHub.emit({ type: 'composer_state_changed', state }, true, {
2261
- sessionId: activeSessionId,
2262
- });
2263
- }
2264
- return undefined;
2265
- }
2266
- const activeThread = activeSessionId && this.activeOrionRuntime?.sessionId === activeSessionId
2267
- ? this.activeOrionRuntime.runtime.thread.getProjection().threadId
2268
- : undefined;
2269
- const envelope = this.eventHub.emitRuntime(event, {
2270
- ...(activeSessionId ? { sessionId: activeSessionId } : {}),
2271
- ...(activeThread ? { threadId: activeThread } : {}),
2272
- });
2273
- if (event.type === 'session_restored')
2274
- this.emitState();
2275
- if (event.type === 'tool_finished') {
2276
- this.scheduleWorkspaceResourceInvalidation('tool-finished');
2277
- }
2278
- return event.type === 'transcript_append' ? `web-entry-${envelope.cursor}` : undefined;
2279
- },
2280
- };
2281
- this.controllerValue = new agent_runtime_controller_1.AgentRuntimeController({
2282
- runtime,
2283
- eventSink,
2284
- uiRenderer: 'web',
2285
- // Thread events are authoritative for Web transcript projection. Echoing here
2286
- // would duplicate every submitted user item when the Thread observer catches up.
2287
- echoSubmittedInput: false,
2288
- useRuntimeToolPermissions: true,
2289
- uiCapabilities: {
2290
- structuredPickers: true,
2291
- inlineProgress: true,
2292
- suppressLegacyTokenMeta: true,
2293
- extraAssistantSpacing: true,
2294
- suppressAbortNotice: true,
2295
- },
2296
- });
2297
- this.composerRevisionValue = (0, crypto_1.randomUUID)();
2298
- this.composerAuthorityDigest = undefined;
2299
- this.composerStoreUnsubscribe = runtime.store.subscribe(() => this.scheduleComposerStateChanged());
2300
- this.composerControlsUnsubscribe = runtime.sessionComposerControls?.subscribe(() => this.scheduleComposerStateChanged());
2301
- this.installWorkspaceWatchers();
2302
- if (publishState)
2303
- this.emitState(false);
2304
- }
2305
- emitState(advanceRevision = true) {
2306
- if (this.suppressContextEdges > 0)
2307
- return;
2308
- if (advanceRevision)
2309
- this.contextRevisionValue = (0, crypto_1.randomUUID)();
2310
- if (advanceRevision)
2311
- this.composerRevisionValue = (0, crypto_1.randomUUID)();
2312
- const workspace = this.activeWorkspaceEntry();
2313
- const sessionId = this.runtimeValue.getSession()?.id ?? null;
2314
- if (sessionId) {
2315
- try {
2316
- this.composerAuthorityDigest = composerAuthorityDigest(this.projectComposerStateValue(requireSession(sessionId)));
2317
- }
2318
- catch {
2319
- this.composerAuthorityDigest = undefined;
2320
- }
2321
- }
2322
- else {
2323
- this.composerAuthorityDigest = undefined;
2324
- }
2325
- this.eventHub.emit({
2326
- type: 'workbench_state',
2327
- contextRevision: this.contextRevisionValue,
2328
- workspaceId: workspace.id,
2329
- workspace: this.workspaceValue,
2330
- activeSessionId: sessionId,
2331
- });
2332
- }
2333
- emitWorkspaceResourceInvalidation(reason) {
2334
- if (this.closed || this.suppressContextEdges > 0)
2335
- return;
2336
- this.eventHub.emit({
2337
- type: 'workspace_resource_invalidated',
2338
- workspaceId: this.activeWorkspaceEntry().id,
2339
- resources: ['files', 'git', 'review'],
2340
- reason,
2341
- }, false);
2342
- }
2343
- scheduleWorkspaceResourceInvalidation(reason) {
2344
- if (this.closed)
2345
- return;
2346
- if (this.resourceInvalidationTimer)
2347
- clearTimeout(this.resourceInvalidationTimer);
2348
- const workspace = this.workspaceValue;
2349
- this.resourceInvalidationTimer = setTimeout(() => {
2350
- this.resourceInvalidationTimer = undefined;
2351
- if (!this.closed && this.workspaceValue === workspace) {
2352
- this.emitWorkspaceResourceInvalidation(reason);
2353
- }
2354
- }, 120);
2355
- this.resourceInvalidationTimer.unref();
2356
- }
2357
- bumpComposerRevision() {
2358
- this.composerRevisionValue = (0, crypto_1.randomUUID)();
2359
- }
2360
- scheduleComposerStateChanged() {
2361
- if (this.closed ||
2362
- this.suppressComposerEdges > 0 ||
2363
- this.suppressContextEdges > 0 ||
2364
- !this.runtimeValue.getSession()) {
2365
- return;
2366
- }
2367
- if (this.composerChangeTimer)
2368
- clearTimeout(this.composerChangeTimer);
2369
- this.composerChangeTimer = setTimeout(() => {
2370
- this.composerChangeTimer = undefined;
2371
- const sessionId = this.runtimeValue.getSession()?.id;
2372
- if (!sessionId || this.closed || this.suppressComposerEdges > 0)
2373
- return;
2374
- try {
2375
- const state = this.composerState(sessionId);
2376
- this.eventHub.emit({ type: 'composer_state_changed', state }, true, { sessionId });
2377
- }
2378
- catch {
2379
- // A concurrent Context transition publishes a fresh baseline instead.
2380
- }
2381
- }, 100);
2382
- this.composerChangeTimer.unref();
2383
- }
2384
- closeComposerObserver() {
2385
- this.composerStoreUnsubscribe?.();
2386
- this.composerStoreUnsubscribe = undefined;
2387
- this.composerControlsUnsubscribe?.();
2388
- this.composerControlsUnsubscribe = undefined;
2389
- if (this.composerChangeTimer)
2390
- clearTimeout(this.composerChangeTimer);
2391
- this.composerChangeTimer = undefined;
2392
- }
2393
- installWorkspaceWatchers() {
2394
- const watchPaths = [this.workspaceValue, (0, path_1.resolve)(this.workspaceValue, '.git')].filter(path => (0, fs_1.existsSync)(path));
2395
- for (const path of watchPaths) {
2396
- try {
2397
- const watcher = (0, fs_1.watch)(path, { persistent: false }, () => this.scheduleWorkspaceResourceInvalidation('filesystem-change'));
2398
- watcher.on('error', () => {
2399
- watcher.close();
2400
- this.workspaceWatchers = this.workspaceWatchers.filter(item => item !== watcher);
2401
- });
2402
- this.workspaceWatchers.push(watcher);
2403
- }
2404
- catch {
2405
- // Watchers are only refresh hints. Revisioned reads and explicit refresh remain authoritative.
2406
- }
2407
- }
2408
- }
2409
- closeWorkspaceWatchers() {
2410
- if (this.resourceInvalidationTimer)
2411
- clearTimeout(this.resourceInvalidationTimer);
2412
- this.resourceInvalidationTimer = undefined;
2413
- for (const watcher of this.workspaceWatchers)
2414
- watcher.close();
2415
- this.workspaceWatchers = [];
2416
- }
2417
- async restoreContextSession(sessionId) {
2418
- if (!sessionId) {
2419
- this.runtimeValue.setSession(null);
2420
- await this.runtimeValue.rebindSessionRuntime?.();
2421
- if (this.suppressContextEdges === 0) {
2422
- this.eventHub.emitRuntime({ type: 'transcript_clear' });
2423
- }
2424
- return;
2425
- }
2426
- const result = this.controllerValue.handle({
2427
- type: 'select_session',
2428
- sessionId,
2429
- source: 'programmatic',
2430
- });
2431
- await this.controllerValue.waitForIdle();
2432
- if (this.runtimeValue.getSession()?.id !== sessionId) {
2433
- throw new errors_1.WebWorkbenchError(409, `Session activation was rejected by the runtime (${result.type}).`, 'context_session_rejected');
2434
- }
2435
- }
2436
- emitSettingsWorkspaceChange() {
2437
- const describe = this.runtimeValue.describeSettings;
2438
- if (!describe) {
2439
- throw new errors_1.WebWorkbenchError(503, 'The product Settings coordinator is unavailable.', 'settings_document_unavailable');
2440
- }
2441
- const settings = describe();
2442
- this.eventHub.emit({
2443
- type: 'settings_invalidated',
2444
- revision: settings.revision,
2445
- reason: 'workspace-change',
2446
- state: settings.state === 'ready' || settings.state === 'read-only' ? 'ready' : 'invalid',
2447
- }, false);
2448
- }
2449
- observeThreadRuntime(runtime, sessionId, activation) {
2450
- let replaying = true;
2451
- const pending = [];
2452
- const unsubscribe = runtime.thread.observeCommittedEvents(events => {
2453
- if (replaying)
2454
- pending.push(...events);
2455
- else
2456
- for (const event of events)
2457
- this.eventHub.emitThread(event, sessionId);
2458
- });
2459
- try {
2460
- const edge = runtime.thread.getProjection().cursor;
2461
- // Historical transcript state comes from the cursor-bound snapshot.
2462
- // Publishing the entire Thread through the live SSE hub on every switch
2463
- // made activation O(history) and evicted the reconnect window.
2464
- replaying = false;
2465
- for (const event of pending
2466
- .filter(event => event.seq > edge)
2467
- .sort((left, right) => left.seq - right.seq)) {
2468
- this.eventHub.emitThread(event, sessionId);
2469
- }
2470
- if (activation?.sessionId === sessionId && activation.view) {
2471
- this.rememberSessionView(sessionId, activation.view);
2472
- }
2473
- this.activeOrionRuntime = { runtime, sessionId };
2474
- this.activeOrionRuntimes.set(sessionId, runtime);
2475
- }
2476
- catch (error) {
2477
- unsubscribe();
2478
- throw error;
2479
- }
2480
- return () => {
2481
- unsubscribe();
2482
- if (this.activeOrionRuntime?.runtime === runtime)
2483
- this.activeOrionRuntime = undefined;
2484
- if (this.activeOrionRuntimes.get(sessionId) === runtime) {
2485
- this.activeOrionRuntimes.delete(sessionId);
2486
- }
2487
- };
2488
- }
2489
- loadSessionView(session, activeProjection) {
2490
- const expectedFingerprint = activeProjection
2491
- ? threadViewFingerprint(activeProjection)
2492
- : session.threadReadModel
2493
- ? [
2494
- session.threadReadModel.threadId,
2495
- session.threadReadModel.cursor,
2496
- session.threadReadModel.projectionDigest,
2497
- ].join(':')
2498
- : undefined;
2499
- const cached = expectedFingerprint ? this.sessionViews.get(session.id) : undefined;
2500
- if (cached && expectedFingerprint && cached.fingerprint === expectedFingerprint) {
2501
- this.sessionViews.delete(session.id);
2502
- this.sessionViews.set(session.id, cached);
2503
- return cached.view;
2504
- }
2505
- const view = (0, thread_session_view_1.loadThreadSessionViewV1)(this.workspaceValue, session.id);
2506
- if (!view)
2507
- return undefined;
2508
- return this.rememberSessionView(session.id, view);
2509
- }
2510
- rememberSessionView(sessionId, view) {
2511
- const previous = this.sessionViews.get(sessionId);
2512
- if (previous)
2513
- this.sessionViewBytes -= previous.bytes;
2514
- const entry = {
2515
- fingerprint: [view.threadId, view.cursor, view.projectionDigest].join(':'),
2516
- view,
2517
- bytes: estimateSessionViewBytes(view),
2518
- };
2519
- this.sessionViews.delete(sessionId);
2520
- this.sessionViews.set(sessionId, entry);
2521
- this.sessionViewBytes += entry.bytes;
2522
- while (this.sessionViewBytes > SESSION_VIEW_CACHE_BYTES && this.sessionViews.size > 1) {
2523
- const oldest = this.sessionViews.keys().next().value;
2524
- if (!oldest)
2525
- break;
2526
- const evicted = this.sessionViews.get(oldest);
2527
- this.sessionViews.delete(oldest);
2528
- this.sessionViewBytes -= evicted?.bytes ?? 0;
2529
- }
2530
- return view;
2531
- }
2532
- assertReadyForTransition(operation) {
2533
- if (this.closed)
2534
- throw new errors_1.WebWorkbenchError(503, 'Web Workbench is closed.');
2535
- if (this.transition || this.activeMutationCount > 0) {
2536
- throw new errors_1.WebWorkbenchError(409, 'A workspace transition is running.', 'runtime_busy');
2537
- }
2538
- if (this.controllerValue.hasActiveTurn()) {
2539
- throw new errors_1.WebWorkbenchError(409, `Cannot ${operation} while a turn is active.`, 'runtime_busy');
2540
- }
2541
- // P1-A: Session actors are scoped to their own Workspace and survive a
2542
- // Context switch (WEB35-P0-08/09), so an active actor in a non-target
2543
- // Workspace must not block switching the active control plane.
2544
- }
2545
- assertMutationAdmission() {
2546
- if (this.closed)
2547
- throw new errors_1.WebWorkbenchError(503, 'Web Workbench is closed.');
2548
- if (this.transition) {
2549
- throw new errors_1.WebWorkbenchError(409, 'A Context transition is running.', 'runtime_busy');
2550
- }
2551
- }
2552
- reserveMutation(contextTransition) {
2553
- this.assertMutationAdmission();
2554
- if (contextTransition) {
2555
- if (this.contextTransitionReserved || this.activeMutationCount > 0) {
2556
- throw new errors_1.WebWorkbenchError(409, 'Another mutation is still running.', 'runtime_busy');
2557
- }
2558
- this.contextTransitionReserved = true;
2559
- return;
2560
- }
2561
- if (this.contextTransitionReserved) {
2562
- throw new errors_1.WebWorkbenchError(409, 'A Context transition is being admitted.', 'runtime_busy');
2563
- }
2564
- this.activeMutationCount += 1;
2565
- }
2566
- releaseMutation(contextTransition) {
2567
- if (contextTransition) {
2568
- this.contextTransitionReserved = false;
2569
- return;
2570
- }
2571
- this.activeMutationCount = Math.max(0, this.activeMutationCount - 1);
2572
- }
2573
- assertContextGuard(context) {
2574
- this.assertMutationAdmission();
2575
- if (context.expectedContextRevision !== this.contextRevisionValue ||
2576
- context.workspaceId !== this.activeWorkspaceEntry().id) {
2577
- throw new errors_1.WebWorkbenchError(409, 'The active Context changed before the operation was admitted.', 'context_revision_conflict');
2578
- }
2579
- }
2580
- assertCommandSession(expectedSessionId) {
2581
- if (this.closed)
2582
- throw new errors_1.WebWorkbenchError(503, 'Web Workbench is closed.');
2583
- if (this.transition) {
2584
- throw new errors_1.WebWorkbenchError(409, 'A Session transition is running.', 'runtime_busy');
2585
- }
2586
- if (this.runtimeValue.getSession()?.id !== expectedSessionId) {
2587
- throw new errors_1.WebWorkbenchError(409, 'The active Session changed before the command was admitted.', 'active_session_changed');
2588
- }
2589
- }
2590
- assertSessionWorkspace(session) {
2591
- if (canonicalDirectory(session.projectPath) !== this.workspaceValue) {
2592
- throw new errors_1.WebWorkbenchError(409, 'Session belongs to another Workspace.', 'session_workspace_conflict');
2593
- }
2594
- }
2595
- sessionActorKey(session) {
2596
- this.assertSessionWorkspace(session);
2597
- return Object.freeze({
2598
- workspaceId: this.activeWorkspaceEntry().id,
2599
- sessionId: session.id,
2600
- });
2601
- }
2602
- assertSettingsAvailable() {
2603
- if (this.closed) {
2604
- throw new errors_1.WebWorkbenchError(503, 'Web Workbench is closed.', 'settings_document_unavailable');
2605
- }
2606
- if (this.transition) {
2607
- throw new errors_1.WebWorkbenchError(409, 'A workspace transition is running.', 'runtime_busy');
2608
- }
2609
- }
2610
- initializeWorkspaceRegistry() {
2611
- const paths = [this.workspaceValue];
2612
- for (const session of (0, session_storage_1.listSessions)()) {
2613
- try {
2614
- paths.push(canonicalDirectory(session.projectPath));
2615
- }
2616
- catch {
2617
- // Unavailable historical projects remain in the Session catalog but
2618
- // are not imported as selectable Workspace registry entries.
2619
- }
2620
- }
2621
- try {
2622
- this.workspaceRegistry.registerKnown(paths, this.workspaceValue);
2623
- }
2624
- catch (error) {
2625
- throw mapWorkspaceRegistryError(error);
2626
- }
2627
- }
2628
- activeWorkspaceEntry() {
2629
- const entry = this.workspaceRegistry
2630
- .list()
2631
- .find(candidate => candidate.canonicalPath === this.workspaceValue);
2632
- if (!entry) {
2633
- throw new errors_1.WebWorkbenchError(503, 'Active Workspace is missing from the registry.');
2634
- }
2635
- return entry;
2636
- }
2637
- }
2638
- exports.WebWorkbenchController = WebWorkbenchController;
2639
- function mapWorkspaceRegistryError(error) {
2640
- if (error instanceof errors_1.WebWorkbenchError)
2641
- return error;
2642
- if (error instanceof workspace_registry_1.WorkspaceRegistryError) {
2643
- const status = error.code === 'workspace_registry_invalid' ? 503 : 409;
2644
- return new errors_1.WebWorkbenchError(status, error.message, error.code);
2645
- }
2646
- return new errors_1.WebWorkbenchError(503, 'Workspace registry is unavailable.');
2647
- }
2648
- function mapSessionRuntimeError(error) {
2649
- if (error instanceof errors_1.WebWorkbenchError)
2650
- return error;
2651
- if (error instanceof session_runtime_registry_1.WebSessionRuntimeRegistryError) {
2652
- return new errors_1.WebWorkbenchError(error.status, error.message, error.code);
2653
- }
2654
- throw error;
2655
- }
2656
- function mapSettingsError(error) {
2657
- if (error instanceof errors_1.WebWorkbenchError)
2658
- return error;
2659
- if (error instanceof settings_coordinator_1.SettingsCoordinatorError) {
2660
- return new errors_1.WebWorkbenchError(error.status, error.message, error.code);
2661
- }
2662
- return new errors_1.WebWorkbenchError(503, 'The product Settings coordinator is unavailable.', 'settings_document_unavailable');
2663
- }
2664
- function mapComposerControlError(error) {
2665
- if (error instanceof errors_1.WebWorkbenchError)
2666
- return error;
2667
- if (error instanceof agent_runtime_controller_1.FollowupQueueConflictError) {
2668
- return new errors_1.WebWorkbenchError(409, error.message, error.code);
2669
- }
2670
- if (error instanceof session_composer_control_1.SessionComposerControlError) {
2671
- const status = error.code === 'composer_recovery_required'
2672
- ? 503
2673
- : ['runtime_busy', 'composer_control_conflict'].includes(error.code)
2674
- ? 409
2675
- : 422;
2676
- return new errors_1.WebWorkbenchError(status, error.message, error.code);
2677
- }
2678
- if (error instanceof plan_review_1.PlanReviewControlError) {
2679
- const status = error.code === 'plan_review_invalid' ? 422 : 409;
2680
- return new errors_1.WebWorkbenchError(status, error.message, error.code);
2681
- }
2682
- return new errors_1.WebWorkbenchError(503, 'The Session Composer control action failed.', 'composer_control_failed');
2683
- }
2684
- function mapContextReferenceError(error) {
2685
- if (error instanceof errors_1.WebWorkbenchError) {
2686
- if (error.code.startsWith('context_reference_'))
2687
- return error;
2688
- if (error.status === 403 ||
2689
- ['sensitive_file_blocked', 'file_binary', 'file_not_regular'].includes(error.code)) {
2690
- return new errors_1.WebWorkbenchError(403, 'The Context reference is not available to the model.', 'context_reference_forbidden');
2691
- }
2692
- if (error.status === 404 || error.status === 409) {
2693
- return new errors_1.WebWorkbenchError(409, 'The Context reference changed or is no longer available.', 'context_reference_stale');
2694
- }
2695
- }
2696
- return new errors_1.WebWorkbenchError(422, 'The Context reference could not be resolved.', 'context_reference_invalid');
2697
- }
2698
- function composerAuthorityDigest(state) {
2699
- return (0, canonical_1.digestRuntimeValue)({
2700
- workspaceId: state.workspaceId,
2701
- sessionId: state.sessionId,
2702
- mode: state.mode,
2703
- model: state.model,
2704
- permission: state.permission,
2705
- pending: state.pending,
2706
- lastError: state.lastError,
2707
- planReview: state.planReview,
2708
- queue: state.queue,
2709
- });
2710
- }
2711
- function pickPlanReceipt(receipt) {
2712
- return Object.freeze({
2713
- body: receipt.plan,
2714
- returnMode: receipt.returnMode,
2715
- digest: receipt.digest,
2716
- });
2717
- }
2718
- function threadViewFingerprint(projection) {
2719
- return [projection.threadId, projection.cursor, projection.digest].join(':');
2720
- }
2721
- function uniqueCommitProjections(commits) {
2722
- return [...new Map(commits.filter(Boolean).map(commit => [commit.seq, commit])).values()].sort((left, right) => left.seq - right.seq);
2723
- }
2724
- function latestAuthorityCommits(projection) {
2725
- const commits = Object.values(projection.turns)
2726
- .flatMap(turn => (turn.commit ? [turn.commit] : []))
2727
- .sort((left, right) => left.seq - right.seq);
2728
- const latest = commits.at(-1);
2729
- const latestPlan = [...commits].reverse().find(commit => {
2730
- try {
2731
- return Boolean((0, turn_commit_1.parseTurnCommitV1)(commit.receipt).planReceipt);
2732
- }
2733
- catch {
2734
- return false;
2735
- }
2736
- });
2737
- return uniqueCommitProjections([latestPlan, latest]);
2738
- }
2739
- function estimateSessionViewBytes(view) {
2740
- let bytes = 1024;
2741
- for (const message of view.transcriptMessages) {
2742
- bytes += Buffer.byteLength(message.content, 'utf8') + 256;
2743
- if (message.modelVisibleContent) {
2744
- bytes += Buffer.byteLength(message.modelVisibleContent, 'utf8');
2745
- }
2746
- }
2747
- for (const message of view.modelHistory) {
2748
- bytes += Buffer.byteLength(JSON.stringify(message), 'utf8') + 128;
2749
- }
2750
- for (const commit of uniqueCommitProjections([
2751
- view.latestPlanTurnCommit,
2752
- view.latestTurnCommit,
2753
- ])) {
2754
- bytes += Buffer.byteLength(commit.receipt, 'utf8');
2755
- }
2756
- return bytes;
2757
- }
2758
- function pageItems(items, cursor, pageSize = 50) {
2759
- if (!Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > 100) {
2760
- throw new errors_1.WebWorkbenchError(400, 'pageSize must be an integer from 1 through 100.');
2761
- }
2762
- const offset = cursor ? decodePageCursor(cursor) : 0;
2763
- if (offset > items.length)
2764
- throw new errors_1.WebWorkbenchError(400, 'Page cursor is out of range.');
2765
- const page = items.slice(offset, offset + pageSize);
2766
- const nextOffset = offset + page.length;
2767
- return Object.freeze({
2768
- items: Object.freeze(page),
2769
- nextCursor: nextOffset < items.length ? encodePageCursor(nextOffset) : null,
2770
- });
2771
- }
2772
- function pageCollectionItems(scope, items, cursor, pageSize, keyOf) {
2773
- if (!scope || scope.length > 80 || !/^[a-z][a-z0-9_-]*$/.test(scope)) {
2774
- throw new errors_1.WebWorkbenchError(500, 'Collection scope is invalid.');
2775
- }
2776
- if (!Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > 100) {
2777
- throw new errors_1.WebWorkbenchError(400, 'pageSize must be an integer from 1 through 100.');
2778
- }
2779
- const keys = items.map(keyOf);
2780
- if (keys.some(key => !key || key.length > 4096) || new Set(keys).size !== keys.length) {
2781
- throw new errors_1.WebWorkbenchError(500, `Collection ${scope} has invalid or duplicate keys.`);
2782
- }
2783
- const revision = (0, canonical_1.digestRuntimeValue)(items);
2784
- let offset = 0;
2785
- if (cursor) {
2786
- const decoded = decodeCollectionCursor(cursor, scope);
2787
- if (decoded.revision !== revision) {
2788
- throw new errors_1.WebWorkbenchError(409, 'Collection changed after this page cursor was issued.', 'collection_cursor_stale');
2789
- }
2790
- offset = keys.indexOf(decoded.after) + 1;
2791
- if (offset === 0) {
2792
- throw new errors_1.WebWorkbenchError(409, 'Collection page boundary no longer exists.', 'collection_cursor_stale');
2793
- }
2794
- }
2795
- const page = items.slice(offset, offset + pageSize);
2796
- const nextOffset = offset + page.length;
2797
- return Object.freeze({
2798
- items: Object.freeze(page),
2799
- nextCursor: nextOffset < items.length && page.length > 0
2800
- ? encodeCollectionCursor(scope, revision, keys[nextOffset - 1])
2801
- : null,
2802
- });
2803
- }
2804
- function pageTranscriptTail(items, cursor, pageSize = 50) {
2805
- if (!Number.isSafeInteger(pageSize) || pageSize < 1 || pageSize > 100) {
2806
- throw new errors_1.WebWorkbenchError(400, 'pageSize must be an integer from 1 through 100.');
2807
- }
2808
- const end = cursor ? decodePageCursor(cursor) : items.length;
2809
- if (end > items.length)
2810
- throw new errors_1.WebWorkbenchError(400, 'Page cursor is out of range.');
2811
- const offset = Math.max(0, end - pageSize);
2812
- return Object.freeze({
2813
- items: Object.freeze(items.slice(offset, end)),
2814
- nextCursor: offset > 0 ? encodePageCursor(offset) : null,
2815
- offset,
2816
- });
2817
- }
2818
- function encodePageCursor(offset) {
2819
- return Buffer.from(JSON.stringify({ version: 1, offset })).toString('base64url');
2820
- }
2821
- function encodeCollectionCursor(scope, revision, after) {
2822
- return Buffer.from(JSON.stringify({ version: 2, kind: 'collection', scope, revision, after })).toString('base64url');
2823
- }
2824
- function decodeCollectionCursor(cursor, expectedScope) {
2825
- if (!cursor || cursor.length > 8192) {
2826
- throw new errors_1.WebWorkbenchError(400, 'Collection page cursor is invalid.');
2827
- }
2828
- try {
2829
- const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
2830
- if (!parsed ||
2831
- typeof parsed !== 'object' ||
2832
- Array.isArray(parsed) ||
2833
- parsed.version !== 2 ||
2834
- parsed.kind !== 'collection' ||
2835
- parsed.scope !== expectedScope ||
2836
- typeof parsed.revision !== 'string' ||
2837
- typeof parsed.after !== 'string') {
2838
- throw new Error('invalid');
2839
- }
2840
- return {
2841
- revision: parsed.revision,
2842
- after: parsed.after,
2843
- };
2844
- }
2845
- catch {
2846
- throw new errors_1.WebWorkbenchError(400, 'Collection page cursor is invalid.');
2847
- }
2848
- }
2849
- function decodePageCursor(cursor) {
2850
- if (!cursor || cursor.length > 512)
2851
- throw new errors_1.WebWorkbenchError(400, 'Page cursor is invalid.');
2852
- try {
2853
- const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
2854
- if (!parsed ||
2855
- typeof parsed !== 'object' ||
2856
- parsed.version !== 1 ||
2857
- !Number.isSafeInteger(parsed.offset) ||
2858
- (parsed.offset ?? -1) < 0) {
2859
- throw new Error('invalid cursor');
2860
- }
2861
- return parsed.offset;
2862
- }
2863
- catch {
2864
- throw new errors_1.WebWorkbenchError(400, 'Page cursor is invalid.');
2865
- }
2866
- }
2867
- function estimateSessionActorBytes(actor) {
2868
- try {
2869
- return Math.max(256 * 1024, Buffer.byteLength(JSON.stringify(actor.runtime.store.getSnapshot()), 'utf8'));
2870
- }
2871
- catch {
2872
- return 256 * 1024;
2873
- }
2874
- }
2875
- async function captureShutdownFailure(failures, operation) {
2876
- try {
2877
- await operation();
2878
- }
2879
- catch (error) {
2880
- failures.push(error);
2881
- }
2882
- }
2883
- /** v0.3.16 — markers that make a directory interesting as a project. */
2884
- const PROJECT_SIGNAL_MARKERS = [
2885
- '.git',
2886
- 'package.json',
2887
- 'pyproject.toml',
2888
- 'Cargo.toml',
2889
- 'go.mod',
2890
- ];
2891
- /**
2892
- * True when a directory looks like a project root. Only marker *existence* is
2893
- * checked — never file contents — which is what roots discovery filters on.
2894
- */
2895
- function hasProjectSignal(canonicalPath) {
2896
- return PROJECT_SIGNAL_MARKERS.some(marker => {
2897
- try {
2898
- return (0, fs_1.existsSync)((0, path_1.join)(canonicalPath, marker));
2899
- }
2900
- catch {
2901
- return false;
2902
- }
2903
- });
2904
- }
2905
- function requireCandidatePath(path) {
2906
- const trimmed = path.trim();
2907
- if (!trimmed) {
2908
- throw new errors_1.WebWorkbenchError(400, 'A directory path is required.', 'invalid_request');
2909
- }
2910
- if (trimmed.length > 4096) {
2911
- throw new errors_1.WebWorkbenchError(400, 'The directory path is too long.', 'invalid_request');
2912
- }
2913
- return trimmed;
2914
- }
2915
- /** Short budget: an unresponsive mount must never make the picker feel stuck. */
2916
- const INSPECT_BUDGET_MS = 250;
2917
- async function hasPath(absolute) {
2918
- try {
2919
- await (0, promises_1.access)(absolute);
2920
- return true;
2921
- }
2922
- catch {
2923
- return false;
2924
- }
2925
- }
2926
- /** `.git` as a directory (clone) or a file (worktree/submodule) both count. */
2927
- async function detectWorkspaceKind(canonicalPath) {
2928
- try {
2929
- await (0, promises_1.access)((0, path_1.join)(canonicalPath, '.git'));
2930
- return 'git';
2931
- }
2932
- catch {
2933
- return 'folder';
2934
- }
2935
- }
2936
- async function probeDirectory(absolute) {
2937
- let canonical;
2938
- try {
2939
- canonical = await (0, promises_1.realpath)(absolute);
2940
- }
2941
- catch {
2942
- return {
2943
- canonicalPath: absolute,
2944
- availability: (await hasPath(absolute)) ? 'unreadable' : 'missing',
2945
- kind: 'folder',
2946
- timedOut: false,
2947
- };
2948
- }
2949
- let stats;
2950
- try {
2951
- stats = await (0, promises_1.stat)(canonical);
2952
- }
2953
- catch {
2954
- return {
2955
- canonicalPath: canonical,
2956
- availability: 'unreadable',
2957
- kind: 'folder',
2958
- timedOut: false,
2959
- };
2960
- }
2961
- if (!stats.isDirectory()) {
2962
- return {
2963
- canonicalPath: canonical,
2964
- availability: 'not_directory',
2965
- kind: 'folder',
2966
- timedOut: false,
2967
- };
2968
- }
2969
- return {
2970
- canonicalPath: canonical,
2971
- availability: 'available',
2972
- kind: await detectWorkspaceKind(canonical),
2973
- timedOut: false,
2974
- };
2975
- }
2976
- /**
2977
- * Non-throwing canonicalization for the read-only inspector. `canonicalDirectory`
2978
- * below is the mutation path — it rejects missing or unreadable directories,
2979
- * which is what activation wants but not what a preview needs.
2980
- *
2981
- * The whole probe is raced against a short budget so an unresponsive network
2982
- * mount cannot freeze the event loop; on timeout the directory is reported
2983
- * `unreadable` and the caller can retry.
2984
- */
2985
- async function inspectDirectory(path) {
2986
- const absolute = (0, path_1.resolve)(path);
2987
- let timer;
2988
- const budget = new Promise(resolveBudget => {
2989
- timer = setTimeout(() => resolveBudget({
2990
- canonicalPath: absolute,
2991
- availability: 'unreadable',
2992
- kind: 'folder',
2993
- timedOut: true,
2994
- }), INSPECT_BUDGET_MS);
2995
- });
2996
- try {
2997
- return await Promise.race([probeDirectory(absolute), budget]);
2998
- }
2999
- finally {
3000
- if (timer)
3001
- clearTimeout(timer);
3002
- }
3003
- }
3004
- function canonicalDirectory(path) {
3005
- const candidate = (0, path_1.resolve)(path);
3006
- let canonical;
3007
- try {
3008
- canonical = (0, fs_1.realpathSync)(candidate);
3009
- }
3010
- catch {
3011
- throw new errors_1.WebWorkbenchError(400, 'Workspace path does not exist.');
3012
- }
3013
- try {
3014
- if (!(0, fs_1.statSync)(canonical).isDirectory()) {
3015
- throw new errors_1.WebWorkbenchError(400, 'Workspace path must be a directory.');
3016
- }
3017
- }
3018
- catch (error) {
3019
- if (error instanceof errors_1.WebWorkbenchError)
3020
- throw error;
3021
- throw new errors_1.WebWorkbenchError(400, 'Workspace path is not readable.');
3022
- }
3023
- return canonical;
3024
- }
3025
- function requireSession(sessionId) {
3026
- if (!sessionId.trim())
3027
- throw new errors_1.WebWorkbenchError(400, 'Session id is required.');
3028
- const session = (0, session_storage_1.loadSessionMeta)(sessionId);
3029
- if (!session)
3030
- throw new errors_1.WebWorkbenchError(404, 'Session was not found.');
3031
- return session;
3032
- }
3033
- /** Optional metadata must neither block the Host event loop nor delay creation indefinitely. */
3034
- function probeSessionGitBranch(workspace) {
3035
- return new Promise(resolveBranch => {
3036
- (0, child_process_1.execFile)('git', ['-C', workspace, 'rev-parse', '--abbrev-ref', 'HEAD'], {
3037
- encoding: 'utf8',
3038
- timeout: 250,
3039
- killSignal: 'SIGKILL',
3040
- maxBuffer: 4096,
3041
- env: process.env,
3042
- windowsHide: true,
3043
- }, (error, stdout) => resolveBranch(error ? undefined : stdout.trim() || undefined));
3044
- });
3045
- }
3046
- /**
3047
- * v0.3.29 — adapts the control-plane Runtime's LLM service to the shared code
3048
- * review runner's bounded single-completion interface. Returns null when the
3049
- * Host has no configured model so the run service can answer with the typed
3050
- * `review_no_model` error instead of pretending to review.
3051
- */
3052
- function createReviewModelAdapter(llm) {
3053
- if (!llm)
3054
- return null;
3055
- return {
3056
- async complete(messages) {
3057
- const response = await llm.chat(messages.map(message => ({ role: message.role, content: message.content })));
3058
- return {
3059
- content: response.content,
3060
- model: response.model,
3061
- usage: {
3062
- inputTokens: response.usage?.promptTokens ?? 0,
3063
- outputTokens: response.usage?.completionTokens ?? 0,
3064
- },
3065
- };
3066
- },
3067
- };
3068
- }
3069
- function mcpServerIds(config) {
3070
- const ids = new Set();
3071
- for (const envelope of [config.mcpServers, config.servers, config.orion?.mcp?.servers]) {
3072
- for (const id of Object.keys(envelope ?? {}))
3073
- ids.add(id);
3074
- }
3075
- return [...ids].sort();
3076
- }
3077
- //# sourceMappingURL=workbench-controller.js.map