@chroxy/server 0.11.0 → 0.11.10

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 (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +69 -5
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -0,0 +1,264 @@
1
+ /**
2
+ * Narrowing an approved Write/Edit (#8446): how the content that reaches the
3
+ * agent's tool executor is built when the operator drops hunks in the pre-write
4
+ * review (#6543).
5
+ *
6
+ * The client reviews the REDACTED copy of the tool input (`get_permission_input`
7
+ * runs `sanitizeToolInput` over it). Content a client builds from that copy
8
+ * carries `[REDACTED]` wherever a secret-shaped span was, so trusting it writes the
9
+ * placeholder into the user's file in place of the original characters. Two rules
10
+ * keep that from happening, and both live here so the permission manager has one
11
+ * place to call:
12
+ *
13
+ * 1. HUNK DECISIONS, NOT CONTENT. The client says which hunks it dropped and
14
+ * which it kept (their line ranges, the `@@` header numbers of the diff it
15
+ * rendered). The server computes the diff itself over the same redacted copy,
16
+ * with the same differ (`computeHunks`, shared through @chroxy/protocol), and
17
+ * requires the client's ranges to be exactly that list of hunks. It then
18
+ * rebuilds the result from the RAW input it holds, so the written text is made
19
+ * only of lines the agent proposed, and only ever the proposal with whole real
20
+ * hunks reverted.
21
+ * 2. TEXT IS NEVER A BASE. Text a client sends (an older client, or the Bash
22
+ * command editor) was edited from the copy it was shown. Where redaction
23
+ * changed that copy the text cannot be trusted to be the original with an
24
+ * edit, whatever it contains: counting placeholders cannot say where one came
25
+ * from, so such text is refused outright and only `droppedHunks` may narrow
26
+ * the field. Where redaction changed nothing, the text is just text.
27
+ *
28
+ * A refusal throws {@link EditedInputRefusedError}; nothing is written.
29
+ */
30
+ import { computeHunks, splitContentLines } from '@chroxy/protocol'
31
+ import { sanitizeToolInput, PULL_MAX_INPUT_CHARS } from './redaction.js'
32
+
33
+ /**
34
+ * The reserved key of `permission_response.editedInput` that carries the hunk
35
+ * decisions: an array of {@link HunkRange}, the hunks the operator dropped. Its
36
+ * presence puts the field in hunk mode. It is not a content field, so the content
37
+ * whitelist never reads it as one.
38
+ */
39
+ export const DROPPED_HUNKS_KEY = 'droppedHunks'
40
+
41
+ /**
42
+ * The hunks the operator kept: with `droppedHunks`, every hunk of the diff it was shown.
43
+ * Required whenever `droppedHunks` is not empty, because the server needs the whole
44
+ * partition to compare with its own hunk list.
45
+ */
46
+ export const KEPT_HUNKS_KEY = 'keptHunks'
47
+
48
+ /**
49
+ * @typedef {object} HunkRange
50
+ * @property {number} oldStart `@@ -oldStart,oldCount` of the hunk
51
+ * @property {number} oldCount
52
+ * @property {number} newStart `@@ +newStart,newCount`
53
+ * @property {number} newCount
54
+ * Git's convention, as the differ emits it: a side with a non-zero count starts at a
55
+ * 1-based line, a side with a zero count starts AFTER the 0-based line.
56
+ */
57
+
58
+ /**
59
+ * Per tool: the content field a hunk review narrows and the text the diff was drawn
60
+ * against. Write is drawn against the empty file; Edit against the text it replaces.
61
+ * Must match the client's `TOOL_DIFF` (dashboard + app `PreWriteDiffReview`).
62
+ */
63
+ const HUNK_REVIEW = {
64
+ Write: { field: 'content', base: () => '' },
65
+ Edit: { field: 'new_string', base: (input) => input.old_string },
66
+ }
67
+
68
+ /** Whether a tool's content is narrowed by hunk decisions rather than sent as text. */
69
+ export function isHunkReviewedTool(toolName) {
70
+ return Object.prototype.hasOwnProperty.call(HUNK_REVIEW, toolName)
71
+ }
72
+
73
+ export class EditedInputRefusedError extends Error {
74
+ constructor(message) {
75
+ super(message)
76
+ this.name = 'EditedInputRefusedError'
77
+ this.code = 'EDITED_INPUT_REFUSED'
78
+ }
79
+ }
80
+
81
+ /**
82
+ * The 0-based first line of a side of a hunk, from its header number — the inverse
83
+ * of the differ's header math (a zero-count side's start is already 0-based).
84
+ */
85
+ function lineIndex(start, count) {
86
+ return count === 0 ? start : start - 1
87
+ }
88
+
89
+ /** `@@ -a,b +c,d @@` from a client range, refusing anything that is not four whole counts. */
90
+ function headerOf(h) {
91
+ if (!h || typeof h !== 'object') return null
92
+ const { oldStart, oldCount, newStart, newCount } = h
93
+ for (const n of [oldStart, oldCount, newStart, newCount]) {
94
+ if (!Number.isSafeInteger(n) || n < 0) return null
95
+ }
96
+ return `@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`
97
+ }
98
+
99
+ /** Append `lines[from, to)` to `out`. A loop, not a spread: a hunk may be 100K+ lines. */
100
+ function pushRange(out, lines, from, to) {
101
+ for (let i = from; i < to; i++) out.push(lines[i])
102
+ }
103
+
104
+ const NOT_A_DIFF = 'The hunks you named are not the hunks of the change that was proposed, so the edit was not applied.'
105
+ const HIDDEN_DIFFERENCE = 'This change contains differences that redaction hid from the review, so it can only be approved or denied as a whole. The request was denied; the agent can propose it again, and it can be approved whole.'
106
+
107
+ /**
108
+ * The server's own hunks over the shown copy, parsed into line positions in the
109
+ * texts, in order. Each entry carries the hunk's lines so a walk can tell its
110
+ * context from its changes.
111
+ */
112
+ function ownHunks(shownBase, shownProposed) {
113
+ return computeHunks(shownBase, shownProposed).map((hunk) => {
114
+ const m = /^@@ -(\d+),(\d+) \+(\d+),(\d+) @@$/.exec(hunk.header)
115
+ if (!m) throw new EditedInputRefusedError(NOT_A_DIFF)
116
+ const oldCount = Number(m[2])
117
+ const newCount = Number(m[4])
118
+ return {
119
+ header: hunk.header,
120
+ lines: hunk.lines,
121
+ oldIdx: lineIndex(Number(m[1]), oldCount),
122
+ oldCount,
123
+ newIdx: lineIndex(Number(m[3]), newCount),
124
+ newCount,
125
+ }
126
+ })
127
+ }
128
+
129
+ /**
130
+ * Whether the raw texts differ at a line the shown copy reads as unchanged: outside
131
+ * every hunk, or as a hunk's context line. That is a change redaction hid (two
132
+ * different keys both read `[REDACTED]`).
133
+ */
134
+ function hasHiddenDifference(hunks, baseLines, proposedLines) {
135
+ let oldAt = 0
136
+ let newAt = 0
137
+ const sameAt = (o, n) => baseLines[o] !== proposedLines[n]
138
+ for (const h of hunks) {
139
+ for (; oldAt < h.oldIdx; oldAt++, newAt++) if (sameAt(oldAt, newAt)) return true
140
+ for (const line of h.lines) {
141
+ if (line.type === 'context') {
142
+ if (sameAt(oldAt, newAt)) return true
143
+ oldAt++
144
+ newAt++
145
+ } else if (line.type === 'deletion') {
146
+ oldAt++
147
+ } else {
148
+ newAt++
149
+ }
150
+ }
151
+ }
152
+ for (; oldAt < baseLines.length; oldAt++, newAt++) if (sameAt(oldAt, newAt)) return true
153
+ return false
154
+ }
155
+
156
+ /**
157
+ * Build a Write/Edit's narrowed content from the RAW input and the client's hunk
158
+ * decisions: the proposed text with each dropped hunk's lines replaced by the original
159
+ * text's lines, every line taken from the raw input.
160
+ *
161
+ * The client lists EVERY hunk it was shown, dropped or kept. The server diffs the same
162
+ * redacted copy itself (same differ, same context) and requires the client's ranges to
163
+ * be exactly its hunks: the same headers, each once, none missing and none extra. A
164
+ * range that lands off its hunk, a zero-count side that invents an insertion or a
165
+ * deletion, or a partition that deletes a line both sides share, is not that list and is
166
+ * refused. The lines outside the hunks are then unchanged lines by construction.
167
+ *
168
+ * Two things are refused rather than guessed at. The client's line numbers only mean the
169
+ * same lines in the raw text when redaction kept the line count (it never adds a line
170
+ * break; a pattern that spanned one removes it). And when the raw texts differ at a line
171
+ * the shown copy reads as unchanged (a rotated key), dropping any hunk would write that
172
+ * hidden change unseen, so only a whole approve or deny is left.
173
+ *
174
+ * @param {object} rawInput the agent's proposed tool input, as held server-side
175
+ * @param {string} toolName 'Write' | 'Edit'
176
+ * @param {unknown} dropped the client's `editedInput.droppedHunks`
177
+ * @param {unknown} kept the client's `editedInput.keptHunks`
178
+ * @returns {string} the narrowed content for the tool's content field
179
+ */
180
+ export function narrowByDroppedHunks(rawInput, toolName, dropped, kept) {
181
+ const review = HUNK_REVIEW[toolName]
182
+ const rawProposed = rawInput[review.field]
183
+ const rawBase = review.base(rawInput)
184
+ if (typeof rawProposed !== 'string' || typeof rawBase !== 'string') {
185
+ throw new EditedInputRefusedError(`This ${toolName} has no text content to narrow, so the edit was not applied.`)
186
+ }
187
+ if (!Array.isArray(dropped)) {
188
+ throw new EditedInputRefusedError('The dropped hunks were not a list the server can read, so the edit was not applied.')
189
+ }
190
+ // Nothing dropped: the proposal as it stands.
191
+ if (dropped.length === 0) return rawProposed
192
+ if (!Array.isArray(kept)) {
193
+ throw new EditedInputRefusedError('The kept hunks were not a list the server can read, so the edit was not applied.')
194
+ }
195
+
196
+ // The copy the client was shown: the same call `get_permission_input` makes.
197
+ const shown = sanitizeToolInput(rawInput, { maxChars: PULL_MAX_INPUT_CHARS })
198
+ const shownProposed = shown?.[review.field]
199
+ const shownBase = review.base(shown ?? {})
200
+ if (typeof shownProposed !== 'string' || typeof shownBase !== 'string') {
201
+ throw new EditedInputRefusedError('This change is too large to narrow hunk by hunk, so the edit was not applied.')
202
+ }
203
+
204
+ const baseLines = splitContentLines(rawBase)
205
+ const proposedLines = splitContentLines(rawProposed)
206
+ if (baseLines.length !== splitContentLines(shownBase).length
207
+ || proposedLines.length !== splitContentLines(shownProposed).length) {
208
+ throw new EditedInputRefusedError(
209
+ 'Redacting this content changed its line structure, so the hunks you dropped cannot be mapped back to the original text and the edit was not applied.',
210
+ )
211
+ }
212
+
213
+ // The client's partition must be exactly the server's own hunk list.
214
+ const hunks = ownHunks(shownBase, shownProposed)
215
+ if (dropped.length + kept.length !== hunks.length) throw new EditedInputRefusedError(NOT_A_DIFF)
216
+ const decision = new Map() // header -> true when dropped
217
+ for (const [list, isDropped] of [[dropped, true], [kept, false]]) {
218
+ for (const range of list) {
219
+ const header = headerOf(range)
220
+ if (header === null) throw new EditedInputRefusedError(NOT_A_DIFF)
221
+ decision.set(header, isDropped)
222
+ }
223
+ }
224
+ // Same count, and every real hunk named: so nothing is repeated or extra either.
225
+ if (hunks.some((h) => !decision.has(h.header))) throw new EditedInputRefusedError(NOT_A_DIFF)
226
+
227
+ if (hasHiddenDifference(hunks, baseLines, proposedLines)) throw new EditedInputRefusedError(HIDDEN_DIFFERENCE)
228
+
229
+ const out = []
230
+ let newAt = 0
231
+ for (const h of hunks) {
232
+ pushRange(out, proposedLines, newAt, h.newIdx)
233
+ if (decision.get(h.header)) pushRange(out, baseLines, h.oldIdx, h.oldIdx + h.oldCount)
234
+ else pushRange(out, proposedLines, h.newIdx, h.newIdx + h.newCount)
235
+ newAt = h.newIdx + h.newCount
236
+ }
237
+ pushRange(out, proposedLines, newAt, proposedLines.length)
238
+ return out.join('\n')
239
+ }
240
+
241
+ /**
242
+ * Refuse text a client sent for `field` when redaction changed any of the text it was
243
+ * drawn from. `field` is a whitelisted content field; for a hunk-reviewed tool the text
244
+ * an older client narrowed from is the field AND the text it replaces.
245
+ *
246
+ * Fails closed: an input too large to have been shown whole reads as changed.
247
+ *
248
+ * @param {object} rawInput
249
+ * @param {string} toolName
250
+ * @param {string} field
251
+ */
252
+ export function assertClientTextAllowed(rawInput, toolName, field) {
253
+ const shown = sanitizeToolInput(rawInput, { maxChars: PULL_MAX_INPUT_CHARS })
254
+ const names = isHunkReviewedTool(toolName) ? [field, 'old_string'] : [field]
255
+ for (const name of names) {
256
+ const raw = rawInput?.[name]
257
+ if (typeof raw !== 'string') continue
258
+ if (shown?.[name] !== raw) {
259
+ throw new EditedInputRefusedError(
260
+ 'Part of this request was redacted before you saw it, so text edited from that copy cannot be applied. The request was denied; the agent can propose it again, and it can be approved whole.',
261
+ )
262
+ }
263
+ }
264
+ }
@@ -1,22 +1,26 @@
1
1
  import { EventEmitter } from 'events'
2
+ import { assertAuthorized } from './connection-authority.js'
2
3
  import { randomBytes } from 'crypto'
3
4
  import { execFile } from 'child_process'
4
5
  import { existsSync, readFileSync, mkdirSync } from 'fs'
5
- import { dirname, join } from 'path'
6
- import { homedir } from 'os'
6
+ import { dirname } from 'path'
7
7
  import { writeFileRestricted } from './platform.js'
8
8
  import { createLogger } from './logger.js'
9
9
  import { VALID_USERNAME_RE } from './utils/validation-patterns.js'
10
10
  import { DockerBackend } from './environments/backends/docker.js'
11
+ import { configPath } from './config-dir.js'
11
12
  import {
12
13
  parseDevContainer,
13
14
  validateMounts,
14
15
  sanitizeContainerEnv,
15
16
  } from './devcontainer-config.js'
17
+ import { liveSessionsError } from './environments/destroy-with-sessions.js'
16
18
 
17
19
  const log = createLogger('environment-manager')
18
20
 
19
- const DEFAULT_STATE_PATH = join(homedir(), '.chroxy', 'environments.json')
21
+ function defaultStatePath() {
22
+ return configPath('environments.json')
23
+ }
20
24
  const DEFAULT_IMAGE = 'node:22-slim'
21
25
  const DEFAULT_MEMORY_LIMIT = '2g'
22
26
  const DEFAULT_CPU_LIMIT = '2'
@@ -57,10 +61,19 @@ export class EnvironmentManager extends EventEmitter {
57
61
  */
58
62
  constructor({ statePath, _execFile, backend, workspacePVCDefault } = {}) {
59
63
  super()
60
- this._statePath = statePath || DEFAULT_STATE_PATH
64
+ this._statePath = statePath || defaultStatePath()
61
65
  this._environments = new Map()
62
66
  // Per-environment mutex: Map<envId, Promise> — serializes operations
63
67
  this._locks = new Map()
68
+ // #7575 — ids of environments currently mid-teardown. An INTERNAL, never-
69
+ // persisted marker (a Set, not an `env.status` value): `destroy()` adds an id
70
+ // before its first teardown `await` and clears it in a `finally`, and
71
+ // `getContainerInfo()` refuses a create while an id is present. It is NOT a
72
+ // fourth `status` — the wire enum (`EnvironmentStatusSchema`) is closed to
73
+ // running/stopped/error, and this marker is never serialized, so a client
74
+ // snapshot never carries it and a crash mid-teardown clears it for free
75
+ // (the Set is reconstructed empty on restart).
76
+ this._destroying = new Set()
64
77
  // Injected for testing — falls back to real execFile.
65
78
  // _execFile is forwarded to DockerBackend so existing tests that inject a
66
79
  // mock execFile continue to work without modification.
@@ -381,41 +394,111 @@ export class EnvironmentManager extends EventEmitter {
381
394
 
382
395
  /**
383
396
  * Destroy an environment and its container.
397
+ *
398
+ * #7562: REFUSES when sessions are still attached (`env.sessions` non-empty)
399
+ * unless `force` is set. This is the server-side half of a guard that lived
400
+ * only in the dashboard (`EnvironmentPanel`'s disabled Destroy button), so any
401
+ * OTHER sender of the message — a stale dashboard tab, the Control Room's
402
+ * `containers_action` (no UI guard at all), a script, any future client —
403
+ * could `docker rm -f` the container out from under running sessions. (The
404
+ * mobile app is not one of them today: it can put a session INTO an
405
+ * environment via `create_session`'s `environmentId`, but it has no
406
+ * environment-destroy surface. It is a potential victim of this, not a
407
+ * perpetrator.) The check sits HERE, at the one chokepoint every
408
+ * caller reaches, rather than in each handler: a per-caller check is the
409
+ * "guard wired to only some of its callers" shape in
410
+ * docs/false-safety-guards.md, which is precisely how `containers_action`
411
+ * came to have no guard at all.
412
+ *
413
+ * `force` does NOT clean the sessions up — this class has no handle on the
414
+ * SessionManager. The cascade (destroy the sessions cleanly, THEN the
415
+ * environment) is `environments/destroy-with-sessions.js`, which is what both
416
+ * handlers call. A direct `destroy(id, { force: true })` is the deliberate
417
+ * "I know, take it down anyway" escape.
418
+ *
384
419
  * @param {string} envId - Environment ID
420
+ * @param {{force?: boolean}} [opts]
421
+ * @throws {Error & {code: 'ENVIRONMENT_HAS_LIVE_SESSIONS', sessions: string[]}}
422
+ * when sessions are attached and `force` is not set. Nothing is torn down.
385
423
  */
386
- async destroy(envId) {
424
+ async destroy(envId, { force = false, isAuthorized } = {}) {
387
425
  const release = await this._acquireLock(envId)
388
426
  try {
427
+ assertAuthorized(isAuthorized)
389
428
  const env = this._getEnvironmentOrThrow(envId)
429
+ // #7562 — refuse BEFORE any teardown, so a refused destroy leaves the
430
+ // container running and the environment registered.
431
+ if (!force && Array.isArray(env.sessions) && env.sessions.length > 0) {
432
+ log.warn(`Refusing to destroy environment "${env.name}" (${envId}): ${env.sessions.length} live session(s) attached`)
433
+ throw liveSessionsError(env)
434
+ }
390
435
  log.info(`Destroying environment "${env.name}" (${envId})`)
391
436
 
392
- if (env.compose && env.composeProject) {
393
- await this._backend.destroyComposeEnvironment({
394
- composeFile: env.compose,
395
- composeProject: env.composeProject,
396
- cwd: env.cwd,
397
- })
398
- } else if (env.containerId) {
399
- // #6134: remove the container whenever one exists — NOT only when
400
- // status==='running'. Now that stop() makes 'stopped' a reachable state,
401
- // gating on 'running' would orphan a stopped container (the manager
402
- // entry is deleted but `docker rm -f` never runs). `docker rm -f` works
403
- // on stopped/exited containers too, and _removeContainer swallows a
404
- // "no such container" for one that never started.
405
- await this._backend.destroyEnvironment(env.containerId)
406
- }
437
+ // #7575 — mark the environment mid-teardown BEFORE the first `await`, while
438
+ // this method still holds the lock and no other task can run. `destroy` is
439
+ // async and YIELDS at the backend teardown below; a `create_session` that
440
+ // begins during that yield would otherwise attach a session to a container
441
+ // we are about to `docker rm -f` and an environment record we are about to
442
+ // delete — a TOCTOU on the #7562 live-sessions guard, which saw zero
443
+ // sessions and proceeded. Adding the id to `_destroying` here means such a
444
+ // create's `getContainerInfo` is refused with the existing NOT_RUNNING-style
445
+ // error — no new wire shape, and (unlike overloading `env.status`) no value
446
+ // that could leak into the closed `EnvironmentStatusSchema` enum or persist.
447
+ //
448
+ // Why marking synchronously here is SUFFICIENT (and `addSession` is not
449
+ // also gated): the create path reads the container info (the create
450
+ // handler's `getContainerInfo`) and tags the env (`addSession`, via the
451
+ // synchronous `SessionManager.createSession`) in ONE synchronous run — there
452
+ // is no `await` between them — so that whole read→tag sequence is atomic
453
+ // with respect to this method's yields. Every interleaving therefore
454
+ // resolves safely: a create that ran entirely BEFORE this mark tagged the
455
+ // env, so the #7562 check above saw the session and refused this destroy; a
456
+ // create that starts AT OR AFTER this mark sees the env in `_destroying` at
457
+ // `getContainerInfo` and is refused. There is no interleaving where
458
+ // `getContainerInfo` passes AND `addSession` lands during teardown.
459
+ //
460
+ // LOAD-BEARING INVARIANT: that atomicity. If a future change inserts an
461
+ // `await` between `getContainerInfo` and `addSession`, a create whose read
462
+ // already passed could still `addSession` during this teardown, reopening
463
+ // the window — close it then by re-checking `_destroying` inside
464
+ // `addSession` (which runs synchronously and would observe this mark).
465
+ this._destroying.add(envId)
466
+ try {
467
+ if (env.compose && env.composeProject) {
468
+ await this._backend.destroyComposeEnvironment({
469
+ composeFile: env.compose,
470
+ composeProject: env.composeProject,
471
+ cwd: env.cwd,
472
+ })
473
+ } else if (env.containerId) {
474
+ // #6134: remove the container whenever one exists — NOT only when
475
+ // status==='running'. Now that stop() makes 'stopped' a reachable state,
476
+ // gating on 'running' would orphan a stopped container (the manager
477
+ // entry is deleted but `docker rm -f` never runs). `docker rm -f` works
478
+ // on stopped/exited containers too, and _removeContainer swallows a
479
+ // "no such container" for one that never started.
480
+ await this._backend.destroyEnvironment(env.containerId)
481
+ }
407
482
 
408
- // Clean up snapshot images
409
- if (Array.isArray(env.snapshots)) {
410
- for (const snap of env.snapshots) {
411
- await this._backend.removeImage(snap.image)
483
+ // Clean up snapshot images
484
+ if (Array.isArray(env.snapshots)) {
485
+ for (const snap of env.snapshots) {
486
+ await this._backend.removeImage(snap.image)
487
+ }
412
488
  }
413
- }
414
489
 
415
- this._environments.delete(envId)
416
- this._persist()
417
- this.emit('environment_destroyed', { id: envId, name: env.name })
418
- log.info(`Environment "${env.name}" destroyed`)
490
+ this._environments.delete(envId)
491
+ this._persist()
492
+ this.emit('environment_destroyed', { id: envId, name: env.name })
493
+ log.info(`Environment "${env.name}" destroyed`)
494
+ } finally {
495
+ // Clear the marker on BOTH paths. On success the env is already gone, so
496
+ // this only matters on failure: a teardown that threw left the env
497
+ // registered and unchanged (nothing was deleted, `env.status` was never
498
+ // touched), and clearing the mark makes it immediately re-enterable —
499
+ // `getContainerInfo` stops refusing and a subsequent create succeeds.
500
+ this._destroying.delete(envId)
501
+ }
419
502
  } finally {
420
503
  release()
421
504
  }
@@ -431,9 +514,10 @@ export class EnvironmentManager extends EventEmitter {
431
514
  * don't implement the lifecycle (k8s/rancher today) throw a clear error that
432
515
  * the handler surfaces as CONTAINER_ACTION_FAILED.
433
516
  */
434
- async stop(envId) {
517
+ async stop(envId, { isAuthorized } = {}) {
435
518
  const release = await this._acquireLock(envId)
436
519
  try {
520
+ assertAuthorized(isAuthorized)
437
521
  const env = this._getEnvironmentOrThrow(envId)
438
522
  if (env.compose) throw new Error(`Stop is not supported for compose environments yet`)
439
523
  if (!env.containerId) throw new Error(`Environment "${env.name}" has no container to stop`)
@@ -457,9 +541,10 @@ export class EnvironmentManager extends EventEmitter {
457
541
  * currently running or stopped; ends running). Returns the resulting status.
458
542
  * Same compose / backend-support constraints as {@link stop}.
459
543
  */
460
- async restart(envId) {
544
+ async restart(envId, { isAuthorized } = {}) {
461
545
  const release = await this._acquireLock(envId)
462
546
  try {
547
+ assertAuthorized(isAuthorized)
463
548
  const env = this._getEnvironmentOrThrow(envId)
464
549
  if (env.compose) throw new Error(`Restart is not supported for compose environments yet`)
465
550
  if (!env.containerId) throw new Error(`Environment "${env.name}" has no container to restart`)
@@ -501,6 +586,14 @@ export class EnvironmentManager extends EventEmitter {
501
586
  */
502
587
  getContainerInfo(envId) {
503
588
  const env = this._getEnvironmentOrThrow(envId)
589
+ // #7575 — refuse a create against an environment whose teardown is already
590
+ // in flight. `destroy()` adds the id to `_destroying` before its first
591
+ // `await` (and clears it in a `finally`), so this closes the TOCTOU window
592
+ // where `destroy` had passed the #7562 sessions check and was mid-`docker
593
+ // rm -f`: without this, `getContainerInfo` returned live details and the
594
+ // session attached to a container about to vanish. Same NOT_RUNNING-style
595
+ // refusal — no new wire shape.
596
+ if (this._destroying.has(envId)) throw new Error(`Environment "${env.name}" is not running (status: destroying)`)
504
597
  if (env.status !== 'running') throw new Error(`Environment "${env.name}" is not running (status: ${env.status})`)
505
598
  return {
506
599
  containerId: env.containerId,
@@ -511,6 +604,12 @@ export class EnvironmentManager extends EventEmitter {
511
604
 
512
605
  /**
513
606
  * Track a session connecting to an environment.
607
+ *
608
+ * #7552: called from `SessionManager.createSession` for every session created
609
+ * with an `environmentId` — the production writer `env.sessions` spent its
610
+ * whole life without. Idempotent; a no-op for an unknown environment (which
611
+ * can be destroyed between the handler's `getContainerInfo` and the create).
612
+ *
514
613
  * @param {string} envId
515
614
  * @param {string} sessionId
516
615
  */
@@ -520,19 +619,48 @@ export class EnvironmentManager extends EventEmitter {
520
619
  if (!env.sessions.includes(sessionId)) {
521
620
  env.sessions.push(sessionId)
522
621
  this._persist()
622
+ this._emitSessionsChanged(env)
523
623
  }
524
624
  }
525
625
 
526
626
  /**
527
627
  * Track a session disconnecting from an environment.
628
+ *
629
+ * #7552: called from `SessionManager._cleanupSessionMaps` (the single funnel
630
+ * every session takes OUT of `_sessions`) and from `destroyAll()`. A MISSED
631
+ * detach is the inverse of the bug this wiring fixes — a stale id would make
632
+ * the environment permanently undestroyable — so the caller side is pinned
633
+ * path-by-path in `tests/environment-session-wiring.test.js`.
634
+ *
528
635
  * @param {string} envId
529
636
  * @param {string} sessionId
530
637
  */
531
638
  removeSession(envId, sessionId) {
532
639
  const env = this._environments.get(envId)
533
640
  if (!env) return
641
+ if (!env.sessions.includes(sessionId)) return
534
642
  env.sessions = env.sessions.filter(s => s !== sessionId)
535
643
  this._persist()
644
+ this._emitSessionsChanged(env)
645
+ }
646
+
647
+ /**
648
+ * #7552: announce that an environment's session tag CHANGED, so the WsServer
649
+ * can re-broadcast `environment_list` and the dashboard's copy stays true.
650
+ *
651
+ * Without this the dashboard refreshes only when the Environments panel
652
+ * mounts or an environment is created/destroyed — none of which is a session
653
+ * lifecycle event. A destroy guard reading a stale `sessions.length` is the
654
+ * same false safety by a different route, so the freshness is part of the fix
655
+ * rather than a follow-up. Emitted only on a REAL change (a duplicate add or
656
+ * an absent remove is silent) so a busy-but-unchanged daemon broadcasts
657
+ * nothing.
658
+ *
659
+ * @param {Object} env
660
+ * @private
661
+ */
662
+ _emitSessionsChanged(env) {
663
+ this.emit('environment_sessions_changed', { id: env.id, sessions: [...env.sessions] })
536
664
  }
537
665
 
538
666
  /**
@@ -576,11 +704,22 @@ export class EnvironmentManager extends EventEmitter {
576
704
  let allHealthy = true
577
705
 
578
706
  for (const env of this._environments.values()) {
579
- // Clear stale session references unconditionally — in-memory session
580
- // state never survives a server restart, regardless of whether the
581
- // environment's container is reachable, stopped, or has no containerId
582
- // at all. (#3494: this used to live at the bottom of the loop body and
583
- // was skipped by the no-containerId `continue` below.)
707
+ // Clear the PREVIOUS process's session references unconditionally,
708
+ // regardless of whether the environment's container is reachable,
709
+ // stopped, or has no containerId at all. (#3494: this used to live at the
710
+ // bottom of the loop body and was skipped by the no-containerId
711
+ // `continue` below.)
712
+ //
713
+ // #7561: this is no longer the last word on the tag. Sessions now persist
714
+ // their environment binding and RE-ATTACH on restore, so the sequence at
715
+ // boot is: reconnect() wipes the stale ids written by the process that
716
+ // died, then SessionManager.restoreState() re-tags the ones that actually
717
+ // came back. The ordering is load-bearing and holds in server-cli.js —
718
+ // the manager is constructed and reconnect()ed before the SessionManager
719
+ // exists, let alone restores — and is pinned in
720
+ // tests/environment-restore-binding.test.js. A reconnect() AFTER a
721
+ // restore would silently un-tag every restored session and put the
722
+ // destroy guard (#7562) back to sleep.
584
723
  env.sessions = []
585
724
 
586
725
  if (!env.containerId) {