@chroxy/server 0.10.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.
- package/CONFIG.md +602 -19
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +416 -11
- package/package.json +20 -23
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1353 -41
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +24 -1
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +101 -0
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +74 -9
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +1153 -20
- package/src/byok-mcp-config.js +1712 -8
- package/src/byok-mcp-fleet.js +416 -29
- package/src/byok-mcp-oauth-store.js +329 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +257 -40
- package/src/byok-session.js +1400 -149
- package/src/byok-tool-executor.js +2681 -38
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +96 -51
- package/src/chroxy-host-metadata.js +122 -0
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +109 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +223 -60
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3611 -286
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +6 -6
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +46 -11
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +16 -17
- package/src/cli/providers-cmd.js +6 -6
- package/src/cli/schedule-cmd.js +804 -0
- package/src/cli/server-cmd.js +64 -2
- package/src/cli/service-cmd.js +70 -27
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +168 -14
- package/src/cli/tokens-cmd.js +212 -0
- package/src/cli/tunnel-cmd.js +256 -25
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1117 -116
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +2108 -101
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +571 -45
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +738 -52
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +23 -30
- package/src/control-room/skills-inventory.js +8 -3
- package/src/control-room/survey.js +32 -0
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +279 -29
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diagnostics.js +3 -0
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +188 -4
- package/src/docker-session.js +293 -10
- package/src/doctor.js +783 -66
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +39 -10
- package/src/environments/backends/k8s.js +58 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +137 -14
- package/src/event-normalizer.js +363 -110
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +100 -7
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +563 -62
- package/src/handlers/checkpoint-handlers.js +162 -20
- package/src/handlers/control-room-handlers.js +99 -29
- package/src/handlers/conversation-handlers.js +563 -25
- package/src/handlers/credential-handlers.js +43 -2
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +101 -13
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +689 -48
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +584 -0
- package/src/handlers/session-handlers.js +546 -16
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +822 -35
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/handlers/token-handlers.js +11 -2
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +286 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +309 -48
- package/src/jsonl-subprocess-session.js +122 -9
- package/src/keychain.js +160 -13
- package/src/logger.js +240 -31
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +100 -10
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +82 -12
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +63 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +381 -0
- package/src/orchestration/orchestration-manager.js +1342 -0
- package/src/orchestration/permission-gate.js +121 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +206 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +422 -0
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +236 -12
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-audit.js +79 -3
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1770 -0
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +1175 -94
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +174 -12
- package/src/permission-rule-store.js +411 -0
- package/src/permission-scope.js +43 -0
- package/src/platform.js +483 -23
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +228 -6
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +945 -0
- package/src/scheduler.js +1099 -0
- package/src/sdk-session.js +2374 -168
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +50 -4
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +760 -62
- package/src/server-identity.js +42 -14
- package/src/service.js +682 -53
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3879 -308
- package/src/session-message-history.js +749 -37
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-title.js +168 -0
- package/src/session-token-store.js +70 -36
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +22 -5
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +596 -0
- package/src/subagent-counter.js +9 -1
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +99 -38
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/token-manager.js +39 -9
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +413 -31
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +145 -35
- package/src/tunnel/index.js +13 -1
- package/src/tunnel/preview.js +64 -0
- package/src/tunnel-check.js +1 -1
- package/src/turn-outcome.js +137 -0
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +122 -0
- package/src/user-shell-session.js +157 -37
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +301 -0
- package/src/utils/composite-key.js +45 -0
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/iso-datetime.js +51 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +485 -29
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +196 -5
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +634 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +11 -3
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +370 -66
- package/src/ws-file-ops/common.js +384 -11
- package/src/ws-file-ops/git.js +615 -44
- package/src/ws-file-ops/index.js +7 -0
- package/src/ws-file-ops/memory.js +460 -0
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +676 -94
- package/src/ws-forwarding.js +373 -55
- package/src/ws-handler-context.js +89 -2
- package/src/ws-history.js +1018 -177
- package/src/ws-message-handlers.js +23 -1
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +589 -38
- package/src/ws-schemas.js +6 -0
- package/src/ws-server.js +936 -105
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
package/src/event-normalizer.js
CHANGED
|
@@ -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 {
|
|
4
|
+
import { busyStateOf } from './session-busy-state.js'
|
|
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
|
|
|
@@ -112,10 +117,33 @@ Object.assign(EVENT_MAP, {
|
|
|
112
117
|
mode: entry.session.permissionMode || 'approve',
|
|
113
118
|
},
|
|
114
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 })
|
|
115
132
|
}
|
|
116
133
|
return { messages }
|
|
117
134
|
},
|
|
118
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
|
+
|
|
119
147
|
// #5431: claude-tui's idle transcript re-scan saw the outstanding-work set
|
|
120
148
|
// change (a task-notification landed / a wakeup fired while no turn was
|
|
121
149
|
// running). Re-emit `claude_ready` with the fresh snapshot — the session is
|
|
@@ -140,6 +168,27 @@ Object.assign(EVENT_MAP, {
|
|
|
140
168
|
},
|
|
141
169
|
|
|
142
170
|
stream_start: (data, ctx) => {
|
|
171
|
+
// #6756 — a thinking stream_start opens a reasoning bubble on a distinct id.
|
|
172
|
+
// Tag the wire message so the client routes it to a `type: 'thinking'`
|
|
173
|
+
// bubble, and skip the agent_busy / session_list churn: the turn's busy
|
|
174
|
+
// state is already owned by the response stream / the client's 'pending'
|
|
175
|
+
// sentinel, so a per-thinking-block session_list refresh would be noise.
|
|
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)
|
|
181
|
+
return {
|
|
182
|
+
messages: [{
|
|
183
|
+
msg: {
|
|
184
|
+
type: 'stream_start',
|
|
185
|
+
messageId: data.messageId,
|
|
186
|
+
thinking: true,
|
|
187
|
+
...(thinkingPrecedes ? { thinkingPrecedes } : {}),
|
|
188
|
+
},
|
|
189
|
+
}],
|
|
190
|
+
}
|
|
191
|
+
}
|
|
143
192
|
const messages = [
|
|
144
193
|
{ msg: { type: 'stream_start', messageId: data.messageId } },
|
|
145
194
|
{ msg: { type: 'agent_busy' } },
|
|
@@ -154,6 +203,25 @@ Object.assign(EVENT_MAP, {
|
|
|
154
203
|
},
|
|
155
204
|
|
|
156
205
|
stream_delta: (data, _ctx) => {
|
|
206
|
+
// #6818 — thinking deltas ALSO coalesce now. Before this, they broadcast
|
|
207
|
+
// IMMEDIATELY (one WS frame per thinking_delta) because the delta buffer
|
|
208
|
+
// reconstructed a bare {messageId, delta} on flush and so couldn't carry the
|
|
209
|
+
// `thinking: true` flag — a frame/bandwidth storm on a high-budget turn
|
|
210
|
+
// (`high` = 32k, `max` = 128k thinking tokens streamed over the tunnel). The
|
|
211
|
+
// buffer now tracks the flag per key and stamps it back onto every flushed
|
|
212
|
+
// frame, so thinking coalesces the same way response text does. A thinking
|
|
213
|
+
// bubble uses a DISTINCT messageId (`<turnId>-thinking-<n>`, see #6756), so
|
|
214
|
+
// its deltas never share a buffer key with the response text — the two
|
|
215
|
+
// coalesce independently and flush as separate frames with distinct flags.
|
|
216
|
+
// The `thinking` flag rides the result so the caller forwards it to
|
|
217
|
+
// bufferDelta (parallel to how it reads messageId/delta off `data`).
|
|
218
|
+
if (data.thinking) {
|
|
219
|
+
return {
|
|
220
|
+
messages: [{ msg: { type: 'stream_delta', messageId: data.messageId, delta: data.delta, thinking: true } }],
|
|
221
|
+
buffer: true, // signal to caller to buffer this delta
|
|
222
|
+
thinking: true, // signal to caller to buffer it as a thinking delta
|
|
223
|
+
}
|
|
224
|
+
}
|
|
157
225
|
// Delta buffering is handled externally — normalizer returns the raw delta
|
|
158
226
|
// and the caller decides whether to buffer or flush.
|
|
159
227
|
return {
|
|
@@ -163,6 +231,39 @@ Object.assign(EVENT_MAP, {
|
|
|
163
231
|
},
|
|
164
232
|
|
|
165
233
|
stream_end: (data, ctx) => {
|
|
234
|
+
// #6756/#6818 — a thinking stream_end finalises the reasoning bubble's label.
|
|
235
|
+
// Since #6818 thinking deltas ARE buffered (coalesced), so this MUST flush
|
|
236
|
+
// them first — exactly like the response-text path below — or the
|
|
237
|
+
// finalisation frame could overtake the still-buffered thinking deltas and
|
|
238
|
+
// break the "Thinking… → Thought" ordering. flush_deltas runs as a side
|
|
239
|
+
// effect BEFORE the messages broadcast (see ws-forwarding), so the coalesced
|
|
240
|
+
// thinking text is on the wire before this stream_end.
|
|
241
|
+
if (data.thinking) {
|
|
242
|
+
// #6391 footer-stat: forward the session-measured elapsed time (+ token
|
|
243
|
+
// count when a provider supplies one — claude SDK/BYOK do not) so the
|
|
244
|
+
// client renders `thought for Xs · N tokens`. Both optional and additive;
|
|
245
|
+
// the wire schema (ServerStreamEndSchema) validates them. #6941 review
|
|
246
|
+
// (Copilot): a clock jump/suspend on the measuring side could hand us a
|
|
247
|
+
// negative or wildly-oversized duration that would otherwise slip past a
|
|
248
|
+
// bare finite-check and violate the schema's
|
|
249
|
+
// `.int().nonnegative().max(MAX_SANE_DURATION_MS)` contract if a client
|
|
250
|
+
// ever validates leniently. `boundedNonNegInt` enforces that same
|
|
251
|
+
// ceiling here (defense-in-depth) and OMITS the field outright rather
|
|
252
|
+
// than clamping — the deeper monotonic-clock fix is tracked separately
|
|
253
|
+
// (#6943).
|
|
254
|
+
const msg = { type: 'stream_end', messageId: data.messageId, thinking: true }
|
|
255
|
+
const thinkingDurationMs = boundedNonNegInt(data.thinkingDurationMs, { max: MAX_SANE_DURATION_MS })
|
|
256
|
+
if (thinkingDurationMs !== undefined) msg.thinkingDurationMs = thinkingDurationMs
|
|
257
|
+
// thinkingTokens has no protocol ceiling (ThinkingTokensSchema is
|
|
258
|
+
// int().nonnegative().finite() only) — just enforce non-negative int.
|
|
259
|
+
const thinkingTokens = boundedNonNegInt(data.thinkingTokens)
|
|
260
|
+
if (thinkingTokens !== undefined) msg.thinkingTokens = thinkingTokens
|
|
261
|
+
return {
|
|
262
|
+
messages: [{ msg }],
|
|
263
|
+
// #6818: flush the coalesced thinking deltas before this finalisation.
|
|
264
|
+
sideEffects: [{ type: 'flush_deltas', sessionId: ctx.sessionId }],
|
|
265
|
+
}
|
|
266
|
+
}
|
|
166
267
|
return {
|
|
167
268
|
messages: [{ msg: { type: 'stream_end', messageId: data.messageId } }],
|
|
168
269
|
sideEffects: [
|
|
@@ -172,17 +273,7 @@ Object.assign(EVENT_MAP, {
|
|
|
172
273
|
}
|
|
173
274
|
},
|
|
174
275
|
|
|
175
|
-
message: (data, _ctx) => {
|
|
176
|
-
const msg = {
|
|
177
|
-
type: 'message',
|
|
178
|
-
messageType: data.type,
|
|
179
|
-
content: data.content,
|
|
180
|
-
tool: data.tool,
|
|
181
|
-
options: data.options,
|
|
182
|
-
timestamp: data.timestamp,
|
|
183
|
-
}
|
|
184
|
-
return { messages: [{ msg }] }
|
|
185
|
-
},
|
|
276
|
+
message: (data, _ctx) => ({ messages: [{ msg: buildMessageWire(data) }] }),
|
|
186
277
|
|
|
187
278
|
tool_start: (data) => {
|
|
188
279
|
const msg = { type: 'tool_start', messageId: data.messageId, toolUseId: data.toolUseId, tool: data.tool, input: data.input }
|
|
@@ -210,6 +301,27 @@ Object.assign(EVENT_MAP, {
|
|
|
210
301
|
tool_result: (data) => {
|
|
211
302
|
const msg = { type: 'tool_result', toolUseId: data.toolUseId, result: data.result, truncated: data.truncated }
|
|
212
303
|
if (data.images?.length) msg.images = data.images
|
|
304
|
+
// #6712: forward the failed-tool flag onto the LIVE wire (this normalizer is
|
|
305
|
+
// the serialization choke point for both backends). Without it a failed
|
|
306
|
+
// codex mcpToolCall / orphan-sweep result would render plain live but
|
|
307
|
+
// error-styled after a history replay (which sends the entry raw).
|
|
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
|
|
213
325
|
return { messages: [{ msg }] }
|
|
214
326
|
},
|
|
215
327
|
|
|
@@ -278,16 +390,27 @@ Object.assign(EVENT_MAP, {
|
|
|
278
390
|
// path. Also pushes a session_list side effect so the SessionInfo
|
|
279
391
|
// entry's `pendingBackgroundShells` slot refreshes for clients that
|
|
280
392
|
// render off the list rather than subscribing to the event directly.
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
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
|
+
},
|
|
291
414
|
|
|
292
415
|
// #5160: Control Room activity tree. The ActivityRegistry (owned by
|
|
293
416
|
// BaseSession) maps the existing in-flight signals (tool_start /
|
|
@@ -321,11 +444,22 @@ Object.assign(EVENT_MAP, {
|
|
|
321
444
|
}],
|
|
322
445
|
}),
|
|
323
446
|
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
447
|
+
// #6847: stamp the canonical `ctx.sessionId` so the message routes to the
|
|
448
|
+
// RIGHT session on the client — without it, a client subscribed to sessions
|
|
449
|
+
// A+B with B active would patch A's toggle re-emit onto B (store-core's
|
|
450
|
+
// handleMcpServers falls back to activeSessionId when the field is absent).
|
|
451
|
+
// The field is OMITTED on the legacy-cli path where ctx.sessionId is null,
|
|
452
|
+
// matching the `stopped` builder's convention ("applies to the connected
|
|
453
|
+
// legacy CLI" rather than `sessionId: null`) — mcp_servers is in that path's
|
|
454
|
+
// FORWARDED_EVENTS list, unlike the always-multi-session siblings
|
|
455
|
+
// (message_queued / background_work_changed) that stamp unconditionally.
|
|
456
|
+
mcp_servers: (data, ctx) => {
|
|
457
|
+
const msg = { type: 'mcp_servers', servers: data.servers }
|
|
458
|
+
if (typeof ctx.sessionId === 'string' && ctx.sessionId.length > 0) {
|
|
459
|
+
msg.sessionId = ctx.sessionId
|
|
460
|
+
}
|
|
461
|
+
return { messages: [{ msg }] }
|
|
462
|
+
},
|
|
329
463
|
|
|
330
464
|
// #5936 (epic #5935): outgoing-message queue mirror. The session emits these
|
|
331
465
|
// when a send-while-busy follow-up enters (`message_queued`) or leaves
|
|
@@ -458,7 +592,36 @@ Object.assign(EVENT_MAP, {
|
|
|
458
592
|
|
|
459
593
|
result: (data, ctx) => {
|
|
460
594
|
const messages = [
|
|
461
|
-
{
|
|
595
|
+
{
|
|
596
|
+
msg: {
|
|
597
|
+
type: 'result',
|
|
598
|
+
cost: data.cost,
|
|
599
|
+
duration: data.duration,
|
|
600
|
+
usage: data.usage,
|
|
601
|
+
sessionId: data.sessionId,
|
|
602
|
+
// #6819: the session's authoritative outgoing-queue length, stamped
|
|
603
|
+
// centrally by base-session.js's emit() override (#6627/#6706) onto
|
|
604
|
+
// every `result` payload. Forwarding it lets store-core's
|
|
605
|
+
// result-boundary reconcile self-heal a stale "Queued" bubble left
|
|
606
|
+
// by a dropped/late message_dequeued. Only forwarded when finite —
|
|
607
|
+
// absent/non-finite keeps the field off the wire so older-server
|
|
608
|
+
// semantics (client takes the no-op reconcile path) are preserved.
|
|
609
|
+
...(Number.isFinite(data.queueLength) ? { queueLength: data.queueLength } : {}),
|
|
610
|
+
// #6769: occupancy snapshot (claude-sdk getContextUsage() / the
|
|
611
|
+
// byok agent loop's final-round prompt, incl. subclasses like
|
|
612
|
+
// ollama whose endpoint reports usage). Only forwarded when the
|
|
613
|
+
// session emitted one — providers with no occupancy signal keep
|
|
614
|
+
// the field off the wire so clients render their honest dash state.
|
|
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 } : {}),
|
|
623
|
+
},
|
|
624
|
+
},
|
|
462
625
|
{ msg: { type: 'agent_idle' } },
|
|
463
626
|
]
|
|
464
627
|
const sideEffects = [{ type: 'session_list' }]
|
|
@@ -478,6 +641,10 @@ Object.assign(EVENT_MAP, {
|
|
|
478
641
|
// breakdown for the dashboard / app badge). Subscription-only
|
|
479
642
|
// providers (claude-tui) emit `result` without a numeric `cost` so
|
|
480
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
|
+
|
|
481
648
|
session_usage: (data) => ({
|
|
482
649
|
messages: [{ msg: { type: 'session_usage', cumulativeUsage: data.cumulativeUsage } }],
|
|
483
650
|
}),
|
|
@@ -514,6 +681,16 @@ Object.assign(EVENT_MAP, {
|
|
|
514
681
|
description: data.description,
|
|
515
682
|
input: data.input,
|
|
516
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,
|
|
517
694
|
}),
|
|
518
695
|
}],
|
|
519
696
|
registrations: [{ map: 'permission', key: data.requestId, value: ctx.sessionId }],
|
|
@@ -522,17 +699,50 @@ Object.assign(EVENT_MAP, {
|
|
|
522
699
|
category: 'permission',
|
|
523
700
|
title: 'Permission needed',
|
|
524
701
|
body: `Claude wants to use: ${data.tool}`,
|
|
525
|
-
|
|
702
|
+
// #6792: carry the triggering sessionId in the push data (data-only,
|
|
703
|
+
// doesn't change the visible notification) so a notification tap can
|
|
704
|
+
// route straight to this session — matches the registration above and
|
|
705
|
+
// the sessionId already carried by the HTTP hook path's push
|
|
706
|
+
// (ws-permissions.js) and the activity_* pushes. #6847 "omit not null":
|
|
707
|
+
// include the key ONLY when truthy so the wire shape matches the HTTP
|
|
708
|
+
// hook path (ws-permissions.js), which omits it for the null-ctx path.
|
|
709
|
+
data: { requestId: data.requestId, tool: data.tool, ...(ctx.sessionId ? { sessionId: ctx.sessionId } : {}) },
|
|
526
710
|
channelId: 'permission',
|
|
527
711
|
}],
|
|
528
712
|
}),
|
|
529
713
|
|
|
530
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 }],
|
|
531
733
|
messages: [{
|
|
532
734
|
msg: {
|
|
533
735
|
type: 'permission_expired',
|
|
534
736
|
requestId: data.requestId,
|
|
535
|
-
|
|
737
|
+
// #7096: OMIT when absent — do not stamp null. The wire field is
|
|
738
|
+
// `z.string().optional()`, so `undefined` is legal and `null` is not, and the
|
|
739
|
+
// legacy-cli forwarder (ws-forwarding.js) normalises with `sessionId: null`
|
|
740
|
+
// while `permission_expired` IS in its FORWARDED_EVENTS. This mirrors the
|
|
741
|
+
// guarded stamp `mcp_servers` already uses 240 lines above; the unguarded form
|
|
742
|
+
// here was the odd one out among the frames that path can carry.
|
|
743
|
+
...(typeof ctx.sessionId === 'string' && ctx.sessionId.length > 0
|
|
744
|
+
? { sessionId: ctx.sessionId }
|
|
745
|
+
: {}),
|
|
536
746
|
message: data.message,
|
|
537
747
|
},
|
|
538
748
|
}],
|
|
@@ -563,6 +773,13 @@ Object.assign(EVENT_MAP, {
|
|
|
563
773
|
type: 'permission_resolved',
|
|
564
774
|
requestId: data.requestId,
|
|
565
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' } : {}),
|
|
566
783
|
sessionId: ctx.sessionId,
|
|
567
784
|
},
|
|
568
785
|
})
|
|
@@ -578,80 +795,27 @@ Object.assign(EVENT_MAP, {
|
|
|
578
795
|
// normalizer never saw it; widening the gate would now have emitted
|
|
579
796
|
// a malformed broadcast if we kept the unconditional messages entry.
|
|
580
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
|
+
}
|
|
581
813
|
}
|
|
582
814
|
return out
|
|
583
815
|
},
|
|
584
816
|
|
|
585
|
-
error: (data) => {
|
|
586
|
-
|
|
587
|
-
type: 'message',
|
|
588
|
-
messageType: 'error',
|
|
589
|
-
content: data.message,
|
|
590
|
-
timestamp: Date.now(),
|
|
591
|
-
}
|
|
592
|
-
if (data.code) msg.code = data.code
|
|
593
|
-
// #4947: forward `attemptedResumeId` when CliSession's resume-failure
|
|
594
|
-
// path tagged the error envelope (see cli-session.js
|
|
595
|
-
// `_handleChildClose` — emits `error{code:'resume_unknown',
|
|
596
|
-
// attemptedResumeId, message}` from server PR #4944). The dashboard
|
|
597
|
-
// ResumeUnknownChip surfaces this id as subtext so operators can
|
|
598
|
-
// correlate against `~/.chroxy/session-state.json.resumeConversationId`
|
|
599
|
-
// without grepping logs.
|
|
600
|
-
//
|
|
601
|
-
// #4948: also forward on `resume_unknown_exhausted` — the terminal
|
|
602
|
-
// escalation code emitted when the post-fallback retry ALSO matches the
|
|
603
|
-
// unknown-resume pattern. Same operator-correlation rationale; the
|
|
604
|
-
// dashboard renders a distinct "auto-recovery exhausted" affordance but
|
|
605
|
-
// still wants to surface the attempted id as subtext.
|
|
606
|
-
//
|
|
607
|
-
// Hardening (from PR #4967 Copilot review):
|
|
608
|
-
// 1. Gate strictly on the two resume-failure codes so a buggy producer
|
|
609
|
-
// can't sneak the field onto unrelated error envelopes.
|
|
610
|
-
// 2. Trim whitespace and treat whitespace-only as missing — same UX
|
|
611
|
-
// guard the chip's render-time check already applies, but enforced
|
|
612
|
-
// at the wire boundary so downstream consumers (mobile app, future
|
|
613
|
-
// log/console viewers) see a consistent "present or absent, never
|
|
614
|
-
// present-but-empty" shape.
|
|
615
|
-
// 3. Enforce the same 256-char cap the wire schema declares
|
|
616
|
-
// (`ServerMessageSchema.attemptedResumeId`). The server doesn't
|
|
617
|
-
// validate outgoing messages against ServerMessageSchema before
|
|
618
|
-
// send, so without this guard a misbehaving producer could ship a
|
|
619
|
-
// megabyte payload that the dashboard accepts (lax client parse)
|
|
620
|
-
// but trips Zod-validating consumers. Silently truncate rather
|
|
621
|
-
// than drop — the truncated id still helps operator triage.
|
|
622
|
-
if (
|
|
623
|
-
(data.code === 'resume_unknown' || data.code === 'resume_unknown_exhausted') &&
|
|
624
|
-
typeof data.attemptedResumeId === 'string'
|
|
625
|
-
) {
|
|
626
|
-
const trimmed = data.attemptedResumeId.trim()
|
|
627
|
-
if (trimmed.length > 0) {
|
|
628
|
-
msg.attemptedResumeId = trimmed.length > 256 ? trimmed.slice(0, 256) : trimmed
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
// #5067: forward captured `stdout` / `stderr` on docker-byok
|
|
632
|
-
// postCreateCommand failures so the operator can diagnose without
|
|
633
|
-
// re-running the broken setup. The session layer
|
|
634
|
-
// (docker-byok-session.js) already tail-caps each stream to
|
|
635
|
-
// POST_CREATE_OUTPUT_CAP_BYTES (4 KiB) before emitting; we re-cap at
|
|
636
|
-
// the wire boundary at 8 KiB per stream as a belt-and-suspenders
|
|
637
|
-
// bound (matches ServerMessageSchema.{stdout,stderr}.max(8192)) so a
|
|
638
|
-
// misbehaving producer can't ship a megabyte payload that the
|
|
639
|
-
// dashboard accepts but trips Zod-validating consumers. Gated
|
|
640
|
-
// strictly on the post-create-failure code so a buggy producer can't
|
|
641
|
-
// sneak the fields onto unrelated error envelopes — same hardening
|
|
642
|
-
// pattern as the resume_unknown gate above. Empty-string and
|
|
643
|
-
// non-string both treated as "absent" so receivers see a consistent
|
|
644
|
-
// "present or absent, never present-but-empty" shape.
|
|
645
|
-
if (data.code === 'post_create_command_failed') {
|
|
646
|
-
if (typeof data.stdout === 'string' && data.stdout.length > 0) {
|
|
647
|
-
msg.stdout = data.stdout.length > 8192 ? data.stdout.slice(0, 8192) : data.stdout
|
|
648
|
-
}
|
|
649
|
-
if (typeof data.stderr === 'string' && data.stderr.length > 0) {
|
|
650
|
-
msg.stderr = data.stderr.length > 8192 ? data.stderr.slice(0, 8192) : data.stderr
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
return { messages: [{ msg }] }
|
|
654
|
-
},
|
|
817
|
+
error: (data) => ({ messages: [{ msg: buildErrorWire(data) }] }),
|
|
818
|
+
|
|
655
819
|
|
|
656
820
|
// #4756: user-initiated Stop confirmation. CliSession emits `stopped`
|
|
657
821
|
// when the child process exits cleanly after `interrupt()` set the
|
|
@@ -679,6 +843,16 @@ Object.assign(EVENT_MAP, {
|
|
|
679
843
|
msg.sessionId = ctx.sessionId
|
|
680
844
|
}
|
|
681
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
|
+
}
|
|
682
856
|
return { messages: [{ msg }] }
|
|
683
857
|
},
|
|
684
858
|
|
|
@@ -789,6 +963,25 @@ export class EventNormalizer {
|
|
|
789
963
|
// oldest token in a flush spent inside the server (coalescing + forwarding)
|
|
790
964
|
// — a true monotonic duration, same process both ends.
|
|
791
965
|
this._deltaEmitMono = new Map()
|
|
966
|
+
// #6818: key -> whether this buffer key holds THINKING deltas (reasoning
|
|
967
|
+
// content) rather than response text. A thinking stream uses a DISTINCT
|
|
968
|
+
// messageId (`<turnId>-thinking-<n>`, see #6756), so it never shares a key
|
|
969
|
+
// with the response text — this map carries the `thinking: true` flag
|
|
970
|
+
// alongside the coalesced text so each flushed entry can be reconstructed as
|
|
971
|
+
// a thinking stream_delta instead of a bare response delta. Pruned in every
|
|
972
|
+
// flush/clear path in lockstep with _deltaBuffer.
|
|
973
|
+
// #6962: response keys are recorded too, as `false`, so bufferDelta can tell
|
|
974
|
+
// "never seen" (undefined) apart from "seen as response" and DETECT a
|
|
975
|
+
// same-key flag conflict. Every flush site reads `=== true`, so a stored
|
|
976
|
+
// `false` is indistinguishable from an absent key on the wire — response
|
|
977
|
+
// entries stay byte-identical to pre-#6818.
|
|
978
|
+
this._deltaThinking = new Map()
|
|
979
|
+
// #6962: one-shot latch for the key-collision WARN. A provider violating the
|
|
980
|
+
// distinct-messageId invariant would trip the guard on EVERY delta, so the
|
|
981
|
+
// WARN is deduped to once per normalizer (one per daemon in production)
|
|
982
|
+
// rather than tracked per key — a per-key Set would grow unbounded over a
|
|
983
|
+
// long-lived daemon for no extra signal.
|
|
984
|
+
this._warnedThinkingKeyCollision = false
|
|
792
985
|
this._deltaFlushTimer = null
|
|
793
986
|
// #5516: monotonic deadline (performance.now ms) the pending flush timer is
|
|
794
987
|
// scheduled to fire at. Lets a later single-client buffer SHORTEN an
|
|
@@ -849,7 +1042,9 @@ export class EventNormalizer {
|
|
|
849
1042
|
|
|
850
1043
|
/**
|
|
851
1044
|
* Set the flush callback. Called with buffered deltas when the timer fires.
|
|
852
|
-
* @param {Function} cb - (entries: Array<{ key, sessionId, messageId, delta }>) => void
|
|
1045
|
+
* @param {Function} cb - (entries: Array<{ key, sessionId, messageId, delta, emitMonoMs, thinking? }>) => void
|
|
1046
|
+
* `thinking` is present (=== true) only on entries that hold reasoning
|
|
1047
|
+
* content (#6818) so the caller stamps `thinking: true` back onto the wire.
|
|
853
1048
|
*/
|
|
854
1049
|
set onFlush(cb) {
|
|
855
1050
|
this._onFlush = cb
|
|
@@ -877,9 +1072,46 @@ export class EventNormalizer {
|
|
|
877
1072
|
* @param {number} [emitMonoMs] - #5515: monotonic ms the provider emitted this
|
|
878
1073
|
* delta. First-write-wins per flush window so the flushed entry reports how
|
|
879
1074
|
* long the OLDEST coalesced token waited inside the server.
|
|
1075
|
+
* @param {boolean} [thinking] - #6818: true when this is a reasoning
|
|
1076
|
+
* (extended-thinking) delta. Recorded per key so the flushed entry carries
|
|
1077
|
+
* the `thinking` flag and the caller reconstructs a thinking stream_delta.
|
|
1078
|
+
* Thinking uses a distinct messageId (#6756), so the flag is constant per
|
|
1079
|
+
* key. #6962: that constancy is now ENFORCED here rather than assumed — a
|
|
1080
|
+
* same-key flag conflict WARNs and splits the frame (see below).
|
|
880
1081
|
*/
|
|
881
|
-
bufferDelta(sessionId, messageId, delta, emitMonoMs) {
|
|
1082
|
+
bufferDelta(sessionId, messageId, delta, emitMonoMs, thinking) {
|
|
882
1083
|
const key = sessionId ? `${sessionId}:${messageId}` : messageId
|
|
1084
|
+
// #6962: enforce the distinct-messageId invariant #6818 rests on. Thinking
|
|
1085
|
+
// deltas and response text of the same turn must never share a buffer key —
|
|
1086
|
+
// every provider today builds the thinking messageId as
|
|
1087
|
+
// `<turnId>-thinking-<n>` (#6756), but that is an unenforced CROSS-FILE
|
|
1088
|
+
// convention, exactly the shape of bug the BaseSession opt-forwarding trap
|
|
1089
|
+
// (#4797/#5367) turned out to be. A future provider reusing the bare
|
|
1090
|
+
// response messageId for a thinking delta would otherwise concatenate
|
|
1091
|
+
// reasoning into the answer and ship it under one (necessarily wrong) flag,
|
|
1092
|
+
// silently. So: detect the conflict BEFORE touching any buffer state, WARN
|
|
1093
|
+
// once, and CONTAIN it by force-flushing what is already buffered under its
|
|
1094
|
+
// ORIGINAL flag. The conflicting delta then re-buffers fresh behind it with
|
|
1095
|
+
// its own flag — same order-preserving mechanism the #5555 residency caps
|
|
1096
|
+
// use — so no frame ever mixes reasoning and response text. We warn rather
|
|
1097
|
+
// than throw because bufferDelta runs synchronously under the provider's
|
|
1098
|
+
// event emit; a throw here escapes into that emit and can take the daemon
|
|
1099
|
+
// down over one malformed stream (same reasoning as the onFlush containment
|
|
1100
|
+
// in _flushDeltas).
|
|
1101
|
+
const isThinking = thinking === true
|
|
1102
|
+
const priorThinking = this._deltaThinking.get(key)
|
|
1103
|
+
if (priorThinking !== undefined && priorThinking !== isThinking) {
|
|
1104
|
+
if (!this._warnedThinkingKeyCollision) {
|
|
1105
|
+
this._warnedThinkingKeyCollision = true
|
|
1106
|
+
log.warn(
|
|
1107
|
+
`Delta buffer invariant violation (#6962): key '${key}' received a thinking=${isThinking} delta ` +
|
|
1108
|
+
`after thinking=${priorThinking}. Thinking and response deltas of one turn MUST use distinct ` +
|
|
1109
|
+
`messageIds (\`<turnId>-thinking-<n>\`, #6756). Splitting the frame so the coalesced text is not ` +
|
|
1110
|
+
`corrupted; fix the provider emitting this messageId. Further collisions are not logged.`
|
|
1111
|
+
)
|
|
1112
|
+
}
|
|
1113
|
+
this._forceFlushKey(key)
|
|
1114
|
+
}
|
|
883
1115
|
// #5555: coerce a non-string delta to its string form ONCE and use that for
|
|
884
1116
|
// both the buffer concat AND the byte count. A bare `existing + delta` would
|
|
885
1117
|
// string-coerce a non-string into the buffer (real residency) while a
|
|
@@ -893,6 +1125,14 @@ export class EventNormalizer {
|
|
|
893
1125
|
if (typeof emitMonoMs === 'number' && !this._deltaEmitMono.has(key)) {
|
|
894
1126
|
this._deltaEmitMono.set(key, emitMonoMs)
|
|
895
1127
|
}
|
|
1128
|
+
// #6818: record the thinking flag once per key (constant per key — thinking
|
|
1129
|
+
// uses a distinct messageId). #6962: response keys are recorded as `false`
|
|
1130
|
+
// instead of left absent so the conflict check above can distinguish them
|
|
1131
|
+
// from an unseen key; every flush site tests `=== true`, so a stored `false`
|
|
1132
|
+
// still produces an entry byte-identical to pre-#6818.
|
|
1133
|
+
if (!this._deltaThinking.has(key)) {
|
|
1134
|
+
this._deltaThinking.set(key, isThinking)
|
|
1135
|
+
}
|
|
896
1136
|
// #5555: maintain byte-size counters incrementally (UTF-8) — no
|
|
897
1137
|
// re-serialization on the hot path. `text` is the only new content, so its
|
|
898
1138
|
// byte length is the per-call growth for both the key total and the global
|
|
@@ -958,8 +1198,10 @@ export class EventNormalizer {
|
|
|
958
1198
|
if (!this._deltaBuffer.has(key)) return
|
|
959
1199
|
const delta = this._deltaBuffer.get(key)
|
|
960
1200
|
const emitMonoMs = this._deltaEmitMono.get(key)
|
|
1201
|
+
const thinking = this._deltaThinking.get(key) === true
|
|
961
1202
|
this._deltaBuffer.delete(key)
|
|
962
1203
|
this._deltaEmitMono.delete(key)
|
|
1204
|
+
this._deltaThinking.delete(key)
|
|
963
1205
|
this._deltaTotalBytes -= this._deltaKeyBytes.get(key) || 0
|
|
964
1206
|
this._deltaKeyBytes.delete(key)
|
|
965
1207
|
if (this._deltaTotalBytes < 0) this._deltaTotalBytes = 0
|
|
@@ -968,6 +1210,7 @@ export class EventNormalizer {
|
|
|
968
1210
|
const entry = sepIdx !== -1
|
|
969
1211
|
? { key, sessionId: key.slice(0, sepIdx), messageId: key.slice(sepIdx + 1), delta, emitMonoMs }
|
|
970
1212
|
: { key, sessionId: null, messageId: key, delta, emitMonoMs }
|
|
1213
|
+
if (thinking) entry.thinking = true
|
|
971
1214
|
// Mirror _flushDeltas' containment: a throwing broadcast must not escape
|
|
972
1215
|
// the buffer hot path (which runs under the provider's event emit).
|
|
973
1216
|
try {
|
|
@@ -983,7 +1226,8 @@ export class EventNormalizer {
|
|
|
983
1226
|
* Flush all buffered deltas for a specific session (called before stream_end).
|
|
984
1227
|
* Returns the flushed entries so the caller can broadcast them.
|
|
985
1228
|
* @param {string|null} sessionId - Session to flush (null = flush all)
|
|
986
|
-
* @returns {Array<{ key, sessionId, messageId, delta, emitMonoMs }>}
|
|
1229
|
+
* @returns {Array<{ key, sessionId, messageId, delta, emitMonoMs, thinking? }>}
|
|
1230
|
+
* `thinking` is present (=== true) only on reasoning entries (#6818).
|
|
987
1231
|
*/
|
|
988
1232
|
flushSession(sessionId) {
|
|
989
1233
|
const entries = []
|
|
@@ -992,9 +1236,12 @@ export class EventNormalizer {
|
|
|
992
1236
|
for (const [key, delta] of this._deltaBuffer) {
|
|
993
1237
|
if (key.startsWith(prefix)) {
|
|
994
1238
|
const messageId = key.slice(prefix.length)
|
|
995
|
-
|
|
1239
|
+
const entry = { key, sessionId, messageId, delta, emitMonoMs: this._deltaEmitMono.get(key) }
|
|
1240
|
+
if (this._deltaThinking.get(key) === true) entry.thinking = true
|
|
1241
|
+
entries.push(entry)
|
|
996
1242
|
this._deltaBuffer.delete(key)
|
|
997
1243
|
this._deltaEmitMono.delete(key)
|
|
1244
|
+
this._deltaThinking.delete(key)
|
|
998
1245
|
// #5555: keep residency counters in sync as keys leave the buffer.
|
|
999
1246
|
this._deltaTotalBytes -= this._deltaKeyBytes.get(key) || 0
|
|
1000
1247
|
this._deltaKeyBytes.delete(key)
|
|
@@ -1004,10 +1251,13 @@ export class EventNormalizer {
|
|
|
1004
1251
|
} else {
|
|
1005
1252
|
// Legacy mode: flush everything
|
|
1006
1253
|
for (const [key, delta] of this._deltaBuffer) {
|
|
1007
|
-
|
|
1254
|
+
const entry = { key, sessionId: null, messageId: key, delta, emitMonoMs: this._deltaEmitMono.get(key) }
|
|
1255
|
+
if (this._deltaThinking.get(key) === true) entry.thinking = true
|
|
1256
|
+
entries.push(entry)
|
|
1008
1257
|
}
|
|
1009
1258
|
this._deltaBuffer.clear()
|
|
1010
1259
|
this._deltaEmitMono.clear()
|
|
1260
|
+
this._deltaThinking.clear()
|
|
1011
1261
|
this._deltaKeyBytes.clear()
|
|
1012
1262
|
this._deltaTotalBytes = 0
|
|
1013
1263
|
}
|
|
@@ -1032,11 +1282,11 @@ export class EventNormalizer {
|
|
|
1032
1282
|
for (const [key, delta] of this._deltaBuffer) {
|
|
1033
1283
|
const emitMonoMs = this._deltaEmitMono.get(key)
|
|
1034
1284
|
const sepIdx = key.indexOf(':')
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1285
|
+
const entry = sepIdx !== -1
|
|
1286
|
+
? { key, sessionId: key.slice(0, sepIdx), messageId: key.slice(sepIdx + 1), delta, emitMonoMs }
|
|
1287
|
+
: { key, sessionId: null, messageId: key, delta, emitMonoMs }
|
|
1288
|
+
if (this._deltaThinking.get(key) === true) entry.thinking = true
|
|
1289
|
+
entries.push(entry)
|
|
1040
1290
|
}
|
|
1041
1291
|
// #5313 (WP-1.3): _onFlush is a broadcast callback invoked from a
|
|
1042
1292
|
// setTimeout. A throw here escapes the timer → uncaughtException →
|
|
@@ -1052,6 +1302,7 @@ export class EventNormalizer {
|
|
|
1052
1302
|
} finally {
|
|
1053
1303
|
this._deltaBuffer.clear()
|
|
1054
1304
|
this._deltaEmitMono.clear()
|
|
1305
|
+
this._deltaThinking.clear()
|
|
1055
1306
|
this._deltaKeyBytes.clear()
|
|
1056
1307
|
this._deltaTotalBytes = 0
|
|
1057
1308
|
}
|
|
@@ -1059,6 +1310,7 @@ export class EventNormalizer {
|
|
|
1059
1310
|
}
|
|
1060
1311
|
this._deltaBuffer.clear()
|
|
1061
1312
|
this._deltaEmitMono.clear()
|
|
1313
|
+
this._deltaThinking.clear()
|
|
1062
1314
|
this._deltaKeyBytes.clear()
|
|
1063
1315
|
this._deltaTotalBytes = 0
|
|
1064
1316
|
}
|
|
@@ -1074,6 +1326,7 @@ export class EventNormalizer {
|
|
|
1074
1326
|
this._deltaFlushDeadline = 0
|
|
1075
1327
|
this._deltaBuffer.clear()
|
|
1076
1328
|
this._deltaEmitMono.clear()
|
|
1329
|
+
this._deltaThinking.clear()
|
|
1077
1330
|
this._deltaKeyBytes.clear()
|
|
1078
1331
|
this._deltaTotalBytes = 0
|
|
1079
1332
|
}
|