@chroxy/server 0.10.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 (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,320 @@
1
+ // BackgroundShellTracker (#5376) — extracted from BaseSession.
2
+ //
3
+ // Owns the per-session registry of backgrounded Bash shells the agent is
4
+ // still waiting on (#4307), the periodic reaping sweep (#5177), and the
5
+ // advisory / hard quiescence checks (#5247 / #5265). BaseSession composes one
6
+ // of these and delegates `trackBackgroundShell` / `clearBackgroundShell` /
7
+ // `getPendingBackgroundShells` / `_destroyPendingBackgroundShells` to it, and
8
+ // consults `.size` for its `isRunning` liveness getter.
9
+ //
10
+ // Events still flow from the session: the tracker is constructed with an
11
+ // injected `emit` callback so the `background_work_changed` event lands on the
12
+ // session's EventEmitter (every consumer subscribes to the session, not the
13
+ // tracker). The tracker holds NO EventEmitter of its own.
14
+ //
15
+ // Field names are kept identical to the pre-extraction BaseSession fields so
16
+ // the moved method bodies read verbatim and BaseSession's compat shims can
17
+ // delegate without translation.
18
+
19
+ import { statSync } from 'fs'
20
+
21
+ export const BACKGROUND_SHELL_SWEEP_MS = 15 * 1000
22
+ export const BACKGROUND_SHELL_QUIESCE_MS = 60 * 1000
23
+ export const BACKGROUND_SHELL_HARD_QUIESCE_MS = 4 * 60 * 60 * 1000
24
+
25
+ export class BackgroundShellTracker {
26
+ /**
27
+ * @param {{
28
+ * emit: (event: string, payload: object) => void,
29
+ * sweepMs?: number,
30
+ * quiesceMs?: number,
31
+ * hardQuiesceMs?: number,
32
+ * }} opts
33
+ * `emit` — required; the session's `emit.bind(session)` so
34
+ * `background_work_changed` flows from the session. `hardQuiesceMs`
35
+ * honours an explicit `0` (disable) via `??`.
36
+ */
37
+ constructor({ emit, sweepMs, quiesceMs, hardQuiesceMs } = {}) {
38
+ if (typeof emit !== 'function') {
39
+ throw new TypeError('BackgroundShellTracker requires an emit callback')
40
+ }
41
+ this._emit = emit
42
+
43
+ // #4307: per-session map of backgrounded Bash shells the agent is still
44
+ // waiting on. Keyed by the shellId Claude prints in the
45
+ // `Command running in background with ID: <id>` tool_result. See
46
+ // base-session.js for the full lifecycle / #4417 transient-by-design note.
47
+ this._pendingBackgroundShells = new Map()
48
+
49
+ // #5177: periodic sweep that reaps COMPLETED background shells without
50
+ // waiting for the agent to call `BashOutput`. Armed lazily (only while the
51
+ // pending map is non-empty) and stopped when it drains or the session is
52
+ // destroyed (no leak / no idle wakeups). Interval + completion check are
53
+ // injectable for tests.
54
+ this._backgroundShellSweepTimer = null
55
+ this._backgroundShellSweepMs = sweepMs ?? BACKGROUND_SHELL_SWEEP_MS
56
+ // Quiescence window: a shell whose output file has not been written to for
57
+ // this long is treated as complete (advisory — banner only).
58
+ this._backgroundShellQuiesceMs = quiesceMs ?? BACKGROUND_SHELL_QUIESCE_MS
59
+ // Injectable quiescence check — `(entry) => boolean`. Tests override this to
60
+ // drive deterministic quiescence without touching the filesystem or timers.
61
+ this._backgroundShellQuiesceCheck = null
62
+ // #5265 / #5288: HARD-quiesce window (config-driven; `?? constant` keeps the
63
+ // default when unset and honours an explicit 0 = disable hard-reaping).
64
+ this._backgroundShellHardQuiesceMs = hardQuiesceMs ?? BACKGROUND_SHELL_HARD_QUIESCE_MS
65
+ // Injectable hard-quiesce check — `(entry) => boolean`.
66
+ this._backgroundShellHardQuiesceCheck = null
67
+ }
68
+
69
+ /** Pending-shell count — consulted by BaseSession's `isRunning` getter. */
70
+ get size() {
71
+ return this._pendingBackgroundShells.size
72
+ }
73
+
74
+ /**
75
+ * #4307: read-only snapshot of pending background shells, ordered by
76
+ * insertion. Returns a plain array of `{ shellId, startedAt, command }`.
77
+ *
78
+ * #5177: projects to the stable wire shape — `outputPath` is an internal
79
+ * sweep detail and must not leak. #5247: a shell the mtime sweep marked
80
+ * `quiesced` is dropped from this banner snapshot but stays in the map so
81
+ * liveness (`size`) is unaffected (the sweep is advisory; see BaseSession
82
+ * isRunning).
83
+ */
84
+ getPendingBackgroundShells() {
85
+ return Array.from(this._pendingBackgroundShells.values())
86
+ .filter((e) => !e.quiesced)
87
+ .map(({ shellId, startedAt, command }) => ({ shellId, startedAt, command }))
88
+ }
89
+
90
+ /**
91
+ * #4307: record a new pending background shell. Idempotent on shellId —
92
+ * re-registering an existing id is a no-op (preserves the original
93
+ * startedAt + command). Emits `background_work_changed` with the full
94
+ * pending snapshot after a change.
95
+ *
96
+ * #5177: `outputPath` (when known) is stashed so the completion sweep can
97
+ * observe the shell finishing via the output file's mtime. Internal-only —
98
+ * NOT surfaced on the wire snapshot.
99
+ *
100
+ * @param {{ shellId: string, command?: string, outputPath?: string }} opts
101
+ * @returns {boolean} true if a new entry was added
102
+ */
103
+ trackBackgroundShell({ shellId, command, outputPath } = {}) {
104
+ if (typeof shellId !== 'string' || shellId.length === 0) return false
105
+ if (this._pendingBackgroundShells.has(shellId)) return false
106
+ this._pendingBackgroundShells.set(shellId, {
107
+ shellId,
108
+ startedAt: Date.now(),
109
+ command: typeof command === 'string' ? command : '',
110
+ outputPath: typeof outputPath === 'string' && outputPath.length > 0 ? outputPath : null,
111
+ })
112
+ // #5177: start the reaping sweep now that there is work to watch.
113
+ this._ensureBackgroundShellSweep()
114
+ this._emitBackgroundWorkChanged()
115
+ return true
116
+ }
117
+
118
+ /**
119
+ * #4307: clear a pending background shell by id. Returns true when an entry
120
+ * actually existed, false when the id was not tracked. Emits
121
+ * `background_work_changed` with the post-clear snapshot when observable.
122
+ *
123
+ * @param {string} shellId
124
+ * @returns {boolean}
125
+ */
126
+ clearBackgroundShell(shellId) {
127
+ if (typeof shellId !== 'string' || shellId.length === 0) return false
128
+ if (!this._pendingBackgroundShells.delete(shellId)) return false
129
+ // #5177: stop the sweep once the last shell drains so an idle session has
130
+ // no recurring timer. Re-armed by the next trackBackgroundShell.
131
+ if (this._pendingBackgroundShells.size === 0) this._stopBackgroundShellSweep()
132
+ this._emitBackgroundWorkChanged()
133
+ return true
134
+ }
135
+
136
+ /**
137
+ * #4307: emit the current pending-shells snapshot on the
138
+ * `background_work_changed` event. The full snapshot is sent on each change
139
+ * (not just the delta) so a late-joining client sees canonical state.
140
+ *
141
+ * @private
142
+ */
143
+ _emitBackgroundWorkChanged() {
144
+ this._emit('background_work_changed', {
145
+ pending: this.getPendingBackgroundShells(),
146
+ })
147
+ }
148
+
149
+ /**
150
+ * #5177: arm the periodic reaping sweep if not already running and there is
151
+ * pending work to watch. Idempotent. The interval is `unref()`'d so a lone
152
+ * pending shell can never keep the process alive on its own.
153
+ *
154
+ * @private
155
+ */
156
+ _ensureBackgroundShellSweep() {
157
+ if (this._backgroundShellSweepTimer) return
158
+ if (this._pendingBackgroundShells.size === 0) return
159
+ if (!(this._backgroundShellSweepMs > 0)) return
160
+ this._backgroundShellSweepTimer = setInterval(
161
+ () => this._sweepQuiescedBackgroundShells(),
162
+ this._backgroundShellSweepMs,
163
+ )
164
+ if (typeof this._backgroundShellSweepTimer.unref === 'function') {
165
+ this._backgroundShellSweepTimer.unref()
166
+ }
167
+ }
168
+
169
+ /**
170
+ * #5177: stop the reaping sweep. Idempotent.
171
+ * @private
172
+ */
173
+ _stopBackgroundShellSweep() {
174
+ if (!this._backgroundShellSweepTimer) return
175
+ clearInterval(this._backgroundShellSweepTimer)
176
+ this._backgroundShellSweepTimer = null
177
+ }
178
+
179
+ /**
180
+ * #5177: one sweep tick — mark every pending shell whose output has quiesced.
181
+ * #5247: ADVISORY — a quiesced shell is dropped from the banner snapshot (via
182
+ * the `quiesced` flag, NOT clear) so it stays in the map and liveness is
183
+ * unaffected. #5265: hard-quiesced shells are REAPED (removed) so a session
184
+ * pinned "running" by a long-dead command can finally idle-time out.
185
+ *
186
+ * @private
187
+ */
188
+ _sweepQuiescedBackgroundShells() {
189
+ let changed = false
190
+ let anyActive = false
191
+ const hardEnabled = this._backgroundShellHardQuiesceMs > 0
192
+ for (const shellId of Array.from(this._pendingBackgroundShells.keys())) {
193
+ const entry = this._pendingBackgroundShells.get(shellId)
194
+ if (!entry) continue
195
+ // #5265: HARD-quiesce reap — checked first and for EVERY entry (including
196
+ // already advisory-quiesced ones). After the long hard window of output
197
+ // silence the shell is overwhelmingly likely finished, so reap it
198
+ // (remove from the map → liveness flips) so a session pinned "running"
199
+ // by a long-dead, never-polled command can finally idle-time out.
200
+ if (hardEnabled && this._isBackgroundShellHardQuiesced(entry)) {
201
+ this._pendingBackgroundShells.delete(shellId)
202
+ changed = true
203
+ continue
204
+ // NOTE: reaping an entry that was ALREADY advisory-quiesced changes
205
+ // liveness (true→false) but NOT the banner snapshot (already filtered
206
+ // out at advisory time), so the emit below carries an unchanged
207
+ // `pending` payload. Fine TODAY because liveness is consumed via the
208
+ // pull path (SessionTimeoutManager calls the live getter). A future
209
+ // consumer that diffs `pending` to infer liveness would need an
210
+ // explicit liveness field — flagged so this isn't a silent trap.
211
+ }
212
+ if (entry.quiesced) continue // already advisory-cleared from the banner
213
+ if (this._isBackgroundShellQuiesced(entry)) {
214
+ // #5247: ADVISORY only — mark the shell quiesced so it drops out of the
215
+ // banner snapshot, but DO NOT remove it from the map. mtime quiescence
216
+ // can't distinguish "finished" from "idle but alive", so flipping
217
+ // liveness here reaped live processes (re-opening #4307). Real liveness
218
+ // is released only by a BashOutput poll, destroy, or the hard-reap.
219
+ entry.quiesced = true
220
+ changed = true
221
+ } else {
222
+ anyActive = true
223
+ }
224
+ }
225
+ if (changed) this._emitBackgroundWorkChanged()
226
+ // Stop the recurring stat() sweep when nothing remains that could still
227
+ // transition. With hard-quiesce ON, advisory-quiesced shells are still
228
+ // pending a future hard-reap, so keep sweeping while the map is non-empty;
229
+ // with hard-quiesce OFF, stop as soon as nothing can advisory-transition.
230
+ const drained = this._pendingBackgroundShells.size === 0
231
+ if (drained || (!hardEnabled && !anyActive)) this._stopBackgroundShellSweep()
232
+ }
233
+
234
+ /**
235
+ * #5265: decide whether a pending background shell has HARD-quiesced — its
236
+ * output has been silent long enough that it is overwhelmingly likely
237
+ * finished and can be reaped. Tests inject `_backgroundShellHardQuiesceCheck`.
238
+ * The default reads the output file's mtime; a shell with no known output
239
+ * path falls back to its `startedAt`. A stat() error is NOT hard-quiesced.
240
+ *
241
+ * @param {{ shellId: string, outputPath?: string|null, startedAt: number }} entry
242
+ * @returns {boolean}
243
+ * @private
244
+ */
245
+ _isBackgroundShellHardQuiesced(entry) {
246
+ // Disabled short-circuit FIRST so the "0 disables" contract holds even if a
247
+ // stale check is injected (the sweep also gates on hardEnabled).
248
+ if (this._backgroundShellHardQuiesceMs <= 0) return false
249
+ if (typeof this._backgroundShellHardQuiesceCheck === 'function') {
250
+ return this._backgroundShellHardQuiesceCheck(entry) === true
251
+ }
252
+ if (!entry) return false
253
+ // Cheap pre-stat gate (#5287): output can't have been idle longer than the
254
+ // shell has existed, so a shell younger than the hard window can't possibly
255
+ // be hard-quiesced — skip the per-tick statSync until then.
256
+ if (typeof entry.startedAt === 'number'
257
+ && Date.now() - entry.startedAt < this._backgroundShellHardQuiesceMs) {
258
+ return false
259
+ }
260
+ if (typeof entry.outputPath !== 'string' || entry.outputPath.length === 0) {
261
+ // No output file to stat — fall back to wall-clock age since tracked. The
262
+ // WEAKEST signal (accepted per #5265's tradeoff; consequence is only
263
+ // idle-timeout eligibility, never process death — chroxy doesn't own the PID).
264
+ return typeof entry.startedAt === 'number'
265
+ && Date.now() - entry.startedAt >= this._backgroundShellHardQuiesceMs
266
+ }
267
+ try {
268
+ const st = statSync(entry.outputPath)
269
+ return Date.now() - st.mtimeMs >= this._backgroundShellHardQuiesceMs
270
+ } catch {
271
+ return false
272
+ }
273
+ }
274
+
275
+ /**
276
+ * #5177: decide whether a pending background shell's output has QUIESCED —
277
+ * i.e. it can be dropped from the dashboard banner. #5247: this is NOT "the
278
+ * command finished"; mtime quiescence is the best the BANNER can do and the
279
+ * caller treats `true` as ADVISORY only. Tests inject
280
+ * `_backgroundShellQuiesceCheck`. A shell with no output path, or an empty
281
+ * output file (a silent command), is never marked quiesced via this path.
282
+ * A stat() error is treated as NOT quiesced.
283
+ *
284
+ * @param {{ shellId: string, outputPath?: string|null, startedAt: number }} entry
285
+ * @returns {boolean}
286
+ * @private
287
+ */
288
+ _isBackgroundShellQuiesced(entry) {
289
+ if (typeof this._backgroundShellQuiesceCheck === 'function') {
290
+ return this._backgroundShellQuiesceCheck(entry) === true
291
+ }
292
+ if (!entry || typeof entry.outputPath !== 'string' || entry.outputPath.length === 0) {
293
+ return false
294
+ }
295
+ try {
296
+ const st = statSync(entry.outputPath)
297
+ // #5177 (review): a SILENT command leaves the output file empty and
298
+ // untouched after creation. Guard with a non-empty check: an empty output
299
+ // file is NEVER reaped via this path, so silent shells fall back to the
300
+ // existing BashOutput / destroy clear (the conservative #4307 behaviour).
301
+ if (st.size <= 0) return false
302
+ const lastWrite = st.mtimeMs
303
+ return Date.now() - lastWrite >= this._backgroundShellQuiesceMs
304
+ } catch {
305
+ return false
306
+ }
307
+ }
308
+
309
+ /**
310
+ * #4307: stop the sweep and clear the pending map on session destroy. The
311
+ * session-level companions (`_pendingBackgroundCommands`, the activity
312
+ * registry) are torn down by BaseSession around this call.
313
+ */
314
+ destroy() {
315
+ // #5177: stop the reaping sweep before clearing the map so no tick can fire
316
+ // against a half-torn-down session.
317
+ this._stopBackgroundShellSweep()
318
+ this._pendingBackgroundShells.clear()
319
+ }
320
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * #4307 — helpers for tracking `Bash` tool calls dispatched with
3
+ * `run_in_background: true`. Both SdkSession (assistant tool_use →
4
+ * user tool_result) and ClaudeTuiSession (PreToolUse hook → PostToolUse
5
+ * hook) flow their inputs / results through a small parsing surface so
6
+ * BaseSession can record the resulting shell id and survive turn-end.
7
+ *
8
+ * The canonical tool_result text Claude emits when a Bash call returns
9
+ * with `run_in_background: true` is:
10
+ *
11
+ * "Command running in background with ID: brk57kt6pm. Output is being
12
+ * written to: /private/tmp/claude-501/…/tasks/br57k6pm.output. You
13
+ * will be notified when it completes."
14
+ *
15
+ * We do not depend on the format of the surrounding sentence — only on
16
+ * the canonical `Command running in background with ID: <token>` opener,
17
+ * which has been stable across the claude versions chroxy targets.
18
+ *
19
+ * #4417: the pending-shells map populated via these helpers lives in
20
+ * memory only and is intentionally NOT persisted across server
21
+ * restart. See `BaseSession._pendingBackgroundShells` for the full
22
+ * rationale — short version: the OS-level shells are owned by claude,
23
+ * not chroxy, so a restored map would be stale and the activity
24
+ * indicator would lie. Dropping the map on restart is the safe choice.
25
+ */
26
+
27
+ // `[A-Za-z0-9_-]+` is intentionally tight — every shell id observed so
28
+ // far is short alphanumeric (`brk57kt6pm`). A non-whitespace match would
29
+ // also swallow a trailing period or sentence-end punctuation. Keep this
30
+ // narrow: malformed payloads return null and the wait is invisible.
31
+ const SHELL_ID_RE = /Command running in background with ID:\s+([A-Za-z0-9_-]+)/
32
+
33
+ // #5177: the canonical tool_result also names the file claude tails the
34
+ // background command's stdout/stderr into:
35
+ //
36
+ // "Output is being written to: /private/tmp/claude-501/…/tasks/<id>.output"
37
+ //
38
+ // We capture the path so the periodic sweep (see BaseSession) can observe
39
+ // the shell's completion WITHOUT the agent ever calling `BashOutput`: a
40
+ // finished command stops appending to this file, so a quiesced mtime is a
41
+ // reap signal. Match a run of non-whitespace after the colon — the path is
42
+ // always a single token and any trailing sentence punctuation (". You will
43
+ // be notified…") is whitespace-separated. Strip a single trailing period
44
+ // defensively in case a future claude build drops the space before it.
45
+ const SHELL_OUTPUT_PATH_RE = /Output is being written to:\s+(\S+)/
46
+
47
+ /**
48
+ * Parse the shell id from a tool_result text. Returns the id when the
49
+ * canonical pattern matches, else null.
50
+ *
51
+ * Defensive against non-string / empty inputs so callers can hand the
52
+ * raw `tool_result.result` field through without pre-checking.
53
+ *
54
+ * @param {unknown} text
55
+ * @returns {string | null}
56
+ */
57
+ export function parseBackgroundShellId(text) {
58
+ if (typeof text !== 'string' || text.length === 0) return null
59
+ const m = SHELL_ID_RE.exec(text)
60
+ return m ? m[1] : null
61
+ }
62
+
63
+ /**
64
+ * #5177: parse the output file path from a tool_result text. Returns the
65
+ * path when the canonical `Output is being written to: <path>` pattern
66
+ * matches, else null. A single trailing period is stripped so a build that
67
+ * emits `…<id>.output.` (no space before the sentence end) still yields a
68
+ * clean path.
69
+ *
70
+ * Defensive against non-string / empty inputs so callers can hand the raw
71
+ * `tool_result.result` field through without pre-checking. Returning null
72
+ * is non-fatal: the shell is still tracked, the sweep just can't reap it
73
+ * via the output file and falls back to the BashOutput / destroy paths.
74
+ *
75
+ * @param {unknown} text
76
+ * @returns {string | null}
77
+ */
78
+ export function parseBackgroundShellOutputPath(text) {
79
+ if (typeof text !== 'string' || text.length === 0) return null
80
+ const m = SHELL_OUTPUT_PATH_RE.exec(text)
81
+ if (!m) return null
82
+ return m[1].replace(/\.$/, '')
83
+ }
84
+
85
+ /**
86
+ * Returns true when a tool_use block represents a Bash call dispatched
87
+ * with `run_in_background: true`. Used by providers to stash the
88
+ * command text against the tool_use_id so the matching tool_result can
89
+ * record it with its shell id.
90
+ *
91
+ * Strict-boolean on the `run_in_background` field — a malformed input
92
+ * (truthy non-bool) is rejected so a buggy SDK payload can't poison the
93
+ * pending map with a non-background call.
94
+ *
95
+ * @param {string} toolName
96
+ * @param {unknown} input
97
+ * @returns {boolean}
98
+ */
99
+ export function isRunInBackgroundInput(toolName, input) {
100
+ if (toolName !== 'Bash') return false
101
+ if (!input || typeof input !== 'object') return false
102
+ return input.run_in_background === true
103
+ }
104
+
105
+ /**
106
+ * Returns true when a tool_use block represents a `BashOutput` poll. The
107
+ * `bash_id` field identifies the shell whose pending entry should clear
108
+ * — the agent calling BashOutput means it has seen the completion (or
109
+ * is at least aware of the shell), so we drop the entry. If the same
110
+ * shell is still incomplete the agent will poll again later; recording
111
+ * a fresh entry would require parsing claude's BashOutput response
112
+ * format and is intentionally out of scope (issue #4307 documents
113
+ * BashOutput as the canonical clear signal).
114
+ *
115
+ * @param {string} toolName
116
+ * @param {unknown} input
117
+ * @returns {string | null} bash_id when this is a BashOutput call, else null
118
+ */
119
+ export function parseBashOutputShellId(toolName, input) {
120
+ if (toolName !== 'BashOutput') return null
121
+ if (!input || typeof input !== 'object') return null
122
+ const id = input.bash_id
123
+ if (typeof id !== 'string' || id.length === 0) return null
124
+ return id
125
+ }