@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,1290 @@
1
+ #!/usr/bin/env node
2
+ // chroxy-pod-agent — in-pod WebSocket agent for K8s sidecar environments.
3
+ //
4
+ // Starts an HTTP server with a /healthz endpoint and a WebSocket upgrade path.
5
+ // K8sBackend (#3320) connects here to spawn claude processes and stream their
6
+ // output back over the WS connection.
7
+ //
8
+ // Auth pattern adapted from packages/server/src/ws-server.js (token validation
9
+ // + ping/pong heartbeat). Spawn/stream pattern inspired by cli-session.js but
10
+ // intentionally minimal — this is a stdio↔WS pipe, not a full CliSession.
11
+
12
+ import { createServer } from 'node:http'
13
+ import { createInterface } from 'node:readline'
14
+ import { spawn as nodeSpawn } from 'node:child_process'
15
+ import { timingSafeEqual, randomUUID } from 'node:crypto'
16
+ import { readFileSync } from 'node:fs'
17
+ import { fileURLToPath } from 'node:url'
18
+ import { dirname, join } from 'node:path'
19
+ import { Transform } from 'node:stream'
20
+ import { WebSocketServer } from 'ws'
21
+
22
+ const __filename = fileURLToPath(import.meta.url)
23
+ const __dirname = dirname(__filename)
24
+ const _pkg = JSON.parse(readFileSync(join(__dirname, 'package.json'), 'utf-8'))
25
+ const VERSION = _pkg.version
26
+
27
+ const PORT = parseInt(process.env.PORT ?? '7681', 10)
28
+
29
+ // Grace period between SIGTERM and SIGKILL when killing a child whose WS has
30
+ // disconnected. Long enough for claude to flush; short enough that a stuck
31
+ // child does not pin pod memory.
32
+ const KILL_GRACE_MS = 5_000
33
+
34
+ // Grace period between closing the child's stdin (EOF) and sending SIGTERM
35
+ // during eviction. Many CLI processes (including claude --input-format
36
+ // stream-json) exit cleanly when stdin EOFs — closing stdin first is the
37
+ // polite way to terminate before falling back to signals. Short enough that
38
+ // a stuck child still receives SIGTERM promptly. (#3397)
39
+ // Tunable at startup via CHROXY_AGENT_STDIN_CLOSE_GRACE_MS (default 500 ms).
40
+ // Reject NaN / negative values so an invalid env var cannot disable the polite
41
+ // shutdown path; setting 0 is allowed (stdin EOF still fires, but SIGTERM
42
+ // follows synchronously instead of after a grace delay — see _killChild).
43
+ const FALLBACK_STDIN_CLOSE_GRACE_MS = 500
44
+ const _PARSED_STDIN_CLOSE_GRACE_MS = parseInt(
45
+ process.env.CHROXY_AGENT_STDIN_CLOSE_GRACE_MS ?? `${FALLBACK_STDIN_CLOSE_GRACE_MS}`,
46
+ 10,
47
+ )
48
+ const DEFAULT_STDIN_CLOSE_GRACE_MS = Number.isFinite(_PARSED_STDIN_CLOSE_GRACE_MS) && _PARSED_STDIN_CLOSE_GRACE_MS >= 0
49
+ ? _PARSED_STDIN_CLOSE_GRACE_MS
50
+ : FALLBACK_STDIN_CLOSE_GRACE_MS
51
+
52
+ // Ring-buffer capacity: number of output frames retained per session for
53
+ // replay on resume. Tunable at startup via CHROXY_AGENT_BUFFER_SIZE.
54
+ // Reject non-positive / NaN values so an invalid env var cannot disable
55
+ // eviction (NaN >= length is always false → unbounded buffer growth).
56
+ const FALLBACK_BUFFER_SIZE = 1000
57
+ const _PARSED_BUFFER_SIZE = parseInt(process.env.CHROXY_AGENT_BUFFER_SIZE ?? `${FALLBACK_BUFFER_SIZE}`, 10)
58
+ const DEFAULT_BUFFER_SIZE = Number.isFinite(_PARSED_BUFFER_SIZE) && _PARSED_BUFFER_SIZE > 0
59
+ ? _PARSED_BUFFER_SIZE
60
+ : FALLBACK_BUFFER_SIZE
61
+
62
+ // Maximum bytes buffered for a single NDJSON line on stdout. If a line
63
+ // grows beyond this the child is killed, an error frame is emitted, and the
64
+ // WS is closed cleanly. 1 MiB is far above any normal SDK event but tight
65
+ // enough to prevent unbounded memory growth in constrained pods.
66
+ // Override at pod startup via CHROXY_AGENT_MAX_LINE_BYTES.
67
+ const FALLBACK_MAX_LINE_BYTES = 1024 * 1024 // 1 MiB
68
+ const _PARSED_MAX_LINE_BYTES = parseInt(process.env.CHROXY_AGENT_MAX_LINE_BYTES ?? `${FALLBACK_MAX_LINE_BYTES}`, 10)
69
+ export const DEFAULT_MAX_LINE_BYTES = Number.isFinite(_PARSED_MAX_LINE_BYTES) && _PARSED_MAX_LINE_BYTES > 0
70
+ ? _PARSED_MAX_LINE_BYTES
71
+ : FALLBACK_MAX_LINE_BYTES
72
+
73
+ // Idle resume window: how long a disconnected session waits for the client to
74
+ // reconnect before the child is killed and the session is evicted. Prevents
75
+ // orphaned child processes accumulating in long-lived pods.
76
+ // Configurable via CHROXY_AGENT_RESUME_TIMEOUT_MS (default 60 s).
77
+ const FALLBACK_RESUME_TIMEOUT_MS = 60_000
78
+ const _PARSED_RESUME_TIMEOUT = parseInt(process.env.CHROXY_AGENT_RESUME_TIMEOUT_MS ?? `${FALLBACK_RESUME_TIMEOUT_MS}`, 10)
79
+ const DEFAULT_RESUME_TIMEOUT_MS = Number.isFinite(_PARSED_RESUME_TIMEOUT) && _PARSED_RESUME_TIMEOUT > 0
80
+ ? _PARSED_RESUME_TIMEOUT
81
+ : FALLBACK_RESUME_TIMEOUT_MS
82
+
83
+ // Hard cap on concurrent sessions. When a new spawn would exceed the cap the
84
+ // oldest idle session (by lastActiveAt) is evicted first. Defense-in-depth
85
+ // against a client that reconnects repeatedly without resuming.
86
+ // Configurable via CHROXY_AGENT_MAX_SESSIONS (default 8).
87
+ const FALLBACK_MAX_SESSIONS = 8
88
+ const _PARSED_MAX_SESSIONS = parseInt(process.env.CHROXY_AGENT_MAX_SESSIONS ?? `${FALLBACK_MAX_SESSIONS}`, 10)
89
+ const DEFAULT_MAX_SESSIONS = Number.isFinite(_PARSED_MAX_SESSIONS) && _PARSED_MAX_SESSIONS > 0
90
+ ? _PARSED_MAX_SESSIONS
91
+ : FALLBACK_MAX_SESSIONS
92
+
93
+ // Stdin drain timeout: how long the agent will wait for child.stdin to emit
94
+ // 'drain' after a backpressured write before declaring the child wedged
95
+ // (#3476). PR #3475 added cooperative backpressure that pauses the WS until
96
+ // 'drain' fires; a wedged child that accepts input but never reads from stdin
97
+ // would never emit 'drain', leaving the WS paused indefinitely. The drain
98
+ // timeout caps that wait and forces an error+kill recovery so the pod cannot
99
+ // silently get stuck on a non-reading child. Configurable via
100
+ // CHROXY_AGENT_STDIN_DRAIN_TIMEOUT_MS (default 30 s).
101
+ const FALLBACK_STDIN_DRAIN_TIMEOUT_MS = 30_000
102
+ const _PARSED_STDIN_DRAIN_TIMEOUT = parseInt(
103
+ process.env.CHROXY_AGENT_STDIN_DRAIN_TIMEOUT_MS ?? `${FALLBACK_STDIN_DRAIN_TIMEOUT_MS}`,
104
+ 10,
105
+ )
106
+ export const DEFAULT_STDIN_DRAIN_TIMEOUT_MS =
107
+ Number.isFinite(_PARSED_STDIN_DRAIN_TIMEOUT) && _PARSED_STDIN_DRAIN_TIMEOUT > 0
108
+ ? _PARSED_STDIN_DRAIN_TIMEOUT
109
+ : FALLBACK_STDIN_DRAIN_TIMEOUT_MS
110
+
111
+ // Canonical `session_lost` frame `reason` field values. Documented in
112
+ // packages/server/sidecar/PROTOCOL.md (sections "session_lost" and
113
+ // "Hard Session Cap"). Centralised here so the call sites that emit the
114
+ // frame, the eviction call site that forwards the same reason, and any
115
+ // future log/assertion paths share one source of truth — preventing
116
+ // drift/typos between the wire string and the code that produces it.
117
+ const SESSION_LOST_REASONS = Object.freeze({
118
+ EVICTED_BY_CAP: 'evicted_by_cap',
119
+ BUFFER_OVERFLOW: 'buffer_overflow',
120
+ UNKNOWN_SESSION: 'unknown_session',
121
+ })
122
+
123
+ // --- Auth token -----------------------------------------------------------------
124
+ // Read once at boot. If unset we stay up (dev convenience) but reject all WS
125
+ // upgrades so the agent is fail-secure in production.
126
+ const AGENT_TOKEN = process.env.CHROXY_AGENT_TOKEN ?? null
127
+
128
+ // Token-bearing env var names that must NOT leak into the spawned child's
129
+ // environment. The child is the user-facing CLI; agent-internal credentials
130
+ // have no business being readable from inside it.
131
+ const AGENT_SECRET_ENV_KEYS = ['CHROXY_AGENT_TOKEN']
132
+
133
+ // Constant-time token comparison — adapted from token-compare.js in the main server.
134
+ function safeTokenCompare(a, b) {
135
+ let valid = true
136
+ if (typeof a !== 'string' || typeof b !== 'string') {
137
+ valid = false
138
+ a = ''
139
+ b = ''
140
+ }
141
+ const bufA = Buffer.from(a)
142
+ const bufB = Buffer.from(b)
143
+ const maxLen = Math.max(bufA.length, bufB.length)
144
+ if (maxLen === 0) return false
145
+ const paddedA = Buffer.alloc(maxLen)
146
+ const paddedB = Buffer.alloc(maxLen)
147
+ bufA.copy(paddedA)
148
+ bufB.copy(paddedB)
149
+ return valid && timingSafeEqual(paddedA, paddedB) && bufA.length === bufB.length
150
+ }
151
+
152
+ // ---------------------------------------------------------------------------
153
+ // LineLimitTransform — guards readline from unbounded line growth.
154
+ //
155
+ // Sits between child.stdout and readline.createInterface. Counts raw bytes
156
+ // in the current (not-yet-newline-terminated) fragment; if the running total
157
+ // exceeds maxBytes it emits an 'oversized_line' event on the transform
158
+ // instance and drops all further data so readline never buffers the overrun.
159
+ // The caller is responsible for killing the child and closing the WS.
160
+ // ---------------------------------------------------------------------------
161
+
162
+ export class LineLimitTransform extends Transform {
163
+ /**
164
+ * @param {object} opts
165
+ * @param {number} opts.maxBytes Maximum bytes per line before firing the
166
+ * 'oversized_line' event. Must be a finite
167
+ * positive number; falls back to
168
+ * DEFAULT_MAX_LINE_BYTES if invalid.
169
+ */
170
+ constructor({ maxBytes, ...streamOpts } = {}) {
171
+ super(streamOpts)
172
+ this._maxBytes = Number.isFinite(maxBytes) && maxBytes > 0
173
+ ? maxBytes
174
+ : DEFAULT_MAX_LINE_BYTES
175
+ this._pending = 0 // bytes counted in the current un-terminated line
176
+ this._fired = false // emit the event at most once per instance
177
+ }
178
+
179
+ _transform(chunk, _encoding, callback) {
180
+ if (this._fired) {
181
+ // Already tripped — drop all further data so readline never sees it.
182
+ callback()
183
+ return
184
+ }
185
+
186
+ let offset = 0
187
+ for (let i = 0; i < chunk.length; i++) {
188
+ if (chunk[i] === 0x0a /* '\n' */ || chunk[i] === 0x0d /* '\r' */) {
189
+ // LF resets the line counter. CR is treated the same so that a CRLF
190
+ // line of exactly maxBytes content bytes does not false-trip the guard
191
+ // (without this, the CR byte pushes _pending to maxBytes+1 before the
192
+ // LF resets it). readline strips CR from CRLF pairs, so excluding it
193
+ // from the content count matches readline's semantics.
194
+ this._pending = 0
195
+ offset = i + 1
196
+ } else {
197
+ this._pending += 1
198
+ if (this._pending > this._maxBytes) {
199
+ this._fired = true
200
+ // Pass through whatever bytes came before this overrun so readline
201
+ // can flush any complete lines already buffered.
202
+ this.push(chunk.slice(0, offset))
203
+ this.emit('oversized_line')
204
+ callback()
205
+ return
206
+ }
207
+ }
208
+ }
209
+ this.push(chunk)
210
+ callback()
211
+ }
212
+
213
+ _flush(callback) {
214
+ callback()
215
+ }
216
+ }
217
+
218
+ // --- PodAgent class -------------------------------------------------------------
219
+
220
+ export class PodAgent {
221
+ /**
222
+ * @param {object} opts
223
+ * @param {Function} [opts.spawnFn] Override child_process.spawn for tests.
224
+ * @param {string} [opts.token] Override CHROXY_AGENT_TOKEN for tests.
225
+ * @param {number} [opts.killGraceMs] Override SIGTERM→SIGKILL grace (tests).
226
+ * @param {number} [opts.stdinCloseGraceMs] Override stdin-close→SIGTERM grace (default
227
+ * CHROXY_AGENT_STDIN_CLOSE_GRACE_MS or 500 ms).
228
+ * @param {number} [opts.bufferSize] Override ring-buffer capacity per session (tests).
229
+ * @param {number} [opts.maxLineBytes] Override NDJSON line length cap (tests).
230
+ * @param {number} [opts.resumeTimeoutMs] Override idle resume window in ms (tests).
231
+ * @param {number} [opts.maxSessions] Override concurrent session cap (tests).
232
+ * @param {number} [opts.stdinDrainTimeoutMs] Override wedged-child drain timeout in ms (tests).
233
+ * @param {Function} [opts.setTimeoutFn] Override setTimeout for deterministic timer tests.
234
+ * @param {Function} [opts.clearTimeoutFn] Override clearTimeout for deterministic timer tests.
235
+ */
236
+ constructor({ spawnFn = nodeSpawn, token = AGENT_TOKEN, killGraceMs = KILL_GRACE_MS,
237
+ stdinCloseGraceMs = DEFAULT_STDIN_CLOSE_GRACE_MS,
238
+ bufferSize = DEFAULT_BUFFER_SIZE,
239
+ maxLineBytes = DEFAULT_MAX_LINE_BYTES,
240
+ resumeTimeoutMs = DEFAULT_RESUME_TIMEOUT_MS,
241
+ maxSessions = DEFAULT_MAX_SESSIONS,
242
+ stdinDrainTimeoutMs = DEFAULT_STDIN_DRAIN_TIMEOUT_MS,
243
+ setTimeoutFn = setTimeout,
244
+ clearTimeoutFn = clearTimeout } = {}) {
245
+ this._spawnFn = spawnFn
246
+ this._token = token
247
+ this._killGraceMs = killGraceMs
248
+ this._stdinCloseGraceMs = Number.isFinite(stdinCloseGraceMs) && stdinCloseGraceMs >= 0
249
+ ? stdinCloseGraceMs
250
+ : FALLBACK_STDIN_CLOSE_GRACE_MS
251
+ // Validate bufferSize defensively — a NaN or non-positive value would
252
+ // disable eviction (NaN >= length is always false) and let the buffer
253
+ // grow without bound.
254
+ this._bufferSize = Number.isFinite(bufferSize) && bufferSize > 0
255
+ ? bufferSize
256
+ : FALLBACK_BUFFER_SIZE
257
+ this._maxLineBytes = Number.isFinite(maxLineBytes) && maxLineBytes > 0
258
+ ? maxLineBytes
259
+ : FALLBACK_MAX_LINE_BYTES
260
+ this._resumeTimeoutMs = Number.isFinite(resumeTimeoutMs) && resumeTimeoutMs > 0
261
+ ? resumeTimeoutMs
262
+ : FALLBACK_RESUME_TIMEOUT_MS
263
+ this._maxSessions = Number.isFinite(maxSessions) && maxSessions > 0
264
+ ? maxSessions
265
+ : FALLBACK_MAX_SESSIONS
266
+ this._stdinDrainTimeoutMs = Number.isFinite(stdinDrainTimeoutMs) && stdinDrainTimeoutMs > 0
267
+ ? stdinDrainTimeoutMs
268
+ : FALLBACK_STDIN_DRAIN_TIMEOUT_MS
269
+ this._setTimeoutFn = setTimeoutFn
270
+ this._clearTimeoutFn = clearTimeoutFn
271
+
272
+ // Fail-secure warning. Emitted from the constructor (not module-load) so
273
+ // tests and embedders that pass an explicit `token` don't see a misleading
274
+ // log line, and the message reflects the actual configured behaviour.
275
+ if (!this._token) {
276
+ console.warn('[chroxy-pod-agent] WARNING: no auth token configured — all WS upgrades will be rejected')
277
+ }
278
+
279
+ this.httpServer = createServer((req, res) => this._handleHttp(req, res))
280
+ this.wss = new WebSocketServer({ noServer: true })
281
+
282
+ // Only one active client at a time. A second connection attempt is rejected
283
+ // with an explicit error frame rather than silently queued or allowed to
284
+ // clobber the first. K8sBackend is the sole consumer; concurrent connections
285
+ // would indicate a bug in the backend reconnect logic.
286
+ this._activeWs = null
287
+
288
+ // Live sessions, keyed by sessionId. A session persists beyond its current
289
+ // WS connection so that a reconnecting client can resume after a network
290
+ // blip. Structure:
291
+ // { sessionId, child, activeWs, seq, buffer: Array<{seq, frame}>,
292
+ // lastActiveAt: number, idleTimer: TimerHandle|null }
293
+ // `activeWs` is null while disconnected.
294
+ // `idleTimer` fires when the resume window expires and evicts the session.
295
+ this._sessions = new Map()
296
+
297
+ // Ping/pong state mirrors ws-server.js: send ping every 30 s, terminate if
298
+ // no pong received within the next cycle.
299
+ this._pingInterval = null
300
+
301
+ this.httpServer.on('upgrade', (req, socket, head) => this._handleUpgrade(req, socket, head))
302
+ this.wss.on('connection', (ws) => this._handleConnection(ws))
303
+ }
304
+
305
+ // ---------------------------------------------------------------------------
306
+ // Public API
307
+ // ---------------------------------------------------------------------------
308
+
309
+ listen(port = PORT, host = '0.0.0.0') {
310
+ return new Promise((resolve, reject) => {
311
+ this.httpServer.listen(port, host, (err) => {
312
+ if (err) { reject(err); return }
313
+ const addr = this.httpServer.address()
314
+ console.log(`[chroxy-pod-agent] Listening on ${addr.address}:${addr.port}`)
315
+ this._startPingInterval()
316
+ resolve(addr.port)
317
+ })
318
+ this.httpServer.once('error', reject)
319
+ })
320
+ }
321
+
322
+ close() {
323
+ return new Promise((resolve) => {
324
+ if (this._pingInterval) {
325
+ clearInterval(this._pingInterval)
326
+ this._pingInterval = null
327
+ }
328
+ // Kill children for all live sessions and cancel any idle timers.
329
+ for (const session of this._sessions.values()) {
330
+ this._cancelIdleTimer(session)
331
+ this._cancelStdinDrainTimer(session)
332
+ if (session.child) {
333
+ this._killChild(session.child)
334
+ session.child = null
335
+ }
336
+ if (session.activeWs) {
337
+ try { session.activeWs.terminate() } catch {}
338
+ session.activeWs = null
339
+ }
340
+ }
341
+ this._sessions.clear()
342
+
343
+ // Also handle any active WS not yet associated with a session.
344
+ if (this._activeWs) {
345
+ if (this._activeWs._child) {
346
+ this._killChild(this._activeWs._child)
347
+ this._activeWs._child = null
348
+ }
349
+ try { this._activeWs.terminate() } catch {}
350
+ this._activeWs = null
351
+ }
352
+ this.wss.close(() => {
353
+ this.httpServer.close(() => resolve())
354
+ })
355
+ })
356
+ }
357
+
358
+ // ---------------------------------------------------------------------------
359
+ // HTTP handler — /healthz requires no auth (K8s probes)
360
+ // ---------------------------------------------------------------------------
361
+
362
+ _handleHttp(req, res) {
363
+ if (req.method === 'GET' && req.url === '/healthz') {
364
+ const body = JSON.stringify({ ok: true, version: VERSION })
365
+ res.writeHead(200, {
366
+ 'Content-Type': 'application/json',
367
+ 'Content-Length': Buffer.byteLength(body),
368
+ })
369
+ res.end(body)
370
+ return
371
+ }
372
+ res.writeHead(404)
373
+ res.end()
374
+ }
375
+
376
+ // ---------------------------------------------------------------------------
377
+ // WS upgrade — auth gate
378
+ // ---------------------------------------------------------------------------
379
+
380
+ _handleUpgrade(req, socket, head) {
381
+ const authHeader = req.headers['authorization'] ?? ''
382
+ const bearer = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null
383
+
384
+ // Fail-secure: reject if no token configured at boot.
385
+ if (!this._token) {
386
+ socket.end('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\nContent-Length: 0\r\n\r\n')
387
+ console.warn('[chroxy-pod-agent] Rejected upgrade: no CHROXY_AGENT_TOKEN configured')
388
+ return
389
+ }
390
+
391
+ if (!bearer || !safeTokenCompare(bearer, this._token)) {
392
+ socket.end('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\nContent-Length: 0\r\n\r\n')
393
+ console.warn('[chroxy-pod-agent] Rejected upgrade: invalid token')
394
+ return
395
+ }
396
+
397
+ this.wss.handleUpgrade(req, socket, head, (ws) => {
398
+ this.wss.emit('connection', ws, req)
399
+ })
400
+ }
401
+
402
+ // ---------------------------------------------------------------------------
403
+ // WS connection
404
+ // ---------------------------------------------------------------------------
405
+
406
+ _handleConnection(ws) {
407
+ // Reject second concurrent connection with a clear error frame, then close.
408
+ // We send the error frame first and close only after the send is flushed so
409
+ // the client reliably receives the frame before the WS close handshake.
410
+ // Routed through _send so the readyState short-circuit and try/catch around
411
+ // the synchronous send call apply uniformly to every reject/error path
412
+ // (#3473).
413
+ if (this._activeWs) {
414
+ this._send(ws, { type: 'error', message: 'another client is already connected' }, () => {
415
+ try { ws.close(1008, 'already connected') } catch {}
416
+ })
417
+ return
418
+ }
419
+
420
+ this._activeWs = ws
421
+ ws._isAlive = true
422
+ ws._sessionId = null // set by _handleSpawn / _handleResume
423
+
424
+ ws.on('pong', () => { ws._isAlive = true })
425
+ ws.on('message', (data) => this._handleMessage(ws, data))
426
+ ws.on('close', () => {
427
+ this._cleanupConnection(ws)
428
+ })
429
+ ws.on('error', (err) => {
430
+ console.error('[chroxy-pod-agent] WS error:', err.message)
431
+ this._cleanupConnection(ws)
432
+ })
433
+ }
434
+
435
+ // ---------------------------------------------------------------------------
436
+ // Connection cleanup — detach WS from session (child keeps running for
437
+ // resume). Kill the child only if the session has no sessionId (pre-spawn
438
+ // disconnect) because the child was never tracked in _sessions.
439
+ // For sessions with a sessionId, start the idle-resume timer so the session
440
+ // is evicted if the client does not reconnect within the resume window.
441
+ // Idempotent: safe to call from both 'close' and 'error' handlers.
442
+ // ---------------------------------------------------------------------------
443
+
444
+ _cleanupConnection(ws) {
445
+ const sessionId = ws._sessionId
446
+ if (sessionId) {
447
+ const session = this._sessions.get(sessionId)
448
+ if (session && session.activeWs === ws) {
449
+ session.activeWs = null
450
+ // Start the idle-resume timer. The child stays alive until the timer
451
+ // fires so a reconnecting client can resume within the window.
452
+ this._startIdleTimer(session)
453
+ }
454
+ } else {
455
+ // Pre-spawn connection — no session yet; kill any tracked child directly.
456
+ if (ws._child) {
457
+ this._killChild(ws._child)
458
+ ws._child = null
459
+ }
460
+ }
461
+ if (this._activeWs === ws) this._activeWs = null
462
+ }
463
+
464
+ // ---------------------------------------------------------------------------
465
+ // Idle-resume timer — started when a session's WS disconnects. If the
466
+ // client does not resume within _resumeTimeoutMs the session is evicted:
467
+ // child is killed and the session is removed from _sessions.
468
+ // ---------------------------------------------------------------------------
469
+
470
+ _startIdleTimer(session) {
471
+ // Idempotent guard: don't arm a second timer if one is already running.
472
+ if (session.idleTimer !== null) return
473
+
474
+ session.idleTimer = this._setTimeoutFn(() => {
475
+ session.idleTimer = null
476
+ this._evictSession(session, 'idle_timeout')
477
+ }, this._resumeTimeoutMs)
478
+
479
+ // Don't keep the event loop alive just for the eviction timer.
480
+ if (session.idleTimer && typeof session.idleTimer.unref === 'function') {
481
+ session.idleTimer.unref()
482
+ }
483
+ }
484
+
485
+ _cancelIdleTimer(session) {
486
+ if (session.idleTimer !== null) {
487
+ this._clearTimeoutFn(session.idleTimer)
488
+ session.idleTimer = null
489
+ }
490
+ }
491
+
492
+ // ---------------------------------------------------------------------------
493
+ // Stdin drain stall timer (#3476) — guards against a wedged child that
494
+ // accepts input but never reads from stdin (would never emit 'drain' so
495
+ // the WS would stay paused indefinitely). Armed when cooperative
496
+ // backpressure flips _stdinDraining true; cancelled on the actual 'drain'
497
+ // event and on every session-teardown path before the child is killed:
498
+ // - agent.close() (loop over sessions)
499
+ // - _evictSession() (idle TTL + session-cap eviction)
500
+ // - oversized-line guard (line_too_long kill path)
501
+ // - child 'error' handler (async spawn failure)
502
+ // - child 'close' handler (natural exit)
503
+ // - _handleStdinDrainStalled (drain timer expiry — self-clears via callback)
504
+ // _killChild itself does NOT cancel the timer because the timer is per-
505
+ // session while _killChild only holds the child handle (#3514). Each
506
+ // caller is responsible for calling _cancelStdinDrainTimer(session)
507
+ // synchronously before invoking _killChild so a stale callback cannot
508
+ // re-enter and double-kill an already-torn-down session.
509
+ // On expiry the session emits a stdin_drain_stalled error frame, kills
510
+ // the child, and closes the WS with 1011.
511
+ // ---------------------------------------------------------------------------
512
+
513
+ _armStdinDrainTimer(session) {
514
+ // Idempotent — never stack a second timer.
515
+ if (session._stdinDrainTimer !== null) return
516
+
517
+ session._stdinDrainTimer = this._setTimeoutFn(() => {
518
+ session._stdinDrainTimer = null
519
+ this._handleStdinDrainStalled(session)
520
+ }, this._stdinDrainTimeoutMs)
521
+
522
+ // Don't keep the event loop alive solely for the drain-stall timer.
523
+ if (session._stdinDrainTimer && typeof session._stdinDrainTimer.unref === 'function') {
524
+ session._stdinDrainTimer.unref()
525
+ }
526
+ }
527
+
528
+ _cancelStdinDrainTimer(session) {
529
+ if (session._stdinDrainTimer !== null) {
530
+ this._clearTimeoutFn(session._stdinDrainTimer)
531
+ session._stdinDrainTimer = null
532
+ }
533
+ }
534
+
535
+ _handleStdinDrainStalled(session) {
536
+ const { sessionId, child } = session
537
+
538
+ console.warn(
539
+ `[chroxy-pod-agent] stdin drain stalled for session ${sessionId} (${this._stdinDrainTimeoutMs}ms) — killing wedged child`,
540
+ )
541
+
542
+ // Mark the session as having emitted a terminal error frame BEFORE we
543
+ // kill the child. The subsequent child 'close' event must not re-emit a
544
+ // generic exit/close 1000 — the client should observe the explicit
545
+ // stdin_drain_stalled error + close 1011 we send below. Mirrors the
546
+ // _oversized guard used by the line-too-long path (#3513).
547
+ session._terminalErrorSent = true
548
+
549
+ // Clear the draining flag so any late 'drain' event (e.g. once the child
550
+ // is killed) does not try to resume an already-closing WS.
551
+ session._stdinDraining = false
552
+
553
+ if (child) {
554
+ this._killChild(child)
555
+ session.child = null
556
+ }
557
+
558
+ // The WS was paused by the cooperative-backpressure path before this
559
+ // timer fired. A graceful close() handshake requires reading the peer's
560
+ // CLOSE frame back, which is impossible while the underlying socket is
561
+ // paused — the close would hang indefinitely. Resume the socket so the
562
+ // close handshake can complete normally.
563
+ if (session.activeWs && session.activeWs.readyState === 1) {
564
+ try { session.activeWs.resume() } catch {}
565
+ }
566
+
567
+ // Emit the error frame BEFORE closing the WS so the client can
568
+ // distinguish a wedged-child kill from a normal idle eviction
569
+ // (idle_timeout sends session_lost; this path sends an error code).
570
+ this._emitSessionFrame(session, {
571
+ type: 'error',
572
+ code: 'stdin_drain_stalled',
573
+ message: `child stdin did not drain within ${this._stdinDrainTimeoutMs}ms — child killed`,
574
+ }, () => {
575
+ if (session.activeWs && session.activeWs.readyState === 1) {
576
+ try { session.activeWs.close(1011, 'stdin_drain_stalled') } catch {}
577
+ }
578
+ this._cancelIdleTimer(session)
579
+ this._sessions.delete(sessionId)
580
+ })
581
+ }
582
+
583
+ // ---------------------------------------------------------------------------
584
+ // Session eviction — kill the child, drop from _sessions. Called by the
585
+ // idle timer or by the max-sessions cap enforcer.
586
+ // ---------------------------------------------------------------------------
587
+
588
+ _evictSession(session, reason) {
589
+ const { sessionId, child } = session
590
+
591
+ console.warn(`[chroxy-pod-agent] Evicting session ${sessionId} reason=${reason}`)
592
+
593
+ // Eviction supersedes any pending drain-stall recovery — cancel the timer
594
+ // so it cannot fire after the session has already been torn down.
595
+ this._cancelStdinDrainTimer(session)
596
+
597
+ if (child) {
598
+ this._killChild(child)
599
+ session.child = null
600
+ }
601
+
602
+ // If the session still has an activeWs at eviction time (e.g. evicted by
603
+ // the size cap while a connection is live), send a session_lost frame first
604
+ // so the consumer can distinguish a forced eviction from a pre-session
605
+ // connection failure (which K8sBackend also maps to exit(-1) on close(1001)
606
+ // without a preceding frame). The frame is sent directly — not through
607
+ // _emitSessionFrame — because we are mid-eviction and do not want the
608
+ // frame buffered or seq-stamped as session output.
609
+ // Close in the send callback so the session_lost frame is flushed to the
610
+ // socket buffer before the WS close handshake (#3399).
611
+ if (session.activeWs) {
612
+ const ws = session.activeWs
613
+ session.activeWs = null
614
+ this._send(ws, { type: 'session_lost', sessionId, reason: SESSION_LOST_REASONS.EVICTED_BY_CAP }, () => {
615
+ try { ws.close(1001, 'session evicted') } catch {}
616
+ })
617
+ }
618
+
619
+ this._sessions.delete(sessionId)
620
+ }
621
+
622
+ // ---------------------------------------------------------------------------
623
+ // Size-cap enforcer — evict the oldest idle session (by `lastActiveAt`) when
624
+ // `_sessions.size >= _maxSessions`. Called after spawn succeeds, before
625
+ // registering the new session in `_sessions`. Running this post-spawn
626
+ // ensures a failed spawn (ENOENT, EACCES, etc.) never evicts an existing
627
+ // session unnecessarily (#3392, #3430).
628
+ // ---------------------------------------------------------------------------
629
+
630
+ _enforceSessionCap() {
631
+ if (this._sessions.size < this._maxSessions) return
632
+
633
+ // Prefer evicting idle sessions (no activeWs) over live ones.
634
+ let evictTarget = null
635
+ for (const session of this._sessions.values()) {
636
+ if (session.activeWs !== null) continue
637
+ if (evictTarget === null || session.lastActiveAt < evictTarget.lastActiveAt) {
638
+ evictTarget = session
639
+ }
640
+ }
641
+
642
+ // Fall back to evicting the globally oldest session if all are active.
643
+ if (evictTarget === null) {
644
+ for (const session of this._sessions.values()) {
645
+ if (evictTarget === null || session.lastActiveAt < evictTarget.lastActiveAt) {
646
+ evictTarget = session
647
+ }
648
+ }
649
+ }
650
+
651
+ if (evictTarget) {
652
+ this._cancelIdleTimer(evictTarget)
653
+ // Reason matches the `session_lost` frame `reason` field emitted from
654
+ // _evictSession when the session has an active WS (see
655
+ // packages/server/sidecar/PROTOCOL.md → "Hard Session Cap"). Both
656
+ // sites share SESSION_LOST_REASONS.EVICTED_BY_CAP so the argument
657
+ // and frame string can never drift.
658
+ this._evictSession(evictTarget, SESSION_LOST_REASONS.EVICTED_BY_CAP)
659
+ }
660
+ }
661
+
662
+ // ---------------------------------------------------------------------------
663
+ // Kill an orphaned child: close stdin (EOF), then SIGTERM after a short
664
+ // grace, then SIGKILL after a longer grace if still alive.
665
+ //
666
+ // Closing stdin first is the polite way to terminate — many CLI processes
667
+ // (including claude --input-format stream-json) exit cleanly on stdin EOF
668
+ // without ever needing a signal. The stdin-close grace gives the child a
669
+ // chance to finish flushing and exit before we escalate. (#3397)
670
+ //
671
+ // If child.stdin is null/already-ended (e.g. stdio: 'ignore' or stdin_end
672
+ // already sent), the stdin-close step is a no-op and SIGTERM still fires
673
+ // synchronously — preserving the original kill semantics for that path.
674
+ //
675
+ // When stdinCloseGraceMs is configured to 0, SIGTERM also fires
676
+ // synchronously (after the stdin EOF), avoiding a deferred setTimeout(0).
677
+ // ---------------------------------------------------------------------------
678
+
679
+ _killChild(child) {
680
+ if (child._chroxyKilled) return
681
+ child._chroxyKilled = true
682
+
683
+ // Close stdin so the child sees EOF immediately. Wrapped in try/catch
684
+ // because stdin may already be ended (idempotent) or in an error state.
685
+ // Track whether we actually closed an open pipe — when there was no stdin
686
+ // to close, skip the pre-SIGTERM grace and fire SIGTERM synchronously so
687
+ // call sites that never piped stdin retain the original kill timing.
688
+ let stdinClosed = false
689
+ if (child.stdin && typeof child.stdin.end === 'function' && !child.stdin.writableEnded) {
690
+ try {
691
+ child.stdin.end()
692
+ stdinClosed = true
693
+ } catch {}
694
+ }
695
+
696
+ // Use injected timer functions so deterministic-clock tests can advance
697
+ // the stdin-close and SIGKILL grace windows without wall-clock waits.
698
+ let sigtermTimer = null
699
+ if (stdinClosed && this._stdinCloseGraceMs > 0) {
700
+ // SIGTERM after the stdin-close grace. If the child exits cleanly via
701
+ // EOF the close-listener below cancels both timers before SIGTERM fires.
702
+ sigtermTimer = this._setTimeoutFn(() => {
703
+ try { child.kill('SIGTERM') } catch {}
704
+ }, this._stdinCloseGraceMs)
705
+ if (sigtermTimer && typeof sigtermTimer.unref === 'function') sigtermTimer.unref()
706
+ } else {
707
+ // Either no stdin pipe to close, or grace is 0 — fire SIGTERM
708
+ // synchronously to preserve the original kill timing for those paths.
709
+ try { child.kill('SIGTERM') } catch {}
710
+ }
711
+
712
+ // SIGKILL after SIGTERM has had its own grace to take effect. When stdin
713
+ // is closed first with a non-zero grace, the budget extends to
714
+ // stdinCloseGraceMs + killGraceMs.
715
+ const sigkillDelay = (stdinClosed ? this._stdinCloseGraceMs : 0) + this._killGraceMs
716
+ const sigkillTimer = this._setTimeoutFn(() => {
717
+ try { child.kill('SIGKILL') } catch {}
718
+ }, sigkillDelay)
719
+ if (sigkillTimer && typeof sigkillTimer.unref === 'function') sigkillTimer.unref()
720
+
721
+ // If the child exits before the timers fire, cancel both — there is no
722
+ // point signaling a process that has already gone away.
723
+ child.once('close', () => {
724
+ if (sigtermTimer) this._clearTimeoutFn(sigtermTimer)
725
+ this._clearTimeoutFn(sigkillTimer)
726
+ })
727
+ }
728
+
729
+ // ---------------------------------------------------------------------------
730
+ // Incoming frames from client
731
+ // ---------------------------------------------------------------------------
732
+
733
+ _handleMessage(ws, data) {
734
+ let msg
735
+ try {
736
+ msg = JSON.parse(data.toString())
737
+ } catch {
738
+ this._send(ws, { type: 'error', message: 'invalid JSON' })
739
+ return
740
+ }
741
+
742
+ if (msg.type === 'ping') {
743
+ this._send(ws, { type: 'pong' })
744
+ return
745
+ }
746
+
747
+ if (msg.type === 'spawn') {
748
+ this._handleSpawn(ws, msg)
749
+ return
750
+ }
751
+
752
+ if (msg.type === 'resume') {
753
+ this._handleResume(ws, msg)
754
+ return
755
+ }
756
+
757
+ if (msg.type === 'stdin') {
758
+ this._handleStdin(ws, msg)
759
+ return
760
+ }
761
+
762
+ if (msg.type === 'stdin_end') {
763
+ this._handleStdinEnd(ws)
764
+ return
765
+ }
766
+
767
+ this._send(ws, { type: 'error', message: `unknown message type: ${msg.type}` })
768
+ }
769
+
770
+ // ---------------------------------------------------------------------------
771
+ // Spawn a child process and pipe its output back over WS
772
+ // ---------------------------------------------------------------------------
773
+
774
+ _handleSpawn(ws, msg) {
775
+ const { cmd, args = [], env = {}, cwd, stdin: stdinMode = 'pipe' } = msg
776
+
777
+ if (!cmd) {
778
+ this._send(ws, { type: 'error', message: 'spawn: cmd is required' })
779
+ return
780
+ }
781
+
782
+ // One spawn per connection. K8sBackend (#3320) is the sole consumer and
783
+ // assumes single-child semantics; a second 'spawn' frame indicates a bug
784
+ // upstream rather than a feature.
785
+ //
786
+ // We reject any second spawn while this WS is already bound to a session,
787
+ // even if the child has just exited and the session-cleanup timer has not
788
+ // yet fired (#3328 race window between child 'close' and the 50 ms WS-
789
+ // close timer). After natural exit the agent closes the WS — clients are
790
+ // expected to open a fresh connection rather than re-spawn on the same one.
791
+ if (ws._sessionId && this._sessions.has(ws._sessionId)) {
792
+ this._send(ws, { type: 'error', message: 'spawn: child already running' })
793
+ return
794
+ }
795
+
796
+ // stdin option controls how the child's stdin is set up (#3329):
797
+ // 'pipe' — (default) writable stdin; client feeds data via stdin frames.
798
+ // Required for --input-format stream-json workflows.
799
+ // 'inherit' — child inherits the agent's stdin (useful when running
800
+ // interactively; not meaningful when the agent has no tty).
801
+ // 'ignore' — child stdin is /dev/null; correct for fire-and-forget -p runs.
802
+ // Any unrecognised value falls back to 'pipe'.
803
+ const validStdinModes = ['pipe', 'inherit', 'ignore']
804
+ const resolvedStdin = validStdinModes.includes(stdinMode) ? stdinMode : 'pipe'
805
+
806
+ // Build the child env: start from the agent's env, strip agent-only
807
+ // secrets, then layer the per-spawn env on top. This prevents the auth
808
+ // token (and any future agent-internal credentials) from leaking into
809
+ // the user-facing CLI process.
810
+ const sanitizedAgentEnv = { ...process.env }
811
+ for (const key of AGENT_SECRET_ENV_KEYS) {
812
+ delete sanitizedAgentEnv[key]
813
+ }
814
+ const spawnOpts = {
815
+ stdio: [resolvedStdin, 'pipe', 'pipe'],
816
+ env: { ...sanitizedAgentEnv, ...env },
817
+ }
818
+ if (cwd) spawnOpts.cwd = cwd
819
+
820
+ let child
821
+ try {
822
+ child = this._spawnFn(cmd, args, spawnOpts)
823
+ } catch (err) {
824
+ this._send(ws, { type: 'error', message: `spawn failed: ${err.message}` })
825
+ return
826
+ }
827
+
828
+ // Spawn succeeded -- now enforce the concurrent session cap. Evicts the
829
+ // oldest idle session if needed so the Map never exceeds _maxSessions.
830
+ // Enforcing after spawn ensures a failed spawn (ENOENT, EACCES, etc.)
831
+ // never evicts an existing session unnecessarily (#3392).
832
+ this._enforceSessionCap()
833
+
834
+ // Assign a sessionId and create the session object.
835
+ const sessionId = randomUUID()
836
+ const session = {
837
+ sessionId,
838
+ child,
839
+ activeWs: ws,
840
+ seq: 0,
841
+ buffer: [],
842
+ lastActiveAt: Date.now(),
843
+ idleTimer: null,
844
+ // Cooperative backpressure flag for child.stdin.write() (#3396).
845
+ // True while a 'drain' listener is armed and the WS is paused.
846
+ _stdinDraining: false,
847
+ // Drain stall timer (#3476). Armed when _stdinDraining flips true; fires
848
+ // if no 'drain' event arrives within _stdinDrainTimeoutMs and forces a
849
+ // wedged-child recovery (error frame + kill + close 1011).
850
+ _stdinDrainTimer: null,
851
+ // Terminal-error guard (#3513). Set true by any error path that emits a
852
+ // terminal error frame and closes the WS itself (e.g. stdin_drain_stalled,
853
+ // line_too_long via the _oversized flag below). The child 'close' handler
854
+ // checks this flag and returns early so it cannot race with the terminal
855
+ // error path and override the close code with a generic exit/1000.
856
+ _terminalErrorSent: false,
857
+ }
858
+ this._sessions.set(sessionId, session)
859
+ ws._sessionId = sessionId
860
+
861
+ // Notify the client so it can store the sessionId for future resume.
862
+ this._send(ws, { type: 'session_started', sessionId })
863
+
864
+ // Sentinel: emit a recognisable per-spawn stderr frame immediately after
865
+ // the spawn is accepted so that integration tests can assert the sidecar
866
+ // code specifically handled the spawn (not a shorter path that bypasses
867
+ // the agent). The format `[chroxy-pod-agent] spawn cmd=…` is distinct
868
+ // from real child stderr and stable enough to grep reliably. See #3344.
869
+ //
870
+ // Args are truncated to the first 3 elements to avoid leaking sensitive
871
+ // values that callers may pass as CLI flags (e.g. --api-key, --password).
872
+ // Callers MUST NOT pass secret material in args — the sentinel is buffered
873
+ // and replayed to reconnecting clients. See #3393.
874
+ const SENTINEL_MAX_ARGS = 3
875
+ const sentinelArgs = args.length > SENTINEL_MAX_ARGS
876
+ ? [...args.slice(0, SENTINEL_MAX_ARGS), `...[${args.length - SENTINEL_MAX_ARGS} more]`]
877
+ : args
878
+ this._emitSessionFrame(session, {
879
+ type: 'stderr',
880
+ data: `[chroxy-pod-agent] spawn cmd=${cmd} args=${JSON.stringify(sentinelArgs)} sessionId=${sessionId}\n`,
881
+ })
882
+
883
+ // Handle async spawn failures (ENOENT, EACCES) so an unhandled 'error'
884
+ // event does not crash the agent process. Spawn errors arrive after the
885
+ // synchronous spawn() returns, which is why this can't go in the catch
886
+ // block above.
887
+ child.on('error', (err) => {
888
+ if (session.child === child) session.child = null
889
+ // Cancel the drain timer synchronously on async spawn failure (#3514).
890
+ // The post-flush callback below also cancels, but if the timer were
891
+ // to fire between this handler and the ws.send callback it would try
892
+ // to operate on a session whose child is already null.
893
+ this._cancelStdinDrainTimer(session)
894
+ this._emitSessionFrame(session, { type: 'error', message: `spawn failed: ${err.message}` })
895
+ // Async spawn never produced a child — there will be no 'close' event
896
+ // to clean up the session. Synthesize an exit and drop the session
897
+ // entry so the agent does not leak it indefinitely. Closing in the
898
+ // ws.send callback for the exit frame avoids a flush race (#3399).
899
+ this._emitSessionFrame(session, { type: 'exit', code: -1 }, () => {
900
+ if (session.activeWs && session.activeWs.readyState === 1) {
901
+ session.activeWs.close(1000, 'spawn failed')
902
+ }
903
+ this._cancelIdleTimer(session)
904
+ this._cancelStdinDrainTimer(session)
905
+ this._sessions.delete(sessionId)
906
+ })
907
+ })
908
+
909
+ // stdout — read line-by-line; each NDJSON line becomes one 'event' frame.
910
+ //
911
+ // A LineLimitTransform sits upstream of readline and counts raw bytes per
912
+ // line. If a line exceeds _maxLineBytes (default 1 MiB) before a newline
913
+ // arrives the transform fires 'oversized_line', the child is killed, an
914
+ // error frame is emitted, and the WS is closed cleanly. This prevents a
915
+ // runaway tool result or streaming bug from growing the readline internal
916
+ // buffer without bound and OOM-ing the pod.
917
+ const lineGuard = new LineLimitTransform({ maxBytes: this._maxLineBytes })
918
+ lineGuard.once('oversized_line', () => {
919
+ console.error(`[chroxy-pod-agent] stdout line exceeded ${this._maxLineBytes} bytes — killing child`)
920
+ session._oversized = true
921
+ // Suppress the child 'close' handler so it cannot race with this
922
+ // terminal-error path (#3513). _oversized alone already gates that
923
+ // handler, but setting the unified flag too keeps the invariant
924
+ // single-sourced for any future terminal-error code.
925
+ session._terminalErrorSent = true
926
+ // Cancel the drain timer BEFORE killing the child (#3514). The
927
+ // _emitSessionFrame callback below also cancels, but that runs
928
+ // asynchronously after ws.send flushes; if the timer were to fire in
929
+ // the interim it would re-enter _handleStdinDrainStalled and try to
930
+ // kill an already-killed child + tear down a session that is already
931
+ // mid-teardown. Cancelling synchronously here closes that race.
932
+ this._cancelStdinDrainTimer(session)
933
+ if (session.child === child) {
934
+ this._killChild(child)
935
+ session.child = null
936
+ }
937
+ // Close the WS only after ws.send() has flushed the error frame to the
938
+ // socket buffer; closing earlier (e.g. on a fixed 50ms timer) can race
939
+ // with the send and drop the frame on a busy event loop (#3399).
940
+ this._emitSessionFrame(session, {
941
+ type: 'error',
942
+ code: 'line_too_long',
943
+ message: `stdout line exceeded max length (${this._maxLineBytes} bytes) — child killed`,
944
+ }, () => {
945
+ if (session.activeWs && session.activeWs.readyState === 1) {
946
+ // The WS may still be paused from cooperative stdin backpressure
947
+ // (#3475). A graceful close() handshake requires reading the peer's
948
+ // CLOSE frame back, which is impossible while the underlying socket
949
+ // is paused — the close would hang. Resume before close so the
950
+ // handshake can complete normally. Mirrors _handleStdinDrainStalled
951
+ // (agent.js:563) which handles the same issue. (#3550)
952
+ try { session.activeWs.resume() } catch {}
953
+ session._stdinDraining = false
954
+ session.activeWs.close(1008, 'line_too_long')
955
+ }
956
+ this._cancelIdleTimer(session)
957
+ this._cancelStdinDrainTimer(session)
958
+ this._sessions.delete(sessionId)
959
+ })
960
+ })
961
+ child.stdout.pipe(lineGuard)
962
+
963
+ const rl = createInterface({ input: lineGuard })
964
+ rl.on('line', (line) => {
965
+ let payload
966
+ try {
967
+ payload = JSON.parse(line)
968
+ } catch {
969
+ // Not valid JSON — forward as raw data inside the payload string.
970
+ payload = line
971
+ }
972
+ this._emitSessionFrame(session, { type: 'event', payload })
973
+ })
974
+
975
+ // stderr — forward raw text as 'stderr' frames.
976
+ child.stderr.on('data', (chunk) => {
977
+ this._emitSessionFrame(session, { type: 'stderr', data: chunk.toString() })
978
+ })
979
+
980
+ // exit — emit exit code and close the WS. Clear the tracked child so the
981
+ // disconnect handler does not try to kill an already-exited process.
982
+ //
983
+ // If the session was already terminated by an error path (oversized line
984
+ // → close 1008, stdin drain stall → close 1011, or any future terminal-
985
+ // error path), the error frame and WS close are already handled there.
986
+ // Emitting a spurious exit frame + close 1000 here would contradict the
987
+ // protocol (client already received the explicit error + matching close
988
+ // code) and could confuse K8sBackend. Skip the exit path. (#3380, #3513)
989
+ child.on('close', (code) => {
990
+ if (session.child === child) session.child = null
991
+ if (session._oversized || session._terminalErrorSent) return
992
+ // Cancel the drain timer synchronously when the child exits naturally
993
+ // (#3514). The post-flush callback below also cancels, but the timer
994
+ // could otherwise fire between this handler and the ws.send callback
995
+ // and try to kill an already-exited child + tear down a session that
996
+ // is already mid-teardown.
997
+ this._cancelStdinDrainTimer(session)
998
+ const exitFrame = { type: 'exit', code: code ?? 1 }
999
+ // Close the WS only after the exit frame has been flushed to the socket
1000
+ // buffer to avoid a race that can drop the frame (#3399).
1001
+ this._emitSessionFrame(session, exitFrame, () => {
1002
+ if (session.activeWs && session.activeWs.readyState === 1) {
1003
+ // The WS may still be paused from cooperative stdin backpressure
1004
+ // (#3475). A graceful close() handshake requires reading the peer's
1005
+ // CLOSE frame back, which is impossible while the underlying socket
1006
+ // is paused — the close would hang. Resume before close so the
1007
+ // handshake can complete normally. Mirrors _handleStdinDrainStalled
1008
+ // (agent.js:563) which handles the same issue. (#3550)
1009
+ try { session.activeWs.resume() } catch {}
1010
+ session._stdinDraining = false
1011
+ session.activeWs.close(1000, 'process exited')
1012
+ }
1013
+ // Cancel any pending idle / drain timers and remove session from map.
1014
+ this._cancelIdleTimer(session)
1015
+ this._cancelStdinDrainTimer(session)
1016
+ this._sessions.delete(sessionId)
1017
+ })
1018
+ })
1019
+ }
1020
+
1021
+ // ---------------------------------------------------------------------------
1022
+ // stdin — forward data from the client into the child's stdin stream (#3329).
1023
+ //
1024
+ // Sequencing rules:
1025
+ // - Must come AFTER spawn (ws._sessionId must be set and session must exist).
1026
+ // - Must come BEFORE exit (session.child must still be alive).
1027
+ // - Only usable when the child was spawned with stdin: 'pipe'; if stdin is
1028
+ // 'ignore' or 'inherit', child.stdin is null and the write is silently dropped.
1029
+ // ---------------------------------------------------------------------------
1030
+
1031
+ _handleStdin(ws, msg) {
1032
+ const sessionId = ws._sessionId
1033
+ if (!sessionId) {
1034
+ this._send(ws, { type: 'error', message: 'stdin: no active session (send spawn first)' })
1035
+ return
1036
+ }
1037
+
1038
+ const session = this._sessions.get(sessionId)
1039
+ if (!session) {
1040
+ this._send(ws, { type: 'error', message: 'stdin: no active session (send spawn first)' })
1041
+ return
1042
+ }
1043
+
1044
+ const { data } = msg
1045
+ if (typeof data !== 'string') {
1046
+ this._send(ws, { type: 'error', message: 'stdin: data must be a string' })
1047
+ return
1048
+ }
1049
+
1050
+ // child.stdin is null when spawned with stdin: 'ignore' or 'inherit'.
1051
+ // Silently drop — the caller may not know the mode.
1052
+ if (!session.child || !session.child.stdin) return
1053
+
1054
+ try {
1055
+ // Cooperative backpressure (#3396):
1056
+ // stream.Writable.write() returns false when the internal buffer is at
1057
+ // capacity (highWaterMark). A fast WS client streaming many large
1058
+ // stdin frames to a slow child would otherwise grow the stdin
1059
+ // WritableStream's internal buffer without bound and OOM the pod.
1060
+ //
1061
+ // When write() returns false we pause WS message delivery for this
1062
+ // connection and resume it on the next 'drain' event from
1063
+ // child.stdin. ws.pause() halts further 'message' events until
1064
+ // ws.resume() is called, so subsequent stdin frames sit in the kernel
1065
+ // socket buffer (TCP backpressure) rather than in the agent process
1066
+ // memory.
1067
+ //
1068
+ // `_stdinDraining` is an idempotency guard: if pause() and the drain
1069
+ // listener are already armed we don't re-register on every write.
1070
+ const ok = session.child.stdin.write(data)
1071
+ if (!ok && !session._stdinDraining) {
1072
+ session._stdinDraining = true
1073
+ ws.pause()
1074
+ // Arm the wedged-child drain timeout (#3476) BEFORE attaching the
1075
+ // drain listener. If the child accepts input but never reads from
1076
+ // stdin it will never emit 'drain' — without this timer the WS would
1077
+ // stay paused indefinitely. The drain listener cancels the timer on
1078
+ // success.
1079
+ this._armStdinDrainTimer(session)
1080
+ session.child.stdin.once('drain', () => {
1081
+ session._stdinDraining = false
1082
+ this._cancelStdinDrainTimer(session)
1083
+ // Only resume the WS that's still attached to this session — a
1084
+ // disconnect during draining must not call resume() on a stale ws.
1085
+ if (session.activeWs && session.activeWs.readyState === 1) {
1086
+ session.activeWs.resume()
1087
+ }
1088
+ })
1089
+ }
1090
+ } catch {
1091
+ // Ignore write errors — child may have closed its stdin already.
1092
+ }
1093
+ }
1094
+
1095
+ // ---------------------------------------------------------------------------
1096
+ // stdin_end — signal EOF on the child's stdin (#3329).
1097
+ //
1098
+ // After this the child sees EOF on stdin. For --input-format stream-json this
1099
+ // causes claude to stop reading and begin processing the buffered input.
1100
+ // Subsequent stdin frames after stdin_end are silently dropped (stdin.end()
1101
+ // is idempotent on a WritableStream).
1102
+ // ---------------------------------------------------------------------------
1103
+
1104
+ _handleStdinEnd(ws) {
1105
+ const sessionId = ws._sessionId
1106
+ if (!sessionId) {
1107
+ this._send(ws, { type: 'error', message: 'stdin_end: no active session (send spawn first)' })
1108
+ return
1109
+ }
1110
+
1111
+ const session = this._sessions.get(sessionId)
1112
+ if (!session) {
1113
+ this._send(ws, { type: 'error', message: 'stdin_end: no active session (send spawn first)' })
1114
+ return
1115
+ }
1116
+
1117
+ // No-op if stdin was not piped.
1118
+ if (!session.child || !session.child.stdin) return
1119
+
1120
+ try {
1121
+ session.child.stdin.end()
1122
+ } catch {
1123
+ // Ignore — child may have already closed.
1124
+ }
1125
+ }
1126
+
1127
+ // ---------------------------------------------------------------------------
1128
+ // Resume — re-attach a reconnecting client to an existing session
1129
+ // ---------------------------------------------------------------------------
1130
+
1131
+ _handleResume(ws, msg) {
1132
+ const { sessionId, lastSeq = 0 } = msg
1133
+
1134
+ const session = this._sessions.get(sessionId)
1135
+ if (!session) {
1136
+ this._send(ws, { type: 'session_lost', sessionId, reason: SESSION_LOST_REASONS.UNKNOWN_SESSION })
1137
+ return
1138
+ }
1139
+
1140
+ // Single-client policy: if the session already has a live WS attached,
1141
+ // reject the second connection (same error behaviour as _handleConnection).
1142
+ // Close in the send callback so the error frame is flushed first (#3399).
1143
+ if (session.activeWs) {
1144
+ this._send(ws, { type: 'error', message: 'another client is already connected' }, () => {
1145
+ try { ws.close(1008, 'already connected') } catch {}
1146
+ })
1147
+ return
1148
+ }
1149
+
1150
+ // Resume arrived within the window — cancel the idle eviction timer.
1151
+ this._cancelIdleTimer(session)
1152
+
1153
+ // Resume-with-gap detection (#3347).
1154
+ // If the oldest seq still in the ring buffer is greater than `lastSeq + 1`,
1155
+ // some events between (lastSeq, oldestSeq) were evicted by buffer overflow.
1156
+ // Silent partial replay would corrupt the client's NDJSON stream — surface
1157
+ // it as session_lost so the consumer can take recovery action (exit -2).
1158
+ // Close in the send callback so the session_lost frame is flushed first
1159
+ // (#3399).
1160
+ if (session.buffer.length > 0 && session.buffer[0].seq > lastSeq + 1) {
1161
+ this._send(ws, { type: 'session_lost', sessionId, reason: SESSION_LOST_REASONS.BUFFER_OVERFLOW }, () => {
1162
+ try { ws.close(1008, 'resume gap') } catch {}
1163
+ })
1164
+ return
1165
+ }
1166
+
1167
+ // Attach this WS to the session and refresh activity timestamp.
1168
+ session.activeWs = ws
1169
+ session.lastActiveAt = Date.now()
1170
+ ws._sessionId = sessionId
1171
+
1172
+ // Replay any buffered frames the client hasn't seen yet (seq > lastSeq).
1173
+ let replayedCount = 0
1174
+ for (const entry of session.buffer) {
1175
+ if (entry.seq > lastSeq) {
1176
+ this._send(ws, entry.frame)
1177
+ replayedCount += 1
1178
+ }
1179
+ }
1180
+
1181
+ // Emit an explicit `resumed` frame so the client can confirm the resume
1182
+ // succeeded and reset its per-blip retry counter (#3348). Without this
1183
+ // frame the client treats `maxRetries` as a lifetime budget rather than
1184
+ // a per-disconnect budget. PROTOCOL.md documents this frame.
1185
+ this._send(ws, {
1186
+ type: 'resumed',
1187
+ sessionId,
1188
+ lastSeq,
1189
+ replayedCount,
1190
+ })
1191
+ }
1192
+
1193
+ // ---------------------------------------------------------------------------
1194
+ // Session-scoped frame emission — assigns seq, ring-buffers, and sends
1195
+ // ---------------------------------------------------------------------------
1196
+
1197
+ /**
1198
+ * Assigns a sequence number, appends to the ring buffer, and sends on the
1199
+ * active WS (if any). Optional `cb` is invoked when the underlying ws.send()
1200
+ * callback fires — used by callers that need to close the socket only after
1201
+ * the frame has been flushed (#3399). When the session has no activeWs the
1202
+ * callback fires on the next microtask so the caller's close-after-flush
1203
+ * logic still progresses (otherwise the socket would dangle).
1204
+ */
1205
+ _emitSessionFrame(session, frame, cb) {
1206
+ session.seq += 1
1207
+ session.lastActiveAt = Date.now()
1208
+ const seqFrame = { ...frame, seq: session.seq }
1209
+
1210
+ // Ring buffer: drop oldest entry when at capacity.
1211
+ if (session.buffer.length >= this._bufferSize) {
1212
+ session.buffer.shift()
1213
+ }
1214
+ session.buffer.push({ seq: session.seq, frame: seqFrame })
1215
+
1216
+ if (session.activeWs) {
1217
+ this._send(session.activeWs, seqFrame, cb)
1218
+ } else if (cb) {
1219
+ // Defer to next microtask so behaviour matches the async ws.send()
1220
+ // callback (callers may rely on the cb not firing synchronously).
1221
+ queueMicrotask(cb)
1222
+ }
1223
+ }
1224
+
1225
+ // ---------------------------------------------------------------------------
1226
+ // Ping/pong keepalive — mirrors ws-server.js interval logic
1227
+ // ---------------------------------------------------------------------------
1228
+
1229
+ _startPingInterval() {
1230
+ this._pingInterval = setInterval(() => {
1231
+ if (!this._activeWs) return
1232
+ const ws = this._activeWs
1233
+ if (ws.readyState !== 1) return
1234
+ if (!ws._isAlive) {
1235
+ console.warn('[chroxy-pod-agent] Client unresponsive, terminating')
1236
+ // terminate() does not always fire 'close'; clean up the child here
1237
+ // to guarantee the orphan-PID path is closed even on hard terminate.
1238
+ this._cleanupConnection(ws)
1239
+ ws.terminate()
1240
+ return
1241
+ }
1242
+ ws._isAlive = false
1243
+ try { ws.ping() } catch {}
1244
+ }, 30_000)
1245
+ }
1246
+
1247
+ // ---------------------------------------------------------------------------
1248
+ // Helpers
1249
+ // ---------------------------------------------------------------------------
1250
+
1251
+ /**
1252
+ * Send a JSON-serialised frame on the given WS. When `cb` is provided it is
1253
+ * invoked once the underlying ws.send() callback fires — this lets callers
1254
+ * close the socket only after the frame has been flushed to the network
1255
+ * buffer (#3399). The callback is also invoked when the socket is not in the
1256
+ * OPEN state or when ws.send() throws synchronously, so callers can use it
1257
+ * as a uniform "now safe to close" signal regardless of the send outcome.
1258
+ */
1259
+ _send(ws, obj, cb) {
1260
+ if (ws.readyState !== 1) {
1261
+ if (cb) cb()
1262
+ return
1263
+ }
1264
+ try {
1265
+ ws.send(JSON.stringify(obj), () => { if (cb) cb() })
1266
+ } catch {
1267
+ // ignore send errors on a closing socket
1268
+ if (cb) cb()
1269
+ }
1270
+ }
1271
+ }
1272
+
1273
+ // ---------------------------------------------------------------------------
1274
+ // Entrypoint — only runs when executed directly, not when imported in tests.
1275
+ // ---------------------------------------------------------------------------
1276
+
1277
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
1278
+ const agent = new PodAgent()
1279
+ agent.listen(PORT).catch((err) => {
1280
+ console.error('[chroxy-pod-agent] Failed to start:', err)
1281
+ process.exit(1)
1282
+ })
1283
+
1284
+ for (const sig of ['SIGTERM', 'SIGINT']) {
1285
+ process.on(sig, () => {
1286
+ console.log(`[chroxy-pod-agent] ${sig} received, shutting down`)
1287
+ agent.close().then(() => process.exit(0))
1288
+ })
1289
+ }
1290
+ }