@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,691 @@
1
+ # chroxy-pod-agent WebSocket Protocol
2
+
3
+ The `chroxy-pod-agent` sidecar exposes an HTTP/WS server inside each K8s pod.
4
+ `K8sBackend` (issue #3320) is the sole client; no other services should connect.
5
+
6
+ ---
7
+
8
+ ## Transport
9
+
10
+ - HTTP server on `$PORT` (default `7681`), bound to `0.0.0.0`
11
+ - WebSocket upgrade at any path (the agent does not route by path)
12
+ - Frames are UTF-8 JSON objects, one per WS message
13
+
14
+ ---
15
+
16
+ ## Auth
17
+
18
+ All WS upgrades must carry:
19
+
20
+ ```
21
+ Authorization: Bearer <CHROXY_AGENT_TOKEN>
22
+ ```
23
+
24
+ `CHROXY_AGENT_TOKEN` is injected into the pod via a K8s Secret and read once at
25
+ startup. The comparison is constant-time (`crypto.timingSafeEqual`) to
26
+ prevent timing attacks.
27
+
28
+ If the env variable is unset the agent starts but rejects **all** upgrades with
29
+ `401 Unauthorized` and logs a startup warning — fail-secure by default.
30
+
31
+ The `/healthz` endpoint does **not** require auth (K8s readiness/liveness
32
+ probes cannot carry headers).
33
+
34
+ ---
35
+
36
+ ## Handshake Sequences
37
+
38
+ ### New Session (non-interactive `-p` mode)
39
+
40
+ ```
41
+ K8sBackend chroxy-pod-agent
42
+ │ │
43
+ │── GET /healthz ──────────────────▶ 200 { ok: true, version }
44
+ │ │
45
+ │── WS Upgrade (Authorization: Bearer <token>) ──▶
46
+ │ │ reject → 401 (socket end, no WS frame)
47
+ │ │ accept → WS connection open
48
+ │ │
49
+ │── { type: 'spawn', stdin: 'ignore', ... } ──▶
50
+ │◀─ { type: 'session_started', sessionId }
51
+ │◀─ { type: 'stderr', data: '[chroxy-pod-agent] spawn ...', seq: 1 } ← sentinel
52
+ │◀─ { type: 'event', payload: <object|string>, seq: N }
53
+ │◀─ { type: 'stderr', data: '...', seq: N }
54
+ │◀─ { type: 'exit', code: 0, seq: N }
55
+ │ │ (WS close follows within 50 ms)
56
+ ```
57
+
58
+ ### New Session (stream-json input format)
59
+
60
+ For `--input-format stream-json` the client must open a `stdin: 'pipe'` session,
61
+ forward NDJSON lines via `stdin` frames, then close stdin with `stdin_end` so
62
+ the child knows the input is complete.
63
+
64
+ ```
65
+ K8sBackend chroxy-pod-agent
66
+ │ │
67
+ │── WS Upgrade (Authorization: Bearer <token>) ──▶
68
+ │ │ accept → WS connection open
69
+ │ │
70
+ │── { type: 'spawn', stdin: 'pipe', ... } ──▶
71
+ │◀─ { type: 'session_started', sessionId }
72
+ │◀─ { type: 'stderr', data: '[chroxy-pod-agent] spawn ...', seq: 1 } ← sentinel
73
+ │── { type: 'stdin', data: '{"prompt":"hello"}\n' } ──▶
74
+ │── { type: 'stdin_end' } ──────────▶
75
+ │◀─ { type: 'event', payload: <object|string>, seq: N }
76
+ │◀─ { type: 'exit', code: 0, seq: N }
77
+ │ │ (WS close follows within 50 ms)
78
+ ```
79
+
80
+ ### Resume After Reconnect
81
+
82
+ ```
83
+ K8sBackend chroxy-pod-agent
84
+ │ │
85
+ │── WS Upgrade (Authorization: Bearer <token>) ──▶
86
+ │ │ accept → WS connection open
87
+ │ │
88
+ │── { type: 'resume', sessionId, lastSeq } ──▶
89
+ │◀─ { type: 'event', ..., seq: N+1 } (buffered frames replayed)
90
+ │◀─ ...
91
+ │◀─ { type: 'resumed', sessionId, lastSeq, replayedCount }
92
+ │◀─ { type: 'exit', code: 0, seq: M }
93
+ │ │ (WS close follows within 50 ms)
94
+ ```
95
+
96
+ The `resumed` frame is sent **after** the buffered replay finishes and signals
97
+ that the connection is now in live-forwarding mode. Clients use it to confirm
98
+ a successful resume (e.g. to reset per-blip retry budgets — see #3348).
99
+
100
+ ### Session Lost After Agent Restart
101
+
102
+ ```
103
+ K8sBackend chroxy-pod-agent
104
+ │ │
105
+ │── WS Upgrade ───────────────────▶
106
+ │ │
107
+ │── { type: 'resume', sessionId } ─▶
108
+ │◀─ { type: 'session_lost', sessionId, reason: 'unknown_session' }
109
+ │ │ (connection stays open for a new spawn)
110
+ ```
111
+
112
+ ### Session Lost After Resume Gap (Buffer Overflow)
113
+
114
+ ```
115
+ K8sBackend chroxy-pod-agent
116
+ │ │
117
+ │── WS Upgrade ───────────────────▶
118
+ │ │
119
+ │── { type: 'resume', sessionId, lastSeq } ──▶
120
+ │ │ buffer evicted seq <= lastSeq + N
121
+ │◀─ { type: 'session_lost', sessionId, reason: 'buffer_overflow' }
122
+ │ │ (WS closes 1008; session is unrecoverable)
123
+ ```
124
+
125
+ When the requested `lastSeq` is older than the oldest seq still in the agent's
126
+ ring buffer, replaying only what remains would silently drop a contiguous gap
127
+ of frames and corrupt the client's NDJSON stream. The agent surfaces this as
128
+ `session_lost` with `reason: 'buffer_overflow'` so the client can map it to
129
+ `exit(-2)` / unrecoverable rather than continuing with a partial stream.
130
+
131
+ ---
132
+
133
+ ## Frame Reference
134
+
135
+ ### Client → Agent
136
+
137
+ #### `spawn`
138
+
139
+ Start a child process inside the pod.
140
+
141
+ ```json
142
+ {
143
+ "type": "spawn",
144
+ "cmd": "claude",
145
+ "args": ["--input-format", "stream-json", "--output-format", "stream-json", "-p"],
146
+ "env": { "CLAUDE_HEADLESS": "1" },
147
+ "cwd": "/workspace",
148
+ "stdin": "pipe"
149
+ }
150
+ ```
151
+
152
+ | Field | Type | Required | Description |
153
+ |---------|-------------------|----------|--------------------------------------------------------------|
154
+ | `cmd` | string | yes | Binary to execute |
155
+ | `args` | string[] | no | Argument list (default `[]`) |
156
+ | `env` | object (strings) | no | Extra env vars merged on top of the agent's env |
157
+ | `cwd` | string | no | Working directory for the child process |
158
+ | `stdin` | string | no | Child stdin mode: `'pipe'` (default), `'inherit'`, `'ignore'`. Use `'pipe'` for `--input-format stream-json` workflows; use `'ignore'` for fire-and-forget `-p` runs. |
159
+
160
+ #### `stdin`
161
+
162
+ Forward a chunk of data into the child's stdin stream. Must be sent **after**
163
+ `spawn` and **before** the child exits. Multiple `stdin` frames are written to
164
+ the child's stdin in the order they are received.
165
+
166
+ ```json
167
+ { "type": "stdin", "data": "{\"prompt\":\"hello\"}\n" }
168
+ ```
169
+
170
+ | Field | Type | Required | Description |
171
+ |--------|--------|----------|----------------------------------------------------------|
172
+ | `data` | string | yes | UTF-8 text to write to child stdin |
173
+
174
+ Sending `stdin` on a connection that has no active session returns an `error`
175
+ frame with message `stdin: no active session (send spawn first)`. Sending a
176
+ frame with a non-string `data` field returns `stdin: data must be a string`.
177
+
178
+ If the child was spawned with `stdin: 'ignore'` or `stdin: 'inherit'`,
179
+ `child.stdin` is `null`; `stdin` frames are **silently dropped** in that case
180
+ (no error is returned) so callers do not need to track the stdin mode.
181
+
182
+ **Backpressure (#3396).** Writes to `child.stdin` are cooperative: when the
183
+ child's stdin buffer reaches its `highWaterMark`, `child.stdin.write()` returns
184
+ `false`. In that case the agent calls `ws.pause()` on the connection,
185
+ deferring further frame delivery to the kernel socket buffer (TCP-level
186
+ backpressure) until the child consumes its buffered input. On the next
187
+ `drain` event from `child.stdin` the agent calls `ws.resume()` and frame
188
+ delivery continues. This is transparent to the client — no frame is lost,
189
+ delayed beyond the kernel socket buffer, or surfaced as an error — but a
190
+ client sending faster than the child can read may observe slower TCP
191
+ acknowledgements during the back-pressured window.
192
+
193
+ #### `stdin_end`
194
+
195
+ Close the write end of the child's stdin pipe (equivalent to EOF). After this
196
+ the child process will see EOF on its stdin, which for
197
+ `--input-format stream-json` causes `claude` to stop reading and begin
198
+ processing the buffered input.
199
+
200
+ ```json
201
+ { "type": "stdin_end" }
202
+ ```
203
+
204
+ Sending `stdin_end` before `spawn` returns an `error` frame. Sending
205
+ additional `stdin` frames after `stdin_end` is idempotent — the underlying
206
+ `stdin.end()` call is a no-op once the stream has already ended.
207
+
208
+ #### `resume`
209
+
210
+ Reconnect to an existing in-flight session after a network blip.
211
+
212
+ ```json
213
+ { "type": "resume", "sessionId": "<uuid>", "lastSeq": 42 }
214
+ ```
215
+
216
+ | Field | Type | Required | Description |
217
+ |-------------|---------|----------|-------------------------------------------------------|
218
+ | `sessionId` | string | yes | The session UUID received in the prior `session_started` frame |
219
+ | `lastSeq` | number | no | Highest `seq` the client has processed (default `0`). Frames with `seq > lastSeq` are replayed. |
220
+
221
+ #### `ping`
222
+
223
+ Client-side heartbeat. Agent replies with `{ type: 'pong' }`.
224
+
225
+ ```json
226
+ { "type": "ping" }
227
+ ```
228
+
229
+ ---
230
+
231
+ ### Agent → Client
232
+
233
+ #### `session_started`
234
+
235
+ Sent immediately after `spawn` is accepted, before any output frames.
236
+ The client must store `sessionId` to send a `resume` frame if it needs to
237
+ reconnect.
238
+
239
+ ```json
240
+ { "type": "session_started", "sessionId": "550e8400-e29b-41d4-a716-446655440000" }
241
+ ```
242
+
243
+ #### `event`
244
+
245
+ One NDJSON line from the child process's stdout, parsed into `payload`. If
246
+ the line is not valid JSON the raw string is forwarded as `payload`.
247
+
248
+ ```json
249
+ { "type": "event", "payload": { ...claude-sdk-event... }, "seq": 1 }
250
+ ```
251
+
252
+ #### `stderr`
253
+
254
+ A chunk of raw text from the child process's stderr stream.
255
+
256
+ ```json
257
+ { "type": "stderr", "data": "some error text\n", "seq": 2 }
258
+ ```
259
+
260
+ The **first** `stderr` frame on any new session is always the sidecar's own
261
+ per-spawn sentinel line, emitted by the agent immediately after the child is
262
+ spawned. Its format is:
263
+
264
+ ```
265
+ [chroxy-pod-agent] spawn cmd=<cmd> args=<truncated-json-args> sessionId=<uuid>
266
+ ```
267
+
268
+ `args` is **truncated to the first 3 elements**. If the full args array has
269
+ more than 3 elements the remainder is replaced with a summary string
270
+ `"...[N more]"`:
271
+
272
+ ```
273
+ args=["-e","console.log(1)","...[2 more]"]
274
+ ```
275
+
276
+ Example sentinel frame (≤ 3 args — shown in full):
277
+
278
+ ```json
279
+ {
280
+ "type": "stderr",
281
+ "data": "[chroxy-pod-agent] spawn cmd=claude args=[\"--input-format\",\"stream-json\"] sessionId=550e8400-e29b-41d4-a716-446655440000\n",
282
+ "seq": 1
283
+ }
284
+ ```
285
+
286
+ Example sentinel frame (> 3 args — remainder elided):
287
+
288
+ ```json
289
+ {
290
+ "type": "stderr",
291
+ "data": "[chroxy-pod-agent] spawn cmd=claude args=[\"--input-format\",\"stream-json\",\"--output-format\",\"...[2 more]\"] sessionId=550e8400-e29b-41d4-a716-446655440000\n",
292
+ "seq": 1
293
+ }
294
+ ```
295
+
296
+ **Security note:** The sentinel is buffered in the agent's ring buffer and
297
+ replayed to reconnecting clients. Callers **must not** pass secret material
298
+ (e.g. `--api-key`, `--password`) as CLI flags — even truncated, the first 3
299
+ args appear in the sentinel line and could surface in `execInEnvironment`'s
300
+ returned `{ stderr }` string or in any consumer that reads `proc.stderr` from
301
+ `streamCliInEnvironment`. Pass secrets via `env` instead (see #3393).
302
+
303
+ This line is intentionally distinct from real child stderr so integration tests
304
+ can assert that the sidecar code — not a shorter path that bypasses the agent —
305
+ handled the spawn. Clients that display stderr to users should filter lines
306
+ matching `/^\[chroxy-pod-agent\] spawn /` if the sentinel is not meaningful in
307
+ context (see #3344).
308
+
309
+ #### `exit`
310
+
311
+ Child process exited. The WS connection is closed by the agent within 50 ms
312
+ of sending this frame.
313
+
314
+ ```json
315
+ { "type": "exit", "code": 0, "seq": 3 }
316
+ ```
317
+
318
+ #### `resumed`
319
+
320
+ Sent in response to a successful `resume`, after any buffered frames have been
321
+ replayed and before any new live frames. This frame has no `seq` (it is
322
+ control, not session output) and signals the client that:
323
+
324
+ - the resume succeeded (gap-free replay was possible),
325
+ - `replayedCount` frames were sent during the catch-up phase,
326
+ - the connection is now in live-forwarding mode.
327
+
328
+ Clients use this frame to reset per-blip retry budgets (see #3348).
329
+
330
+ ```json
331
+ {
332
+ "type": "resumed",
333
+ "sessionId": "550e8400-e29b-41d4-a716-446655440000",
334
+ "lastSeq": 42,
335
+ "replayedCount": 3
336
+ }
337
+ ```
338
+
339
+ #### `session_lost`
340
+
341
+ Sent in response to a `resume` frame when the session is unrecoverable.
342
+
343
+ | `reason` | Meaning |
344
+ |---------------------|------------------------------------------------------------|
345
+ | `unknown_session` | No record of the given `sessionId` (agent restarted, etc.) |
346
+ | `buffer_overflow` | `lastSeq` predates the oldest buffered frame — gap detected |
347
+ | `evicted_by_cap` | Session was forcibly evicted because all slots were active and the hard session cap was hit by a new spawn |
348
+
349
+ For `unknown_session` the connection stays open so the client can open a fresh
350
+ session with `spawn`. For `buffer_overflow` the agent closes the WS with code
351
+ `1008` because continuing on the same WS would still see a partial stream. For
352
+ `evicted_by_cap` the agent closes the WS with code `1001`; the session is
353
+ unrecoverable (the child has been killed).
354
+
355
+ ```json
356
+ {
357
+ "type": "session_lost",
358
+ "sessionId": "550e8400-e29b-41d4-a716-446655440000",
359
+ "reason": "unknown_session"
360
+ }
361
+ ```
362
+
363
+ #### `pong`
364
+
365
+ Response to a client `ping`.
366
+
367
+ ```json
368
+ { "type": "pong" }
369
+ ```
370
+
371
+ #### `error`
372
+
373
+ Protocol or runtime error. There are two categories:
374
+
375
+ **Connection-scoped** errors are emitted before a session is established (e.g.
376
+ auth failures, bad request format) and carry no `seq` field:
377
+
378
+ ```json
379
+ { "type": "error", "message": "spawn: cmd is required" }
380
+ ```
381
+
382
+ **Session-scoped** errors are emitted through the session frame pipeline (via
383
+ `_emitSessionFrame`) and therefore carry a `seq` counter, just like `event` and
384
+ `exit` frames from the same session:
385
+
386
+ ```json
387
+ {
388
+ "type": "error",
389
+ "code": "line_too_long",
390
+ "message": "stdout line exceeded max length (1048576 bytes) — child killed",
391
+ "seq": 3
392
+ }
393
+ ```
394
+
395
+ When a child process stdout line exceeds the NDJSON line length cap (see
396
+ [NDJSON Line Length Limit](#ndjson-line-length-limit) below), the error frame
397
+ includes an additional `code` field as shown above.
398
+
399
+ The child is killed and the WS is closed with code `1008` within 50 ms of this
400
+ frame. No `exit` frame follows — the `error` frame is the terminal event for
401
+ the session.
402
+
403
+ When a wedged child accepts stdin but never reads from it (so no `'drain'`
404
+ event ever fires after a backpressured `child.stdin.write()` returned `false`),
405
+ the agent emits a session-scoped error frame with `code: 'stdin_drain_stalled'`
406
+ once `CHROXY_AGENT_STDIN_DRAIN_TIMEOUT_MS` (default 30 s) elapses:
407
+
408
+ ```json
409
+ {
410
+ "type": "error",
411
+ "code": "stdin_drain_stalled",
412
+ "message": "child stdin did not drain within 30000ms — child killed",
413
+ "seq": 7
414
+ }
415
+ ```
416
+
417
+ The child is killed and the WS is closed with code `1011` (server-side
418
+ condition) right after this frame. As with `line_too_long`, no `exit` frame
419
+ follows — the error frame is the terminal event for the session, and the close
420
+ code distinguishes it from a normal idle eviction (`1001`).
421
+
422
+ ---
423
+
424
+ ## One Active Client
425
+
426
+ The agent enforces a single active WS client at a time. A second connection
427
+ attempt is accepted at the TCP/WS level (so the handshake completes and auth
428
+ is validated) but is then immediately rejected with:
429
+
430
+ ```json
431
+ { "type": "error", "message": "another client is already connected" }
432
+ ```
433
+
434
+ followed by `ws.close(1008)`. The first connection is unaffected.
435
+
436
+ ---
437
+
438
+ ## One Spawn Per Connection
439
+
440
+ Each connection may run **one** child process at a time. A second `spawn`
441
+ frame on a connection that already has a running child is rejected with:
442
+
443
+ ```json
444
+ { "type": "error", "message": "spawn: child already running" }
445
+ ```
446
+
447
+ The first child continues unaffected. K8sBackend (#3320) is the sole consumer
448
+ and is expected to open one connection per session; multi-spawn semantics are
449
+ not part of this protocol.
450
+
451
+ ---
452
+
453
+ ## Session Lifecycle and Resume Semantics
454
+
455
+ When a `spawn` is accepted the agent assigns a UUID `sessionId` and begins
456
+ buffering output frames (up to `CHROXY_AGENT_BUFFER_SIZE`, default 1000).
457
+ **Output frames** (`event`, `stderr`, `exit`) carry a monotonically increasing
458
+ `seq` number scoped to the session. **Control frames** (`session_started`,
459
+ `resumed`, `session_lost`, `error`, `pong`) do **not** carry a `seq` — they
460
+ are out-of-band acknowledgements, not replayable session output.
461
+
462
+ When the WS connection closes — for any reason other than a natural child
463
+ exit — the **child process continues running** inside the pod. This allows
464
+ a reconnecting client to resume the session and receive replayed output.
465
+
466
+ When the client reconnects it sends `{ type: 'resume', sessionId, lastSeq }`.
467
+ The agent then chooses one of:
468
+
469
+ 1. **Successful resume** — replay any buffered frames with `seq > lastSeq`
470
+ followed by a single `{ type: 'resumed', sessionId, lastSeq, replayedCount }`
471
+ frame, then continue live forwarding.
472
+ 2. **Unknown session** — `{ type: 'session_lost', reason: 'unknown_session' }`.
473
+ 3. **Resume gap** — `{ type: 'session_lost', reason: 'buffer_overflow' }` when
474
+ the requested `lastSeq` predates the oldest buffered seq. Followed by
475
+ `ws.close(1008)`.
476
+
477
+ If the agent has no record of the `sessionId` (e.g. the agent process
478
+ restarted), it sends `{ type: 'session_lost', sessionId, reason: 'unknown_session' }`.
479
+ The child process is gone in this case; the session is unrecoverable.
480
+
481
+ ### Idle Resume Window
482
+
483
+ When the WS connection drops with an active session, the agent starts an
484
+ **idle-resume timer** (default 60 s, configurable via
485
+ `CHROXY_AGENT_RESUME_TIMEOUT_MS`). If the client sends a valid `resume` frame
486
+ before the timer fires, the timer is cancelled and normal live-forwarding
487
+ resumes. If the timer fires first, the agent:
488
+
489
+ 1. Closes the child's stdin (polite EOF) and waits up to
490
+ `CHROXY_AGENT_STDIN_CLOSE_GRACE_MS` (default 500 ms) for the child to exit
491
+ on its own.
492
+ 2. Sends `SIGTERM` to the child (with a 5 s `SIGKILL` escalation).
493
+ 3. Deletes the session from `_sessions`.
494
+
495
+ A subsequent `resume` for the evicted session receives
496
+ `session_lost(unknown_session)` — the same response as for a session that was
497
+ never created. The eviction reason is **not** exposed to the client; consumers
498
+ should treat both cases identically (unrecoverable, open a fresh session with
499
+ `spawn`).
500
+
501
+ The resume window is a best-effort safety net against **short** network blips.
502
+ It is not intended as durable session persistence.
503
+
504
+ ### Hard Session Cap
505
+
506
+ The agent limits concurrent sessions to `CHROXY_AGENT_MAX_SESSIONS` (default
507
+ 8). When a new `spawn` would exceed the cap, the agent evicts the idle session
508
+ (no active WS) with the oldest `lastActiveAt` timestamp before inserting the
509
+ new one. If all sessions are active, the globally oldest session is evicted:
510
+ the agent sends `{ type: 'session_lost', sessionId, reason: 'evicted_by_cap' }`
511
+ to the live consumer before closing the WS with code `1001`.
512
+
513
+ `K8sBackend` maps `session_lost` to `exit(-2)` regardless of reason, so the
514
+ caller can distinguish a cap eviction (session-loss semantics) from a
515
+ pre-session connection failure (which maps to `exit(-1)`).
516
+
517
+ This cap is defense-in-depth against a buggy K8sBackend that reconnects
518
+ repeatedly without resuming.
519
+
520
+ ### PID 1 Reaping Limitation
521
+
522
+ This resume mechanism survives **network blips** (transient WS disconnects)
523
+ only. It does **not** survive agent process restarts. If the pod is evicted,
524
+ OOM-killed, or the `chroxy-pod-agent` process itself crashes, the in-pod child
525
+ is reaped by PID 1 (the container init process) and all session state is lost.
526
+ The reconnecting K8sBackend will receive `session_lost` and surface `exit(-2)`
527
+ to the caller.
528
+
529
+ True cross-restart session persistence (disk-backed buffer, NATS, etc.) is
530
+ deferred to a later phase.
531
+
532
+ ---
533
+
534
+ ## Orphan Prevention
535
+
536
+ When the child exits naturally the agent sends an `exit` frame and closes the
537
+ WS within 50 ms. If the agent itself is shut down (`SIGTERM`/`SIGINT`), all
538
+ running children are sent `SIGTERM` with a 5 s `SIGKILL` escalation.
539
+
540
+ In contrast to the pre-#3321 behaviour, a WS disconnect alone **no longer
541
+ kills the child** — it keeps running to support resume.
542
+
543
+ ---
544
+
545
+ ## Stream Ordering Guarantees
546
+
547
+ Frames produced by the agent have the following ordering properties:
548
+
549
+ - **Same-stream order is preserved.** All `event` frames arrive in the order
550
+ the child wrote NDJSON lines to stdout. All `stderr` frames arrive in the
551
+ order the child wrote bytes to stderr.
552
+ - **Cross-stream order is NOT preserved.** stdout is line-buffered (via
553
+ `readline`), so an `event` frame is only emitted on a newline. stderr is
554
+ forwarded as raw `data` chunks the moment they arrive. This means a stderr
555
+ byte written *before* a stdout newline can appear *after* the resulting
556
+ `event` frame on the wire — and vice-versa, a partial stdout line that
557
+ finally completes can flush *after* later stderr writes.
558
+ - **`seq` is cross-stream.** The `seq` counter increments for every emitted
559
+ frame regardless of stream (event/stderr/exit), so it provides a total
560
+ ordering of all output frames within a session.
561
+
562
+ Consumers that need to interleave the two streams (e.g. for log display) must
563
+ buffer them locally and reconcile by `seq` or timestamp — the wire order of
564
+ `event` and `stderr` frames is not authoritative.
565
+
566
+ The terminal `exit` frame is always the last frame on the connection, after
567
+ which the WS close handshake follows within 50 ms.
568
+
569
+ ---
570
+
571
+ ## Ping / Pong Keepalive
572
+
573
+ The agent sends a WebSocket `ping` frame (not a `{ type: 'ping' }` JSON frame)
574
+ to the active client every 30 seconds. If no `pong` is received before the
575
+ next tick the connection is terminated with `ws.terminate()`.
576
+
577
+ Clients may also send `{ type: 'ping' }` JSON frames at any time; the agent
578
+ replies with `{ type: 'pong' }`.
579
+
580
+ ---
581
+
582
+ ## Error Cases
583
+
584
+ | Condition | Agent behaviour |
585
+ |----------------------------------------------|------------------------------------------------------------------|
586
+ | No `Authorization` header | `401` socket end, no WS frame |
587
+ | Wrong token | `401` socket end, no WS frame |
588
+ | `CHROXY_AGENT_TOKEN` not set | `401` socket end for all upgrades + startup warn |
589
+ | Second WS connection | Auth validated, then `error` frame + close `1008` |
590
+ | `spawn` without `cmd` | `error` frame, connection stays open |
591
+ | `spawn` while child already running | `error` frame, first child unaffected |
592
+ | Unknown message type | `error` frame, connection stays open |
593
+ | Child process spawn failure | `error` frame, connection stays open |
594
+ | Invalid JSON frame from client | `error` frame, connection stays open |
595
+ | `resume` with unknown sessionId | `session_lost` frame (`reason: unknown_session`), connection stays open |
596
+ | `resume` with stale lastSeq (gap) | `session_lost` frame (`reason: buffer_overflow`) + close `1008` |
597
+ | `resume` while session has active client | `error` frame + close `1008` |
598
+ | stdout line exceeds `CHROXY_AGENT_MAX_LINE_BYTES` | `error` frame (`code: line_too_long`) + child SIGTERM + close `1008` |
599
+ | child stdin does not drain within `CHROXY_AGENT_STDIN_DRAIN_TIMEOUT_MS` | `error` frame (`code: stdin_drain_stalled`) + child SIGTERM + close `1011` |
600
+ | active session evicted by hard session cap | `session_lost` frame (`reason: evicted_by_cap`) + child SIGTERM + close `1001` |
601
+ | `stdin` before `spawn` | `error` frame (`stdin: no active session (send spawn first)`), connection stays open |
602
+ | `stdin_end` before `spawn` | `error` frame (`stdin_end: no active session (send spawn first)`), connection stays open |
603
+ | `stdin` with non-string `data` | `error` frame (`stdin: data must be a string`), connection stays open |
604
+ | `stdin` when child stdin is not piped | silently dropped (no error frame) |
605
+
606
+ ---
607
+
608
+ ## NDJSON Line Length Limit
609
+
610
+ Node's `readline` buffers raw bytes until a newline arrives. A runaway tool
611
+ result or streaming bug in the child process that never writes a newline would
612
+ grow that buffer without bound and eventually OOM the pod.
613
+
614
+ To prevent this the agent inserts a `LineLimitTransform` between `child.stdout`
615
+ and `readline`. The transform counts bytes per line (resetting on each `\n`);
616
+ if a line exceeds the cap before a newline arrives it:
617
+
618
+ 1. Emits `{ type: 'error', code: 'line_too_long', message: '...', seq: N }`.
619
+ 2. Sends `SIGTERM` to the child (with a `SIGKILL` escalation after 5 s).
620
+ 3. Closes the WS with code `1008` within 50 ms.
621
+
622
+ **Default cap:** 1 MiB (`1 048 576` bytes) — far above any normal SDK event.
623
+
624
+ **Override:** set `CHROXY_AGENT_MAX_LINE_BYTES` in the pod environment (parsed
625
+ as a base-10 integer; non-positive / NaN values fall back to the 1 MiB
626
+ default).
627
+
628
+ ---
629
+
630
+ ## Polite Shutdown Grace
631
+
632
+ When the agent terminates a child process (idle-resume eviction, hard
633
+ session-cap eviction, or `agent.close()` shutdown) it closes the child's
634
+ stdin first so that CLIs which exit cleanly on EOF — including `claude
635
+ --input-format stream-json` — can shut down without signal handling. After
636
+ closing stdin the agent waits a short grace period before escalating to
637
+ `SIGTERM`, then a longer grace before `SIGKILL`.
638
+
639
+ **Default stdin-close grace:** 500 ms.
640
+
641
+ **Override:** set `CHROXY_AGENT_STDIN_CLOSE_GRACE_MS` in the pod environment
642
+ (parsed as a base-10 integer; NaN / negative values fall back to the 500 ms
643
+ default). Setting `0` is allowed: the agent still closes the child's stdin
644
+ (polite EOF), but `SIGTERM` follows synchronously rather than after a grace
645
+ delay — useful for deployments where the child is known not to honour stdin
646
+ EOF and the grace would just be wasted shutdown latency.
647
+
648
+ ---
649
+
650
+ ## claude-code Version Pinning
651
+
652
+ The `Dockerfile` installs `@anthropic-ai/claude-code` at a fixed version via
653
+ the `CLAUDE_CODE_VERSION` build ARG (default: `2.1.128`).
654
+
655
+ **Override at build time:**
656
+ ```sh
657
+ docker build --build-arg CLAUDE_CODE_VERSION=2.2.0 .
658
+ ```
659
+
660
+ **Bump cadence:** update the ARG default in `Dockerfile` via a regular PR
661
+ whenever you need a newer release. There is no automated renovation yet — the
662
+ upgrade is intentionally manual so that breaking changes in claude-code surface
663
+ at review time, not silently in CI.
664
+
665
+ ---
666
+
667
+ ## Future Work
668
+
669
+ **K8sBackend stdin wiring (#3336)**
670
+
671
+ This PR adds the `stdin` / `stdin_end` frame types to the agent and documents
672
+ the protocol. The `K8sBackend` client-side plumbing — reading the prompt from
673
+ the SDK session and forwarding it as `stdin` frames — is tracked separately in
674
+ issue #3336.
675
+
676
+ **Disk-backed session buffer**
677
+
678
+ The current in-memory ring buffer is lost when the agent process exits. A
679
+ disk-backed buffer (e.g. append-only log file per session) would allow
680
+ recovery from agent restarts, not just network blips.
681
+
682
+ **Multi-client session**
683
+
684
+ The single-client policy is intentional for Phase 1. Future work could allow
685
+ multiple observers to attach to a session (e.g. a monitoring dashboard and the
686
+ active K8sBackend).
687
+
688
+ **Cross-Pod session migration**
689
+
690
+ A session that survives pod rescheduling would require distributed session
691
+ state (e.g. Redis or a shared volume). Not planned in the near term.