@chroxy/server 0.11.0 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +69 -5
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -1,7 +1,12 @@
1
1
  import { performance } from 'node:perf_hooks'
2
2
  import { toShortModelId } from './models.js'
3
3
  import { createLogger } from './logger.js'
4
+ import { busyStateOf } from './session-busy-state.js'
4
5
  import { buildPermissionRequestMessage, MAX_SANE_DURATION_MS } from '@chroxy/protocol'
6
+ import { boundedNonNegInt, boundedThinkingPrecedes, buildMessageWire, buildErrorWire } from './message-wire.js'
7
+ import { turnOutcomeField } from './turn-outcome.js'
8
+ import { permissionScope } from './permission-scope.js'
9
+ import { buildThinkingLevelChanged } from './thinking-level-wire.js'
5
10
 
6
11
  const log = createLogger('event-normalizer')
7
12
 
@@ -35,118 +40,6 @@ const MAX_DELTA_TOTAL_BYTES = 2 * 1024 * 1024 // 2 MB across all streams
35
40
  const DEFLATE_FLUSH_INTERVAL_MS = 25 // any deflate subscriber, multi-client
36
41
  const DEFLATE_SINGLE_CLIENT_FLUSH_INTERVAL_MS = 16 // any deflate subscriber, single client
37
42
 
38
- /**
39
- * #6941 review (Copilot) — coerce+bound a footer-stat numeric field
40
- * (`thinkingDurationMs` / `thinkingTokens`) before forwarding it onto the
41
- * wire. Mirrors the protocol schema's
42
- * `z.number().int().nonnegative().finite()[.max(ceiling)]`: floors a stray
43
- * fractional value (matches store-core's `parseFiniteNonNegIntField`, which
44
- * re-guards the same field client-side) and OMITS — never clamps — when the
45
- * value is negative, non-finite, or exceeds an optional ceiling. A clock
46
- * jump / suspend producing a bogus multi-day duration should vanish from the
47
- * footer, not render as an incorrect exact-ceiling number.
48
- *
49
- * @param {*} value - candidate value straight off the session event.
50
- * @param {{ max?: number }} [opts] - optional upper bound (inclusive).
51
- * @returns {number|undefined}
52
- */
53
- function boundedNonNegInt(value, { max } = {}) {
54
- if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return undefined
55
- const floored = Math.floor(value)
56
- if (typeof max === 'number' && floored > max) return undefined
57
- return floored
58
- }
59
-
60
- /**
61
- * #6973 (agent-review on #6970) — coerce+bound `compactMetadata`'s
62
- * `preTokens`/`postTokens`/`durationMs` sub-fields before forwarding onto
63
- * the wire, same defense-in-depth as `boundedNonNegInt` above (the #6941
64
- * thinkingDurationMs pattern) applied field-by-field. Unlike
65
- * thinkingDurationMs/thinkingTokens (fully optional on the wire), these
66
- * three sub-fields are `.nullable()` — not `.optional()` — on
67
- * `ServerCompactMetadataSchema`, so the shape always carries all three keys;
68
- * an out-of-range/malformed value is coerced to `null` here rather than
69
- * dropped, matching `parseCompactBoundaryMeta`'s own "null for
70
- * missing/malformed" convention (claude-stream-parser.js) so a client always
71
- * gets the stable shape to pattern-match against. `durationMs` is
72
- * additionally bounded by `MAX_SANE_DURATION_MS` (the same clock-jump guard
73
- * as `thinkingDurationMs`); `preTokens`/`postTokens` have no documented
74
- * ceiling — legitimate context windows run into the millions of tokens — so
75
- * only non-negative-integer coercion applies.
76
- *
77
- * @param {{trigger?: *, preTokens?: *, postTokens?: *, durationMs?: *}} meta
78
- * @returns {{trigger: 'manual'|'auto', preTokens: number|null, postTokens: number|null, durationMs: number|null}}
79
- */
80
- function boundedCompactMetadata(meta) {
81
- const boundedOrNull = (value, opts) => {
82
- const bounded = boundedNonNegInt(value, opts)
83
- return bounded === undefined ? null : bounded
84
- }
85
- return {
86
- trigger: meta.trigger === 'manual' ? 'manual' : 'auto',
87
- preTokens: boundedOrNull(meta.preTokens),
88
- postTokens: boundedOrNull(meta.postTokens),
89
- durationMs: boundedOrNull(meta.durationMs, { max: MAX_SANE_DURATION_MS }),
90
- }
91
- }
92
-
93
- // #6845: wire-boundary caps for the MCP-prompt expansion marker. server/prompt
94
- // mirror ServerMcpPromptExpansionSchema's 256-char names; `text` mirrors its
95
- // 8192 ceiling. byok-session already caps the display copy (4000 + a
96
- // truncation marker); this is the defense-in-depth re-bound at the serialization
97
- // choke point (same posture as boundedCompactMetadata) so a wire-bypassing or
98
- // malformed producer can't push an unbounded payload onto clients.
99
- const MCP_PROMPT_EXPANSION_NAME_CAP = 256
100
- const MCP_PROMPT_EXPANSION_TEXT_CAP = 8192
101
-
102
- // Thread-2/honesty-nit fix (post-#6845 review): the suffix now says the FULL
103
- // text still reached the model, matching byok-session.js's display-cap suffix
104
- // and store-core's client-side re-bound suffix — a reader who only sees the
105
- // truncated marker (mobile, System tab) must not conclude the model saw less
106
- // than it did. Sliced-length arithmetic below subtracts THIS string's actual
107
- // length rather than a hardcoded magic number, so the total (slice + suffix)
108
- // never exceeds the cap even if the wording changes again later.
109
- const MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX = '\n…(truncated for display; full text sent to the model)'
110
-
111
- /**
112
- * #6845 — coerce+bound the `mcpPromptExpansion` marker fields before forwarding
113
- * onto the wire. Requires a string `text` (the marker is meaningless without
114
- * the injected content) — returns `null` when `text` is not a string so the
115
- * caller skips attaching `subtype`/`mcpPromptExpansion` entirely rather than
116
- * forwarding a marker with blank/coerced content. This mirrors store-core's
117
- * `parseMcpPromptExpansion` reject-on-non-string-text contract (post-#6845
118
- * review thread 1 — the two layers previously disagreed: this function used to
119
- * silently stringify a non-string `text`, while the client rejected the whole
120
- * marker; they now agree on reject).
121
- *
122
- * `server`/`prompt` are cosmetic provenance labels (not content), so they stay
123
- * on the more forgiving "coerce" side: a non-string value becomes `''` rather
124
- * than failing the whole marker, then caps at 256. `text` caps at 8192,
125
- * appending {@link MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX} when it overflows so
126
- * the client never silently drops content; `truncated` stays true if EITHER
127
- * the producer flagged it or this re-bound truncated.
128
- *
129
- * @param {{server?: *, prompt?: *, text?: *, truncated?: *}} meta
130
- * @returns {{server: string, prompt: string, text: string, truncated: boolean} | null}
131
- */
132
- function boundedMcpPromptExpansion(meta) {
133
- if (typeof meta?.text !== 'string') return null
134
- const asString = (v) => (typeof v === 'string' ? v : '')
135
- const cap = (s, n) => (s.length > n ? s.slice(0, n) : s)
136
- const rawText = meta.text
137
- const overflow = rawText.length > MCP_PROMPT_EXPANSION_TEXT_CAP
138
- const sliceLen = Math.max(0, MCP_PROMPT_EXPANSION_TEXT_CAP - MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX.length)
139
- const text = overflow
140
- ? `${cap(rawText, sliceLen)}${MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX}`
141
- : rawText
142
- return {
143
- server: cap(asString(meta?.server), MCP_PROMPT_EXPANSION_NAME_CAP),
144
- prompt: cap(asString(meta?.prompt), MCP_PROMPT_EXPANSION_NAME_CAP),
145
- text,
146
- truncated: meta?.truncated === true || overflow,
147
- }
148
- }
149
-
150
43
  /**
151
44
  * Declarative event-to-WS-message mapping.
152
45
  *
@@ -224,10 +117,33 @@ Object.assign(EVENT_MAP, {
224
117
  mode: entry.session.permissionMode || 'approve',
225
118
  },
226
119
  })
120
+ // #7792: the creating client's replay (ws-history.js `sendSessionInfo`)
121
+ // runs at `session_switched` time, before `thread/start` has answered —
122
+ // so it can only ever replay whatever was already known (`default` for
123
+ // a fresh codex session). This `ready` push is the only moment that
124
+ // can carry the booted effort to the client that created the session.
125
+ // Built by the same `buildThinkingLevelChanged` as ws-history's replay
126
+ // (#8700), so the two paths can never disagree: a provider whose
127
+ // `thinkingLevel` getter is `undefined` (the BaseSession default) sends
128
+ // nothing here either, rather than a bogus 'default' that would stomp a
129
+ // client that already has the right value.
130
+ const thinkingLevelMsg = buildThinkingLevelChanged(entry.session)
131
+ if (thinkingLevelMsg) messages.push({ msg: thinkingLevelMsg })
227
132
  }
228
133
  return { messages }
229
134
  },
230
135
 
136
+ // #8700: the SESSION changed or learned its level — a model switch dropped a
137
+ // level the new model does not offer, or Claude Code reported the effort it
138
+ // applied at the start of a turn. The frame is rebuilt from the session's
139
+ // current state rather than from `data`, so it says exactly what the next
140
+ // reconnect replay will say; `data` carries only the log fields
141
+ // session-manager prints.
142
+ thinking_level_changed: (_data, ctx) => {
143
+ const msg = buildThinkingLevelChanged(ctx.getSessionEntry?.()?.session)
144
+ return msg ? { messages: [{ msg }] } : null
145
+ },
146
+
231
147
  // #5431: claude-tui's idle transcript re-scan saw the outstanding-work set
232
148
  // change (a task-notification landed / a wakeup fired while no turn was
233
149
  // running). Re-emit `claude_ready` with the fresh snapshot — the session is
@@ -258,8 +174,19 @@ Object.assign(EVENT_MAP, {
258
174
  // state is already owned by the response stream / the client's 'pending'
259
175
  // sentinel, so a per-thinking-block session_list refresh would be noise.
260
176
  if (data.thinking) {
177
+ // #8518: where this block belongs relative to a tool row / the answer, for a
178
+ // block that reached the wire after them. Re-bounded here like every other
179
+ // optional field; the history records the same value (session-message-history).
180
+ const thinkingPrecedes = boundedThinkingPrecedes(data.thinkingPrecedes)
261
181
  return {
262
- messages: [{ msg: { type: 'stream_start', messageId: data.messageId, thinking: true } }],
182
+ messages: [{
183
+ msg: {
184
+ type: 'stream_start',
185
+ messageId: data.messageId,
186
+ thinking: true,
187
+ ...(thinkingPrecedes ? { thinkingPrecedes } : {}),
188
+ },
189
+ }],
263
190
  }
264
191
  }
265
192
  const messages = [
@@ -346,46 +273,7 @@ Object.assign(EVENT_MAP, {
346
273
  }
347
274
  },
348
275
 
349
- message: (data, _ctx) => {
350
- const msg = {
351
- type: 'message',
352
- messageType: data.type,
353
- content: data.content,
354
- tool: data.tool,
355
- options: data.options,
356
- timestamp: data.timestamp,
357
- }
358
- // #6768: forward the structured compaction-boundary marker fields.
359
- // Gated strictly on `messageType === 'system'` + the compact_boundary
360
- // subtype (mirrors the `code`/`attemptedResumeId` gating pattern in the
361
- // `error:` normalizer below) so a buggy producer can't sneak
362
- // `compactMetadata` onto an unrelated message type. #6973: the numeric
363
- // sub-fields are bounded (see `boundedCompactMetadata`) rather than
364
- // forwarded raw, so a malformed/out-of-range value from the SDK/CLI
365
- // can't reach the wire unbounded.
366
- if (data.type === 'system' && data.subtype === 'compact_boundary' && data.compactMetadata) {
367
- msg.subtype = data.subtype
368
- msg.compactMetadata = boundedCompactMetadata(data.compactMetadata)
369
- }
370
- // #6845: forward the MCP-prompt expansion marker (the honesty surface for a
371
- // server-controlled `/mcp__server__prompt` expansion injected as the user
372
- // turn). Gated identically to compact_boundary — `messageType: 'system'` +
373
- // the `mcp_prompt_expansion` subtype + a present payload — and re-bounded
374
- // here so a malformed producer can't reach the wire unbounded. Unlike
375
- // compact_boundary, `boundedMcpPromptExpansion` can return `null` (a
376
- // non-string `text` — see its doc comment), in which case neither
377
- // `subtype` nor `mcpPromptExpansion` is attached: the envelope falls back
378
- // to a plain system message rather than claiming a structured marker it
379
- // can't honestly populate.
380
- if (data.type === 'system' && data.subtype === 'mcp_prompt_expansion' && data.mcpPromptExpansion) {
381
- const bounded = boundedMcpPromptExpansion(data.mcpPromptExpansion)
382
- if (bounded) {
383
- msg.subtype = data.subtype
384
- msg.mcpPromptExpansion = bounded
385
- }
386
- }
387
- return { messages: [{ msg }] }
388
- },
276
+ message: (data, _ctx) => ({ messages: [{ msg: buildMessageWire(data) }] }),
389
277
 
390
278
  tool_start: (data) => {
391
279
  const msg = { type: 'tool_start', messageId: data.messageId, toolUseId: data.toolUseId, tool: data.tool, input: data.input }
@@ -418,6 +306,22 @@ Object.assign(EVENT_MAP, {
418
306
  // codex mcpToolCall / orphan-sweep result would render plain live but
419
307
  // error-styled after a history replay (which sends the entry raw).
420
308
  if (typeof data.isError === 'boolean') msg.isError = data.isError
309
+ // #7376: the tool was cut off because its TURN was terminated (permission-
310
+ // mode switch, Stop, crash, watchdog), not because it failed. Forwarded on
311
+ // the live wire for the same reason as `isError` above -- the persisted
312
+ // history entry carries it (session-message-history.js) so a replay agrees.
313
+ if (typeof data.terminatedReason === 'string') msg.terminatedReason = data.terminatedReason
314
+ // #7346/#8135 (review): forward the finalized tool input — cli-session.js
315
+ // / sdk-session.js attach it via tool-result.js's emitToolResults (already
316
+ // sanitized + size-capped at capture, base-session.js's _recordToolInput).
317
+ // This normalizer is the LIVE-broadcast choke point; without this the new
318
+ // field never left the server on the live path (only the persisted-history
319
+ // replay, which forwards `tool_start` entries raw, delivered it) — the
320
+ // store-core handleToolResult fold and the ServerToolResultSchema field
321
+ // were otherwise dead on the live wire. Undefined (BYOK, and any tool that
322
+ // never resolved a tracked input) is omitted, same as every optional field
323
+ // here.
324
+ if (data.input !== undefined) msg.input = data.input
421
325
  return { messages: [{ msg }] }
422
326
  },
423
327
 
@@ -486,16 +390,27 @@ Object.assign(EVENT_MAP, {
486
390
  // path. Also pushes a session_list side effect so the SessionInfo
487
391
  // entry's `pendingBackgroundShells` slot refreshes for clients that
488
392
  // render off the list rather than subscribing to the event directly.
489
- background_work_changed: (data, ctx) => ({
490
- messages: [{
491
- msg: {
492
- type: 'background_work_changed',
493
- sessionId: ctx.sessionId,
494
- pending: Array.isArray(data?.pending) ? data.pending : [],
495
- },
496
- }],
497
- sideEffects: [{ type: 'session_list' }],
498
- }),
393
+ //
394
+ // #8302: also carries WHY the session is busy right now (`busyReason`) and the
395
+ // tracker's shell count, read live off the session at emit time. The `pending`
396
+ // list alone cannot say it: it hides advisory-quiesced shells that still hold
397
+ // the session busy, so `pending: []` next to a busy session was ambiguous. The
398
+ // fields are OMITTED (not null) when the session cannot be resolved — null
399
+ // means "idle", and "unknown" must not read as that.
400
+ background_work_changed: (data, ctx) => {
401
+ const session = ctx?.getSessionEntry?.()?.session
402
+ return {
403
+ messages: [{
404
+ msg: {
405
+ type: 'background_work_changed',
406
+ sessionId: ctx.sessionId,
407
+ pending: Array.isArray(data?.pending) ? data.pending : [],
408
+ ...(session ? busyStateOf(session) : {}),
409
+ },
410
+ }],
411
+ sideEffects: [{ type: 'session_list' }],
412
+ }
413
+ },
499
414
 
500
415
  // #5160: Control Room activity tree. The ActivityRegistry (owned by
501
416
  // BaseSession) maps the existing in-flight signals (tool_start /
@@ -698,6 +613,13 @@ Object.assign(EVENT_MAP, {
698
613
  // session emitted one — providers with no occupancy signal keep
699
614
  // the field off the wire so clients render their honest dash state.
700
615
  ...(data.contextOccupancy ? { contextOccupancy: data.contextOccupancy } : {}),
616
+ // #7326: how the turn ended (completed / truncated / refused /
617
+ // stopped), when the provider said. Absent = unknown, which clients
618
+ // render as nothing; an unrecognised value never reaches the wire.
619
+ ...turnOutcomeField(data.turnOutcome),
620
+ // The marker's identity (see BaseSession.emit): the replayed history
621
+ // entry carries the same value.
622
+ ...(Number.isFinite(data.timestamp) ? { timestamp: data.timestamp } : {}),
701
623
  },
702
624
  },
703
625
  { msg: { type: 'agent_idle' } },
@@ -719,6 +641,10 @@ Object.assign(EVENT_MAP, {
719
641
  // breakdown for the dashboard / app badge). Subscription-only
720
642
  // providers (claude-tui) emit `result` without a numeric `cost` so
721
643
  // their session_usage never fires and `cumulativeUsage` stays zero.
644
+ session_status: (data, ctx) => ({
645
+ messages: [{ msg: { type: 'session_status', sessionId: ctx.sessionId, declaredStatus: data.declaredStatus } }],
646
+ }),
647
+
722
648
  session_usage: (data) => ({
723
649
  messages: [{ msg: { type: 'session_usage', cumulativeUsage: data.cumulativeUsage } }],
724
650
  }),
@@ -755,6 +681,16 @@ Object.assign(EVENT_MAP, {
755
681
  description: data.description,
756
682
  input: data.input,
757
683
  remainingMs: data.remainingMs,
684
+ // #7968: the permission-floor verdict permission-manager.js computed
685
+ // (protectedTarget / isFlooredTarget) for this prompt. Coerced to a
686
+ // real boolean, and FAIL-CLOSED: only an explicit `false` goes out as
687
+ // `false`. A missing or non-boolean value means the emitter stated no
688
+ // verdict, and `false` is the one value a consumer (#7854's
689
+ // agent-control) reads as clearance to `allow` unattended — so
690
+ // "unknown" must become `true` here, never `false`.
691
+ floored: data.floored !== false,
692
+ explicitConsent: data.explicitConsent,
693
+ nonDelegable: data.nonDelegable,
758
694
  }),
759
695
  }],
760
696
  registrations: [{ map: 'permission', key: data.requestId, value: ctx.sessionId }],
@@ -776,6 +712,24 @@ Object.assign(EVENT_MAP, {
776
712
  }),
777
713
 
778
714
  permission_expired: (data, ctx) => ({
715
+ // #7379: retiring the card in the clients is only half of it — the daemon's
716
+ // own pending entry has to go too, or `resendPendingPermissions` hands the
717
+ // dead prompt to the next client that connects. Carried as an effect rather
718
+ // than wired at the two event-subscription sites because those are separate
719
+ // code paths (multi-session and legacy-CLI) and wiring one is how this class
720
+ // of bug happens; the executor runs on both.
721
+ //
722
+ // AFTER-effect, not a side effect, and the distinction is load-bearing:
723
+ // releasing runs ws-permissions' shared cleanup() -> tearDownRoute ->
724
+ // WsServer._unregisterPermissionRoute, which UNSUBSCRIBES every client whose
725
+ // subscription to this session was permission-induced and who is not
726
+ // actively viewing it (the #4798 "view A, get prompted for A, switch to B"
727
+ // flow). broadcastToSession's recipient filter is `active || subscribed`, so
728
+ // releasing first drops exactly the clients that still need to hear the
729
+ // prompt is dead — their card would keep a live Allow button until the
730
+ // client-side expiry, which is the bug this whole change exists to remove.
731
+ // Tell the clients first, then release.
732
+ afterEffects: [{ type: 'release_permission', requestId: data?.requestId }],
779
733
  messages: [{
780
734
  msg: {
781
735
  type: 'permission_expired',
@@ -819,6 +773,13 @@ Object.assign(EVENT_MAP, {
819
773
  type: 'permission_resolved',
820
774
  requestId: data.requestId,
821
775
  decision: data.decision,
776
+ // #8374: WHY it was resolved. A Stop resolves a pending prompt as a deny
777
+ // with `reason: 'stopped'`; without the reason the clients cannot tell
778
+ // that from the user pressing Deny, and the card reads "Denied" for a
779
+ // tool nobody refused.
780
+ ...(typeof data.reason === 'string' && data.reason ? { reason: data.reason } : {}),
781
+ // #8517: "Allow for Session" -- the decision above stays a plain `allow`.
782
+ ...(permissionScope(data.decision, data.scope) ? { scope: 'session' } : {}),
822
783
  sessionId: ctx.sessionId,
823
784
  },
824
785
  })
@@ -834,80 +795,27 @@ Object.assign(EVENT_MAP, {
834
795
  // normalizer never saw it; widening the gate would now have emitted
835
796
  // a malformed broadcast if we kept the unconditional messages entry.
836
797
  out.registrations = [{ map: 'question', key: data.toolUseId, action: 'delete' }]
798
+ // #8470: the one exception. A question a NEWER one replaced was not
799
+ // answered by anyone, so no round-trip is coming to dismiss its card on any
800
+ // client: say so, keyed by the question's `toolUseId`. Every other reason
801
+ // (answered / timeout / aborted / cleared) still emits nothing here.
802
+ if (data.reason === 'superseded') {
803
+ out.messages.push({
804
+ msg: {
805
+ type: 'permission_resolved',
806
+ toolUseId: data.toolUseId,
807
+ decision: 'deny',
808
+ reason: 'superseded',
809
+ sessionId: ctx.sessionId,
810
+ },
811
+ })
812
+ }
837
813
  }
838
814
  return out
839
815
  },
840
816
 
841
- error: (data) => {
842
- const msg = {
843
- type: 'message',
844
- messageType: 'error',
845
- content: data.message,
846
- timestamp: Date.now(),
847
- }
848
- if (data.code) msg.code = data.code
849
- // #4947: forward `attemptedResumeId` when CliSession's resume-failure
850
- // path tagged the error envelope (see cli-session.js
851
- // `_handleChildClose` — emits `error{code:'resume_unknown',
852
- // attemptedResumeId, message}` from server PR #4944). The dashboard
853
- // ResumeUnknownChip surfaces this id as subtext so operators can
854
- // correlate against `~/.chroxy/session-state.json.resumeConversationId`
855
- // without grepping logs.
856
- //
857
- // #4948: also forward on `resume_unknown_exhausted` — the terminal
858
- // escalation code emitted when the post-fallback retry ALSO matches the
859
- // unknown-resume pattern. Same operator-correlation rationale; the
860
- // dashboard renders a distinct "auto-recovery exhausted" affordance but
861
- // still wants to surface the attempted id as subtext.
862
- //
863
- // Hardening (from PR #4967 Copilot review):
864
- // 1. Gate strictly on the two resume-failure codes so a buggy producer
865
- // can't sneak the field onto unrelated error envelopes.
866
- // 2. Trim whitespace and treat whitespace-only as missing — same UX
867
- // guard the chip's render-time check already applies, but enforced
868
- // at the wire boundary so downstream consumers (mobile app, future
869
- // log/console viewers) see a consistent "present or absent, never
870
- // present-but-empty" shape.
871
- // 3. Enforce the same 256-char cap the wire schema declares
872
- // (`ServerMessageSchema.attemptedResumeId`). The server doesn't
873
- // validate outgoing messages against ServerMessageSchema before
874
- // send, so without this guard a misbehaving producer could ship a
875
- // megabyte payload that the dashboard accepts (lax client parse)
876
- // but trips Zod-validating consumers. Silently truncate rather
877
- // than drop — the truncated id still helps operator triage.
878
- if (
879
- (data.code === 'resume_unknown' || data.code === 'resume_unknown_exhausted') &&
880
- typeof data.attemptedResumeId === 'string'
881
- ) {
882
- const trimmed = data.attemptedResumeId.trim()
883
- if (trimmed.length > 0) {
884
- msg.attemptedResumeId = trimmed.length > 256 ? trimmed.slice(0, 256) : trimmed
885
- }
886
- }
887
- // #5067: forward captured `stdout` / `stderr` on docker-byok
888
- // postCreateCommand failures so the operator can diagnose without
889
- // re-running the broken setup. The session layer
890
- // (docker-byok-session.js) already tail-caps each stream to
891
- // POST_CREATE_OUTPUT_CAP_BYTES (4 KiB) before emitting; we re-cap at
892
- // the wire boundary at 8 KiB per stream as a belt-and-suspenders
893
- // bound (matches ServerMessageSchema.{stdout,stderr}.max(8192)) so a
894
- // misbehaving producer can't ship a megabyte payload that the
895
- // dashboard accepts but trips Zod-validating consumers. Gated
896
- // strictly on the post-create-failure code so a buggy producer can't
897
- // sneak the fields onto unrelated error envelopes — same hardening
898
- // pattern as the resume_unknown gate above. Empty-string and
899
- // non-string both treated as "absent" so receivers see a consistent
900
- // "present or absent, never present-but-empty" shape.
901
- if (data.code === 'post_create_command_failed') {
902
- if (typeof data.stdout === 'string' && data.stdout.length > 0) {
903
- msg.stdout = data.stdout.length > 8192 ? data.stdout.slice(0, 8192) : data.stdout
904
- }
905
- if (typeof data.stderr === 'string' && data.stderr.length > 0) {
906
- msg.stderr = data.stderr.length > 8192 ? data.stderr.slice(0, 8192) : data.stderr
907
- }
908
- }
909
- return { messages: [{ msg }] }
910
- },
817
+ error: (data) => ({ messages: [{ msg: buildErrorWire(data) }] }),
818
+
911
819
 
912
820
  // #4756: user-initiated Stop confirmation. CliSession emits `stopped`
913
821
  // when the child process exits cleanly after `interrupt()` set the
@@ -935,6 +843,16 @@ Object.assign(EVENT_MAP, {
935
843
  msg.sessionId = ctx.sessionId
936
844
  }
937
845
  if (Number.isInteger(data?.code)) msg.code = data.code
846
+ // #8497: a Stop that ended the turn without a `result` must still take the
847
+ // session out of busy. The forwarder sets `announceIdle` only when no
848
+ // `result` already did, so this never repeats one. Opt-in on purpose: the
849
+ // legacy single-CLI path does not set it and keeps its prior output.
850
+ // The session_list refresh a `result` pairs with this is NOT returned here:
851
+ // `stopped` is emitted before most providers clear their busy flag, so a
852
+ // list built synchronously would still say busy. The forwarder defers it.
853
+ if (ctx.announceIdle === true) {
854
+ return { messages: [{ msg }, { msg: { type: 'agent_idle' } }] }
855
+ }
938
856
  return { messages: [{ msg }] }
939
857
  },
940
858
 
@@ -1,4 +1,7 @@
1
+ import { MAX_DECLARATION_MESSAGE_CHARS } from './declared-status.js'
2
+ import { assistantResponseText } from './assistant-response.js'
1
3
  import { JsonlSubprocessSession } from './jsonl-subprocess-session.js'
4
+ import { GEMINI_CUSTOMIZATION } from './provider-customization.js'
2
5
  import { buildBaseSessionOpts } from './base-session.js'
3
6
  import { synthesizeModelUsage } from './usage-normalize.js'
4
7
  import { homedir } from 'os'
@@ -14,7 +17,9 @@ import {
14
17
  import { BILLING_CLASSES } from './billing-class.js'
15
18
 
16
19
  /**
17
- * Manages a Gemini CLI session using `gemini -p --output-format stream-json`.
20
+ * Manages a Gemini CLI session using
21
+ * `gemini --prompt=<text> --output-format stream-json`. The prompt is
22
+ * `=`-joined to its flag, never a second token — see `_buildArgs` (#7342).
18
23
  *
19
24
  * Implements the same EventEmitter interface as SdkSession/CliSession so
20
25
  * SessionManager and WsServer work identically regardless of provider.
@@ -116,6 +121,12 @@ export function _maybeRatchetContextWindow(session, modelId, inputTokens) {
116
121
  }
117
122
 
118
123
  export class GeminiSession extends JsonlSubprocessSession {
124
+ static canonicalAssistantResponses = true
125
+
126
+ static get customizationDescriptor() {
127
+ return GEMINI_CUSTOMIZATION
128
+ }
129
+
119
130
  // ------------------------------------------------------------------
120
131
  // Static provider identity — required by JsonlSubprocessSession
121
132
  // ------------------------------------------------------------------
@@ -184,6 +195,10 @@ export class GeminiSession extends JsonlSubprocessSession {
184
195
  resume: false,
185
196
  terminal: false,
186
197
  thinkingLevel: false,
198
+ // #7725: Gemini never sees detect-thinking-keyword.js — the magic words
199
+ // are plain prose on this path.
200
+ thinkingKeywords: false,
201
+ thinkingLevelEffective: false, // #8700: no report of the applied level
187
202
  // #3932: declared explicitly so the capability matrix matches across
188
203
  // providers — claude-tui is the only one that sets this to false.
189
204
  streaming: true,
@@ -335,10 +350,25 @@ export class GeminiSession extends JsonlSubprocessSession {
335
350
  // JsonlSubprocessSession overrides
336
351
  // ------------------------------------------------------------------
337
352
 
353
+ // #7342/#7291 — the prompt and the model id are `=`-JOINED to their long
354
+ // flags, never passed as a second token. `text` is the raw client chat
355
+ // message; gemini-cli's yargs declares `-p/--prompt` and `-m/--model` with
356
+ // `requiresArg`, which REFUSES a dash-leading value in the two-token form.
357
+ // Measured against gemini-cli 0.46.0:
358
+ //
359
+ // gemini -p "- first bullet" → "Not enough arguments following: p", exit 1
360
+ // gemini … -m "--yolo" → "Not enough arguments following: m", exit 1
361
+ // gemini "--prompt=- first bullet" → parses, value taken literally
362
+ // gemini "--prompt=--version" → runs the turn; does NOT print a version
363
+ //
364
+ // So this fails closed rather than open — but it is a live functional bug:
365
+ // any message starting with `-` (a markdown bullet) errored the turn out.
366
+ // `--` is NOT the fix here and would make it worse: an end-of-options
367
+ // separator BREAKS a `requiresArg` flag (see utils/argv-safety.js case 3).
338
368
  _buildArgs(text) {
339
- const args = ['-p', text, '--output-format', 'stream-json', '-y']
369
+ const args = [`--prompt=${text}`, '--output-format', 'stream-json', '-y']
340
370
  if (this.model) {
341
- args.push('-m', this.model)
371
+ args.push(`--model=${this.model}`)
342
372
  }
343
373
  return args
344
374
  }
@@ -352,6 +382,14 @@ export class GeminiSession extends JsonlSubprocessSession {
352
382
  return msg.includes('DeprecationWarning')
353
383
  }
354
384
 
385
+ // Gemini 0.46 supplies deltas, not complete assistant text. This one bounded
386
+ // message buffer ends at the next tool request or result (native boundaries).
387
+ _flushAssistantResponse(ctx) {
388
+ if (ctx.assistantResponseText === undefined) return
389
+ this.emit('assistant_response', { text: ctx.assistantResponseText })
390
+ delete ctx.assistantResponseText
391
+ }
392
+
355
393
  /**
356
394
  * Map a Gemini JSONL event to the standard Chroxy event stream.
357
395
  * Called once per JSONL line by the base class sendMessage() runtime.
@@ -365,7 +403,43 @@ export class GeminiSession extends JsonlSubprocessSession {
365
403
  if (!event || !event.type) return
366
404
 
367
405
  switch (event.type) {
406
+ case 'error': {
407
+ const terminalWarning = typeof event.message === 'string'
408
+ && /^(?:Loop detected, stopping execution|Maximum session turns exceeded|Agent execution blocked:)/i.test(event.message)
409
+ if (event.severity === 'error' || terminalWarning) ctx.declarationStopped = true
410
+ break
411
+ }
412
+
413
+ case 'message': {
414
+ if (event.role !== 'assistant') break
415
+ if (typeof event.content !== 'string') {
416
+ ctx.assistantResponseText = null
417
+ break
418
+ }
419
+ if (event.delta !== true) {
420
+ this._flushAssistantResponse(ctx)
421
+ this.emit('assistant_response', { responseId: event.id, text: assistantResponseText(event.content) })
422
+ } else if (ctx.assistantResponseText !== null) {
423
+ const previous = ctx.assistantResponseText ?? ''
424
+ ctx.assistantResponseText = previous.length + event.content.length <= MAX_DECLARATION_MESSAGE_CHARS ? previous + event.content : null
425
+ }
426
+ if (!ctx.didStreamStart) {
427
+ this.emit('stream_start', { messageId: ctx.messageId })
428
+ ctx.didStreamStart = true
429
+ }
430
+ this.emit('stream_delta', { messageId: ctx.messageId, delta: event.content })
431
+ break
432
+ }
433
+
434
+ case 'tool_use': {
435
+ this._flushAssistantResponse(ctx)
436
+ this.emit('tool_start', { messageId: ctx.messageId, toolUseId: event.tool_id, tool: event.tool_name || 'unknown', input: event.parameters || {} })
437
+ break
438
+ }
439
+
368
440
  case 'assistant': {
441
+ ctx.legacyAssistantFormat = true
442
+ this.emit('assistant_response', { responseId: event.id, text: assistantResponseText(event.content) })
369
443
  if (!event.content || !Array.isArray(event.content)) break
370
444
  for (const block of event.content) {
371
445
  if (block.type === 'text') {
@@ -388,7 +462,7 @@ export class GeminiSession extends JsonlSubprocessSession {
388
462
  }
389
463
 
390
464
  case 'tool_result': {
391
- const toolUseId = event.tool_use_id || event.id || `gemini-tool-${this._messageCounter}`
465
+ const toolUseId = event.tool_id || event.tool_use_id || event.id || `gemini-tool-${this._messageCounter}`
392
466
  this.emit('tool_result', {
393
467
  toolUseId,
394
468
  result: event.content || event.output || '',
@@ -397,6 +471,7 @@ export class GeminiSession extends JsonlSubprocessSession {
397
471
  }
398
472
 
399
473
  case 'result': {
474
+ this._flushAssistantResponse(ctx)
400
475
  ctx.didEmitResult = true
401
476
  // Close any open stream before emitting result (provider contract)
402
477
  if (ctx.didStreamStart) {
@@ -421,6 +496,7 @@ export class GeminiSession extends JsonlSubprocessSession {
421
496
  this.emit('result', {
422
497
  cost: null,
423
498
  duration: null,
499
+ declarationEligible: ctx.declarationStopped !== true && !event.error && (event.status === 'success' || (event.status === undefined && ctx.legacyAssistantFormat === true)),
424
500
  usage: {
425
501
  input_tokens: inputTokens,
426
502
  output_tokens: outputTokens,
@@ -473,7 +549,7 @@ export class GeminiSession extends JsonlSubprocessSession {
473
549
  }
474
550
 
475
551
  case 'tool_result': {
476
- const toolUseId = event.tool_use_id || event.id || `gemini-tool-${this._messageCounter}`
552
+ const toolUseId = event.tool_id || event.tool_use_id || event.id || `gemini-tool-${this._messageCounter}`
477
553
  this.emit('tool_result', {
478
554
  toolUseId,
479
555
  result: event.content || event.output || '',