@chroxy/server 0.10.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 (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  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 +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  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 +74 -9
  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 +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -0,0 +1,596 @@
1
+ /**
2
+ * statusLine — read the user's Claude Code `statusLine` command from their own
3
+ * settings.json, execute it the way Claude Code does, and surface its stdout.
4
+ *
5
+ * Feature #6791. A user who has configured a `statusLine` script (git branch,
6
+ * model, a cost tracker, …) sees none of it in Chroxy today; this module reads
7
+ * the effective config and runs it so its output can be broadcast to clients.
8
+ *
9
+ * ── Trust + security model (this EXECUTES a shell command) ────────────────────
10
+ * The command is ONLY ever the one in the user's OWN settings.json — the same
11
+ * trust boundary Claude Code itself honours when it runs the script. There is
12
+ * NO client-supplied command and NO client-supplied path: the settings files
13
+ * are read from fixed, server-chosen locations only
14
+ * - <sessionCwd>/.claude/settings.json (project — highest precedence)
15
+ * - ~/.claude/project-settings.json (user project-settings)
16
+ * - ~/.claude/settings.json (user — lowest precedence)
17
+ * (mirrors Claude Code's precedence — see docs.claude.com "statusline").
18
+ * `sessionCwd` comes from the server's session record, never from the wire.
19
+ *
20
+ * Robustness hardening, none of which Claude Code documents but all of which a
21
+ * long-lived daemon needs so a slow/hostile script can't wedge it:
22
+ * - strict TIMEOUT (default 5s) — SIGTERM then SIGKILL after a grace window;
23
+ * - stdout SIZE CAP (default 8 KB) — truncated, never buffered unbounded;
24
+ * - the session JSON is delivered on STDIN (the documented contract), never
25
+ * interpolated into the command string, so untrusted context can't inject;
26
+ * - chroxy's own daemon secrets are stripped from the child env (buildSpawnEnv);
27
+ * - non-zero exit / no output / timeout → blank (matches Claude Code), no crash;
28
+ * - no `statusLine` configured → silent no-op (feature simply inactive).
29
+ */
30
+
31
+ import { spawn } from 'node:child_process'
32
+ import { readFile } from 'node:fs/promises'
33
+ import { claudeConfigDir } from './utils/claude-config-dir.js'
34
+ import { join } from 'node:path'
35
+ import { EventEmitter } from 'node:events'
36
+ import { createLogger } from './logger.js'
37
+ import { CHROXY_SECRET_DENYLIST, stripInheritedChroxySecrets, stripParentClaudeSessionEnv } from './utils/spawn-env.js'
38
+
39
+ const log = createLogger('statusline')
40
+
41
+ /** Kill a script that runs longer than this (ms). */
42
+ export const STATUSLINE_DEFAULT_TIMEOUT_MS = 5_000
43
+ /** Hard cap on captured stdout+stderr bytes; output past this is truncated. */
44
+ export const STATUSLINE_MAX_OUTPUT_BYTES = 8 * 1024
45
+ /** SIGTERM → SIGKILL grace after a timeout / cap kill. */
46
+ export const STATUSLINE_HARD_KILL_GRACE_MS = 2_000
47
+ /** Floor between two spawns of the same session's script (debounce). */
48
+ export const STATUSLINE_MIN_REFRESH_INTERVAL_MS = 1_000
49
+ /** Periodic re-run cadence when the config gives no explicit `refreshInterval`. */
50
+ export const STATUSLINE_DEFAULT_REFRESH_INTERVAL_MS = 10_000
51
+ /** Ceiling for a configured `refreshInterval` so a tiny value can't hot-loop. */
52
+ export const STATUSLINE_MIN_CONFIGURED_INTERVAL_MS = 1_000
53
+ /** How long a resolved (or null) config is cached per cwd before a re-read. */
54
+ export const STATUSLINE_CONFIG_CACHE_TTL_MS = 5_000
55
+
56
+ /**
57
+ * Settings files consulted for the effective `statusLine`, in Claude Code's
58
+ * precedence order (first match wins). Every path is derived server-side from
59
+ * the session cwd and the user home — none is client-supplied.
60
+ *
61
+ * @param {string} cwd - session working directory (project scope)
62
+ * @param {string} claudeDir - claude's user-level config dir (`CLAUDE_CONFIG_DIR`, else `~/.claude`)
63
+ * @returns {string[]} absolute settings.json paths, highest precedence first
64
+ */
65
+ export function statusLineSettingsPaths(cwd, claudeDir) {
66
+ const paths = []
67
+ if (cwd) paths.push(join(cwd, '.claude', 'settings.json'))
68
+ if (claudeDir) {
69
+ paths.push(join(claudeDir, 'project-settings.json'))
70
+ paths.push(join(claudeDir, 'settings.json'))
71
+ }
72
+ return paths
73
+ }
74
+
75
+ /**
76
+ * Extract a usable `statusLine` config from a parsed settings object, or null.
77
+ * Only `type: "command"` with a non-empty string `command` is honoured — every
78
+ * other shape (missing, wrong type, empty command) is treated as "not
79
+ * configured" so a malformed entry is inert rather than throwing.
80
+ *
81
+ * @param {unknown} settings - parsed settings.json object
82
+ * @returns {{command: string, refreshIntervalMs: number|null}|null}
83
+ */
84
+ export function parseStatusLineConfig(settings) {
85
+ if (!settings || typeof settings !== 'object') return null
86
+ const sl = settings.statusLine
87
+ if (!sl || typeof sl !== 'object') return null
88
+ if (sl.type !== 'command') return null
89
+ if (typeof sl.command !== 'string' || sl.command.trim() === '') return null
90
+
91
+ // `refreshInterval` is documented in SECONDS (minimum 1). Absent → the
92
+ // StatusLineManager periodic loop (see `_tick`) falls back to
93
+ // STATUSLINE_DEFAULT_REFRESH_INTERVAL_MS rather than going event-driven-only;
94
+ // we still apply a floor here so a tiny configured value can't spin the daemon.
95
+ let refreshIntervalMs = null
96
+ if (Number.isFinite(sl.refreshInterval) && sl.refreshInterval > 0) {
97
+ refreshIntervalMs = Math.max(Math.floor(sl.refreshInterval * 1000), STATUSLINE_MIN_CONFIGURED_INTERVAL_MS)
98
+ }
99
+ return { command: sl.command, refreshIntervalMs }
100
+ }
101
+
102
+ /**
103
+ * Build the JSON object Claude Code pipes to a `statusLine` command on stdin.
104
+ * Chroxy populates every field it actually knows; fields it doesn't are OMITTED
105
+ * (the contract allows absent fields — scripts already guard for them). Nothing
106
+ * here is interpolated into the command — it is the stdin payload only.
107
+ *
108
+ * @param {object} ctx - server-side session context (see StatusLineManager)
109
+ * @returns {object} the stdin JSON payload
110
+ */
111
+ export function buildStatusLineInput(ctx = {}) {
112
+ const input = {}
113
+ if (ctx.cwd) input.cwd = ctx.cwd
114
+ if (ctx.sessionId) input.session_id = ctx.sessionId
115
+ if (ctx.sessionName) input.session_name = ctx.sessionName
116
+ if (ctx.transcriptPath) input.transcript_path = ctx.transcriptPath
117
+ if (ctx.version) input.version = ctx.version
118
+
119
+ if (ctx.model && (ctx.model.id || ctx.model.displayName)) {
120
+ input.model = {}
121
+ if (ctx.model.id) input.model.id = ctx.model.id
122
+ if (ctx.model.displayName) input.model.display_name = ctx.model.displayName
123
+ }
124
+
125
+ const currentDir = ctx.cwd || null
126
+ const projectDir = ctx.projectDir || ctx.cwd || null
127
+ if (currentDir || projectDir) {
128
+ input.workspace = {}
129
+ if (currentDir) input.workspace.current_dir = currentDir
130
+ if (projectDir) input.workspace.project_dir = projectDir
131
+ }
132
+
133
+ if (ctx.outputStyle) input.output_style = { name: ctx.outputStyle }
134
+
135
+ if (ctx.cost && typeof ctx.cost === 'object') {
136
+ const cost = {}
137
+ if (Number.isFinite(ctx.cost.totalCostUsd)) cost.total_cost_usd = ctx.cost.totalCostUsd
138
+ if (Number.isFinite(ctx.cost.totalDurationMs)) cost.total_duration_ms = ctx.cost.totalDurationMs
139
+ if (Number.isFinite(ctx.cost.totalApiDurationMs)) cost.total_api_duration_ms = ctx.cost.totalApiDurationMs
140
+ if (Number.isFinite(ctx.cost.totalLinesAdded)) cost.total_lines_added = ctx.cost.totalLinesAdded
141
+ if (Number.isFinite(ctx.cost.totalLinesRemoved)) cost.total_lines_removed = ctx.cost.totalLinesRemoved
142
+ if (Object.keys(cost).length > 0) input.cost = cost
143
+ }
144
+
145
+ return input
146
+ }
147
+
148
+ /**
149
+ * Default child env: the user's full environment (like Claude Code) minus
150
+ * chroxy's own daemon secrets (the CHROXY_SECRET_DENYLIST — e.g. the primary
151
+ * API_TOKEN) and ANTHROPIC_API_KEY, plus the COLUMNS/LINES the contract says to
152
+ * set. Deliberately does NOT go through `buildSpawnEnv` / the credential store:
153
+ * a status script needs no provider OAuth token, and injecting one would hit
154
+ * the keychain on every periodic spawn (every ~10s) for no benefit.
155
+ *
156
+ * Also strips CHROXY_PORT/CHROXY_HOOK_SECRET (#7360): the statusline script is
157
+ * an arbitrary operator-configured command with no permission-hook role, so
158
+ * any value present is necessarily AMBIENTLY inherited (e.g. this daemon was
159
+ * itself launched from inside another chroxy session) rather than something
160
+ * this builder set itself — exported so the strip is directly unit-testable.
161
+ */
162
+ export function defaultBuildEnv() {
163
+ const env = { ...process.env }
164
+ for (const key of [...CHROXY_SECRET_DENYLIST, 'ANTHROPIC_API_KEY']) delete env[key]
165
+ stripInheritedChroxySecrets(env)
166
+ stripParentClaudeSessionEnv(env) // #8262
167
+ env.COLUMNS = '80'
168
+ env.LINES = '1'
169
+ return env
170
+ }
171
+
172
+ /** setTimeout that never keeps the event loop alive (self-exit safety). */
173
+ function unrefTimer(fn, ms) {
174
+ const t = setTimeout(fn, ms)
175
+ if (typeof t.unref === 'function') t.unref()
176
+ return t
177
+ }
178
+
179
+ /**
180
+ * Execute a `statusLine` command once, feeding `input` (a JSON string) on stdin,
181
+ * capturing stdout/stderr under a byte cap, and killing it if it exceeds
182
+ * `timeoutMs`. Never throws — every failure folds into the returned result.
183
+ *
184
+ * Modeled on built-in-tools/bash-exec.js (same SIGTERM→SIGKILL grace + byte-cap
185
+ * discipline) but pipes stdin and runs through the platform shell to match
186
+ * Claude Code's own invocation: `/bin/sh -c` on POSIX, `cmd.exe /d /s /c` on
187
+ * Windows (COMSPEC — same precedent as `utils/win-spawn.js`'s `prepareSpawn`
188
+ * and `platform.js`'s `defaultShell`), so statusLine also works on win32
189
+ * instead of silently failing to spawn `/bin/sh`.
190
+ *
191
+ * @param {object} opts
192
+ * @param {string} opts.command - the shell command (user's own config)
193
+ * @param {string} opts.cwd - working directory for the child
194
+ * @param {string} opts.input - JSON string written to the child's stdin
195
+ * @param {object} [opts.env] - child env (defaults to secret-stripped user env)
196
+ * @param {number} [opts.timeoutMs]
197
+ * @param {number} [opts.maxOutputBytes]
198
+ * @param {Function} [opts.spawnFn] - injectable spawn (tests)
199
+ * @param {Function} [opts.setTimer] - injectable setTimeout (tests)
200
+ * @param {Function} [opts.clearTimer] - injectable clearTimeout (tests)
201
+ * @param {NodeJS.Platform} [opts.platform=process.platform] - override for tests
202
+ * @returns {Promise<{stdout:string, stderr:string, exitCode:number|null, signal:string|null, timedOut:boolean, truncated:boolean, durationMs:number, error:string|null}>}
203
+ */
204
+ export async function runStatusLineCommand({
205
+ command,
206
+ cwd,
207
+ input = '',
208
+ env,
209
+ timeoutMs = STATUSLINE_DEFAULT_TIMEOUT_MS,
210
+ maxOutputBytes = STATUSLINE_MAX_OUTPUT_BYTES,
211
+ spawnFn = spawn,
212
+ setTimer = unrefTimer,
213
+ clearTimer = clearTimeout,
214
+ platform = process.platform,
215
+ } = {}) {
216
+ const startedAt = Date.now()
217
+ const base = { stdout: '', stderr: '', exitCode: null, signal: null, timedOut: false, truncated: false, durationMs: 0, error: null }
218
+
219
+ if (typeof command !== 'string' || command.trim() === '') {
220
+ return { ...base, error: 'no command', durationMs: 0 }
221
+ }
222
+
223
+ let child
224
+ try {
225
+ const isWin = platform === 'win32'
226
+ // Same shell-selection precedent as `utils/win-spawn.js#prepareSpawn` and
227
+ // `platform.js#defaultShell`: Windows has no `/bin/sh`, so route through
228
+ // COMSPEC (cmd.exe) with `/d` (skip AutoRun) `/s` (strip exactly the outer
229
+ // quote pair) `/c` (run then exit) and `windowsVerbatimArguments` so Node
230
+ // doesn't re-quote our already-quoted command line — mirrors Node's own
231
+ // internal `{ shell: true }` behavior on win32.
232
+ const shellCommand = isWin ? (process.env.COMSPEC || 'cmd.exe') : '/bin/sh'
233
+ const shellArgs = isWin ? ['/d', '/s', '/c', `"${command}"`] : ['-c', command]
234
+ child = spawnFn(shellCommand, shellArgs, {
235
+ cwd: cwd || process.cwd(),
236
+ env: env || defaultBuildEnv(),
237
+ stdio: ['pipe', 'pipe', 'pipe'],
238
+ ...(isWin ? { windowsVerbatimArguments: true } : {}),
239
+ })
240
+ } catch (err) {
241
+ return { ...base, error: err?.message || 'spawn failed', durationMs: Date.now() - startedAt }
242
+ }
243
+
244
+ let stdout = ''
245
+ let stderr = ''
246
+ let totalBytes = 0
247
+ let truncated = false
248
+ let timedOut = false
249
+ let hardKillTimer = null
250
+
251
+ const killChild = (sig) => {
252
+ if (!child || child.killed || child.exitCode !== null) return
253
+ try {
254
+ child.kill(sig)
255
+ } catch {
256
+ // already gone
257
+ }
258
+ if (sig === 'SIGTERM' && hardKillTimer === null) {
259
+ hardKillTimer = setTimer(() => {
260
+ try {
261
+ if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL')
262
+ } catch {}
263
+ }, STATUSLINE_HARD_KILL_GRACE_MS)
264
+ }
265
+ }
266
+
267
+ const capture = (chunk, which) => {
268
+ if (totalBytes >= maxOutputBytes) return
269
+ const chunkBytes = chunk.length
270
+ const remaining = maxOutputBytes - totalBytes
271
+ if (chunkBytes > remaining) {
272
+ const sliced = chunk.subarray(0, remaining).toString('utf8')
273
+ if (which === 'stdout') stdout += sliced
274
+ else stderr += sliced
275
+ totalBytes += remaining
276
+ truncated = true
277
+ killChild('SIGTERM')
278
+ } else {
279
+ const text = chunk.toString('utf8')
280
+ if (which === 'stdout') stdout += text
281
+ else stderr += text
282
+ totalBytes += chunkBytes
283
+ }
284
+ }
285
+
286
+ child.stdout?.on('data', (c) => capture(c, 'stdout'))
287
+ child.stderr?.on('data', (c) => capture(c, 'stderr'))
288
+
289
+ // Feed the session JSON on stdin, then close it. A script that never reads
290
+ // stdin makes the pipe error with EPIPE — swallow it (it is expected, not a
291
+ // fault) so an unhandled 'error' can't crash the daemon.
292
+ if (child.stdin) {
293
+ child.stdin.on('error', () => {})
294
+ try {
295
+ child.stdin.end(input)
296
+ } catch {
297
+ // ignore — child may have exited before we wrote
298
+ }
299
+ }
300
+
301
+ const timeoutHandle = setTimer(() => {
302
+ timedOut = true
303
+ killChild('SIGTERM')
304
+ }, timeoutMs)
305
+
306
+ const { code, sig, spawnError } = await new Promise((resolve) => {
307
+ child.on('exit', (c, s) => resolve({ code: c, sig: s, spawnError: null }))
308
+ child.on('error', (err) => resolve({ code: null, sig: null, spawnError: err }))
309
+ })
310
+
311
+ clearTimer(timeoutHandle)
312
+ if (hardKillTimer !== null) clearTimer(hardKillTimer)
313
+
314
+ return {
315
+ stdout,
316
+ stderr,
317
+ exitCode: code,
318
+ signal: sig,
319
+ timedOut,
320
+ truncated,
321
+ durationMs: Date.now() - startedAt,
322
+ error: spawnError ? (spawnError.message || 'spawn error') : null,
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Reduce a raw execution result to the text a client should DISPLAY, following
328
+ * Claude Code's rules: non-zero exit, no output, a timeout, or a spawn error
329
+ * all render blank (empty string). Trailing whitespace is trimmed; the ANSI in
330
+ * the payload is left intact for the renderer to strip/interpret.
331
+ *
332
+ * @param {object} result - a runStatusLineCommand result
333
+ * @returns {string} the display text ('' == blank)
334
+ */
335
+ export function statusLineDisplayText(result) {
336
+ if (!result || result.error || result.timedOut) return ''
337
+ if (result.exitCode !== 0) return ''
338
+ const text = (result.stdout || '').replace(/\s+$/, '')
339
+ return text
340
+ }
341
+
342
+ /**
343
+ * Orchestrates statusLine reads/execs for live sessions and emits an `output`
344
+ * event ({ sessionId, active, text, truncated, timedOut, exitCode }) whenever a
345
+ * session's rendered status text CHANGES. Owns all timers (each unref'd + cleared
346
+ * on stopSession/stopAll) so the daemon can self-exit and tests leak nothing.
347
+ *
348
+ * Every side-effecting dependency (spawn, timers, clock, file read, env) is
349
+ * injectable so the whole thing is deterministic under test.
350
+ */
351
+ export class StatusLineManager extends EventEmitter {
352
+ constructor({
353
+ homeDir,
354
+ claudeDir,
355
+ readFileFn = readFile,
356
+ spawnFn = spawn,
357
+ buildEnv = defaultBuildEnv,
358
+ now = Date.now,
359
+ setTimer = unrefTimer,
360
+ clearTimer = clearTimeout,
361
+ timeoutMs = STATUSLINE_DEFAULT_TIMEOUT_MS,
362
+ maxOutputBytes = STATUSLINE_MAX_OUTPUT_BYTES,
363
+ minRefreshIntervalMs = STATUSLINE_MIN_REFRESH_INTERVAL_MS,
364
+ defaultRefreshIntervalMs = STATUSLINE_DEFAULT_REFRESH_INTERVAL_MS,
365
+ configCacheTtlMs = STATUSLINE_CONFIG_CACHE_TTL_MS,
366
+ } = {}) {
367
+ super()
368
+ // The user-level dir follows CLAUDE_CONFIG_DIR (#8974). `claudeDir` pins it;
369
+ // a bare `homeDir` (test seam) means `<homeDir>/.claude`; with neither, each
370
+ // resolveConfig() call resolves `claudeConfigDir()` from the daemon's process.env.
371
+ this._claudeDir = claudeDir ?? (homeDir ? join(homeDir, '.claude') : null)
372
+ this._readFileFn = readFileFn
373
+ this._spawnFn = spawnFn
374
+ this._buildEnv = buildEnv
375
+ this._now = now
376
+ this._setTimer = setTimer
377
+ this._clearTimer = clearTimer
378
+ this._timeoutMs = timeoutMs
379
+ this._maxOutputBytes = maxOutputBytes
380
+ this._minRefreshIntervalMs = minRefreshIntervalMs
381
+ this._defaultRefreshIntervalMs = defaultRefreshIntervalMs
382
+ this._configCacheTtlMs = configCacheTtlMs
383
+
384
+ /** @type {Map<string, {config: object|null, expiresAt: number}>} keyed by cwd */
385
+ this._configCache = new Map()
386
+ /** @type {Map<string, {getContext: Function, timer: any, lastRunAt: number, running: boolean, lastText: string|null}>} */
387
+ this._sessions = new Map()
388
+ this._stopped = false
389
+ }
390
+
391
+ /**
392
+ * Resolve the effective statusLine config for a cwd (project > project-settings
393
+ * > user; first match wins), cached per cwd with a short TTL. Returns null when
394
+ * no location configures a usable command. Never throws — a missing/malformed
395
+ * settings file is skipped.
396
+ *
397
+ * @param {string} cwd
398
+ * @returns {Promise<{command:string, refreshIntervalMs:number|null}|null>}
399
+ */
400
+ async resolveConfig(cwd) {
401
+ const cached = this._configCache.get(cwd)
402
+ if (cached && cached.expiresAt > this._now()) return cached.config
403
+
404
+ let config = null
405
+ for (const path of statusLineSettingsPaths(cwd, this._claudeDir ?? claudeConfigDir())) {
406
+ let raw
407
+ try {
408
+ raw = await this._readFileFn(path, 'utf8')
409
+ } catch {
410
+ continue // file absent / unreadable — try the next scope
411
+ }
412
+ let parsed
413
+ try {
414
+ parsed = JSON.parse(raw)
415
+ } catch {
416
+ continue // malformed JSON — skip this scope, don't fail the whole read
417
+ }
418
+ const found = parseStatusLineConfig(parsed)
419
+ if (found) {
420
+ config = found
421
+ break
422
+ }
423
+ }
424
+
425
+ this._configCache.set(cwd, { config, expiresAt: this._now() + this._configCacheTtlMs })
426
+ return config
427
+ }
428
+
429
+ /** Drop any cached config (e.g. session ended) so a re-read is forced. */
430
+ invalidateConfig(cwd) {
431
+ this._configCache.delete(cwd)
432
+ }
433
+
434
+ /**
435
+ * Run the configured script once for a context and return the raw result plus
436
+ * `active` (false == no statusLine configured for this cwd). Does not emit or
437
+ * throttle — that's `refresh`.
438
+ *
439
+ * @param {object} ctx - session context (must include `cwd`)
440
+ * @returns {Promise<{active:boolean, text:string, result:object|null}>}
441
+ */
442
+ async run(ctx) {
443
+ const config = await this.resolveConfig(ctx?.cwd)
444
+ if (!config) return { active: false, text: '', result: null }
445
+
446
+ let env
447
+ try {
448
+ env = this._buildEnv()
449
+ } catch (err) {
450
+ log.warn(`statusLine env build failed: ${err?.message || err}`)
451
+ env = undefined
452
+ }
453
+
454
+ const result = await runStatusLineCommand({
455
+ command: config.command,
456
+ cwd: ctx.cwd,
457
+ input: JSON.stringify(buildStatusLineInput(ctx)),
458
+ env,
459
+ timeoutMs: this._timeoutMs,
460
+ maxOutputBytes: this._maxOutputBytes,
461
+ spawnFn: this._spawnFn,
462
+ setTimer: this._setTimer,
463
+ clearTimer: this._clearTimer,
464
+ })
465
+ return { active: true, text: statusLineDisplayText(result), result }
466
+ }
467
+
468
+ /**
469
+ * Throttled single-shot refresh for a session: skips if a run is already in
470
+ * flight or the last run was under the debounce floor (unless `force`), runs
471
+ * the script, and emits `output` only when the rendered text CHANGED. Clearing
472
+ * (config removed after prior output) emits once with an empty string.
473
+ *
474
+ * @param {string} sessionId
475
+ * @param {object} ctx - session context (must include `cwd`)
476
+ * @param {{force?: boolean}} [opts]
477
+ * @returns {Promise<{active:boolean, text:string, emitted:boolean}|null>} null == skipped
478
+ */
479
+ async refresh(sessionId, ctx, { force = false } = {}) {
480
+ if (this._stopped) return null
481
+ let session = this._sessions.get(sessionId)
482
+ if (!session) {
483
+ // Refresh for a session we aren't tracking a loop for is still valid
484
+ // (event-driven trigger before startSession); create a lightweight record.
485
+ session = { getContext: null, timer: null, lastRunAt: 0, running: false, lastText: null }
486
+ this._sessions.set(sessionId, session)
487
+ }
488
+ if (session.running) return null
489
+ if (!force && session.lastRunAt && (this._now() - session.lastRunAt) < this._minRefreshIntervalMs) {
490
+ return null
491
+ }
492
+
493
+ session.running = true
494
+ session.lastRunAt = this._now()
495
+ let outcome
496
+ try {
497
+ outcome = await this.run(ctx)
498
+ } catch (err) {
499
+ log.warn(`statusLine run failed for ${sessionId}: ${err?.message || err}`)
500
+ outcome = { active: false, text: '', result: null }
501
+ } finally {
502
+ // The session may have been stopped mid-run.
503
+ const still = this._sessions.get(sessionId)
504
+ if (still) still.running = false
505
+ }
506
+
507
+ const still = this._sessions.get(sessionId)
508
+ if (!still) return outcome ? { ...outcome, emitted: false } : null
509
+
510
+ let emitted = false
511
+ if (outcome.active) {
512
+ if (outcome.text !== still.lastText) {
513
+ still.lastText = outcome.text
514
+ this.emit('output', {
515
+ sessionId,
516
+ active: true,
517
+ text: outcome.text,
518
+ truncated: Boolean(outcome.result?.truncated),
519
+ timedOut: Boolean(outcome.result?.timedOut),
520
+ exitCode: outcome.result?.exitCode ?? null,
521
+ })
522
+ emitted = true
523
+ }
524
+ } else if (still.lastText) {
525
+ // Config removed after we had shown something — clear it once.
526
+ still.lastText = null
527
+ this.emit('output', { sessionId, active: false, text: '', truncated: false, timedOut: false, exitCode: null })
528
+ emitted = true
529
+ }
530
+ return { active: outcome.active, text: outcome.text, emitted }
531
+ }
532
+
533
+ /**
534
+ * Begin tracking a session: store its context provider and start the periodic
535
+ * refresh loop (a self-rescheduling, unref'd timer — never setInterval, so an
536
+ * in-flight run never overlaps the next tick). Idempotent — a second call just
537
+ * updates the context provider.
538
+ *
539
+ * @param {string} sessionId
540
+ * @param {Function} getContext - () => session context object (read fresh each tick)
541
+ */
542
+ startSession(sessionId, getContext) {
543
+ if (this._stopped) return
544
+ let session = this._sessions.get(sessionId)
545
+ if (!session) {
546
+ session = { getContext, timer: null, lastRunAt: 0, running: false, lastText: null }
547
+ this._sessions.set(sessionId, session)
548
+ } else {
549
+ session.getContext = getContext
550
+ }
551
+ if (session.timer === null) this._scheduleTick(sessionId, 0)
552
+ }
553
+
554
+ _scheduleTick(sessionId, delayMs) {
555
+ const session = this._sessions.get(sessionId)
556
+ if (!session || this._stopped) return
557
+ session.timer = this._setTimer(() => this._tick(sessionId), delayMs)
558
+ }
559
+
560
+ async _tick(sessionId) {
561
+ const session = this._sessions.get(sessionId)
562
+ if (!session || this._stopped) return
563
+ session.timer = null
564
+ let intervalMs = this._defaultRefreshIntervalMs
565
+ try {
566
+ const ctx = session.getContext ? session.getContext() : null
567
+ if (ctx) {
568
+ const config = await this.resolveConfig(ctx.cwd)
569
+ if (config?.refreshIntervalMs) intervalMs = config.refreshIntervalMs
570
+ await this.refresh(sessionId, ctx)
571
+ }
572
+ } catch (err) {
573
+ log.warn(`statusLine tick failed for ${sessionId}: ${err?.message || err}`)
574
+ }
575
+ // Reschedule only if the session is still tracked and we weren't stopped.
576
+ if (this._sessions.has(sessionId) && !this._stopped) this._scheduleTick(sessionId, intervalMs)
577
+ }
578
+
579
+ /** Stop tracking a session and clear its timer. Safe to call for an unknown id. */
580
+ stopSession(sessionId) {
581
+ const session = this._sessions.get(sessionId)
582
+ if (!session) return
583
+ if (session.timer !== null) this._clearTimer(session.timer)
584
+ this._sessions.delete(sessionId)
585
+ }
586
+
587
+ /** Stop everything (server shutdown). Clears every timer; further calls are no-ops. */
588
+ stopAll() {
589
+ this._stopped = true
590
+ for (const session of this._sessions.values()) {
591
+ if (session.timer !== null) this._clearTimer(session.timer)
592
+ }
593
+ this._sessions.clear()
594
+ this._configCache.clear()
595
+ }
596
+ }
@@ -32,6 +32,8 @@
32
32
  * project key has no source dimension either.
33
33
  */
34
34
 
35
+ import { compositeKey } from './utils/composite-key.js'
36
+
35
37
  /** Default time-to-live for an untouched entry. */
36
38
  export const SUBAGENT_ENTRY_TTL_MS = 2 * 60 * 60 * 1000 // 2h
37
39
 
@@ -52,7 +54,13 @@ export class SubagentCounter {
52
54
  }
53
55
 
54
56
  _key(source, sessionId) {
55
- return `${source}\u0000${sessionId}`
57
+ // Length-prefixed, plain-ASCII encoding (#7103), matching the two sibling
58
+ // aggregates (turn-tracker.js, external-session-registry.js). The previous
59
+ // key flattened the pair onto a single separator, which is injective only
60
+ // while no part can contain it -- a CALLER-side invariant this module
61
+ // cannot enforce, and `sessionId` (the attacker-influenced half, per the
62
+ // header) is NOT charset-restricted by IngestEventSchema.
63
+ return compositeKey(source, sessionId)
56
64
  }
57
65
 
58
66
  _sweep(force = false) {