@chroxy/server 0.10.0 → 0.11.0

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 (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
@@ -0,0 +1,584 @@
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 { homedir } from 'node:os'
34
+ import { join } from 'node:path'
35
+ import { EventEmitter } from 'node:events'
36
+ import { createLogger } from './logger.js'
37
+ import { CHROXY_SECRET_DENYLIST } 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} homeDir - user home directory (~/.claude scope)
63
+ * @returns {string[]} absolute settings.json paths, highest precedence first
64
+ */
65
+ export function statusLineSettingsPaths(cwd, homeDir) {
66
+ const paths = []
67
+ if (cwd) paths.push(join(cwd, '.claude', 'settings.json'))
68
+ if (homeDir) {
69
+ paths.push(join(homeDir, '.claude', 'project-settings.json'))
70
+ paths.push(join(homeDir, '.claude', '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
+ function defaultBuildEnv() {
157
+ const env = { ...process.env }
158
+ for (const key of [...CHROXY_SECRET_DENYLIST, 'ANTHROPIC_API_KEY']) delete env[key]
159
+ env.COLUMNS = '80'
160
+ env.LINES = '1'
161
+ return env
162
+ }
163
+
164
+ /** setTimeout that never keeps the event loop alive (self-exit safety). */
165
+ function unrefTimer(fn, ms) {
166
+ const t = setTimeout(fn, ms)
167
+ if (typeof t.unref === 'function') t.unref()
168
+ return t
169
+ }
170
+
171
+ /**
172
+ * Execute a `statusLine` command once, feeding `input` (a JSON string) on stdin,
173
+ * capturing stdout/stderr under a byte cap, and killing it if it exceeds
174
+ * `timeoutMs`. Never throws — every failure folds into the returned result.
175
+ *
176
+ * Modeled on built-in-tools/bash-exec.js (same SIGTERM→SIGKILL grace + byte-cap
177
+ * discipline) but pipes stdin and runs through the platform shell to match
178
+ * Claude Code's own invocation: `/bin/sh -c` on POSIX, `cmd.exe /d /s /c` on
179
+ * Windows (COMSPEC — same precedent as `utils/win-spawn.js`'s `prepareSpawn`
180
+ * and `platform.js`'s `defaultShell`), so statusLine also works on win32
181
+ * instead of silently failing to spawn `/bin/sh`.
182
+ *
183
+ * @param {object} opts
184
+ * @param {string} opts.command - the shell command (user's own config)
185
+ * @param {string} opts.cwd - working directory for the child
186
+ * @param {string} opts.input - JSON string written to the child's stdin
187
+ * @param {object} [opts.env] - child env (defaults to secret-stripped user env)
188
+ * @param {number} [opts.timeoutMs]
189
+ * @param {number} [opts.maxOutputBytes]
190
+ * @param {Function} [opts.spawnFn] - injectable spawn (tests)
191
+ * @param {Function} [opts.setTimer] - injectable setTimeout (tests)
192
+ * @param {Function} [opts.clearTimer] - injectable clearTimeout (tests)
193
+ * @param {NodeJS.Platform} [opts.platform=process.platform] - override for tests
194
+ * @returns {Promise<{stdout:string, stderr:string, exitCode:number|null, signal:string|null, timedOut:boolean, truncated:boolean, durationMs:number, error:string|null}>}
195
+ */
196
+ export async function runStatusLineCommand({
197
+ command,
198
+ cwd,
199
+ input = '',
200
+ env,
201
+ timeoutMs = STATUSLINE_DEFAULT_TIMEOUT_MS,
202
+ maxOutputBytes = STATUSLINE_MAX_OUTPUT_BYTES,
203
+ spawnFn = spawn,
204
+ setTimer = unrefTimer,
205
+ clearTimer = clearTimeout,
206
+ platform = process.platform,
207
+ } = {}) {
208
+ const startedAt = Date.now()
209
+ const base = { stdout: '', stderr: '', exitCode: null, signal: null, timedOut: false, truncated: false, durationMs: 0, error: null }
210
+
211
+ if (typeof command !== 'string' || command.trim() === '') {
212
+ return { ...base, error: 'no command', durationMs: 0 }
213
+ }
214
+
215
+ let child
216
+ try {
217
+ const isWin = platform === 'win32'
218
+ // Same shell-selection precedent as `utils/win-spawn.js#prepareSpawn` and
219
+ // `platform.js#defaultShell`: Windows has no `/bin/sh`, so route through
220
+ // COMSPEC (cmd.exe) with `/d` (skip AutoRun) `/s` (strip exactly the outer
221
+ // quote pair) `/c` (run then exit) and `windowsVerbatimArguments` so Node
222
+ // doesn't re-quote our already-quoted command line — mirrors Node's own
223
+ // internal `{ shell: true }` behavior on win32.
224
+ const shellCommand = isWin ? (process.env.COMSPEC || 'cmd.exe') : '/bin/sh'
225
+ const shellArgs = isWin ? ['/d', '/s', '/c', `"${command}"`] : ['-c', command]
226
+ child = spawnFn(shellCommand, shellArgs, {
227
+ cwd: cwd || process.cwd(),
228
+ env: env || defaultBuildEnv(),
229
+ stdio: ['pipe', 'pipe', 'pipe'],
230
+ ...(isWin ? { windowsVerbatimArguments: true } : {}),
231
+ })
232
+ } catch (err) {
233
+ return { ...base, error: err?.message || 'spawn failed', durationMs: Date.now() - startedAt }
234
+ }
235
+
236
+ let stdout = ''
237
+ let stderr = ''
238
+ let totalBytes = 0
239
+ let truncated = false
240
+ let timedOut = false
241
+ let hardKillTimer = null
242
+
243
+ const killChild = (sig) => {
244
+ if (!child || child.killed || child.exitCode !== null) return
245
+ try {
246
+ child.kill(sig)
247
+ } catch {
248
+ // already gone
249
+ }
250
+ if (sig === 'SIGTERM' && hardKillTimer === null) {
251
+ hardKillTimer = setTimer(() => {
252
+ try {
253
+ if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL')
254
+ } catch {}
255
+ }, STATUSLINE_HARD_KILL_GRACE_MS)
256
+ }
257
+ }
258
+
259
+ const capture = (chunk, which) => {
260
+ if (totalBytes >= maxOutputBytes) return
261
+ const chunkBytes = chunk.length
262
+ const remaining = maxOutputBytes - totalBytes
263
+ if (chunkBytes > remaining) {
264
+ const sliced = chunk.subarray(0, remaining).toString('utf8')
265
+ if (which === 'stdout') stdout += sliced
266
+ else stderr += sliced
267
+ totalBytes += remaining
268
+ truncated = true
269
+ killChild('SIGTERM')
270
+ } else {
271
+ const text = chunk.toString('utf8')
272
+ if (which === 'stdout') stdout += text
273
+ else stderr += text
274
+ totalBytes += chunkBytes
275
+ }
276
+ }
277
+
278
+ child.stdout?.on('data', (c) => capture(c, 'stdout'))
279
+ child.stderr?.on('data', (c) => capture(c, 'stderr'))
280
+
281
+ // Feed the session JSON on stdin, then close it. A script that never reads
282
+ // stdin makes the pipe error with EPIPE — swallow it (it is expected, not a
283
+ // fault) so an unhandled 'error' can't crash the daemon.
284
+ if (child.stdin) {
285
+ child.stdin.on('error', () => {})
286
+ try {
287
+ child.stdin.end(input)
288
+ } catch {
289
+ // ignore — child may have exited before we wrote
290
+ }
291
+ }
292
+
293
+ const timeoutHandle = setTimer(() => {
294
+ timedOut = true
295
+ killChild('SIGTERM')
296
+ }, timeoutMs)
297
+
298
+ const { code, sig, spawnError } = await new Promise((resolve) => {
299
+ child.on('exit', (c, s) => resolve({ code: c, sig: s, spawnError: null }))
300
+ child.on('error', (err) => resolve({ code: null, sig: null, spawnError: err }))
301
+ })
302
+
303
+ clearTimer(timeoutHandle)
304
+ if (hardKillTimer !== null) clearTimer(hardKillTimer)
305
+
306
+ return {
307
+ stdout,
308
+ stderr,
309
+ exitCode: code,
310
+ signal: sig,
311
+ timedOut,
312
+ truncated,
313
+ durationMs: Date.now() - startedAt,
314
+ error: spawnError ? (spawnError.message || 'spawn error') : null,
315
+ }
316
+ }
317
+
318
+ /**
319
+ * Reduce a raw execution result to the text a client should DISPLAY, following
320
+ * Claude Code's rules: non-zero exit, no output, a timeout, or a spawn error
321
+ * all render blank (empty string). Trailing whitespace is trimmed; the ANSI in
322
+ * the payload is left intact for the renderer to strip/interpret.
323
+ *
324
+ * @param {object} result - a runStatusLineCommand result
325
+ * @returns {string} the display text ('' == blank)
326
+ */
327
+ export function statusLineDisplayText(result) {
328
+ if (!result || result.error || result.timedOut) return ''
329
+ if (result.exitCode !== 0) return ''
330
+ const text = (result.stdout || '').replace(/\s+$/, '')
331
+ return text
332
+ }
333
+
334
+ /**
335
+ * Orchestrates statusLine reads/execs for live sessions and emits an `output`
336
+ * event ({ sessionId, active, text, truncated, timedOut, exitCode }) whenever a
337
+ * session's rendered status text CHANGES. Owns all timers (each unref'd + cleared
338
+ * on stopSession/stopAll) so the daemon can self-exit and tests leak nothing.
339
+ *
340
+ * Every side-effecting dependency (spawn, timers, clock, file read, env) is
341
+ * injectable so the whole thing is deterministic under test.
342
+ */
343
+ export class StatusLineManager extends EventEmitter {
344
+ constructor({
345
+ homeDir = homedir(),
346
+ readFileFn = readFile,
347
+ spawnFn = spawn,
348
+ buildEnv = defaultBuildEnv,
349
+ now = Date.now,
350
+ setTimer = unrefTimer,
351
+ clearTimer = clearTimeout,
352
+ timeoutMs = STATUSLINE_DEFAULT_TIMEOUT_MS,
353
+ maxOutputBytes = STATUSLINE_MAX_OUTPUT_BYTES,
354
+ minRefreshIntervalMs = STATUSLINE_MIN_REFRESH_INTERVAL_MS,
355
+ defaultRefreshIntervalMs = STATUSLINE_DEFAULT_REFRESH_INTERVAL_MS,
356
+ configCacheTtlMs = STATUSLINE_CONFIG_CACHE_TTL_MS,
357
+ } = {}) {
358
+ super()
359
+ this._homeDir = homeDir
360
+ this._readFileFn = readFileFn
361
+ this._spawnFn = spawnFn
362
+ this._buildEnv = buildEnv
363
+ this._now = now
364
+ this._setTimer = setTimer
365
+ this._clearTimer = clearTimer
366
+ this._timeoutMs = timeoutMs
367
+ this._maxOutputBytes = maxOutputBytes
368
+ this._minRefreshIntervalMs = minRefreshIntervalMs
369
+ this._defaultRefreshIntervalMs = defaultRefreshIntervalMs
370
+ this._configCacheTtlMs = configCacheTtlMs
371
+
372
+ /** @type {Map<string, {config: object|null, expiresAt: number}>} keyed by cwd */
373
+ this._configCache = new Map()
374
+ /** @type {Map<string, {getContext: Function, timer: any, lastRunAt: number, running: boolean, lastText: string|null}>} */
375
+ this._sessions = new Map()
376
+ this._stopped = false
377
+ }
378
+
379
+ /**
380
+ * Resolve the effective statusLine config for a cwd (project > project-settings
381
+ * > user; first match wins), cached per cwd with a short TTL. Returns null when
382
+ * no location configures a usable command. Never throws — a missing/malformed
383
+ * settings file is skipped.
384
+ *
385
+ * @param {string} cwd
386
+ * @returns {Promise<{command:string, refreshIntervalMs:number|null}|null>}
387
+ */
388
+ async resolveConfig(cwd) {
389
+ const cached = this._configCache.get(cwd)
390
+ if (cached && cached.expiresAt > this._now()) return cached.config
391
+
392
+ let config = null
393
+ for (const path of statusLineSettingsPaths(cwd, this._homeDir)) {
394
+ let raw
395
+ try {
396
+ raw = await this._readFileFn(path, 'utf8')
397
+ } catch {
398
+ continue // file absent / unreadable — try the next scope
399
+ }
400
+ let parsed
401
+ try {
402
+ parsed = JSON.parse(raw)
403
+ } catch {
404
+ continue // malformed JSON — skip this scope, don't fail the whole read
405
+ }
406
+ const found = parseStatusLineConfig(parsed)
407
+ if (found) {
408
+ config = found
409
+ break
410
+ }
411
+ }
412
+
413
+ this._configCache.set(cwd, { config, expiresAt: this._now() + this._configCacheTtlMs })
414
+ return config
415
+ }
416
+
417
+ /** Drop any cached config (e.g. session ended) so a re-read is forced. */
418
+ invalidateConfig(cwd) {
419
+ this._configCache.delete(cwd)
420
+ }
421
+
422
+ /**
423
+ * Run the configured script once for a context and return the raw result plus
424
+ * `active` (false == no statusLine configured for this cwd). Does not emit or
425
+ * throttle — that's `refresh`.
426
+ *
427
+ * @param {object} ctx - session context (must include `cwd`)
428
+ * @returns {Promise<{active:boolean, text:string, result:object|null}>}
429
+ */
430
+ async run(ctx) {
431
+ const config = await this.resolveConfig(ctx?.cwd)
432
+ if (!config) return { active: false, text: '', result: null }
433
+
434
+ let env
435
+ try {
436
+ env = this._buildEnv()
437
+ } catch (err) {
438
+ log.warn(`statusLine env build failed: ${err?.message || err}`)
439
+ env = undefined
440
+ }
441
+
442
+ const result = await runStatusLineCommand({
443
+ command: config.command,
444
+ cwd: ctx.cwd,
445
+ input: JSON.stringify(buildStatusLineInput(ctx)),
446
+ env,
447
+ timeoutMs: this._timeoutMs,
448
+ maxOutputBytes: this._maxOutputBytes,
449
+ spawnFn: this._spawnFn,
450
+ setTimer: this._setTimer,
451
+ clearTimer: this._clearTimer,
452
+ })
453
+ return { active: true, text: statusLineDisplayText(result), result }
454
+ }
455
+
456
+ /**
457
+ * Throttled single-shot refresh for a session: skips if a run is already in
458
+ * flight or the last run was under the debounce floor (unless `force`), runs
459
+ * the script, and emits `output` only when the rendered text CHANGED. Clearing
460
+ * (config removed after prior output) emits once with an empty string.
461
+ *
462
+ * @param {string} sessionId
463
+ * @param {object} ctx - session context (must include `cwd`)
464
+ * @param {{force?: boolean}} [opts]
465
+ * @returns {Promise<{active:boolean, text:string, emitted:boolean}|null>} null == skipped
466
+ */
467
+ async refresh(sessionId, ctx, { force = false } = {}) {
468
+ if (this._stopped) return null
469
+ let session = this._sessions.get(sessionId)
470
+ if (!session) {
471
+ // Refresh for a session we aren't tracking a loop for is still valid
472
+ // (event-driven trigger before startSession); create a lightweight record.
473
+ session = { getContext: null, timer: null, lastRunAt: 0, running: false, lastText: null }
474
+ this._sessions.set(sessionId, session)
475
+ }
476
+ if (session.running) return null
477
+ if (!force && session.lastRunAt && (this._now() - session.lastRunAt) < this._minRefreshIntervalMs) {
478
+ return null
479
+ }
480
+
481
+ session.running = true
482
+ session.lastRunAt = this._now()
483
+ let outcome
484
+ try {
485
+ outcome = await this.run(ctx)
486
+ } catch (err) {
487
+ log.warn(`statusLine run failed for ${sessionId}: ${err?.message || err}`)
488
+ outcome = { active: false, text: '', result: null }
489
+ } finally {
490
+ // The session may have been stopped mid-run.
491
+ const still = this._sessions.get(sessionId)
492
+ if (still) still.running = false
493
+ }
494
+
495
+ const still = this._sessions.get(sessionId)
496
+ if (!still) return outcome ? { ...outcome, emitted: false } : null
497
+
498
+ let emitted = false
499
+ if (outcome.active) {
500
+ if (outcome.text !== still.lastText) {
501
+ still.lastText = outcome.text
502
+ this.emit('output', {
503
+ sessionId,
504
+ active: true,
505
+ text: outcome.text,
506
+ truncated: Boolean(outcome.result?.truncated),
507
+ timedOut: Boolean(outcome.result?.timedOut),
508
+ exitCode: outcome.result?.exitCode ?? null,
509
+ })
510
+ emitted = true
511
+ }
512
+ } else if (still.lastText) {
513
+ // Config removed after we had shown something — clear it once.
514
+ still.lastText = null
515
+ this.emit('output', { sessionId, active: false, text: '', truncated: false, timedOut: false, exitCode: null })
516
+ emitted = true
517
+ }
518
+ return { active: outcome.active, text: outcome.text, emitted }
519
+ }
520
+
521
+ /**
522
+ * Begin tracking a session: store its context provider and start the periodic
523
+ * refresh loop (a self-rescheduling, unref'd timer — never setInterval, so an
524
+ * in-flight run never overlaps the next tick). Idempotent — a second call just
525
+ * updates the context provider.
526
+ *
527
+ * @param {string} sessionId
528
+ * @param {Function} getContext - () => session context object (read fresh each tick)
529
+ */
530
+ startSession(sessionId, getContext) {
531
+ if (this._stopped) return
532
+ let session = this._sessions.get(sessionId)
533
+ if (!session) {
534
+ session = { getContext, timer: null, lastRunAt: 0, running: false, lastText: null }
535
+ this._sessions.set(sessionId, session)
536
+ } else {
537
+ session.getContext = getContext
538
+ }
539
+ if (session.timer === null) this._scheduleTick(sessionId, 0)
540
+ }
541
+
542
+ _scheduleTick(sessionId, delayMs) {
543
+ const session = this._sessions.get(sessionId)
544
+ if (!session || this._stopped) return
545
+ session.timer = this._setTimer(() => this._tick(sessionId), delayMs)
546
+ }
547
+
548
+ async _tick(sessionId) {
549
+ const session = this._sessions.get(sessionId)
550
+ if (!session || this._stopped) return
551
+ session.timer = null
552
+ let intervalMs = this._defaultRefreshIntervalMs
553
+ try {
554
+ const ctx = session.getContext ? session.getContext() : null
555
+ if (ctx) {
556
+ const config = await this.resolveConfig(ctx.cwd)
557
+ if (config?.refreshIntervalMs) intervalMs = config.refreshIntervalMs
558
+ await this.refresh(sessionId, ctx)
559
+ }
560
+ } catch (err) {
561
+ log.warn(`statusLine tick failed for ${sessionId}: ${err?.message || err}`)
562
+ }
563
+ // Reschedule only if the session is still tracked and we weren't stopped.
564
+ if (this._sessions.has(sessionId) && !this._stopped) this._scheduleTick(sessionId, intervalMs)
565
+ }
566
+
567
+ /** Stop tracking a session and clear its timer. Safe to call for an unknown id. */
568
+ stopSession(sessionId) {
569
+ const session = this._sessions.get(sessionId)
570
+ if (!session) return
571
+ if (session.timer !== null) this._clearTimer(session.timer)
572
+ this._sessions.delete(sessionId)
573
+ }
574
+
575
+ /** Stop everything (server shutdown). Clears every timer; further calls are no-ops. */
576
+ stopAll() {
577
+ this._stopped = true
578
+ for (const session of this._sessions.values()) {
579
+ if (session.timer !== null) this._clearTimer(session.timer)
580
+ }
581
+ this._sessions.clear()
582
+ this._configCache.clear()
583
+ }
584
+ }
@@ -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) {