@orion-agents/orion-code 0.3.66 → 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 +81 -0
  2. package/README.md +78 -361
  3. package/README.zh-CN.md +71 -262
  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 -133
  112. package/dist/runtime/release-receipts.js +129 -693
  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-CPDovK_K.js +0 -1
  335. package/dist/web-client/assets/GitPanel-DtU_TD61.js +0 -4
  336. package/dist/web-client/assets/ReviewPanel-vMO7BEA3.js +0 -6
  337. package/dist/web-client/assets/TerminalPanel-C9vDTAlS.js +0 -23
  338. package/dist/web-client/assets/TerminalPanel-DLuoa74B.css +0 -1
  339. package/dist/web-client/assets/index-CABdwh4l.css +0 -1
  340. package/dist/web-client/assets/index-KvshfEbl.js +0 -20
  341. package/dist/web-client/assets/useAutoNotice-IE1g2wcb.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,1453 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.startOrionWebServer = startOrionWebServer;
4
- const crypto_1 = require("crypto");
5
- const fs_1 = require("fs");
6
- const http_1 = require("http");
7
- const path_1 = require("path");
8
- const version_1 = require("../product/version");
9
- const redaction_1 = require("../services/redaction");
10
- const protocol_1 = require("./protocol");
11
- const errors_1 = require("./errors");
12
- const code_review_run_service_1 = require("./code-review-run-service");
13
- const cli_options_1 = require("./cli-options");
14
- const terminal_server_1 = require("./terminal-server");
15
- const workbench_controller_1 = require("./workbench-controller");
16
- const native_directory_picker_1 = require("./native-directory-picker");
17
- const HOST = '127.0.0.1';
18
- const API_PREFIX = '/api/v1';
19
- /**
20
- * Names that always resolve to this machine.
21
- *
22
- * The Host check exists to stop DNS rebinding: an attacker who points their own domain at
23
- * 127.0.0.1 still sends *their* name in the Host header, and that is what must be refused.
24
- * `localhost` is not attacker-controlled — it is resolved from the OS hosts file — so refusing
25
- * it only broke the most natural way to open the UI (`http://localhost:4242` returned 421 for
26
- * every request, including the document itself). The loopback block is accepted for the same
27
- * reason: the whole of 127.0.0.0/8 is this machine.
28
- */
29
- const LOOPBACK_HOSTNAMES = new Set(['localhost', '::1', '[::1]']);
30
- function isLoopbackHostname(hostname) {
31
- const value = hostname.toLowerCase();
32
- if (LOOPBACK_HOSTNAMES.has(value))
33
- return true;
34
- const octets = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/u.exec(value);
35
- if (!octets)
36
- return false;
37
- if (octets[1] !== '127')
38
- return false;
39
- return octets.slice(2).every(part => Number(part) <= 255);
40
- }
41
- /** Splits a Host header or an Origin into comparable parts. */
42
- function parseEndpoint(value) {
43
- if (!value)
44
- return null;
45
- try {
46
- const url = new URL(value.includes('://') ? value : `http://${value}`);
47
- return Object.freeze({
48
- protocol: url.protocol,
49
- hostname: url.hostname.toLowerCase(),
50
- // `new URL` normalises an explicit :80 away, so both sides go through this same path
51
- // and stay comparable.
52
- port: url.port || '80',
53
- });
54
- }
55
- catch {
56
- return null;
57
- }
58
- }
59
- /**
60
- * True when `actual` names the same loopback endpoint as the listener's `origin`.
61
- *
62
- * Shared by the Host and Origin checks on purpose: they used to compare differently, so fixing
63
- * one would have left the other still refusing `localhost` — and a mutation refused at the
64
- * Origin step looks nothing like a document refused at the Host step.
65
- *
66
- * The properties that make the check meaningful are preserved: the hostname must be a loopback
67
- * name (this is what stops DNS rebinding) and the port and scheme must match the listener.
68
- */
69
- function isSameLoopbackEndpoint(actual, origin) {
70
- const expected = parseEndpoint(origin);
71
- const candidate = parseEndpoint(actual);
72
- if (expected === null || candidate === null)
73
- return false;
74
- if (candidate.port !== expected.port)
75
- return false;
76
- if (candidate.protocol !== expected.protocol)
77
- return false;
78
- return isLoopbackHostname(candidate.hostname);
79
- }
80
- async function startOrionWebServer(options) {
81
- const requestedPort = options.port ?? cli_options_1.DEFAULT_WEB_PORT;
82
- if (!Number.isSafeInteger(requestedPort) || requestedPort < 0 || requestedPort > 65535) {
83
- throw new Error('Web port must be an integer from 0 through 65535.');
84
- }
85
- const nonce = options.nonce ?? (0, crypto_1.randomBytes)(32).toString('base64url');
86
- if (!/^[A-Za-z0-9_-]+$/u.test(nonce)) {
87
- throw new Error('Web nonce must use unpadded base64url characters.');
88
- }
89
- // v0.3.17 — E2E drives the picker from a script file so CI never opens a real
90
- // Finder dialog. Unset in production, which keeps the native adapter.
91
- const fixturePicker = (0, native_directory_picker_1.fixturePickerFromEnvironment)();
92
- const workbench = options.workbench ??
93
- (await workbench_controller_1.WebWorkbenchController.create({
94
- cwd: options.cwd,
95
- ...(fixturePicker ? { nativeDirectoryPicker: fixturePicker } : {}),
96
- }));
97
- const staticRoot = options.staticRoot ?? resolveDefaultStaticRoot();
98
- let origin = '';
99
- let closing;
100
- const server = (0, http_1.createServer)((request, response) => {
101
- void handleRequest({ request, response, nonce, origin, staticRoot, workbench }).catch(error => {
102
- if (response.headersSent) {
103
- response.destroy();
104
- return;
105
- }
106
- sendProblem(response, error);
107
- });
108
- });
109
- const terminalSockets = (0, terminal_server_1.attachTerminalWebSocketServer)(server, () => origin, workbench.terminalManager);
110
- server.requestTimeout = 30000;
111
- server.headersTimeout = 15000;
112
- server.keepAliveTimeout = 5000;
113
- server.maxHeadersCount = 64;
114
- await listen(server, requestedPort);
115
- const address = server.address();
116
- if (!address || typeof address === 'string') {
117
- await workbench.shutdown();
118
- throw new Error('Web server did not expose a TCP address.');
119
- }
120
- const port = address.port;
121
- origin = `http://${HOST}:${port}`;
122
- const heartbeat = setInterval(() => workbench.eventHub.heartbeat(), 15000);
123
- heartbeat.unref();
124
- const close = () => {
125
- if (closing)
126
- return closing;
127
- closing = (async () => {
128
- clearInterval(heartbeat);
129
- const failures = [];
130
- await captureCloseFailure(failures, () => terminalSockets.close());
131
- await captureCloseFailure(failures, () => workbench.shutdown());
132
- await captureCloseFailure(failures, () => closeServer(server));
133
- if (failures.length > 0) {
134
- const error = new Error('Orion Web Host shutdown was incomplete.');
135
- Object.defineProperty(error, 'failures', { value: Object.freeze([...failures]) });
136
- throw error;
137
- }
138
- })();
139
- return closing;
140
- };
141
- return Object.freeze({ host: HOST, port, url: origin, nonce, workbench, server, close });
142
- }
143
- async function captureCloseFailure(failures, operation) {
144
- try {
145
- await operation();
146
- }
147
- catch (error) {
148
- failures.push(error);
149
- }
150
- }
151
- async function handleRequest(context) {
152
- const { request, response } = context;
153
- applySecurityHeaders(response, context.nonce);
154
- assertHost(request, context.origin);
155
- const url = new URL(request.url ?? '/', context.origin);
156
- if (!url.pathname.startsWith(API_PREFIX)) {
157
- await serveStatic(request, response, url.pathname, context.staticRoot);
158
- return;
159
- }
160
- const path = url.pathname.slice(API_PREFIX.length) || '/';
161
- const method = request.method ?? 'GET';
162
- if (method === 'GET' && path === '/health') {
163
- sendJson(response, 200, { ok: true, version: version_1.PACKAGE_VERSION });
164
- return;
165
- }
166
- if (method === 'GET' && path === '/bootstrap') {
167
- sendJson(response, 200, context.workbench.bootstrap(context.nonce));
168
- return;
169
- }
170
- if (method === 'GET' && path === '/events') {
171
- openEventStream(request, response, url, context.workbench);
172
- return;
173
- }
174
- if (method === 'GET' && path === '/workspaces') {
175
- const contextGuard = requireContextGuardQuery(url);
176
- sendJson(response, 200, collectionPage(url, 'workspaces', context.workbench.listWorkspaces(contextGuard), workspace => workspace.id));
177
- return;
178
- }
179
- const workspaceSessionsMatch = path.match(/^\/workspaces\/([^/]+)\/sessions$/);
180
- if (method === 'GET' && workspaceSessionsMatch) {
181
- const workspaceId = safeDecodePathSegment(workspaceSessionsMatch[1]);
182
- const contextGuard = requireContextGuardQuery(url);
183
- sendJson(response, 200, collectionPage(url, `workspace-sessions-${workspaceId}`, context.workbench.listWorkspaceSessions(workspaceId, contextGuard), session => session.id));
184
- return;
185
- }
186
- const archivedSessionsMatch = path.match(/^\/workspaces\/([^/]+)\/sessions\/archived$/);
187
- if (method === 'GET' && archivedSessionsMatch) {
188
- const workspaceId = safeDecodePathSegment(archivedSessionsMatch[1]);
189
- const contextGuard = requireContextGuardQuery(url);
190
- sendJson(response, 200, collectionPage(url, `workspace-sessions-archived-${workspaceId}`, context.workbench.listArchivedWorkspaceSessions(workspaceId, contextGuard), session => session.id));
191
- return;
192
- }
193
- const workspaceSummaryMatch = path.match(/^\/workspaces\/([^/]+)\/summary$/);
194
- if (method === 'GET' && workspaceSummaryMatch) {
195
- const workspaceId = requireUuid(safeDecodePathSegment(workspaceSummaryMatch[1]), 'workspaceId');
196
- sendJson(response, 200, await context.workbench.workspaceProjectSummary(workspaceId, requireContextGuardQuery(url)));
197
- return;
198
- }
199
- const workspacePinMatch = path.match(/^\/workspaces\/([^/]+)\/pin$/);
200
- if (method === 'POST' && workspacePinMatch) {
201
- assertMutation(request, context.nonce, context.origin);
202
- const body = requireRecord(await readJson(request), 'Workspace pin request');
203
- assertOnlyKeys(body, ['requestId', 'pinned', 'expectedContextRevision', 'workspaceId']);
204
- const requestId = requireUuid(body.requestId, 'requestId');
205
- const contextGuard = requireContextGuardRecord(body);
206
- if (typeof body.pinned !== 'boolean') {
207
- throw new errors_1.WebWorkbenchError(400, 'pinned must be a boolean.', 'invalid_request');
208
- }
209
- const workspaceId = requireUuid(safeDecodePathSegment(workspacePinMatch[1]), 'workspaceId');
210
- const result = await context.workbench.executeMutation(requestId, 'workspace.pin', { targetWorkspaceId: workspaceId, pinned: body.pinned, ...contextGuard }, () => ({
211
- requestId,
212
- workspace: context.workbench.setWorkspacePinned(workspaceId, body.pinned, contextGuard),
213
- }));
214
- sendJson(response, 200, result);
215
- return;
216
- }
217
- const workspaceRemoveMatch = path.match(/^\/workspaces\/([^/]+)$/);
218
- if (method === 'DELETE' && workspaceRemoveMatch) {
219
- assertMutation(request, context.nonce, context.origin);
220
- const body = requireRecord(await readJson(request), 'Workspace removal request');
221
- assertOnlyKeys(body, ['requestId', 'expectedContextRevision', 'workspaceId']);
222
- const requestId = requireUuid(body.requestId, 'requestId');
223
- const contextGuard = requireContextGuardRecord(body);
224
- const workspaceId = requireUuid(safeDecodePathSegment(workspaceRemoveMatch[1]), 'workspaceId');
225
- const result = await context.workbench.executeMutation(requestId, 'workspace.remove', { targetWorkspaceId: workspaceId, ...contextGuard }, () => {
226
- context.workbench.removeWorkspace(workspaceId, contextGuard);
227
- return { requestId, removed: true };
228
- });
229
- sendJson(response, 200, result);
230
- return;
231
- }
232
- if (method === 'POST' && path === '/context/activate') {
233
- assertMutation(request, context.nonce, context.origin);
234
- const body = (0, protocol_1.parseWebContextActivate)(await readJson(request));
235
- const result = await context.workbench.executeMutation(body.requestId, 'context.activate', {
236
- expectedContextRevision: body.expectedContextRevision,
237
- workspaceId: body.workspaceId,
238
- sessionId: body.sessionId,
239
- }, async () => {
240
- await context.workbench.activateContext(body);
241
- return {
242
- requestId: body.requestId,
243
- contextRevision: context.workbench.contextRevision,
244
- bootstrap: context.workbench.bootstrap(context.nonce),
245
- };
246
- });
247
- sendJson(response, 200, result);
248
- return;
249
- }
250
- if (method === 'POST' && path === '/workspaces/activate') {
251
- assertMutation(request, context.nonce, context.origin);
252
- const body = requireRecord(await readJson(request), 'Workspace request');
253
- assertOnlyKeys(body, ['requestId', 'path', 'expectedContextRevision', 'workspaceId']);
254
- const requestId = requireUuid(body.requestId, 'requestId');
255
- const contextGuard = requireContextGuardRecord(body);
256
- const workspace = requireText(body.path, 'path', 4096);
257
- const result = await context.workbench.executeMutation(requestId, 'workspace.activate', { path: workspace, ...contextGuard }, async () => {
258
- await context.workbench.switchWorkspace(workspace, contextGuard, requestId);
259
- return {
260
- requestId,
261
- active: context.workbench.workspace,
262
- page: (0, workbench_controller_1.pageCollectionItems)('workspaces', context.workbench.listWorkspaces(), undefined, 50, workspace => workspace.id),
263
- };
264
- });
265
- sendJson(response, 200, result);
266
- return;
267
- }
268
- // v0.3.16 — open the OS directory picker. A browse action: the result is a
269
- // path the client must still confirm, so nothing is registered or activated.
270
- // v0.3.17 — browse admission: authenticated and single-flight, but NOT a
271
- // mutation. It must not raise the global Context mutation admission or enter
272
- // the idempotency ledger, otherwise an open Finder dialog looks like a busy
273
- // Runtime and a project switch is refused while the user is still browsing.
274
- if (method === 'POST' && path === '/workspaces/pick-directory') {
275
- assertMutation(request, context.nonce, context.origin);
276
- const body = requireRecord(await readJson(request), 'Directory pick request');
277
- assertOnlyKeys(body, ['requestId', 'title', 'initialPath']);
278
- const requestId = requireUuid(body.requestId, 'requestId');
279
- const title = optionalText(body.title, 'title', 200);
280
- const initialPath = optionalText(body.initialPath, 'initialPath', 4096);
281
- const picked = await context.workbench.pickDirectory({ title, initialPath, requestId });
282
- sendJson(response, 200, {
283
- requestId,
284
- outcome: picked.kind,
285
- ...(picked.kind === 'selected' ? { path: picked.path } : {}),
286
- ...(picked.kind === 'unavailable' ? { reason: picked.reason } : {}),
287
- });
288
- return;
289
- }
290
- // v0.3.16 — read-only preview of a candidate directory. Authenticated
291
- // transport only: no mutation reservation and no idempotency cache, because
292
- // this writes nothing and a retry is harmless.
293
- if (method === 'POST' && path === '/workspaces/inspect') {
294
- assertMutation(request, context.nonce, context.origin);
295
- const body = requireRecord(await readJson(request), 'Workspace inspect request');
296
- assertOnlyKeys(body, ['requestId', 'path', 'source']);
297
- const requestId = requireUuid(body.requestId, 'requestId');
298
- const candidatePath = requireText(body.path, 'path', 4096);
299
- const source = requireCandidateSource(optionalText(body.source, 'source', 32));
300
- const candidate = await context.workbench.inspectWorkspaceFast(candidatePath, source, requestId);
301
- sendJson(response, 200, { requestId, candidate });
302
- return;
303
- }
304
- // v0.3.21 — saved project roots: read-only list. Roots are scan boundaries,
305
- // not workspaces; listing them changes nothing.
306
- if (method === 'GET' && path === '/workspaces/roots') {
307
- sendJson(response, 200, { roots: context.workbench.listWorkspaceRoots() });
308
- return;
309
- }
310
- // v0.3.21 — add a root through the native picker's confirmed path. A local
311
- // configuration mutation: transport-guarded, naturally idempotent (roots
312
- // dedupe by canonical path), and never a Context mutation.
313
- if (method === 'POST' && path === '/workspaces/roots/add') {
314
- assertMutation(request, context.nonce, context.origin);
315
- const body = requireRecord(await readJson(request), 'Workspace root request');
316
- assertOnlyKeys(body, ['requestId', 'path']);
317
- const requestId = requireUuid(body.requestId, 'requestId');
318
- const rootPath = requireText(body.path, 'path', 4096);
319
- const root = await context.workbench.addWorkspaceRoot(rootPath, requestId);
320
- sendJson(response, 200, { requestId, root });
321
- return;
322
- }
323
- // v0.3.21 — remove a root. Cancels any in-flight scan for it first; the
324
- // workspaces registry is untouched.
325
- if (method === 'POST' && path === '/workspaces/roots/remove') {
326
- assertMutation(request, context.nonce, context.origin);
327
- const body = requireRecord(await readJson(request), 'Workspace root request');
328
- assertOnlyKeys(body, ['requestId', 'rootId']);
329
- const requestId = requireUuid(body.requestId, 'requestId');
330
- const rootId = requireText(body.rootId, 'rootId', 128);
331
- const removed = context.workbench.removeWorkspaceRoot(rootId);
332
- sendJson(response, 200, { requestId, removed });
333
- return;
334
- }
335
- // v0.3.21 — bounded discovery inside one saved root. Read-only, abortable,
336
- // host-wide single-flight; the newest request aborts the previous scan. A
337
- // candidate is a hint: the client still runs inspect → confirm → activate.
338
- if (method === 'POST' && path === '/workspaces/roots/discover') {
339
- assertMutation(request, context.nonce, context.origin);
340
- const body = requireRecord(await readJson(request), 'Workspace discovery request');
341
- assertOnlyKeys(body, ['requestId', 'rootId', 'refresh']);
342
- const requestId = requireUuid(body.requestId, 'requestId');
343
- const rootId = requireText(body.rootId, 'rootId', 128);
344
- const refresh = body.refresh === undefined ? true : body.refresh === true;
345
- const outcome = await context.workbench.discoverWorkspaceRoot(rootId, requestId, { refresh });
346
- sendJson(response, 200, outcome);
347
- return;
348
- }
349
- if (method === 'GET' && path === '/sessions') {
350
- const contextGuard = requireContextGuardQuery(url);
351
- sendJson(response, 200, collectionPage(url, 'sessions', context.workbench.listSessions(contextGuard), session => session.id));
352
- return;
353
- }
354
- if (method === 'POST' && path === '/sessions') {
355
- assertMutation(request, context.nonce, context.origin);
356
- const body = requireRecord(await readJson(request), 'Session request');
357
- assertOnlyKeys(body, ['requestId', 'name', 'expectedContextRevision', 'workspaceId']);
358
- const requestId = requireUuid(body.requestId, 'requestId');
359
- const contextGuard = requireContextGuardRecord(body);
360
- const name = body.name === undefined ? undefined : requireText(body.name, 'name', 120);
361
- const result = await context.workbench.executeMutation(requestId, 'session.create', { name, ...contextGuard }, async () => ({
362
- requestId,
363
- session: await context.workbench.createSession(name, contextGuard),
364
- }));
365
- sendJson(response, 201, result);
366
- return;
367
- }
368
- const activateMatch = path.match(/^\/sessions\/([^/]+)\/activate$/);
369
- if (method === 'POST' && activateMatch) {
370
- assertMutation(request, context.nonce, context.origin);
371
- const body = requireRecord(await readJson(request), 'Session activation request');
372
- assertOnlyKeys(body, ['requestId', 'expectedContextRevision', 'workspaceId']);
373
- const requestId = requireUuid(body.requestId, 'requestId');
374
- const contextGuard = requireContextGuardRecord(body);
375
- const sessionId = safeDecodePathSegment(activateMatch[1]);
376
- const result = await context.workbench.executeMutation(requestId, 'session.activate', { sessionId, ...contextGuard }, async () => ({
377
- ...(await context.workbench.activateSession(sessionId, contextGuard)),
378
- requestId,
379
- }));
380
- sendJson(response, 200, result);
381
- return;
382
- }
383
- const snapshotMatch = path.match(/^\/sessions\/([^/]+)\/snapshot$/);
384
- if (method === 'GET' && snapshotMatch) {
385
- const contextGuard = requireContextGuardQuery(url);
386
- sendJson(response, 200, context.workbench.sessionSnapshot(safeDecodePathSegment(snapshotMatch[1]), url.searchParams.get('cursor') ?? undefined, pageSize(url),
387
- // A recovery snapshot starts at the latest bounded transcript page and
388
- // pages backward. Older clients did not send the internal `tail=1`
389
- // hint, so absence must still use the indexed tail path rather than
390
- // reopening and replaying the complete Thread.
391
- url.searchParams.get('tail') !== '0', contextGuard));
392
- return;
393
- }
394
- const composerStateMatch = path.match(/^\/sessions\/([^/]+)\/composer-state$/);
395
- if (method === 'GET' && composerStateMatch) {
396
- const contextGuard = requireContextGuardQuery(url);
397
- sendJson(response, 200, context.workbench.composerState(safeDecodePathSegment(composerStateMatch[1]), contextGuard));
398
- return;
399
- }
400
- const modelCatalogMatch = path.match(/^\/sessions\/([^/]+)\/model-catalog$/);
401
- if (method === 'GET' && modelCatalogMatch) {
402
- const contextGuard = requireContextGuardQuery(url);
403
- const sessionId = safeDecodePathSegment(modelCatalogMatch[1]);
404
- const catalog = context.workbench.modelCatalog(sessionId, contextGuard);
405
- const page = (0, workbench_controller_1.pageCollectionItems)('composer_models', catalog.models, url.searchParams.get('cursor') ?? undefined, pageSize(url), model => model.id);
406
- sendJson(response, 200, {
407
- revision: catalog.revision,
408
- unavailableProviders: catalog.unavailableProviders,
409
- ...page,
410
- });
411
- return;
412
- }
413
- const composerActionMatch = path.match(/^\/sessions\/([^/]+)\/composer-actions$/);
414
- if (method === 'POST' && composerActionMatch) {
415
- assertMutation(request, context.nonce, context.origin);
416
- const sessionId = safeDecodePathSegment(composerActionMatch[1]);
417
- const body = (0, protocol_1.parseWebComposerAction)(await readJson(request));
418
- if (body.expectedSessionId !== sessionId) {
419
- throw new protocol_1.WebProtocolError('expectedSessionId must match the Composer action route');
420
- }
421
- const result = await context.workbench.executeMutation(body.requestId, 'composer.action', body, () => context.workbench.applyComposerAction(body));
422
- sendJson(response, 200, result);
423
- return;
424
- }
425
- const sessionMatch = path.match(/^\/sessions\/([^/]+)$/);
426
- if (method === 'PATCH' && sessionMatch) {
427
- assertMutation(request, context.nonce, context.origin);
428
- const body = requireRecord(await readJson(request), 'Session update request');
429
- assertOnlyKeys(body, ['requestId', 'name', 'expectedContextRevision', 'workspaceId']);
430
- const requestId = requireUuid(body.requestId, 'requestId');
431
- const contextGuard = requireContextGuardRecord(body);
432
- const name = requireText(body.name, 'name', 120);
433
- const sessionId = safeDecodePathSegment(sessionMatch[1]);
434
- const result = await context.workbench.executeMutation(requestId, 'session.rename', { sessionId, name, ...contextGuard }, () => ({
435
- requestId,
436
- session: context.workbench.renameSession(sessionId, name, contextGuard),
437
- }));
438
- sendJson(response, 200, result);
439
- return;
440
- }
441
- // v0.3.7 — Session tags / archive / restore / delete. One mutation family:
442
- // every body carries a requestId so the idempotency ledger dedupes retries.
443
- const sessionTagsMatch = path.match(/^\/sessions\/([^/]+)\/tags$/);
444
- if (method === 'POST' && sessionTagsMatch) {
445
- assertMutation(request, context.nonce, context.origin);
446
- const body = requireRecord(await readJson(request), 'Session tags request');
447
- assertOnlyKeys(body, ['requestId', 'tags', 'expectedContextRevision', 'workspaceId']);
448
- const requestId = requireUuid(body.requestId, 'requestId');
449
- const contextGuard = requireContextGuardRecord(body);
450
- const sessionId = safeDecodePathSegment(sessionTagsMatch[1]);
451
- const result = await context.workbench.executeMutation(requestId, 'session.tags', { sessionId, tags: body.tags, ...contextGuard }, () => ({
452
- requestId,
453
- session: context.workbench.setSessionTags(sessionId, body.tags, contextGuard),
454
- }));
455
- sendJson(response, 200, result);
456
- return;
457
- }
458
- const sessionArchiveMatch = path.match(/^\/sessions\/([^/]+)\/archive$/);
459
- if (method === 'POST' && sessionArchiveMatch) {
460
- assertMutation(request, context.nonce, context.origin);
461
- const body = requireRecord(await readJson(request), 'Session archive request');
462
- assertOnlyKeys(body, ['requestId', 'expectedContextRevision', 'workspaceId']);
463
- const requestId = requireUuid(body.requestId, 'requestId');
464
- const contextGuard = requireContextGuardRecord(body);
465
- const sessionId = safeDecodePathSegment(sessionArchiveMatch[1]);
466
- const result = await context.workbench.executeMutation(requestId, 'session.archive', { sessionId, ...contextGuard }, () => ({
467
- requestId,
468
- session: context.workbench.archiveSession(sessionId, contextGuard),
469
- }));
470
- sendJson(response, 200, result);
471
- return;
472
- }
473
- const sessionRestoreMatch = path.match(/^\/sessions\/([^/]+)\/restore$/);
474
- if (method === 'POST' && sessionRestoreMatch) {
475
- assertMutation(request, context.nonce, context.origin);
476
- const body = requireRecord(await readJson(request), 'Session restore request');
477
- assertOnlyKeys(body, ['requestId', 'expectedContextRevision', 'workspaceId']);
478
- const requestId = requireUuid(body.requestId, 'requestId');
479
- const contextGuard = requireContextGuardRecord(body);
480
- const sessionId = safeDecodePathSegment(sessionRestoreMatch[1]);
481
- const result = await context.workbench.executeMutation(requestId, 'session.restore', { sessionId, ...contextGuard }, () => ({
482
- requestId,
483
- session: context.workbench.restoreSession(sessionId, contextGuard),
484
- }));
485
- sendJson(response, 200, result);
486
- return;
487
- }
488
- const sessionDeleteMatch = path.match(/^\/sessions\/([^/]+)$/);
489
- if (method === 'DELETE' && sessionDeleteMatch) {
490
- assertMutation(request, context.nonce, context.origin);
491
- const body = requireRecord(await readJson(request), 'Session delete request');
492
- assertOnlyKeys(body, ['requestId', 'expectedContextRevision', 'workspaceId']);
493
- const requestId = requireUuid(body.requestId, 'requestId');
494
- const contextGuard = requireContextGuardRecord(body);
495
- const sessionId = safeDecodePathSegment(sessionDeleteMatch[1]);
496
- const result = await context.workbench.executeMutation(requestId, 'session.delete', { sessionId, ...contextGuard }, () => ({
497
- requestId,
498
- deleted: context.workbench.deleteSession(sessionId, contextGuard).deleted,
499
- }));
500
- sendJson(response, 200, result);
501
- return;
502
- }
503
- if (method === 'POST' && path === '/commands') {
504
- assertMutation(request, context.nonce, context.origin);
505
- sendJson(response, 202, await context.workbench.dispatch(await readJson(request)));
506
- return;
507
- }
508
- if (method === 'GET' && path === '/settings') {
509
- sendJson(response, 200, await context.workbench.settings());
510
- return;
511
- }
512
- if (method === 'PATCH' && path === '/settings') {
513
- assertMutation(request, context.nonce, context.origin, 'settings_write_forbidden');
514
- const body = (0, protocol_1.parseWebSettingsUpdate)(await readJson(request));
515
- const result = await context.workbench.executeMutation(body.requestId, 'settings.update', {
516
- workspaceId: body.workspaceId,
517
- expectedContextRevision: body.expectedContextRevision,
518
- expectedRevision: body.expectedRevision,
519
- operations: body.operations,
520
- }, async () => ({ requestId: body.requestId, ...(await context.workbench.updateSettings(body)) }));
521
- sendJson(response, 200, result);
522
- return;
523
- }
524
- if (method === 'POST' && path === '/settings/open-document') {
525
- assertMutation(request, context.nonce, context.origin, 'settings_write_forbidden');
526
- const { requestId } = (0, protocol_1.parseWebOpenSettingsDocument)(await readJson(request));
527
- const result = await context.workbench.executeMutation(requestId, 'settings.open-document', {}, async () => ({ requestId, opened: await context.workbench.openSettingsDocument() }));
528
- sendJson(response, 200, result);
529
- return;
530
- }
531
- if (method === 'GET' && path === '/skills') {
532
- const contextGuard = requireContextGuardQuery(url);
533
- sendJson(response, 200, collectionPage(url, 'skills', await context.workbench.skills(contextGuard), skill => skill.id));
534
- return;
535
- }
536
- if (method === 'GET' && path === '/mcp') {
537
- const contextGuard = requireContextGuardQuery(url);
538
- sendJson(response, 200, collectionPage(url, 'mcp', context.workbench.mcp(contextGuard), server => server.id));
539
- return;
540
- }
541
- if (method === 'GET' && path === '/files/search') {
542
- const contextGuard = requireContextGuardQuery(url);
543
- const query = url.searchParams.get('q') ?? '';
544
- const scopeValue = url.searchParams.get('scope');
545
- const scope = scopeValue === 'content' ? 'content' : 'name';
546
- const limit = boundedInteger(url.searchParams.get('limit'), 50, 1, 200);
547
- sendJson(response, 200, context.workbench.searchFiles(contextGuard, { query, scope, limit }));
548
- return;
549
- }
550
- if (method === 'GET' && path === '/files') {
551
- const contextGuard = requireContextGuardQuery(url);
552
- sendJson(response, 200, context.workbench.listFiles(contextGuard, {
553
- ...(url.searchParams.get('parentId')
554
- ? { parentId: url.searchParams.get('parentId') }
555
- : {}),
556
- ...(url.searchParams.get('cursor')
557
- ? { cursor: url.searchParams.get('cursor') }
558
- : {}),
559
- pageSize: pageSize(url),
560
- }));
561
- return;
562
- }
563
- const fileContentMatch = path.match(/^\/files\/([^/]+)\/content$/);
564
- if (method === 'GET' && fileContentMatch) {
565
- const contextGuard = requireContextGuardQuery(url);
566
- sendJson(response, 200, context.workbench.readFileContent(contextGuard, {
567
- fileId: safeDecodePathSegment(fileContentMatch[1]),
568
- ...(url.searchParams.get('cursor')
569
- ? { cursor: url.searchParams.get('cursor') }
570
- : {}),
571
- limitBytes: boundedInteger(url.searchParams.get('limitBytes'), 64 * 1024, 1, 256 * 1024),
572
- }));
573
- return;
574
- }
575
- if (method === 'GET' && path === '/git/status') {
576
- const contextGuard = requireContextGuardQuery(url);
577
- const group = url.searchParams.get('group');
578
- const searchQuery = url.searchParams.get('query');
579
- sendJson(response, 200, await context.workbench.gitStatus(contextGuard, {
580
- ...(url.searchParams.get('cursor')
581
- ? { cursor: url.searchParams.get('cursor') }
582
- : {}),
583
- pageSize: boundedInteger(url.searchParams.get('pageSize'), 200, 1, 2000),
584
- // v0.3.17 S1 — filtering happens in the Host so result counts cover the whole
585
- // matching set. v0.3.17 S4 — the cast is to the *working-tree* source set: a status
586
- // query can never filter by the comparison-only `commit` source, and the service
587
- // validates the value either way.
588
- ...(group ? { group: group } : {}),
589
- ...(searchQuery ? { query: searchQuery } : {}),
590
- }));
591
- return;
592
- }
593
- const fileWriteMatch = path === '/files/write';
594
- if (method === 'POST' && fileWriteMatch) {
595
- assertMutation(request, context.nonce, context.origin, 'file_mutation_forbidden');
596
- assertFileUserGesture(request);
597
- const body = requireRecord(await readJson(request), 'File write request');
598
- assertOnlyKeys(body, [
599
- 'requestId',
600
- 'fileId',
601
- 'content',
602
- 'expectedRevision',
603
- 'workspaceId',
604
- 'expectedContextRevision',
605
- ]);
606
- const requestId = requireUuid(body.requestId, 'requestId');
607
- const contextGuard = requireContextGuardRecord(body);
608
- const fileId = requireText(body.fileId, 'fileId', 256);
609
- const content = requireText(body.content, 'content', 512 * 1024 + 8);
610
- const expectedRevision = requireFileRevision(body.expectedRevision);
611
- const result = await context.workbench.executeMutation(requestId, 'file.write', { fileId, expectedRevision, ...contextGuard }, () => context.workbench.writeFileContent(contextGuard, {
612
- fileId,
613
- content,
614
- expectedRevision,
615
- }));
616
- sendJson(response, 200, result);
617
- return;
618
- }
619
- if (method === 'POST' && (path === '/git/stage' || path === '/git/unstage')) {
620
- assertMutation(request, context.nonce, context.origin, 'git_mutation_forbidden');
621
- assertGitUserGesture(request);
622
- const body = requireRecord(await readJson(request), 'Git stage request');
623
- assertOnlyKeys(body, [
624
- 'requestId',
625
- 'expectedContextRevision',
626
- 'workspaceId',
627
- 'fileIds',
628
- 'expectedRepositoryRevision',
629
- ]);
630
- const requestId = requireUuid(body.requestId, 'requestId');
631
- const contextGuard = requireContextGuardRecord(body);
632
- const fileIds = requireStringArray(body.fileIds, 'fileIds', 200, 256);
633
- const expectedRepositoryRevision = requireGitRevision(body.expectedRepositoryRevision);
634
- const action = path === '/git/stage' ? 'stage' : 'unstage';
635
- const result = await context.workbench.executeMutation(requestId, 'git.mutation', { action, fileIds, expectedRepositoryRevision, ...contextGuard }, async () => action === 'stage'
636
- ? context.workbench.gitStage(contextGuard, { fileIds, expectedRepositoryRevision })
637
- : context.workbench.gitUnstage(contextGuard, { fileIds, expectedRepositoryRevision }));
638
- sendJson(response, 200, result);
639
- return;
640
- }
641
- if (method === 'GET' && path === '/git/commit/preview') {
642
- const contextGuard = requireContextGuardQuery(url);
643
- sendJson(response, 200, await context.workbench.gitCommitPreview(contextGuard));
644
- return;
645
- }
646
- // v0.3.17 S4 — history reads. All of these are read-only: none of them can touch the
647
- // working tree or the index, which is the S4 exit criterion.
648
- if (method === 'GET' && path === '/git/refs') {
649
- const contextGuard = requireContextGuardQuery(url);
650
- sendJson(response, 200, await context.workbench.gitRefs(contextGuard));
651
- return;
652
- }
653
- if (method === 'GET' && path === '/git/history') {
654
- const contextGuard = requireContextGuardQuery(url);
655
- sendJson(response, 200, await context.workbench.gitHistory(contextGuard, {
656
- ...optionalQueryParams(url, [
657
- 'message',
658
- 'author',
659
- 'sha',
660
- 'path',
661
- 'since',
662
- 'until',
663
- 'rev',
664
- 'cursor',
665
- ]),
666
- pageSize: boundedInteger(url.searchParams.get('pageSize'), 30, 1, 100),
667
- }));
668
- return;
669
- }
670
- if (method === 'GET' && path === '/git/compare') {
671
- const contextGuard = requireContextGuardQuery(url);
672
- const baseRef = url.searchParams.get('base');
673
- const headRef = url.searchParams.get('head');
674
- const mode = url.searchParams.get('mode') === 'merge-base' ? 'merge-base' : 'snapshot';
675
- if (!baseRef || !headRef)
676
- throw new HttpProblem(400, 'base and head are required.');
677
- sendJson(response, 200, await context.workbench.gitCompare(contextGuard, { baseRef, headRef, mode }));
678
- return;
679
- }
680
- if (method === 'GET' && path === '/git/compare/file') {
681
- const contextGuard = requireContextGuardQuery(url);
682
- const baseOid = url.searchParams.get('baseOid');
683
- const headOid = url.searchParams.get('headOid');
684
- const filePath = url.searchParams.get('path');
685
- if (!baseOid || !headOid || !filePath) {
686
- throw new HttpProblem(400, 'baseOid, headOid and path are required.');
687
- }
688
- sendJson(response, 200, await context.workbench.gitCompareFileDiff(contextGuard, {
689
- baseOid,
690
- headOid,
691
- path: filePath,
692
- ...(url.searchParams.get('cursor')
693
- ? { cursor: url.searchParams.get('cursor') }
694
- : {}),
695
- }));
696
- return;
697
- }
698
- if (method === 'GET' && path === '/git/blame') {
699
- const contextGuard = requireContextGuardQuery(url);
700
- const filePath = url.searchParams.get('path');
701
- if (!filePath)
702
- throw new HttpProblem(400, 'path is required.');
703
- sendJson(response, 200, await context.workbench.gitBlame(contextGuard, {
704
- path: filePath,
705
- ...(url.searchParams.get('rev') ? { rev: url.searchParams.get('rev') } : {}),
706
- limit: boundedInteger(url.searchParams.get('limit'), 2000, 1, 5000),
707
- }));
708
- return;
709
- }
710
- if (method === 'GET' && path === '/git/graph') {
711
- const contextGuard = requireContextGuardQuery(url);
712
- sendJson(response, 200, await context.workbench.gitGraph(contextGuard, {
713
- limit: boundedInteger(url.searchParams.get('limit'), 200, 1, 2000),
714
- }));
715
- return;
716
- }
717
- if (method === 'GET' && path === '/git/files-target') {
718
- const contextGuard = requireContextGuardQuery(url);
719
- const fileToken = url.searchParams.get('fileToken');
720
- if (!fileToken)
721
- throw new HttpProblem(400, 'fileToken is required.');
722
- sendJson(response, 200, await context.workbench.gitFilesTarget(contextGuard, fileToken));
723
- return;
724
- }
725
- if (method === 'GET' && path === '/git/submodules') {
726
- const contextGuard = requireContextGuardQuery(url);
727
- sendJson(response, 200, await context.workbench.gitSubmodules(contextGuard));
728
- return;
729
- }
730
- if (method === 'GET' && path === '/git/conflict') {
731
- const contextGuard = requireContextGuardQuery(url);
732
- const filePath = url.searchParams.get('path');
733
- if (!filePath)
734
- throw new HttpProblem(400, 'path is required.');
735
- sendJson(response, 200, await context.workbench.gitConflictVersions(contextGuard, filePath));
736
- return;
737
- }
738
- if (method === 'GET' && path === '/git/blob') {
739
- const contextGuard = requireContextGuardQuery(url);
740
- const filePath = url.searchParams.get('path');
741
- const rev = url.searchParams.get('rev');
742
- if (!filePath || !rev)
743
- throw new HttpProblem(400, 'path and rev are required.');
744
- sendJson(response, 200, await context.workbench.gitBlob(contextGuard, { path: filePath, rev }));
745
- return;
746
- }
747
- if (method === 'GET' && path === '/git/file-history') {
748
- const contextGuard = requireContextGuardQuery(url);
749
- const filePath = url.searchParams.get('path');
750
- if (!filePath)
751
- throw new HttpProblem(400, 'path is required.');
752
- sendJson(response, 200, await context.workbench.gitFileHistory(contextGuard, {
753
- path: filePath,
754
- ...(url.searchParams.get('rev') ? { rev: url.searchParams.get('rev') } : {}),
755
- limit: boundedInteger(url.searchParams.get('limit'), 30, 1, 200),
756
- }));
757
- return;
758
- }
759
- if (method === 'GET' && path.startsWith('/git/commit/')) {
760
- const contextGuard = requireContextGuardQuery(url);
761
- const [, , , rawOid, sub] = path.split('/');
762
- const oid = decodeURIComponent(rawOid ?? '');
763
- const parentIndex = boundedInteger(url.searchParams.get('parent'), 0, 0, 63);
764
- if (sub === 'files') {
765
- sendJson(response, 200, await context.workbench.gitCommitFiles(contextGuard, oid, parentIndex));
766
- return;
767
- }
768
- if (sub === 'diff') {
769
- const filePath = url.searchParams.get('path');
770
- if (!filePath)
771
- throw new HttpProblem(400, 'path is required.');
772
- sendJson(response, 200, await context.workbench.gitCommitDiff(contextGuard, {
773
- oid,
774
- path: filePath,
775
- parentIndex,
776
- ...(url.searchParams.get('cursor')
777
- ? { cursor: url.searchParams.get('cursor') }
778
- : {}),
779
- }));
780
- return;
781
- }
782
- sendJson(response, 200, await context.workbench.gitCommitDetail(contextGuard, oid, parentIndex));
783
- return;
784
- }
785
- // v0.3.17 S3 — hunk / line level staging. The body carries ids only; the Host rebuilds the
786
- // patch from the reviewed document, so a browser can never submit patch text or Git flags.
787
- if (method === 'POST' && path === '/git/patch') {
788
- assertMutation(request, context.nonce, context.origin, 'git_mutation_forbidden');
789
- assertGitUserGesture(request);
790
- const body = requireRecord(await readJson(request), 'Git patch request');
791
- assertOnlyKeys(body, [
792
- 'requestId',
793
- 'expectedContextRevision',
794
- 'workspaceId',
795
- 'fileId',
796
- 'hunkIds',
797
- 'lineIds',
798
- 'expectedRepositoryRevision',
799
- ]);
800
- const requestId = requireUuid(body.requestId, 'requestId');
801
- const contextGuard = requireContextGuardRecord(body);
802
- const fileId = requireText(body.fileId, 'fileId', 256);
803
- const hunkIds = optionalStringList(body.hunkIds, 'hunkIds', 200, 256);
804
- const lineIds = optionalStringList(body.lineIds, 'lineIds', 2000, 256);
805
- if (hunkIds.length === 0 && lineIds.length === 0) {
806
- throw new errors_1.WebWorkbenchError(400, 'Select at least one hunk or line.', 'git_patch_invalid');
807
- }
808
- const expectedRepositoryRevision = requireGitRevision(body.expectedRepositoryRevision);
809
- const result = await context.workbench.executeMutation(requestId, 'git.patch', { fileId, hunkIds, lineIds, expectedRepositoryRevision, ...contextGuard }, async () => context.workbench.gitApplyPatch(contextGuard, {
810
- fileId,
811
- hunkIds,
812
- lineIds,
813
- expectedRepositoryRevision,
814
- }));
815
- sendJson(response, 200, result);
816
- return;
817
- }
818
- if (method === 'POST' && path === '/git/commit') {
819
- assertMutation(request, context.nonce, context.origin, 'git_mutation_forbidden');
820
- assertGitUserGesture(request);
821
- const body = requireRecord(await readJson(request), 'Git commit request');
822
- assertOnlyKeys(body, [
823
- 'requestId',
824
- 'expectedContextRevision',
825
- 'workspaceId',
826
- 'summary',
827
- 'body',
828
- 'expectedRepositoryRevision',
829
- ]);
830
- const requestId = requireUuid(body.requestId, 'requestId');
831
- const contextGuard = requireContextGuardRecord(body);
832
- // Newlines are legitimate in a commit body; only control characters are rejected, and
833
- // that check lives with the message builder so the two never drift apart.
834
- const summary = requireText(body.summary, 'summary', 2000);
835
- const commitBody = body.body === undefined ? undefined : requireTextAllowingNewlines(body.body, 'body', 20000);
836
- const expectedRepositoryRevision = requireGitRevision(body.expectedRepositoryRevision);
837
- const result = await context.workbench.executeMutation(requestId, 'git.commit', { summary, body: commitBody, expectedRepositoryRevision, ...contextGuard }, async () => context.workbench.gitCommit(contextGuard, {
838
- summary,
839
- ...(commitBody === undefined ? {} : { body: commitBody }),
840
- expectedRepositoryRevision,
841
- requestId,
842
- }));
843
- sendJson(response, 200, result);
844
- return;
845
- }
846
- if (method === 'GET' && path === '/git/log') {
847
- const contextGuard = requireContextGuardQuery(url);
848
- sendJson(response, 200, await context.workbench.gitLog(contextGuard, {
849
- ...(url.searchParams.get('cursor')
850
- ? { cursor: url.searchParams.get('cursor') }
851
- : {}),
852
- pageSize: boundedInteger(url.searchParams.get('pageSize'), 30, 1, 100),
853
- }));
854
- return;
855
- }
856
- const gitDiffV2Match = path.match(/^\/git\/diff-v2\/([^/]+)$/);
857
- if (method === 'GET' && gitDiffV2Match) {
858
- const contextGuard = requireContextGuardQuery(url);
859
- sendJson(response, 200, await context.workbench.gitDiffDocument(contextGuard, {
860
- fileId: safeDecodePathSegment(gitDiffV2Match[1]),
861
- ...(url.searchParams.get('cursor')
862
- ? { cursor: url.searchParams.get('cursor') }
863
- : {}),
864
- lineLimit: boundedInteger(url.searchParams.get('lineLimit'), 240, 1, 500),
865
- byteLimit: boundedInteger(url.searchParams.get('byteLimit'), 256 * 1024, 1024, 1024 * 1024),
866
- // v0.3.17 S5 — bound into the pagination cursor by the service.
867
- ...(url.searchParams.get('ignoreWhitespace') === '1' ? { ignoreWhitespace: true } : {}),
868
- ...(url.searchParams.get('wordDiff') === '1' ? { wordDiff: true } : {}),
869
- }));
870
- return;
871
- }
872
- const gitDiffMatch = path.match(/^\/git\/diff\/([^/]+)$/);
873
- if (method === 'GET' && gitDiffMatch) {
874
- const contextGuard = requireContextGuardQuery(url);
875
- sendJson(response, 200, await context.workbench.gitDiff(contextGuard, {
876
- fileId: safeDecodePathSegment(gitDiffMatch[1]),
877
- ...(url.searchParams.get('cursor')
878
- ? { cursor: url.searchParams.get('cursor') }
879
- : {}),
880
- lineLimit: boundedInteger(url.searchParams.get('lineLimit'), 240, 1, 500),
881
- byteLimit: boundedInteger(url.searchParams.get('byteLimit'), 256 * 1024, 1024, 1024 * 1024),
882
- }));
883
- return;
884
- }
885
- if (method === 'GET' && path === '/review') {
886
- sendJson(response, 200, await context.workbench.review(requireContextGuardQuery(url)));
887
- return;
888
- }
889
- // v0.3.29 — shared code-review runs. Start is a fast mutation (admission
890
- // only; the model completion runs in the background and clients poll the
891
- // read-only list/get endpoints below).
892
- if (method === 'POST' && path === '/review/run') {
893
- assertMutation(request, context.nonce, context.origin);
894
- const body = requireRecord(await readJson(request), 'Review run request');
895
- assertOnlyKeys(body, ['requestId', 'selector', 'expectedContextRevision', 'workspaceId']);
896
- const requestId = requireUuid(body.requestId, 'requestId');
897
- const contextGuard = requireContextGuardRecord(body);
898
- const selector = (0, code_review_run_service_1.parseWebReviewSelectorV1)(body.selector);
899
- const result = await context.workbench.executeMutation(requestId, 'review.run', { selector, ...contextGuard }, () => context.workbench.reviewRunStart(selector, contextGuard));
900
- sendJson(response, 200, result);
901
- return;
902
- }
903
- if (method === 'GET' && path === '/review/runs') {
904
- sendJson(response, 200, await context.workbench.reviewRunList(requireContextGuardQuery(url)));
905
- return;
906
- }
907
- const reviewRunMatch = path.match(/^\/review\/runs\/([^/]+)$/);
908
- if (method === 'GET' && reviewRunMatch) {
909
- const runId = requireUuid(safeDecodePathSegment(reviewRunMatch[1]), 'runId');
910
- sendJson(response, 200, await context.workbench.reviewRunGet(runId, requireContextGuardQuery(url)));
911
- return;
912
- }
913
- const reviewRunCancelMatch = path.match(/^\/review\/runs\/([^/]+)\/cancel$/);
914
- if (method === 'POST' && reviewRunCancelMatch) {
915
- assertMutation(request, context.nonce, context.origin);
916
- const body = requireRecord(await readJson(request), 'Review cancel request');
917
- assertOnlyKeys(body, ['requestId', 'expectedContextRevision', 'workspaceId']);
918
- const requestId = requireUuid(body.requestId, 'requestId');
919
- const contextGuard = requireContextGuardRecord(body);
920
- const runId = requireUuid(safeDecodePathSegment(reviewRunCancelMatch[1]), 'runId');
921
- const result = await context.workbench.executeMutation(requestId, 'review.run.cancel', { runId, ...contextGuard }, () => context.workbench.reviewRunCancel(runId, contextGuard));
922
- sendJson(response, 200, result);
923
- return;
924
- }
925
- if (method === 'GET' && path === '/terminals') {
926
- const contextGuard = requireContextGuardQuery(url);
927
- sendJson(response, 200, collectionPage(url, 'terminals', context.workbench.listTerminals(contextGuard), terminal => terminal.id));
928
- return;
929
- }
930
- if (method === 'POST' && path === '/terminals') {
931
- assertMutation(request, context.nonce, context.origin, 'terminal_create_forbidden');
932
- assertTerminalUserGesture(request);
933
- const body = requireRecord(await readJson(request), 'Terminal create request');
934
- assertOnlyKeys(body, ['requestId', 'expectedContextRevision', 'workspaceId', 'cols', 'rows']);
935
- const requestId = requireUuid(body.requestId, 'requestId');
936
- const expectedContextRevision = requireUuid(body.expectedContextRevision, 'expectedContextRevision');
937
- const workspaceId = requireUuid(body.workspaceId, 'workspaceId');
938
- const cols = boundedIntegerValue(body.cols, 100, 2, 400, 'cols');
939
- const rows = boundedIntegerValue(body.rows, 30, 1, 200, 'rows');
940
- const result = await context.workbench.executeMutation(requestId, 'terminal.create', { expectedContextRevision, workspaceId, cols, rows }, () => ({
941
- requestId,
942
- ...context.workbench.terminalManager.create({
943
- expectedContextRevision,
944
- workspaceId,
945
- cols,
946
- rows,
947
- }),
948
- }));
949
- sendJson(response, 201, result);
950
- return;
951
- }
952
- const terminalTicketMatch = path.match(/^\/terminals\/([^/]+)\/attach-ticket$/);
953
- if (method === 'POST' && terminalTicketMatch) {
954
- assertMutation(request, context.nonce, context.origin, 'terminal_attach_forbidden');
955
- const body = requireRecord(await readJson(request), 'Terminal ticket request');
956
- assertOnlyKeys(body, ['requestId', 'expectedContextRevision', 'workspaceId']);
957
- const requestId = requireUuid(body.requestId, 'requestId');
958
- const expectedContextRevision = requireUuid(body.expectedContextRevision, 'expectedContextRevision');
959
- const workspaceId = requireUuid(body.workspaceId, 'workspaceId');
960
- const terminalId = safeDecodePathSegment(terminalTicketMatch[1]);
961
- const result = await context.workbench.executeMutation(requestId, 'terminal.attach-ticket', { terminalId, expectedContextRevision, workspaceId }, () => ({
962
- requestId,
963
- ...context.workbench.terminalManager.issueAttachTicket({
964
- terminalId,
965
- expectedContextRevision,
966
- workspaceId,
967
- }),
968
- }));
969
- sendJson(response, 200, result);
970
- return;
971
- }
972
- const terminalMatch = path.match(/^\/terminals\/([^/]+)$/);
973
- if (method === 'DELETE' && terminalMatch) {
974
- assertMutation(request, context.nonce, context.origin, 'terminal_close_forbidden');
975
- const body = requireRecord(await readJson(request), 'Terminal close request');
976
- assertOnlyKeys(body, ['requestId', 'expectedContextRevision', 'workspaceId']);
977
- const requestId = requireUuid(body.requestId, 'requestId');
978
- const expectedContextRevision = requireUuid(body.expectedContextRevision, 'expectedContextRevision');
979
- const workspaceId = requireUuid(body.workspaceId, 'workspaceId');
980
- const terminalId = safeDecodePathSegment(terminalMatch[1]);
981
- const result = await context.workbench.executeMutation(requestId, 'terminal.close', { terminalId, expectedContextRevision, workspaceId }, () => ({
982
- requestId,
983
- terminal: context.workbench.terminalManager.closeTerminal({
984
- terminalId,
985
- expectedContextRevision,
986
- workspaceId,
987
- }),
988
- }));
989
- sendJson(response, 200, result);
990
- return;
991
- }
992
- if (method === 'GET' && path === '/tool-details') {
993
- const contextGuard = requireContextGuardQuery(url);
994
- sendJson(response, 200, collectionPage(url, 'tool-details', await context.workbench.listToolDetails(contextGuard), detail => `${detail.sequence}:${detail.callId}`));
995
- return;
996
- }
997
- const toolDetailMatch = path.match(/^\/tool-details\/([^/]+)$/);
998
- if (method === 'GET' && toolDetailMatch) {
999
- const contextGuard = requireContextGuardQuery(url);
1000
- const offsetBytes = boundedInteger(url.searchParams.get('offsetBytes'), 0, 0, 2 ** 31 - 1);
1001
- const limitBytes = boundedInteger(url.searchParams.get('limitBytes'), 64 * 1024, 1, 1024 * 1024);
1002
- sendJson(response, 200, await context.workbench.readToolDetail(safeDecodePathSegment(toolDetailMatch[1]), offsetBytes, limitBytes, contextGuard));
1003
- return;
1004
- }
1005
- if (method === 'GET' && path === '/diagnostics') {
1006
- sendJson(response, 200, await context.workbench.diagnostics(requireContextGuardQuery(url)));
1007
- return;
1008
- }
1009
- throw new HttpProblem(404, 'Route not found.');
1010
- }
1011
- function openEventStream(request, response, url, workbench) {
1012
- const rawCursor = url.searchParams.get('cursor') ?? request.headers['last-event-id'] ?? '0';
1013
- const cursor = Number(rawCursor);
1014
- if (!Number.isSafeInteger(cursor) || cursor < 0) {
1015
- throw new HttpProblem(400, 'Event cursor must be a non-negative integer.');
1016
- }
1017
- response.writeHead(200, {
1018
- 'Content-Type': 'text/event-stream; charset=utf-8',
1019
- 'Cache-Control': 'no-cache, no-store, must-revalidate',
1020
- Connection: 'keep-alive',
1021
- 'X-Accel-Buffering': 'no',
1022
- });
1023
- response.flushHeaders();
1024
- response.write('retry: 1000\n\n');
1025
- const detach = workbench.eventHub.attach(response, cursor);
1026
- request.once('aborted', detach);
1027
- response.once('close', detach);
1028
- }
1029
- function assertMutation(request, nonce, origin, forbiddenCode = 'request_forbidden') {
1030
- if (!isSameLoopbackEndpoint(request.headers.origin ?? '', origin)) {
1031
- throw new HttpProblem(403, 'Mutation requires the exact loopback Origin.', forbiddenCode);
1032
- }
1033
- const fetchSite = request.headers['sec-fetch-site'];
1034
- if (fetchSite && fetchSite !== 'same-origin' && fetchSite !== 'none') {
1035
- throw new HttpProblem(403, 'Cross-site mutation is not allowed.', forbiddenCode);
1036
- }
1037
- if (request.headers[protocol_1.WEB_NONCE_HEADER] !== nonce) {
1038
- throw new HttpProblem(403, 'Invalid Web Workbench nonce.', forbiddenCode);
1039
- }
1040
- const contentType = request.headers['content-type']?.split(';', 1)[0]?.trim().toLowerCase();
1041
- if (contentType !== 'application/json') {
1042
- throw new HttpProblem(415, 'Mutations require application/json.');
1043
- }
1044
- }
1045
- function requireStringArray(value, name, maxLength, maxItemBytes) {
1046
- if (!Array.isArray(value) || value.length === 0 || value.length > maxLength) {
1047
- throw new HttpProblem(400, `${name} must list 1 through ${maxLength} items.`);
1048
- }
1049
- return value.map(item => {
1050
- if (typeof item !== 'string' || item.length === 0 || item.length > maxItemBytes) {
1051
- throw new HttpProblem(400, `${name} contains an invalid item.`);
1052
- }
1053
- return item;
1054
- });
1055
- }
1056
- function requireGitRevision(value) {
1057
- const text = requireText(value, 'expectedRepositoryRevision', 64);
1058
- if (!/^[0-9a-f]{40,64}$/u.test(text)) {
1059
- throw new HttpProblem(400, 'expectedRepositoryRevision must be a git revision.');
1060
- }
1061
- return text;
1062
- }
1063
- function assertFileUserGesture(request) {
1064
- if (request.headers[protocol_1.WEB_USER_GESTURE_HEADER] !== 'file-mutation-v1') {
1065
- throw new HttpProblem(403, 'File mutations require an explicit browser user gesture.', 'file_user_gesture_required');
1066
- }
1067
- }
1068
- function requireFileRevision(value) {
1069
- const text = requireText(value, 'expectedRevision', 64);
1070
- if (!/^[0-9a-f]{64}$/u.test(text)) {
1071
- throw new HttpProblem(400, 'expectedRevision must be a file content revision.');
1072
- }
1073
- return text;
1074
- }
1075
- function assertGitUserGesture(request) {
1076
- if (request.headers[protocol_1.WEB_USER_GESTURE_HEADER] !== 'git-mutation-v1') {
1077
- throw new HttpProblem(403, 'Git mutations require an explicit browser user gesture.', 'git_user_gesture_required');
1078
- }
1079
- }
1080
- function assertTerminalUserGesture(request) {
1081
- if (request.headers[protocol_1.WEB_USER_GESTURE_HEADER] !== 'terminal-create-v1') {
1082
- throw new HttpProblem(403, 'Terminal creation requires an explicit browser user gesture.', 'terminal_user_gesture_required');
1083
- }
1084
- }
1085
- /**
1086
- * Rejects any request whose Host is not this machine and this port.
1087
- *
1088
- * `evil.invalid` / `attacker.invalid` stay refused (the anti-rebinding property), while
1089
- * `localhost` and the loopback block are accepted because they name the same listener.
1090
- */
1091
- function assertHost(request, origin) {
1092
- if (!origin)
1093
- return;
1094
- if (!isSameLoopbackEndpoint(request.headers.host ?? '', origin)) {
1095
- throw new HttpProblem(421, 'Request Host does not match the loopback listener.');
1096
- }
1097
- }
1098
- async function readJson(request) {
1099
- const declared = Number(request.headers['content-length'] ?? 0);
1100
- if (Number.isFinite(declared) && declared > protocol_1.WEB_MAX_BODY_BYTES) {
1101
- throw new HttpProblem(413, 'Request body is too large.');
1102
- }
1103
- const chunks = [];
1104
- let bytes = 0;
1105
- for await (const chunk of request) {
1106
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1107
- bytes += buffer.length;
1108
- if (bytes > protocol_1.WEB_MAX_BODY_BYTES)
1109
- throw new HttpProblem(413, 'Request body is too large.');
1110
- chunks.push(buffer);
1111
- }
1112
- try {
1113
- return JSON.parse(Buffer.concat(chunks).toString('utf8'));
1114
- }
1115
- catch {
1116
- throw new HttpProblem(400, 'Request body is not valid JSON.');
1117
- }
1118
- }
1119
- async function serveStatic(request, response, pathname, staticRoot) {
1120
- if (request.method !== 'GET' && request.method !== 'HEAD') {
1121
- throw new HttpProblem(405, 'Static assets support only GET and HEAD.');
1122
- }
1123
- if (!(0, fs_1.existsSync)(staticRoot) || !(0, fs_1.statSync)(staticRoot).isDirectory()) {
1124
- throw new HttpProblem(503, 'Web client assets are missing; run npm run build:web.');
1125
- }
1126
- const decoded = safeDecode(pathname);
1127
- const relative = (0, path_1.normalize)(decoded.replace(/^[/\\]+/, ''));
1128
- if (relative === '..' || relative.startsWith(`..${path_1.sep}`)) {
1129
- throw new HttpProblem(403, 'Static asset path escapes the Web root.');
1130
- }
1131
- const resolvedRoot = (0, path_1.resolve)(staticRoot);
1132
- const candidate = (0, path_1.resolve)(resolvedRoot, relative || 'index.html');
1133
- const lexicalBoundary = `${resolvedRoot}${path_1.sep}`;
1134
- if (candidate !== resolvedRoot && !candidate.startsWith(lexicalBoundary)) {
1135
- throw new HttpProblem(403, 'Static asset path escapes the Web root.');
1136
- }
1137
- const selected = (0, fs_1.existsSync)(candidate) && (0, fs_1.statSync)(candidate).isFile()
1138
- ? candidate
1139
- : (0, path_1.join)(resolvedRoot, 'index.html');
1140
- if (!(0, fs_1.existsSync)(selected) || !(0, fs_1.statSync)(selected).isFile()) {
1141
- throw new HttpProblem(404, 'Asset not found.');
1142
- }
1143
- const canonicalRoot = (0, fs_1.realpathSync)(resolvedRoot);
1144
- const file = (0, fs_1.realpathSync)(selected);
1145
- const canonicalBoundary = `${canonicalRoot}${path_1.sep}`;
1146
- if (file !== canonicalRoot && !file.startsWith(canonicalBoundary)) {
1147
- throw new HttpProblem(403, 'Static asset path escapes the Web root.');
1148
- }
1149
- const headers = {
1150
- 'Content-Type': contentType(file),
1151
- 'Content-Length': (0, fs_1.statSync)(file).size,
1152
- 'Cache-Control': file.endsWith('index.html')
1153
- ? 'no-store'
1154
- : 'public, max-age=31536000, immutable',
1155
- };
1156
- response.writeHead(200, headers);
1157
- if (request.method === 'HEAD') {
1158
- response.end();
1159
- return;
1160
- }
1161
- await new Promise((resolveStream, reject) => {
1162
- const stream = (0, fs_1.createReadStream)(file);
1163
- stream.once('error', reject);
1164
- stream.once('end', resolveStream);
1165
- stream.pipe(response);
1166
- });
1167
- }
1168
- function applySecurityHeaders(response, styleNonce) {
1169
- response.setHeader('Content-Security-Policy', `default-src 'self'; base-uri 'none'; connect-src 'self'; font-src 'self'; form-action 'self'; frame-ancestors 'none'; img-src 'self' data:; object-src 'none'; script-src 'self'; style-src 'self'; style-src-elem 'self' 'nonce-${styleNonce}'; style-src-attr 'unsafe-inline'`);
1170
- response.setHeader('X-Content-Type-Options', 'nosniff');
1171
- response.setHeader('X-Frame-Options', 'DENY');
1172
- response.setHeader('Referrer-Policy', 'no-referrer');
1173
- response.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
1174
- response.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
1175
- response.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
1176
- }
1177
- function sendJson(response, status, value) {
1178
- const body = JSON.stringify(value);
1179
- response.writeHead(status, {
1180
- 'Content-Type': 'application/json; charset=utf-8',
1181
- 'Content-Length': Buffer.byteLength(body),
1182
- 'Cache-Control': 'no-store',
1183
- });
1184
- response.end(body);
1185
- }
1186
- function sendProblem(response, error) {
1187
- const status = error instanceof HttpProblem || error instanceof errors_1.WebWorkbenchError
1188
- ? error.status
1189
- : error instanceof protocol_1.WebProtocolError
1190
- ? error.status
1191
- : 500;
1192
- const detail = status >= 500
1193
- ? 'The local Web Workbench request failed.'
1194
- : (0, redaction_1.redactTraceText)(error instanceof Error ? error.message : String(error));
1195
- const code = error instanceof HttpProblem ||
1196
- error instanceof errors_1.WebWorkbenchError ||
1197
- error instanceof protocol_1.WebProtocolError
1198
- ? error.code
1199
- : 'web_internal_error';
1200
- const body = JSON.stringify({
1201
- type: `https://orioncode.dev/problems/${code}`,
1202
- title: statusTitle(status),
1203
- status,
1204
- code,
1205
- detail,
1206
- });
1207
- response.writeHead(status, {
1208
- 'Content-Type': 'application/problem+json; charset=utf-8',
1209
- 'Content-Length': Buffer.byteLength(body),
1210
- 'Cache-Control': 'no-store',
1211
- });
1212
- response.end(body);
1213
- }
1214
- class HttpProblem extends Error {
1215
- constructor(status, message, code = defaultProblemCode(status)) {
1216
- super(message);
1217
- this.status = status;
1218
- this.code = code;
1219
- this.name = 'HttpProblem';
1220
- }
1221
- }
1222
- function defaultProblemCode(status) {
1223
- switch (status) {
1224
- case 400:
1225
- return 'invalid_request';
1226
- case 403:
1227
- return 'request_forbidden';
1228
- case 409:
1229
- return 'request_conflict';
1230
- case 413:
1231
- return 'request_too_large';
1232
- case 415:
1233
- return 'unsupported_media_type';
1234
- case 421:
1235
- return 'misdirected_request';
1236
- case 429:
1237
- return 'too_many_requests';
1238
- case 503:
1239
- return 'service_unavailable';
1240
- default:
1241
- return `web_${status}`;
1242
- }
1243
- }
1244
- function requireRecord(value, name) {
1245
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
1246
- throw new HttpProblem(400, `${name} must be an object.`);
1247
- }
1248
- return value;
1249
- }
1250
- /** v0.3.17 S4 — copies only the named, non-empty query parameters. */
1251
- function optionalQueryParams(url, names) {
1252
- const out = {};
1253
- for (const name of names) {
1254
- const value = url.searchParams.get(name);
1255
- if (value !== null && value !== '')
1256
- out[name] = value;
1257
- }
1258
- return out;
1259
- }
1260
- function requireText(value, name, maxLength) {
1261
- if (typeof value !== 'string' || !value.trim()) {
1262
- throw new HttpProblem(400, `${name} must be a non-empty string.`);
1263
- }
1264
- if (value.length > maxLength)
1265
- throw new HttpProblem(400, `${name} is too long.`);
1266
- return value.trim();
1267
- }
1268
- function optionalText(value, name, maxLength) {
1269
- if (value === undefined || value === null)
1270
- return undefined;
1271
- return requireText(value, name, maxLength);
1272
- }
1273
- /**
1274
- * v0.3.17 S3 — commit bodies legitimately span lines, so trimming happens without
1275
- * rejecting newlines. Control characters are rejected later by `normalizeCommitMessage`,
1276
- * which is the single owner of that rule.
1277
- */
1278
- function requireTextAllowingNewlines(value, name, maxLength) {
1279
- if (typeof value !== 'string') {
1280
- throw new HttpProblem(400, `${name} must be a string.`);
1281
- }
1282
- if (value.length > maxLength)
1283
- throw new HttpProblem(400, `${name} is too long.`);
1284
- return value;
1285
- }
1286
- /** v0.3.17 S3 — bounded list of opaque ids; never interpreted as paths or flags. */
1287
- function optionalStringList(value, name, maxItems, maxItemLength) {
1288
- if (value === undefined || value === null)
1289
- return [];
1290
- if (!Array.isArray(value))
1291
- throw new HttpProblem(400, `${name} must be an array.`);
1292
- if (value.length > maxItems)
1293
- throw new HttpProblem(400, `${name} has too many entries.`);
1294
- const items = [];
1295
- for (const entry of value) {
1296
- if (typeof entry !== 'string' || !entry || entry.length > maxItemLength) {
1297
- throw new HttpProblem(400, `${name} contains an invalid entry.`);
1298
- }
1299
- items.push(entry);
1300
- }
1301
- return items;
1302
- }
1303
- /** v0.3.16 — where a workspace candidate came from; `manual` is the default. */
1304
- const CANDIDATE_SOURCES = [
1305
- 'picker',
1306
- 'recent',
1307
- 'pinned',
1308
- 'discovered',
1309
- 'manual',
1310
- ];
1311
- function requireCandidateSource(value) {
1312
- if (value === undefined)
1313
- return 'manual';
1314
- const source = CANDIDATE_SOURCES.find(candidate => candidate === value);
1315
- if (!source)
1316
- throw new HttpProblem(400, 'Unknown workspace candidate source.');
1317
- return source;
1318
- }
1319
- function requireUuid(value, name) {
1320
- const text = requireText(value, name, 128);
1321
- if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(text)) {
1322
- throw new HttpProblem(400, `${name} must be a UUID.`);
1323
- }
1324
- return text;
1325
- }
1326
- function requireContextGuardRecord(value) {
1327
- return Object.freeze({
1328
- expectedContextRevision: requireUuid(value.expectedContextRevision, 'expectedContextRevision'),
1329
- workspaceId: requireUuid(value.workspaceId, 'workspaceId'),
1330
- });
1331
- }
1332
- function requireContextGuardQuery(url) {
1333
- return Object.freeze({
1334
- expectedContextRevision: requireUuid(url.searchParams.get('expectedContextRevision'), 'expectedContextRevision'),
1335
- workspaceId: requireUuid(url.searchParams.get('workspaceId'), 'workspaceId'),
1336
- });
1337
- }
1338
- function boundedIntegerValue(value, fallback, minimum, maximum, name) {
1339
- if (value === undefined)
1340
- return fallback;
1341
- if (!Number.isSafeInteger(value) || Number(value) < minimum || Number(value) > maximum) {
1342
- throw new HttpProblem(400, `${name} must be between ${minimum} and ${maximum}.`);
1343
- }
1344
- return Number(value);
1345
- }
1346
- function assertOnlyKeys(value, allowedKeys) {
1347
- const allowed = new Set(allowedKeys);
1348
- const unknown = Object.keys(value).find(key => !allowed.has(key));
1349
- if (unknown)
1350
- throw new HttpProblem(400, `Unknown request field: ${unknown}.`);
1351
- }
1352
- function statusTitle(status) {
1353
- if (status === 400)
1354
- return 'Invalid request';
1355
- if (status === 403)
1356
- return 'Request rejected';
1357
- if (status === 404)
1358
- return 'Not found';
1359
- if (status === 409)
1360
- return 'State conflict';
1361
- if (status === 413)
1362
- return 'Payload too large';
1363
- if (status === 415)
1364
- return 'Unsupported media type';
1365
- if (status === 421)
1366
- return 'Misdirected request';
1367
- if (status === 429)
1368
- return 'Too many requests';
1369
- if (status === 503)
1370
- return 'Service unavailable';
1371
- return 'Internal server error';
1372
- }
1373
- function safeDecode(pathname) {
1374
- try {
1375
- return decodeURIComponent(pathname);
1376
- }
1377
- catch {
1378
- throw new HttpProblem(400, 'Malformed asset path.');
1379
- }
1380
- }
1381
- function safeDecodePathSegment(value) {
1382
- const decoded = safeDecode(value);
1383
- if (!decoded || decoded.includes('/') || decoded.includes('\\')) {
1384
- throw new HttpProblem(400, 'Malformed path identifier.');
1385
- }
1386
- return decoded;
1387
- }
1388
- function boundedInteger(raw, fallback, minimum, maximum) {
1389
- if (raw === null)
1390
- return fallback;
1391
- const value = Number(raw);
1392
- if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
1393
- throw new HttpProblem(400, `Integer query value must be between ${minimum} and ${maximum}.`);
1394
- }
1395
- return value;
1396
- }
1397
- function pageSize(url) {
1398
- return boundedInteger(url.searchParams.get('pageSize'), 50, 1, 100);
1399
- }
1400
- function collectionPage(url, scope, items, keyOf) {
1401
- return (0, workbench_controller_1.pageCollectionItems)(scope, items, url.searchParams.get('cursor') ?? undefined, pageSize(url), keyOf);
1402
- }
1403
- function contentType(path) {
1404
- switch ((0, path_1.extname)(path).toLowerCase()) {
1405
- case '.html':
1406
- return 'text/html; charset=utf-8';
1407
- case '.js':
1408
- case '.mjs':
1409
- return 'text/javascript; charset=utf-8';
1410
- case '.css':
1411
- return 'text/css; charset=utf-8';
1412
- case '.json':
1413
- return 'application/json; charset=utf-8';
1414
- case '.svg':
1415
- return 'image/svg+xml';
1416
- case '.png':
1417
- return 'image/png';
1418
- case '.woff2':
1419
- return 'font/woff2';
1420
- default:
1421
- return 'application/octet-stream';
1422
- }
1423
- }
1424
- function resolveDefaultStaticRoot() {
1425
- const candidates = [
1426
- (0, path_1.resolve)(__dirname, '../../dist/web-client'),
1427
- (0, path_1.resolve)(__dirname, '../../web/dist'),
1428
- (0, path_1.resolve)(process.cwd(), 'dist/web-client'),
1429
- ];
1430
- return candidates.find(candidate => (0, fs_1.existsSync)(candidate)) ?? candidates[0];
1431
- }
1432
- function listen(server, port) {
1433
- return new Promise((resolveListen, reject) => {
1434
- const onError = (error) => {
1435
- server.off('listening', onListening);
1436
- reject(error);
1437
- };
1438
- const onListening = () => {
1439
- server.off('error', onError);
1440
- resolveListen();
1441
- };
1442
- server.once('error', onError);
1443
- server.once('listening', onListening);
1444
- server.listen(port, HOST);
1445
- });
1446
- }
1447
- function closeServer(server) {
1448
- if (!server.listening)
1449
- return Promise.resolve();
1450
- server.closeAllConnections?.();
1451
- return new Promise(resolveClose => server.close(() => resolveClose()));
1452
- }
1453
- //# sourceMappingURL=server.js.map