@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,300 @@
1
+ import { formatWriteConfirmation } from './built-in-tools/tool-transforms.js'
2
+
3
+ /**
4
+ * Normalise a claude-tui PostToolUse hook's `tool_response` into the same
5
+ * kind of flat display text SdkSession/CliSession forward for a tool_result
6
+ * (see tool-result.js's `emitToolResults`).
7
+ *
8
+ * #8082: the PostToolUse hook payload's `tool_response` field is Claude
9
+ * Code's raw structured tool result (the same object the on-disk transcript
10
+ * stores as `toolUseResult`, alongside a `tool_result` content block whose
11
+ * `content` is the flattened text the model actually saw). The claude-tui
12
+ * provider only observes the hook payload, not the transcript's sibling
13
+ * content block, so — unlike SdkSession/CliSession, which read `content`
14
+ * directly off the tool_result block via `emitToolResults` — there is no
15
+ * flattened-text field available here for the built-in tools. This function
16
+ * unwraps the known structured shapes into the same kind of plain text
17
+ * instead of forwarding (and previously, JSON.stringify-ing) the envelope.
18
+ *
19
+ * Order of preference (see the #8082 PR review, Critical #1 — a plain
20
+ * string `content` field is AMBIGUOUS and its priority relative to the
21
+ * Write-shape check is load-bearing; a fixture that pins this ordering
22
+ * lives in the test suite as the "rule order" regression case):
23
+ *
24
+ * 1a. A `content` field that is an ARRAY of `{ type: 'text', text }`
25
+ * blocks — this shape is unambiguous (Write/Edit/Bash/Read never
26
+ * produce it) and always wins: it's the exact shape emitToolResults()
27
+ * flattens, and it's what an MCP `{ content: [...], isError }` tool
28
+ * response carries verbatim.
29
+ * 1b. A `content` field that is a STRING — used as-is, UNLESS the object
30
+ * is shaped like the built-in Write tool's result (see
31
+ * `isFileWriteResponseShape`), in which case this branch is skipped
32
+ * and rule 2 handles it instead. Grep's content-mode result
33
+ * (`{ mode: 'content', content: '<rg output>', numLines }`) and a
34
+ * string-content MCP response both qualify here; Write's result also
35
+ * carries a string `content` field, but there it is the ENTIRE
36
+ * written file, not a flattened summary — the whole reason this rule
37
+ * needs the Write-shape exclusion (#8082 review, Critical #1).
38
+ * 2. The known built-in Write shape: `{ type: 'create'|'update', filePath,
39
+ * content, structuredPatch, originalFile, userModified }` — rendered as
40
+ * the SAME short confirmation text `byok-tool-executor.js`'s `runWrite`
41
+ * already produces for a successful write (`formatWriteConfirmation`,
42
+ * built-in-tools/tool-transforms.js), never the file body. Checked
43
+ * BEFORE the Bash/Read unwraps below too — not just before rule 1b —
44
+ * so a (pathological, never real) object that happened to satisfy both
45
+ * the Write shape and a Bash/Read shape still renders the Write
46
+ * confirmation, never the file body misread as stdout/file content.
47
+ * 3. The known built-in Bash shape: `{ stdout, stderr, interrupted,
48
+ * isImage, noOutputExpected }`.
49
+ * 4. The known built-in Read shape: `{ type: 'text', file: { content } }`.
50
+ * 4b. (checked right after rule 1a) `{ type: 'file_unchanged', file: {
51
+ * filePath } }` — a repeated Read of an unchanged file — rendered as
52
+ * "File unchanged since it was last read (<path>)" (#8252).
53
+ * 5. Anything else — unchanged from before this normalizer existed:
54
+ * `JSON.stringify(resp)`. This is a deliberate no-regression floor: an
55
+ * unrecognised structured shape must render exactly as it did before,
56
+ * never worse.
57
+ *
58
+ * KNOWN LIMITATION (not a regression — see the #8082 PR review, Suggestion
59
+ * #3): an array `content` mixing a `{ type: 'image', ... }` block with text
60
+ * blocks silently drops the image block with no placeholder (unlike Bash's
61
+ * `isImage: true`, which renders `[Image output omitted]`). Before this
62
+ * normalizer existed the whole envelope was JSON.stringify-d — including raw
63
+ * base64 — so this is not worse than before, but it means MCP tool results
64
+ * get parity with SdkSession/CliSession for TEXT content only; a real
65
+ * `tool_result` event carries images via a separate `images` array
66
+ * (tool-result.js's `emitToolResults`) that claude-tui's `tool_result` event
67
+ * has no field for at all today.
68
+ *
69
+ * @param {string} toolName
70
+ * @param {unknown} resp - `payload.tool_response` from a PostToolUse hook.
71
+ * @returns {string}
72
+ */
73
+ export function normalizeClaudeTuiToolResponse(toolName, resp) {
74
+ if (typeof resp === 'string') return resp
75
+ if (resp === null || resp === undefined) return ''
76
+ if (typeof resp !== 'object') return ''
77
+
78
+ // Rule 1a — array-of-text-blocks content ALWAYS qualifies. This shape is
79
+ // unambiguous: Write/Edit/Bash/Read never produce it, so checking it
80
+ // unconditionally (before the Write-shape check even runs) cannot regress
81
+ // anything.
82
+ const fromArrayContent = flattenArrayContent(resp.content)
83
+ if (fromArrayContent !== null) return fromArrayContent
84
+
85
+ // Rule 4b, checked right after rule 1a (#8252) — a repeated Read of a file that has not changed. Claude
86
+ // Code answers with `{ type: 'file_unchanged', file: { filePath } }` instead of
87
+ // the content, and the model is told to refer to the earlier read. Shape-
88
+ // matched, not tool-matched: the type tag is unambiguous.
89
+ if (resp.type === 'file_unchanged') return normalizeFileUnchangedResponse(resp)
90
+
91
+ // The Write-shape check MUST be computed (and consulted by rule 1b)
92
+ // BEFORE a string `content` field is allowed to win. Reversing this —
93
+ // checking Bash/Read/Write shapes only after an unconditional string
94
+ // rule 1 — is exactly the regression the #8082 PR review found: Write's
95
+ // structured result carries a string `content` field (the entire file),
96
+ // and an unscoped rule 1 renders it verbatim instead of a short
97
+ // confirmation. See the "rule order" mutant in the test suite for the
98
+ // fixture that pins this.
99
+ const isWriteShape = isFileWriteResponseShape(resp)
100
+
101
+ // Rule 1b — a plain string `content` field, when the object is NOT
102
+ // shaped like a Write result (Grep content-mode, string-content MCP).
103
+ if (typeof resp.content === 'string' && !isWriteShape) {
104
+ return resp.content
105
+ }
106
+
107
+ // The Write-shape check ALSO has to win over the Bash/Read tool-specific
108
+ // unwraps below, not just over rule 1b — a pathological object could in
109
+ // principle satisfy both isFileWriteResponseShape AND
110
+ // normalizeBashResponse's "has stdout or stderr" test (or Read's file.content
111
+ // test); Write must still take priority so its `content` (the whole file)
112
+ // is never mistaken for stdout/file-content text. A genuine Bash/Read
113
+ // result never carries filePath/structuredPatch/type:create|update, so
114
+ // this ordering has NO effect on any real tool response — see the
115
+ // "rule-order regression" fixtures in the test suite that pin it.
116
+ if (isWriteShape) {
117
+ return normalizeWriteResponse(resp)
118
+ }
119
+
120
+ if (toolName === 'Bash') {
121
+ const bash = normalizeBashResponse(resp)
122
+ if (bash !== null) return bash
123
+ }
124
+
125
+ if (toolName === 'Read') {
126
+ const read = normalizeReadResponse(resp)
127
+ if (read !== null) return read
128
+ }
129
+
130
+ // Unknown/unmapped shape — unchanged from today's behavior.
131
+ try {
132
+ return JSON.stringify(resp)
133
+ } catch {
134
+ return String(resp)
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Flatten a tool_result-block-shaped `content` field that is an ARRAY of
140
+ * `{ type: 'text', text }` blocks, the same way tool-result.js's
141
+ * `emitToolResults` flattens `block.content`: filtered to `type: 'text'`
142
+ * blocks and joined with `\n`. Returns null when `content` is not an array,
143
+ * or is an array with no text block at all (so the caller falls through to
144
+ * the Write-shape check / a tool-specific unwrap), NOT when it flattens to
145
+ * an empty string (a legitimately empty text result is a valid result).
146
+ *
147
+ * Deliberately does NOT handle a string `content` — that branch is
148
+ * ambiguous (see `normalizeClaudeTuiToolResponse`'s rule 1b) and is decided
149
+ * by the caller together with `isFileWriteResponseShape`, not here.
150
+ *
151
+ * @param {unknown} content
152
+ * @returns {string|null}
153
+ */
154
+ function flattenArrayContent(content) {
155
+ if (!Array.isArray(content)) return null
156
+ const hasTextBlock = content.some((b) => b && typeof b === 'object' && b.type === 'text')
157
+ if (!hasTextBlock) return null
158
+ return content
159
+ .filter((b) => b && b.type === 'text' && typeof b.text === 'string')
160
+ .map((b) => b.text)
161
+ .join('\n')
162
+ }
163
+
164
+ /**
165
+ * Does `resp` look like the built-in Write tool's structured result —
166
+ * `{ type: 'create'|'update', filePath, content, structuredPatch,
167
+ * originalFile, userModified }` — where `content` is the ENTIRE written
168
+ * file, not a flattened model-facing summary?
169
+ *
170
+ * Checked by shape rather than tool name: `type: 'create'|'update'` AND a
171
+ * string `content`. Both are required. `filePath` or `structuredPatch` alone
172
+ * is NOT enough, because Edit's result carries both (`{ filePath, oldString,
173
+ * newString, originalFile, structuredPatch, … }`) and has no `content`;
174
+ * matching it here would render "Wrote 0 bytes to <path>", a false
175
+ * statement, where Edit's unchanged fallback is at least accurate.
176
+ *
177
+ * @param {Record<string, unknown>} resp
178
+ * @returns {boolean}
179
+ */
180
+ function isFileWriteResponseShape(resp) {
181
+ return (resp.type === 'create' || resp.type === 'update') && typeof resp.content === 'string'
182
+ }
183
+
184
+ /**
185
+ * Unwrap the built-in Bash tool's structured result:
186
+ * `{ stdout, stderr, interrupted, isImage, noOutputExpected }`.
187
+ *
188
+ * - stdout alone → stdout, unchanged (matches the SdkSession/CliSession
189
+ * shape: a Bash result with no stderr is just the command's output text).
190
+ * - stdout + non-empty stderr → stdout, then stderr on its own line. stderr
191
+ * must never be silently dropped — that's the whole "Bash cards show
192
+ * stdout, and stderr when it isn't empty" acceptance criterion.
193
+ * - stderr alone (stdout empty) → stderr by itself, so a failing command
194
+ * with no stdout still shows *something* rather than a blank card.
195
+ * - both empty + interrupted → a short placeholder rather than a blank
196
+ * card with no explanation.
197
+ * - both empty, not interrupted → '' (matches ToolBubble's existing
198
+ * "empty string result renders nothing" contract — nothing ran wrong,
199
+ * there's just nothing to show).
200
+ * - `isImage: true` → the hook payload carries no actual image bytes for
201
+ * Bash (unlike Read/MCP image content blocks, which flow through
202
+ * `flattenArrayContent` above and tool-result.js's own image
203
+ * extraction), so `stdout` here is not decodable image data by this
204
+ * provider today. A placeholder avoids dumping raw/base64 noise into a
205
+ * plain-text tool card; see the PR for the "Needs live check" note.
206
+ *
207
+ * Returns null when `resp` doesn't carry either of `stdout`/`stderr` as a
208
+ * string at all (not really a Bash-shaped response), so the caller falls
209
+ * through to the generic JSON.stringify floor.
210
+ *
211
+ * @param {Record<string, unknown>} resp
212
+ * @returns {string|null}
213
+ */
214
+ function normalizeBashResponse(resp) {
215
+ if (typeof resp.stdout !== 'string' && typeof resp.stderr !== 'string') return null
216
+
217
+ const stdout = typeof resp.stdout === 'string' ? resp.stdout : ''
218
+ const stderr = typeof resp.stderr === 'string' ? resp.stderr : ''
219
+
220
+ if (resp.isImage === true) {
221
+ return stderr ? `[Image output omitted]\n${stderr}` : '[Image output omitted]'
222
+ }
223
+
224
+ if (!stdout && !stderr) {
225
+ return resp.interrupted === true ? '[Interrupted — no output]' : ''
226
+ }
227
+
228
+ if (stderr) {
229
+ return stdout ? `${stdout}\n${stderr}` : stderr
230
+ }
231
+ return stdout
232
+ }
233
+
234
+ /**
235
+ * Unwrap the built-in Read tool's structured result:
236
+ * `{ type: 'text', file: { filePath, content, numLines, startLine,
237
+ * totalLines } }`. Returns the file content verbatim, or null when `resp`
238
+ * doesn't carry a `file.content` string (falls through to the generic
239
+ * JSON.stringify floor).
240
+ *
241
+ * @param {Record<string, unknown>} resp
242
+ * @returns {string|null}
243
+ */
244
+ function normalizeReadResponse(resp) {
245
+ const file = resp.file
246
+ if (!file || typeof file !== 'object' || typeof file.content !== 'string') return null
247
+ return file.content
248
+ }
249
+
250
+ /**
251
+ * Render the built-in Write tool's structured result — `{ type:
252
+ * 'create'|'update', filePath, content, structuredPatch, originalFile,
253
+ * userModified }` — as the SAME short confirmation text
254
+ * `byok-tool-executor.js`'s `runWrite` already produces for a successful
255
+ * write, via the shared `formatWriteConfirmation` helper
256
+ * (built-in-tools/tool-transforms.js). NEVER the file body (#8082 PR
257
+ * review, Critical #1) — `resp.content` here is the entire written file,
258
+ * which is exactly why this function exists instead of letting rule 1b
259
+ * render it.
260
+ *
261
+ * `bytesWritten` isn't carried on the hook's `tool_response` the way it is
262
+ * on `byok-tool-executor.js`'s own write result, so it's derived from the
263
+ * written content's UTF-8 byte length — the same measure `writeFileTool`
264
+ * itself reports for an ordinary write.
265
+ *
266
+ * Only called when `isFileWriteResponseShape(resp)` is true — which can
267
+ * match on `structuredPatch` or `type` alone, so `filePath` is NOT
268
+ * guaranteed to be present here. A missing/non-string `filePath` or
269
+ * `content` still renders a confirmation (empty path / `0` bytes
270
+ * respectively) rather than throwing.
271
+ *
272
+ * @param {Record<string, unknown>} resp
273
+ * @returns {string}
274
+ */
275
+ function normalizeWriteResponse(resp) {
276
+ const content = typeof resp.content === 'string' ? resp.content : ''
277
+ return formatWriteConfirmation({
278
+ bytesWritten: Buffer.byteLength(content, 'utf8'),
279
+ filePath: typeof resp.filePath === 'string' ? resp.filePath : '',
280
+ created: resp.type === 'create',
281
+ })
282
+ }
283
+
284
+ /**
285
+ * Render the built-in Read tool's repeated-read result — `{ type:
286
+ * 'file_unchanged', file: { filePath } }` — as one plain sentence naming the
287
+ * file, instead of the JSON envelope (#8252). A missing path drops the
288
+ * parenthetical rather than printing an empty one.
289
+ *
290
+ * @param {Record<string, unknown>} resp
291
+ * @returns {string}
292
+ */
293
+ function normalizeFileUnchangedResponse(resp) {
294
+ const filePath = resp.file && typeof resp.file === 'object' && typeof resp.file.filePath === 'string'
295
+ ? resp.file.filePath
296
+ : ''
297
+ return filePath
298
+ ? `File unchanged since it was last read (${filePath})`
299
+ : 'File unchanged since it was last read'
300
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * chroxy agent-control — stdio MCP server exposing this daemon's session
3
+ * control surface to an external agent harness (Codex, Claude, Gemini, …).
4
+ *
5
+ * chroxy agent-control --stdio → local daemon, read-write
6
+ * chroxy agent-control --stdio --read-only → local daemon, mutation tools absent
7
+ * chroxy agent-control --stdio --url wss://host --pin-identity <key>
8
+ * → remote daemon (token via env — see below)
9
+ * chroxy agent-control --stdio --url ws://host --allow-insecure-ws
10
+ * → remote daemon over cleartext ws:// (see below)
11
+ *
12
+ * This is a thin CLI wrapper around `agent-control/mcp-server.js`'s own
13
+ * `main()`, passing Commander's parsed options so both `--url value` and
14
+ * `--url=value` preserve the explicit target and identity pin. See
15
+ * docs/guides/agent-control.md for the full design, security
16
+ * model, and MCP-host configuration examples.
17
+ *
18
+ * There is deliberately NO `--token` flag: argv is visible to every other
19
+ * process on this machine via `ps`. A remote connection's token is read
20
+ * ONLY from the `CHROXY_AGENT_CONTROL_TOKEN` environment variable; the local
21
+ * (default) case needs no token in argv or config at all — it reads
22
+ * connection.json itself.
23
+ *
24
+ * A plain `ws://` URL to a host that is not loopback is REFUSED at startup
25
+ * (#7969): the bearer token goes out in the first `auth` frame, before any key
26
+ * exchange, so on cleartext `ws://` anyone on the network path can read it, and
27
+ * `--pin-identity` cannot protect it (the pin is checked only afterwards). Use
28
+ * `wss://`, or pass `--allow-insecure-ws` to accept that risk on a network you
29
+ * trust. "Loopback" is strict: `localhost`, an IPv4 address in 127.0.0.0/8, or
30
+ * `[::1]` — see `hostStaysOnThisMachine` in agent-control/local-connection.js. The
31
+ * flag is argv-only: a URL configured through CHROXY_AGENT_CONTROL_URL still
32
+ * needs `--allow-insecure-ws` in the arguments. The rule lives in
33
+ * `validateExplicitUrl` (agent-control/local-connection.js), shared by the
34
+ * resolver and `main()`'s startup check; this wrapper only declares the option.
35
+ */
36
+
37
+ export function registerAgentControlCommand(program) {
38
+ program
39
+ .command('agent-control')
40
+ // Boolean flags take no value, but Commander tolerates a stray positional
41
+ // word by default, so `--allow-insecure-ws false` (or `0`, or
42
+ // `--allow-command-approvals false`) parsed as the flag being SET: the
43
+ // operator wrote "false" and got cleartext transport / command approvals
44
+ // (#7969). Reject excess arguments on THIS command only, so a value after
45
+ // a boolean flag is an error instead of silently enabling it. The command
46
+ // takes no positional arguments, so nothing legitimate is lost.
47
+ .allowExcessArguments(false)
48
+ .description('Run a stdio MCP server exposing chroxy session control to an external agent harness (Codex, Claude, Gemini, …). Requires --stdio (the only supported mode). Remote connections read the token ONLY from CHROXY_AGENT_CONTROL_TOKEN — there is no --token flag.')
49
+ .option('--stdio', 'Run as a stdio MCP server (required — this command has no other mode)')
50
+ .option('--read-only', 'Disable mutation tools (create/send-input/interrupt/respond-permission)')
51
+ .option('--url <url>', 'Explicit remote daemon URL — never inferred; token via CHROXY_AGENT_CONTROL_TOKEN. Use wss://. A ws:// URL to any host other than loopback (localhost, 127.0.0.0/8, [::1]) is refused unless --allow-insecure-ws is given, because the token is sent in cleartext before any key exchange.')
52
+ .option('--allow-insecure-ws', 'Accept a ws:// --url (or CHROXY_AGENT_CONTROL_URL) to a non-loopback host, sending the bearer token in cleartext before any key exchange — anyone on the network path can read it and --pin-identity cannot protect it. Argv only: there is no environment-variable equivalent. Prints a startup WARNING. Prefer wss://.')
53
+ .option('--pin-identity <key>', "Pin the daemon's Ed25519 identity public key (base64) — or set CHROXY_AGENT_CONTROL_PIN")
54
+ .option('--allow-command-approvals', "Let the connected planner approve command-style tool calls (Bash, PowerShell, Monitor, codex shell) via chroxy_respond_permission — off by default because the protected-path floor cannot see through an arbitrary command string (e.g. `cat .env` looks like an ordinary, unfloored Bash call). Still subject to the floored/ownership gates. Logs a startup warning when enabled.")
55
+ .action(async (options) => {
56
+ if (!options.stdio) {
57
+ process.stderr.write('chroxy agent-control requires --stdio (the only supported mode).\n')
58
+ process.stderr.write('Usage: chroxy agent-control --stdio [--read-only] [--url <url>] [--pin-identity <key>] [--allow-command-approvals] [--allow-insecure-ws]\n')
59
+ process.exitCode = 1
60
+ return
61
+ }
62
+ const { main } = await import('../agent-control/mcp-server.js')
63
+ await main({ readOnly: options.readOnly, url: options.url, identityPublicKey: options.pinIdentity, allowCommandApprovals: options.allowCommandApprovals, allowInsecureWs: options.allowInsecureWs })
64
+ })
65
+ }
@@ -2,22 +2,22 @@
2
2
  * chroxy config — Show current configuration
3
3
  */
4
4
  import { existsSync, readFileSync } from 'fs'
5
- import { CONFIG_FILE } from './shared.js'
5
+ import { configFile } from './shared.js'
6
6
 
7
7
  export function registerConfigCommand(program) {
8
8
  program
9
9
  .command('config')
10
10
  .description('Show current configuration')
11
11
  .action(() => {
12
- if (!existsSync(CONFIG_FILE)) {
12
+ if (!existsSync(configFile())) {
13
13
  console.log('No config found. Run \'chroxy init\' first.')
14
14
  process.exit(1)
15
15
  }
16
16
 
17
- const config = JSON.parse(readFileSync(CONFIG_FILE, 'utf-8'))
17
+ const config = JSON.parse(readFileSync(configFile(), 'utf-8'))
18
18
 
19
19
  console.log('\n📋 Current Configuration\n')
20
- console.log(` Config file: ${CONFIG_FILE}`)
20
+ console.log(` Config file: ${configFile()}`)
21
21
  console.log(` Port: ${config.port}`)
22
22
  const tunnelMode = config.tunnel || 'quick'
23
23
  if (tunnelMode === 'named') {
@@ -0,0 +1,234 @@
1
+ // `chroxy config-dir` — inspect and migrate the daemon's config/state root (#7240).
2
+ //
3
+ // #7052 made CHROXY_CONFIG_DIR relocate ALL daemon state. Anyone who already set
4
+ // it has ~20 files silently stranded at ~/.chroxy on upgrade. The daemon warns
5
+ // at startup and `chroxy doctor` reports it, but neither moves anything: copying
6
+ // an identity key and credentials into a directory the operator may have pointed
7
+ // at a shared, synced or bind-mounted volume is the operator's security decision,
8
+ // and the daemon cannot tell a fresh relocation from a deliberately clean root.
9
+ // So the copy lives here, behind an explicit command.
10
+ //
11
+ // #7244 — an operator who runs a deliberate second root (the isolated-preview
12
+ // recipe does) has no way to say "I know". `ack` records the CURRENT stranded
13
+ // names into the target root; the warning then stays quiet only while every
14
+ // stranded name is in that snapshot, so an entry that appears later warns.
15
+
16
+ import {
17
+ ackCommand,
18
+ detectStrandedState,
19
+ migrateStrandedState,
20
+ partitionStranded,
21
+ readStrandedAck,
22
+ writeStrandedAck,
23
+ } from '../config-dir-migration.js'
24
+
25
+ /**
26
+ * `chroxy config-dir status` — report the resolved root and anything stranded.
27
+ *
28
+ * @param {object} [deps] Injected seams: `write`, `detect`, `readAck`.
29
+ * @returns {{ relocated: boolean, stranded: string[], acknowledged: string[] }}
30
+ */
31
+ export function runConfigDirStatus(deps = {}) {
32
+ const out = deps.write || console.log
33
+ const detect = deps.detect || detectStrandedState
34
+ const readAck = deps.readAck || readStrandedAck
35
+ const d = detect()
36
+
37
+ out(`Config/state root: ${d.target}${d.relocated ? ' (from CHROXY_CONFIG_DIR)' : ''}`)
38
+
39
+ if (!d.relocated) {
40
+ out('Not relocated — nothing can be stranded.')
41
+ return { relocated: false, stranded: [], acknowledged: [] }
42
+ }
43
+ if (d.unreadable) {
44
+ out(`Could not check ${d.source} for stranded state: ${d.unreadable}`)
45
+ return { relocated: true, stranded: [], acknowledged: [] }
46
+ }
47
+ if (d.stranded.length === 0) {
48
+ out(`No state stranded at ${d.source}.`)
49
+ return { relocated: true, stranded: [], acknowledged: [] }
50
+ }
51
+
52
+ // partitionStranded, not applyStrandedAck: status must still list every
53
+ // stranded entry (marking the acknowledged ones), so it needs the split, not
54
+ // the filtered view the warning and doctor use.
55
+ const { acknowledged } = partitionStranded(d, readAck(d))
56
+
57
+ out('')
58
+ out(`${d.stranded.length} state ${d.stranded.length === 1 ? 'entry is' : 'entries are'} still at ${d.source}:`)
59
+ for (const name of d.stranded) {
60
+ const marks = [
61
+ d.highConsequence.includes(name) ? '<- high consequence' : null,
62
+ acknowledged.includes(name) ? '(acknowledged)' : null,
63
+ ].filter(Boolean)
64
+ out(` ${name}${marks.length > 0 ? ` ${marks.join(' ')}` : ''}`)
65
+ }
66
+ out('')
67
+ if (acknowledged.length > 0) {
68
+ out(`${acknowledged.length} of these ${acknowledged.length === 1 ? 'is' : 'are'} acknowledged, so the startup warning and 'chroxy doctor' leave ${acknowledged.length === 1 ? 'it' : 'them'} out.`)
69
+ }
70
+ out('Copy them forward with: chroxy config-dir migrate --yes')
71
+ out(`Or keep this root on purpose: ${ackCommand(d.target)}`)
72
+ return { relocated: true, stranded: d.stranded, acknowledged }
73
+ }
74
+
75
+ /**
76
+ * `chroxy config-dir ack` — acknowledge the state currently stranded at the
77
+ * default root, because the relocated root is deliberate (#7244).
78
+ *
79
+ * Writes a snapshot of the stranded entry NAMES into the target root. It is not
80
+ * a switch: an entry that appears afterwards is not in the snapshot and warns
81
+ * again. With nothing stranded, or no relocation, it says so and writes nothing.
82
+ *
83
+ * @param {object} [deps] Injected seams: `write`, `detect`, `ack`.
84
+ * @returns {{ acknowledged: boolean, names: string[] }}
85
+ */
86
+ export function runConfigDirAck(deps = {}) {
87
+ const out = deps.write || console.log
88
+ const detect = deps.detect || detectStrandedState
89
+ const ack = deps.ack || writeStrandedAck
90
+ const d = detect()
91
+
92
+ if (!d.relocated) {
93
+ out(`Config/state root is ${d.target} — not relocated, so there is nothing to acknowledge.`)
94
+ out('To acknowledge a deliberate second root, run this with CHROXY_CONFIG_DIR set to that root')
95
+ out('(the one the daemon reads), e.g. CHROXY_CONFIG_DIR=/path/to/root chroxy config-dir ack')
96
+ return { acknowledged: false, names: [] }
97
+ }
98
+ if (d.unreadable) {
99
+ out(`Could not read ${d.source}: ${d.unreadable} — nothing was acknowledged.`)
100
+ return { acknowledged: false, names: [] }
101
+ }
102
+ if (d.stranded.length === 0) {
103
+ out(`No state stranded at ${d.source} — nothing to acknowledge.`)
104
+ return { acknowledged: false, names: [] }
105
+ }
106
+
107
+ const { file, acknowledged } = ack(d)
108
+ out(`Acknowledged ${acknowledged.length} state ${acknowledged.length === 1 ? 'entry' : 'entries'} left at ${d.source}:`)
109
+ for (const name of acknowledged) out(` ${name}`)
110
+ out('')
111
+ out(`Recorded in ${file}. The startup warning and 'chroxy doctor' now stay quiet about`)
112
+ out('these. An entry whose name was not acknowledged will warn again; re-running this')
113
+ out('command replaces the snapshot with the current set.')
114
+ return { acknowledged: true, names: acknowledged }
115
+ }
116
+
117
+ /**
118
+ * `chroxy config-dir migrate` — copy stranded entries into the resolved root.
119
+ *
120
+ * Consequential (it moves secrets across a directory boundary the operator drew),
121
+ * so it requires an explicit `--yes`; without it the command only explains.
122
+ * Never overwrites: only entries absent from the target are copied.
123
+ *
124
+ * @param {{ yes?: boolean }} options
125
+ * @param {object} [deps] Injected seams: `write`, `detect`, `migrate`.
126
+ * @returns {{ migrated: boolean, result: object|null }}
127
+ */
128
+ export function runConfigDirMigrate(options = {}, deps = {}) {
129
+ const out = deps.write || console.log
130
+ const detect = deps.detect || detectStrandedState
131
+ const migrate = deps.migrate || migrateStrandedState
132
+ const d = detect()
133
+
134
+ if (!d.relocated) {
135
+ out(`Config/state root is ${d.target} — not relocated, so nothing can be stranded.`)
136
+ return { migrated: false, result: null }
137
+ }
138
+ if (d.unreadable) {
139
+ out(`Could not read ${d.source}: ${d.unreadable}`)
140
+ return { migrated: false, result: null }
141
+ }
142
+ if (d.stranded.length === 0) {
143
+ out(`No state stranded at ${d.source} — ${d.target} is already up to date.`)
144
+ return { migrated: false, result: null }
145
+ }
146
+
147
+ if (!options.yes) {
148
+ out(
149
+ [
150
+ 'chroxy config-dir migrate — copy stranded daemon state into the relocated root.',
151
+ '',
152
+ ` from: ${d.source}`,
153
+ ` to: ${d.target}`,
154
+ '',
155
+ `Would copy ${d.stranded.length} ${d.stranded.length === 1 ? 'entry' : 'entries'}:`,
156
+ ...d.stranded.map((n) => ` ${n}${d.highConsequence.includes(n) ? ' <- high consequence' : ''}`),
157
+ '',
158
+ 'Nothing already present in the destination is overwritten, and the source is',
159
+ 'left in place — this copies, it does not move.',
160
+ '',
161
+ 'Note this copies secrets (identity key, credentials, API token) into the',
162
+ 'destination. If that directory is shared, synced or bind-mounted into a',
163
+ 'container, decide whether you want them there before proceeding.',
164
+ '',
165
+ 'Re-run with --yes to proceed:',
166
+ ' chroxy config-dir migrate --yes',
167
+ ].join('\n'),
168
+ )
169
+ return { migrated: false, result: null }
170
+ }
171
+
172
+ const result = migrate({ detection: d })
173
+
174
+ if (result.copied.length > 0) {
175
+ out(`Copied ${result.copied.length} ${result.copied.length === 1 ? 'entry' : 'entries'} to ${result.target}:`)
176
+ for (const name of result.copied) out(` ${name}`)
177
+ }
178
+ if (result.failed.length > 0) {
179
+ out('')
180
+ out(`${result.failed.length} ${result.failed.length === 1 ? 'entry' : 'entries'} could NOT be copied:`)
181
+ for (const f of result.failed) out(` ${f.name}: ${f.error}`)
182
+ }
183
+ out('')
184
+ out(`The original files are still at ${result.source} — remove them once the daemon`)
185
+ out('has restarted successfully against the new root.')
186
+
187
+ return { migrated: result.copied.length > 0, result }
188
+ }
189
+
190
+ export function registerConfigDirCommand(program) {
191
+ const configDirCmd = program
192
+ .command('config-dir')
193
+ .description('Inspect and migrate the daemon\'s config/state root (CHROXY_CONFIG_DIR)')
194
+
195
+ configDirCmd
196
+ .command('status')
197
+ .description('Show the resolved config/state root and any state stranded at ~/.chroxy')
198
+ .action(() => {
199
+ try {
200
+ runConfigDirStatus()
201
+ } catch (err) {
202
+ console.error(`config-dir status failed: ${err.message}`)
203
+ process.exitCode = 1
204
+ }
205
+ })
206
+
207
+ configDirCmd
208
+ .command('ack')
209
+ .description('Acknowledge the state left at ~/.chroxy because this relocated root is deliberate (new entries still warn)')
210
+ .action(() => {
211
+ try {
212
+ runConfigDirAck()
213
+ } catch (err) {
214
+ console.error(`config-dir ack failed: ${err.message}`)
215
+ process.exitCode = 1
216
+ }
217
+ })
218
+
219
+ configDirCmd
220
+ .command('migrate')
221
+ .description('Copy state stranded at ~/.chroxy into the relocated root (never overwrites)')
222
+ .option('--yes', 'Confirm the copy (without this, the command only explains what it would do)')
223
+ .action((options) => {
224
+ try {
225
+ const { result } = runConfigDirMigrate(options)
226
+ // A partial copy is a failure the caller must be able to see — a script
227
+ // that ignores it would report a migration that only half happened.
228
+ if (result?.failed.length > 0) process.exitCode = 1
229
+ } catch (err) {
230
+ console.error(`config-dir migrate failed: ${err.message}`)
231
+ process.exitCode = 1
232
+ }
233
+ })
234
+ }