@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
|
@@ -1,9 +1,165 @@
|
|
|
1
1
|
import { EventEmitter } from 'events'
|
|
2
2
|
import { createLogger } from './logger.js'
|
|
3
|
+
import { truncateTitle } from './session-title.js'
|
|
4
|
+
import { redactBounded, sanitizeToolInput, isSanitizedToolInput, MAX_INPUT_CHARS, RECORD_DESCRIPTION_MAX } from './redaction.js'
|
|
5
|
+
import { 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
|
+
|
|
9
|
+
/**
|
|
10
|
+
* #8259: how far past the seq being issued a persisted reservation reaches. See
|
|
11
|
+
* `_nextSeq`: it bounds how often the state file is rewritten for reservations
|
|
12
|
+
* (once per this many entries per session), not how far a cursor can run ahead.
|
|
13
|
+
*/
|
|
14
|
+
export const SEQ_RESERVATION_STEP = 1000
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* #8259: fallback only. A state file written before reservations existed has no
|
|
18
|
+
* persisted high-water mark, so the marker is numbered this far past the last
|
|
19
|
+
* persisted seq (best effort, NOT a guarantee). Files written by this build
|
|
20
|
+
* always carry the reservation.
|
|
21
|
+
*/
|
|
22
|
+
export const RESTART_SEQ_GAP = 100000
|
|
3
23
|
|
|
4
24
|
const log = createLogger('session-message-history')
|
|
5
25
|
const MAX_PENDING_STREAM_SIZE = 100 * 1024 * 1024 // 100MB
|
|
6
26
|
|
|
27
|
+
/**
|
|
28
|
+
* #8348 -- the outcomes a permission prompt can end in, as recorded in history.
|
|
29
|
+
* `expired` covers every way a prompt ended with NO decision: it timed out, the
|
|
30
|
+
* turn behind it ended, or the session cleared it. `stopped` (#8374) is the one
|
|
31
|
+
* of those with its own name: the user pressed Stop while the prompt was open.
|
|
32
|
+
*/
|
|
33
|
+
export const PERMISSION_OUTCOMES = Object.freeze(['allowed', 'denied', 'expired', 'stopped'])
|
|
34
|
+
// Bounds on the two free-text fields of a `permission_outcome` entry. The
|
|
35
|
+
// description already went to clients capped and redacted; these bound what the
|
|
36
|
+
// ring buffer and the state file keep, so a long hook-path description (the hook
|
|
37
|
+
// route broadcasts it uncapped) cannot bloat either.
|
|
38
|
+
export const PERMISSION_OUTCOME_TOOL_MAX = 100
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* #8503: the decision tokens an `allowed` outcome may name. `allowAlways` writes a
|
|
42
|
+
* persistent rule and `allowSession` a session one, so a record of either must stay
|
|
43
|
+
* distinguishable from a one-time `allow` after a rebuild (a replayed group of
|
|
44
|
+
* "allowed x N" must not fold them together). `deny` is not here: a denial needs no
|
|
45
|
+
* token, and an outcome with no decision at all (expired, stopped) has none to name.
|
|
46
|
+
*/
|
|
47
|
+
export const PERMISSION_ALLOW_DECISIONS = Object.freeze(['allow', 'allowSession', 'allowAlways'])
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The decision token an outcome may keep, or `undefined`: only an `allowed` outcome,
|
|
51
|
+
* only one of {@link PERMISSION_ALLOW_DECISIONS}. One rule for the recorder and the
|
|
52
|
+
* replay, so a damaged restored entry cannot send what the recorder would not keep.
|
|
53
|
+
*
|
|
54
|
+
* @param {unknown} outcome
|
|
55
|
+
* @param {unknown} decision
|
|
56
|
+
* @returns {'allow'|'allowSession'|'allowAlways'|undefined}
|
|
57
|
+
*/
|
|
58
|
+
export function permissionOutcomeDecision(outcome, decision) {
|
|
59
|
+
return outcome === 'allowed' && PERMISSION_ALLOW_DECISIONS.includes(decision) ? decision : undefined
|
|
60
|
+
}
|
|
61
|
+
export const PERMISSION_OUTCOME_DESCRIPTION_MAX = RECORD_DESCRIPTION_MAX
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* #8503: the most the journaled tool input of a `permission_outcome` may weigh,
|
|
65
|
+
* SERIALIZED, whatever its shape. `sanitizeToolInput` returns at most
|
|
66
|
+
* `MAX_INPUT_CHARS` serialized characters, or, past that, a `{ _truncated, summary }`
|
|
67
|
+
* wrapper whose summary is the first `MAX_INPUT_CHARS` characters of the input's JSON
|
|
68
|
+
* plus a marker. That summary is itself JSON text, so serializing the wrapper escapes
|
|
69
|
+
* its quotes and backslashes again: at most twice the summary, plus the wrapper's own
|
|
70
|
+
* keys. This is that figure, so every value the broadcast ever sends fits and nothing
|
|
71
|
+
* larger is kept. On disk this is the weight of one entry's `input`; `truncateEntry`
|
|
72
|
+
* caps it at 50 KB regardless and the ring buffer holds 1000 entries per session, the
|
|
73
|
+
* bound a `tool_start` entry's input already has.
|
|
74
|
+
*/
|
|
75
|
+
const TRUNCATION_MARKER = '... [truncated]'
|
|
76
|
+
export const PERMISSION_OUTCOME_INPUT_MAX = 2 * (MAX_INPUT_CHARS + TRUNCATION_MARKER.length) + 64
|
|
77
|
+
|
|
78
|
+
function isPlainObject(value) {
|
|
79
|
+
return !!value && typeof value === 'object' && !Array.isArray(value)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* #8503: the tool input a `permission_outcome` may keep, or `undefined` for none.
|
|
84
|
+
*
|
|
85
|
+
* The journal is what the clients were SHOWN: the value `sanitizeToolInput` produced
|
|
86
|
+
* for the live `permission_request`, handed over by the caller. That value is kept
|
|
87
|
+
* EXACTLY, never re-shaped, never re-redacted. A wrapper stays the sanitizer's
|
|
88
|
+
* wrapper, and an input an agent wrote with a `_truncated` or `summary` key stays the
|
|
89
|
+
* agent's input: nothing here reads the VALUE's content to decide what it is, because
|
|
90
|
+
* an agent controls every key in it.
|
|
91
|
+
*
|
|
92
|
+
* What tells "already broadcast" from "raw" is identity, not content:
|
|
93
|
+
* `isSanitizedToolInput` is true only for an object `sanitizeToolInput` returned. An
|
|
94
|
+
* input that is not one (a raw input by a future caller's mistake, a copy that lost
|
|
95
|
+
* its identity) is sanitized first, so what is journaled is what the broadcast would
|
|
96
|
+
* have sent for it. The journal is persisted and replayed to every client of the
|
|
97
|
+
* session, so it does not trust its caller to have done that.
|
|
98
|
+
*
|
|
99
|
+
* Not a plain object (a string, an array, a number, null) or absent: no input is kept
|
|
100
|
+
* and the entry reads like one from before the field. A value heavier than
|
|
101
|
+
* {@link PERMISSION_OUTCOME_INPUT_MAX} is dropped, not cut: the pull path's larger
|
|
102
|
+
* sanitized inputs are the one such source, and cutting would re-shape them.
|
|
103
|
+
*
|
|
104
|
+
* @param {unknown} input
|
|
105
|
+
* @returns {object|undefined}
|
|
106
|
+
*/
|
|
107
|
+
export function boundPermissionOutcomeInput(input) {
|
|
108
|
+
if (!isPlainObject(input)) return undefined
|
|
109
|
+
try {
|
|
110
|
+
const kept = isSanitizedToolInput(input) ? input : sanitizeToolInput(input)
|
|
111
|
+
if (!isPlainObject(kept)) return undefined
|
|
112
|
+
return JSON.stringify(kept).length <= PERMISSION_OUTCOME_INPUT_MAX ? kept : undefined
|
|
113
|
+
} catch {
|
|
114
|
+
return undefined
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// `<turnId>-thinking-<n>` (sdk, byok) and `<turnId>-thinking` (acp).
|
|
119
|
+
const LEGACY_THINKING_ID = /-thinking(?:-\d+)?$/
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* #6630 / #8282: which kind of stream a recorded `response` entry was. Today
|
|
123
|
+
* only `'thinking'` (extended-thinking reasoning) is distinguished; anything
|
|
124
|
+
* else is a reply and returns `undefined`.
|
|
125
|
+
*
|
|
126
|
+
* The recorder stamps `kind: 'thinking'` on new entries. An entry written
|
|
127
|
+
* before that field existed (a state file from an older run) is classified by
|
|
128
|
+
* the message id the providers give a reasoning stream: `<turnId>-thinking-<n>`
|
|
129
|
+
* (sdk-session, byok-session) and ACP's `<turnId>-thinking` (acp-session), so
|
|
130
|
+
* those still replay as reasoning instead of as an answer. ONE classifier, used by the replay emitter -- a client reads the
|
|
131
|
+
* `kind` on the frame and never re-derives it from an id.
|
|
132
|
+
*
|
|
133
|
+
* @param {object} entry - a ring-buffer entry
|
|
134
|
+
* @returns {'thinking'|undefined}
|
|
135
|
+
*/
|
|
136
|
+
export function streamKindOf(entry) {
|
|
137
|
+
if (!entry || entry.type !== 'message' || entry.messageType !== 'response') return undefined
|
|
138
|
+
if (entry.kind === 'thinking') return 'thinking'
|
|
139
|
+
if (typeof entry.messageId === 'string' && LEGACY_THINKING_ID.test(entry.messageId)) return 'thinking'
|
|
140
|
+
return undefined
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** `{ input }` when there is one, else nothing: an absent input is an absent key. */
|
|
144
|
+
function inputField(input) {
|
|
145
|
+
return input === undefined ? {} : { input }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** `{ decision }` when there is one, else nothing. */
|
|
149
|
+
function decisionField(decision) {
|
|
150
|
+
return decision === undefined ? {} : { decision }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function clipText(value, max) {
|
|
154
|
+
const text = typeof value === 'string' ? value : ''
|
|
155
|
+
return text.length > max ? text.slice(0, max - 1) + '\u2026' : text
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Pattern-redact (never cutting a token in half), THEN clip: clipping first could leave a partial secret the patterns miss. */
|
|
159
|
+
function clipRedacted(value, max) {
|
|
160
|
+
return clipText(redactBounded(typeof value === 'string' ? value : ''), max)
|
|
161
|
+
}
|
|
162
|
+
|
|
7
163
|
/**
|
|
8
164
|
* Manages per-session message history ring buffers, stream delta accumulation,
|
|
9
165
|
* truncation tracking, and auto-labeling from first user input.
|
|
@@ -11,7 +167,9 @@ const MAX_PENDING_STREAM_SIZE = 100 * 1024 * 1024 // 100MB
|
|
|
11
167
|
* Extracted from SessionManager to isolate history concerns.
|
|
12
168
|
*
|
|
13
169
|
* Events emitted:
|
|
14
|
-
* auto_label { sessionId, label } — when first user input triggers
|
|
170
|
+
* auto_label { sessionId, label, text } — when first user input triggers a
|
|
171
|
+
* session rename. `label` is the truncation applied synchronously; `text` is
|
|
172
|
+
* the untruncated first message (source for the #6764 semantic-title upgrade).
|
|
15
173
|
*/
|
|
16
174
|
export class SessionMessageHistory extends EventEmitter {
|
|
17
175
|
/**
|
|
@@ -33,6 +191,19 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
33
191
|
// over-size delta for the same message also exceeds the cap and would
|
|
34
192
|
// otherwise re-fire the error). Cleared on stream_end / session clear.
|
|
35
193
|
this._truncatedStreams = new Set() // sessionId:messageId
|
|
194
|
+
// #6630 / #8282 -- sessionId:messageId -> stream kind, for the streams that
|
|
195
|
+
// are not ordinary replies (reasoning). Kept beside `_pendingStreams` rather
|
|
196
|
+
// than inside its value because that map is read as plain strings elsewhere.
|
|
197
|
+
this._streamKinds = new Map()
|
|
198
|
+
// #8518 -- sessionId:messageId -> the ordering hint a reasoning stream_start
|
|
199
|
+
// carried (what it precedes). The entry is written at stream_end, so the
|
|
200
|
+
// start's hint is held here until then.
|
|
201
|
+
this._streamPrecedes = new Map()
|
|
202
|
+
// #9022 -- sessionId:messageId -> the seq the NEXT history entry would take when
|
|
203
|
+
// the stream's first text arrived. A reply is recorded only at stream_end, so while it is open
|
|
204
|
+
// a replay has no entry for it; this is where that text belongs in the replay
|
|
205
|
+
// (before every entry recorded after the stream began). Cleared with the stream.
|
|
206
|
+
this._streamStartSeqs = new Map()
|
|
36
207
|
this._historyTruncated = new Map() // sessionId -> boolean
|
|
37
208
|
// #5555.3 (lastSeq delta replay) — per-session monotonic history sequence.
|
|
38
209
|
// Every entry pushed into the ring buffer is stamped with a strictly
|
|
@@ -43,6 +214,10 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
43
214
|
// seq is server-internal bookkeeping; the wire only exposes it as
|
|
44
215
|
// `historySeq` on replayed entries (see ws-history.js).
|
|
45
216
|
this._seqCounters = new Map() // sessionId -> next seq to assign (>= 1)
|
|
217
|
+
// #8259: sessionId -> highest seq this process may issue, already handed to the
|
|
218
|
+
// reservation handler (the SessionManager persists it synchronously).
|
|
219
|
+
this._seqReserved = new Map()
|
|
220
|
+
this._onSeqReservation = null
|
|
46
221
|
}
|
|
47
222
|
|
|
48
223
|
/**
|
|
@@ -52,10 +227,47 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
52
227
|
*/
|
|
53
228
|
_nextSeq(sessionId) {
|
|
54
229
|
const next = this._seqCounters.get(sessionId) || 1
|
|
230
|
+
// #8259 RESERVATION INVARIANT: no seq above `_seqReserved` is ever issued
|
|
231
|
+
// before the reservation covering it has been handed to the handler, which
|
|
232
|
+
// persists it synchronously. So the persisted `seqReservedThrough` is >= every
|
|
233
|
+
// seq this process ever gave a client, whatever the lazy state-file debounce
|
|
234
|
+
// has or has not written. A restart numbers new entries above it, so a cursor
|
|
235
|
+
// a client took from the previous process can never equal or exceed them.
|
|
236
|
+
// The persist runs here (once per SEQ_RESERVATION_STEP entries), before the
|
|
237
|
+
// counter moves.
|
|
238
|
+
if (next > (this._seqReserved.get(sessionId) || 0)) {
|
|
239
|
+
this._seqReserved.set(sessionId, next + SEQ_RESERVATION_STEP)
|
|
240
|
+
if (this._onSeqReservation) {
|
|
241
|
+
try { this._onSeqReservation(sessionId) } catch (err) { log.warn(`seq reservation handler failed for ${sessionId}: ${err?.message || err}`) }
|
|
242
|
+
}
|
|
243
|
+
}
|
|
55
244
|
this._seqCounters.set(sessionId, next + 1)
|
|
56
245
|
return next
|
|
57
246
|
}
|
|
58
247
|
|
|
248
|
+
/** #8259: install the callback that persists a seq reservation synchronously. */
|
|
249
|
+
setSeqReservationHandler(fn) {
|
|
250
|
+
this._onSeqReservation = typeof fn === 'function' ? fn : null
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** #8259: the persisted-or-persisting high-water mark for a session, or 0 when none. */
|
|
254
|
+
getSeqReservedThrough(sessionId) {
|
|
255
|
+
return this._seqReserved.get(sessionId) || 0
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* #8259: adopt the previous process's reservation on restore and move the
|
|
260
|
+
* counter above it, so nothing this process issues can reuse a seq a client
|
|
261
|
+
* holds. Returns false (and changes nothing) for a state file without a usable
|
|
262
|
+
* value, which then falls back to the best-effort gap.
|
|
263
|
+
*/
|
|
264
|
+
restoreSeqReservation(sessionId, reservedThrough) {
|
|
265
|
+
if (!Number.isSafeInteger(reservedThrough) || reservedThrough < 1) return false
|
|
266
|
+
this._seqReserved.set(sessionId, reservedThrough)
|
|
267
|
+
this._seqCounters.set(sessionId, Math.max(this._seqCounters.get(sessionId) || 1, reservedThrough + 1))
|
|
268
|
+
return true
|
|
269
|
+
}
|
|
270
|
+
|
|
59
271
|
/**
|
|
60
272
|
* #5555.3 — seq of the oldest entry still retained in the ring buffer, or
|
|
61
273
|
* null when the session has no history. Used by the cursor-replay path to
|
|
@@ -124,11 +336,46 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
124
336
|
closedMessageIds.push(messageId)
|
|
125
337
|
this._pendingStreams.delete(key)
|
|
126
338
|
this._truncatedStreams.delete(key) // #6431 — release the truncation guard
|
|
339
|
+
this._streamKinds.delete(key)
|
|
340
|
+
this._streamPrecedes.delete(key)
|
|
341
|
+
this._streamStartSeqs.delete(key)
|
|
127
342
|
}
|
|
128
343
|
}
|
|
129
344
|
return closedMessageIds
|
|
130
345
|
}
|
|
131
346
|
|
|
347
|
+
/**
|
|
348
|
+
* #9022 -- the reply text a session has streamed so far but not yet closed.
|
|
349
|
+
*
|
|
350
|
+
* History only ever holds a COMPLETED reply (the entry is pushed at
|
|
351
|
+
* `stream_end`), so a turn paused mid-stream -- on a permission prompt, say --
|
|
352
|
+
* has its text in no replay, and a client that reloads shows the tool card and
|
|
353
|
+
* the prompt but none of what the model already said. This is that text, for
|
|
354
|
+
* the replay to splice in at its place in the transcript.
|
|
355
|
+
*
|
|
356
|
+
* Reasoning streams are left out (they replay as their own kind, on a
|
|
357
|
+
* capability), as is a stream that has produced no text yet.
|
|
358
|
+
*
|
|
359
|
+
* @param {string} sessionId
|
|
360
|
+
* @returns {Array<{ messageId: string, content: string, startSeq: number }>}
|
|
361
|
+
* `startSeq` is the seq the next recorded entry had when its first text arrived:
|
|
362
|
+
* the reply belongs before every entry with `_seq >= startSeq`.
|
|
363
|
+
*/
|
|
364
|
+
getPendingResponseStreams(sessionId) {
|
|
365
|
+
const prefix = sessionId + ':'
|
|
366
|
+
const out = []
|
|
367
|
+
for (const [key, content] of this._pendingStreams) {
|
|
368
|
+
if (!key.startsWith(prefix) || !content) continue
|
|
369
|
+
if (this._streamKinds.get(key) === 'thinking') continue
|
|
370
|
+
out.push({
|
|
371
|
+
messageId: key.slice(prefix.length),
|
|
372
|
+
content,
|
|
373
|
+
startSeq: this._streamStartSeqs.get(key) ?? Infinity,
|
|
374
|
+
})
|
|
375
|
+
}
|
|
376
|
+
return out
|
|
377
|
+
}
|
|
378
|
+
|
|
132
379
|
/**
|
|
133
380
|
* Get message history for a session.
|
|
134
381
|
* @param {string} sessionId
|
|
@@ -156,28 +403,142 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
156
403
|
return this._historyTruncated.get(sessionId) || false
|
|
157
404
|
}
|
|
158
405
|
|
|
406
|
+
/**
|
|
407
|
+
* #8336 — the highest seq this session has handed out (0 when none). It is
|
|
408
|
+
* what a state file records so the NEXT run can keep numbering past it; the
|
|
409
|
+
* newest retained entry carries it, but the counter is the authority because
|
|
410
|
+
* it survives a front-trim of the whole buffer.
|
|
411
|
+
* @param {string} sessionId
|
|
412
|
+
* @returns {number}
|
|
413
|
+
*/
|
|
414
|
+
getLastIssuedSeq(sessionId) {
|
|
415
|
+
return (this._seqCounters.get(sessionId) || 1) - 1
|
|
416
|
+
}
|
|
417
|
+
|
|
159
418
|
/**
|
|
160
419
|
* Set pre-existing history for a session (used during state restore).
|
|
420
|
+
*
|
|
421
|
+
* #8336 -- SEQUENCE CONTINUITY. Entries are stamped `firstSeq, firstSeq + 1, ...`
|
|
422
|
+
* and the counter is left just past the last one. The caller passes the first
|
|
423
|
+
* seq so that the entries the previous run persisted keep (roughly) the
|
|
424
|
+
* numbers that run served them under: a reconnecting client's cursor
|
|
425
|
+
* (`lastSeq`) then still means what it meant, and every entry added after the
|
|
426
|
+
* restore (a tail correction, the next turn) is numbered PAST every cursor the
|
|
427
|
+
* previous run issued. Restarting from 1 broke that: with the ring buffer
|
|
428
|
+
* already full, the restore's own additions plus the post-restart traffic could
|
|
429
|
+
* climb through the old cursor's value, and `resolveReplayPlan` then honoured a
|
|
430
|
+
* cursor that no longer pointed at what the client had seen.
|
|
431
|
+
*
|
|
432
|
+
* Without `firstSeq` (a state file from before this field, or a malformed one)
|
|
433
|
+
* numbering starts at 1: the pre-#8336 behaviour, where a cursor from the prior
|
|
434
|
+
* run is honoured only by accident and falls back to a full replay otherwise.
|
|
435
|
+
*
|
|
436
|
+
* The history is also trimmed to the ring-buffer cap, oldest first. A restore
|
|
437
|
+
* can add entries (synthetic tool results, a marked question copy) to a buffer
|
|
438
|
+
* that was already full, and `_pushHistory` only ever evicts one entry per push,
|
|
439
|
+
* so without this the buffer grew by the restore's additions on EVERY restart.
|
|
440
|
+
* The trimmed front is what falls off, so a cursor older than the new oldest
|
|
441
|
+
* entry takes the "trimmed past" full-replay fallback, as designed.
|
|
442
|
+
*
|
|
161
443
|
* @param {string} sessionId
|
|
162
444
|
* @param {Array} history
|
|
445
|
+
* @param {object} [opts]
|
|
446
|
+
* @param {number} [opts.firstSeq] - seq to give the first entry (integer >= 1)
|
|
163
447
|
*/
|
|
164
|
-
setHistory(sessionId, history) {
|
|
165
|
-
// #5555.3 — restored entries predate the seq scheme (it is server-internal
|
|
166
|
-
// and not persisted), so stamp them with a fresh 1..N sequence and advance
|
|
167
|
-
// the counter past the end. A reconnecting client's cursor from a PRIOR
|
|
168
|
-
// server process can't be honoured across a restart (seqs reset to 1), so
|
|
169
|
-
// it will simply fall through to a full replay — the safe default.
|
|
448
|
+
setHistory(sessionId, history, { firstSeq } = {}) {
|
|
170
449
|
if (Array.isArray(history)) {
|
|
171
|
-
|
|
450
|
+
const start = Number.isSafeInteger(firstSeq) && firstSeq >= 1 ? firstSeq : 1
|
|
451
|
+
let seq = start
|
|
172
452
|
for (const entry of history) {
|
|
173
453
|
if (entry && typeof entry === 'object') entry._seq = seq
|
|
174
454
|
seq++
|
|
175
455
|
}
|
|
176
456
|
this._seqCounters.set(sessionId, seq)
|
|
457
|
+
const excess = history.length - this._maxHistory
|
|
458
|
+
if (excess > 0) {
|
|
459
|
+
history = history.slice(excess)
|
|
460
|
+
this._historyTruncated.set(sessionId, true)
|
|
461
|
+
}
|
|
177
462
|
}
|
|
178
463
|
this._messageHistory.set(sessionId, history)
|
|
179
464
|
}
|
|
180
465
|
|
|
466
|
+
/**
|
|
467
|
+
* #8362 -- record that the server ACCEPTED an answer to a `user_question`.
|
|
468
|
+
*
|
|
469
|
+
* The restore-time sweep (`sweepUnresolvedToolStarts`) calls a question
|
|
470
|
+
* interrupted when its AskUserQuestion tool has no `tool_result`. For
|
|
471
|
+
* claude-cli and claude-tui the answer is delivered to the provider BEFORE the
|
|
472
|
+
* tool's result event arrives, so a restart in that window cut off a question
|
|
473
|
+
* that had in fact been answered, and a client rebuilding from scratch showed
|
|
474
|
+
* "Interrupted -- chroxy restarted before this was answered". This is the
|
|
475
|
+
* record the sweep consults.
|
|
476
|
+
*
|
|
477
|
+
* A flag only: the answer text is not stored (it is not already in the entry,
|
|
478
|
+
* and the history would otherwise start persisting user answers). Idempotent.
|
|
479
|
+
* Mutates the entry in place, like `tool_result`'s input backfill: nothing a
|
|
480
|
+
* client could hold is changed on the live wire, and `sendHistoryEntry` keeps
|
|
481
|
+
* the field off replay frames.
|
|
482
|
+
*
|
|
483
|
+
* @param {string} sessionId
|
|
484
|
+
* @param {string} [toolUseId] - The question's id (the one its route and wire
|
|
485
|
+
* frame carry). Without one, the newest question not yet marked answered:
|
|
486
|
+
* only clients that send no id reach that, and they have one question in
|
|
487
|
+
* flight.
|
|
488
|
+
* @returns {boolean} true when an entry was newly marked (the caller persists)
|
|
489
|
+
*/
|
|
490
|
+
markQuestionAnswered(sessionId, toolUseId) {
|
|
491
|
+
const history = this._messageHistory.get(sessionId)
|
|
492
|
+
if (!Array.isArray(history)) return false
|
|
493
|
+
for (let i = history.length - 1; i >= 0; i--) {
|
|
494
|
+
const entry = history[i]
|
|
495
|
+
if (!entry || entry.type !== 'user_question') continue
|
|
496
|
+
if (typeof toolUseId === 'string') {
|
|
497
|
+
if (entry.toolUseId !== toolUseId) continue
|
|
498
|
+
} else if (entry.answered === true) {
|
|
499
|
+
continue
|
|
500
|
+
}
|
|
501
|
+
if (entry.answered === true) return false
|
|
502
|
+
entry.answered = true
|
|
503
|
+
return true
|
|
504
|
+
}
|
|
505
|
+
return false
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* #8470 -- record that a newer question REPLACED this one, so nobody answered it
|
|
510
|
+
* and nobody will. `permission_resolved` is transient, so without this a client
|
|
511
|
+
* that was not watching live (a fresh dashboard, a full rebuild, a reconnect)
|
|
512
|
+
* replays the question as unanswered and stamps it "(resolved)", which reads as
|
|
513
|
+
* answered.
|
|
514
|
+
*
|
|
515
|
+
* Two writes, for the same reason the restore-time sweep makes two (#8336): the
|
|
516
|
+
* entry is flagged IN PLACE (a full rebuild receives the question where it was
|
|
517
|
+
* asked, already marked), and a marked COPY is appended at the tail with a fresh
|
|
518
|
+
* seq (a client whose cursor is already past the question would otherwise never
|
|
519
|
+
* hear; the client collapses the copy onto the card it holds by `toolUseId`).
|
|
520
|
+
* The flag also stops the restore-time sweep calling the question interrupted
|
|
521
|
+
* when a restart lands before the denial's `tool_result`.
|
|
522
|
+
*
|
|
523
|
+
* @param {string} sessionId
|
|
524
|
+
* @param {string} toolUseId - the question's id (the `ask-...` id on its frame)
|
|
525
|
+
* @returns {boolean} true when an entry was newly marked (the caller persists)
|
|
526
|
+
*/
|
|
527
|
+
markQuestionSuperseded(sessionId, toolUseId) {
|
|
528
|
+
const history = this._messageHistory.get(sessionId)
|
|
529
|
+
if (!Array.isArray(history) || typeof toolUseId !== 'string') return false
|
|
530
|
+
for (let i = history.length - 1; i >= 0; i--) {
|
|
531
|
+
const entry = history[i]
|
|
532
|
+
if (!entry || entry.type !== 'user_question' || entry.toolUseId !== toolUseId) continue
|
|
533
|
+
if (entry.superseded === true || entry.answered === true) return false
|
|
534
|
+
entry.superseded = true
|
|
535
|
+
const { _seq: _dropped, ...copy } = entry
|
|
536
|
+
this._pushHistory(history, copy, sessionId)
|
|
537
|
+
return true
|
|
538
|
+
}
|
|
539
|
+
return false
|
|
540
|
+
}
|
|
541
|
+
|
|
181
542
|
/**
|
|
182
543
|
* Sweep an in-memory history array for `tool_start` entries that lack a
|
|
183
544
|
* matching `tool_result` and splice in a synthetic `tool_result` right
|
|
@@ -193,6 +554,17 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
193
554
|
* downstream consumers that sort by timestamp stay monotonic without
|
|
194
555
|
* pretending the tool completed "now".
|
|
195
556
|
*
|
|
557
|
+
* #8336: a `user_question` entry for one of the swept `tool_start`s (matched
|
|
558
|
+
* on its `sourceToolUseId` when it has one, else its `toolUseId`) is returned
|
|
559
|
+
* as a COPY carrying `interrupted: true` (the question was cut off, not
|
|
560
|
+
* answered), so a replaying client can say so instead of stamping it
|
|
561
|
+
* "(resolved)". A second marked copy is appended at the END of the history so
|
|
562
|
+
* that a delta replay for a client whose cursor is already past the question
|
|
563
|
+
* still delivers the mark. Other entries are passed through. A question carrying
|
|
564
|
+
* `answered: true` (#8362: the server accepted an answer before the restart) is
|
|
565
|
+
* passed through unmarked, as is one carrying `superseded: true` (#8470: a newer
|
|
566
|
+
* question replaced it, which is its own verdict).
|
|
567
|
+
*
|
|
196
568
|
* Safe to call on:
|
|
197
569
|
* - empty / non-array input (returns the input unchanged)
|
|
198
570
|
* - history with no tool_start entries (returns a shallow copy)
|
|
@@ -210,7 +582,41 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
210
582
|
}
|
|
211
583
|
}
|
|
212
584
|
const out = []
|
|
585
|
+
// #8336: the toolUseIds this sweep cuts off. A `user_question` entry for
|
|
586
|
+
// one of them was never answered (an answer would have produced the
|
|
587
|
+
// tool_result), so it is marked `interrupted` below rather than left
|
|
588
|
+
// looking like every other replayed question, which the client's
|
|
589
|
+
// history_replay_end sweep stamps "(resolved)".
|
|
590
|
+
const interruptedIds = new Set()
|
|
213
591
|
for (const entry of history) {
|
|
592
|
+
if (
|
|
593
|
+
entry
|
|
594
|
+
&& entry.type === 'tool_start'
|
|
595
|
+
&& typeof entry.toolUseId === 'string'
|
|
596
|
+
&& !resolved.has(entry.toolUseId)
|
|
597
|
+
) {
|
|
598
|
+
interruptedIds.add(entry.toolUseId)
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
// #8336: the marked copies to re-append at the tail, see below.
|
|
602
|
+
const redelivered = []
|
|
603
|
+
for (const rawEntry of history) {
|
|
604
|
+
// `user_question` is copied, never mutated: the input array is the
|
|
605
|
+
// caller's, and the contract above says it is not modified. The set was
|
|
606
|
+
// collected up front, so the question is marked whichever side of its
|
|
607
|
+
// tool_start it was recorded on. A question names its tool by
|
|
608
|
+
// `sourceToolUseId` when it has one (SDK, BYOK: `toolUseId` is chroxy's
|
|
609
|
+
// own `ask-...` id there), else by `toolUseId` itself (CLI, TUI).
|
|
610
|
+
const questionToolId = rawEntry && rawEntry.type === 'user_question'
|
|
611
|
+
? (typeof rawEntry.sourceToolUseId === 'string' ? rawEntry.sourceToolUseId : rawEntry.toolUseId)
|
|
612
|
+
: undefined
|
|
613
|
+
// #8362: a question the server accepted an answer for is not cut off even
|
|
614
|
+
// though its tool_result has not arrived yet (cli/tui deliver the answer
|
|
615
|
+
// first). The tool_start is still swept below -- the TOOL was in flight.
|
|
616
|
+
const entry = (typeof questionToolId === 'string' && interruptedIds.has(questionToolId) && rawEntry.answered !== true && rawEntry.superseded !== true)
|
|
617
|
+
? { ...rawEntry, interrupted: true }
|
|
618
|
+
: rawEntry
|
|
619
|
+
if (entry !== rawEntry) redelivered.push({ ...entry })
|
|
214
620
|
out.push(entry)
|
|
215
621
|
if (
|
|
216
622
|
entry
|
|
@@ -221,15 +627,16 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
221
627
|
const baseTs = typeof entry.timestamp === 'number' && Number.isFinite(entry.timestamp)
|
|
222
628
|
? entry.timestamp
|
|
223
629
|
: Date.now()
|
|
224
|
-
//
|
|
225
|
-
//
|
|
226
|
-
//
|
|
227
|
-
//
|
|
228
|
-
//
|
|
229
|
-
//
|
|
230
|
-
//
|
|
231
|
-
//
|
|
232
|
-
//
|
|
630
|
+
// #6712: `isError` is now a first-class wire field
|
|
631
|
+
// (`ServerToolResultSchema`) that BOTH clients branch on to style a
|
|
632
|
+
// failed result (a red alert icon / ✕ marker) — so a replayed synthetic
|
|
633
|
+
// sweep entry surfaces the error affordance too (replay sends the entry
|
|
634
|
+
// raw). `synthetic` / `interrupted` / `reason` remain diagnostic hints
|
|
635
|
+
// that no client branches on and the schema strips on parse; kept so the
|
|
636
|
+
// synthetic stays grep-able on disk and a future renderer can show a
|
|
637
|
+
// distinct "interrupted" badge without a protocol change. The activeTools
|
|
638
|
+
// clear is driven purely by the `tool_result` type + matching `toolUseId`
|
|
639
|
+
// through `handleToolResult.applyToActiveTools`.
|
|
233
640
|
out.push({
|
|
234
641
|
type: 'tool_result',
|
|
235
642
|
toolUseId: entry.toolUseId,
|
|
@@ -238,6 +645,9 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
238
645
|
isError: true,
|
|
239
646
|
synthetic: true,
|
|
240
647
|
reason: 'session_restored',
|
|
648
|
+
// #7376: the restore-time sweep is the one termination whose OUTCOME is
|
|
649
|
+
// unknown (the daemon went down mid-tool) -- say so distinctly.
|
|
650
|
+
terminatedReason: 'daemon_restart',
|
|
241
651
|
timestamp: baseTs + 1,
|
|
242
652
|
})
|
|
243
653
|
// Mark this toolUseId resolved so a malformed history with two
|
|
@@ -245,9 +655,76 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
245
655
|
resolved.add(entry.toolUseId)
|
|
246
656
|
}
|
|
247
657
|
}
|
|
658
|
+
// #8336: the marked question is ALSO appended as a fresh entry at the tail.
|
|
659
|
+
// Marking it in place changes an entry a client may already be past: a
|
|
660
|
+
// reconnecting client's cursor is honoured when it falls inside the restored
|
|
661
|
+
// range, and the delta replay then sends only what lies past it. A client
|
|
662
|
+
// whose cursor sits beyond the question's position would never hear that it
|
|
663
|
+
// was cut off, and its replay-end sweep would stamp the card "(resolved)".
|
|
664
|
+
// A tail entry is numbered past every cursor the previous run could have
|
|
665
|
+
// issued -- `setHistory` continues the previous run's numbering rather than
|
|
666
|
+
// restarting at 1, and the tail is beyond its last entry by construction --
|
|
667
|
+
// so it always arrives. The client collapses it onto the card it holds (same
|
|
668
|
+
// `toolUseId`, same questions), so nobody sees two; a client rebuilding from
|
|
669
|
+
// scratch gets the question in place from the marked entry above and the copy
|
|
670
|
+
// merges onto it. If the ring-buffer cap later evicts the in-place original
|
|
671
|
+
// first (oldest-first), the copy is what remains: a full replay then shows the
|
|
672
|
+
// question after newer messages rather than where it was asked, which is the
|
|
673
|
+
// price of never losing the verdict.
|
|
674
|
+
for (const copy of redelivered) out.push(copy)
|
|
248
675
|
return out
|
|
249
676
|
}
|
|
250
677
|
|
|
678
|
+
/**
|
|
679
|
+
* #8259: close a turn the daemon went down under. Called by the SessionManager's
|
|
680
|
+
* restore ONLY for a session whose persisted state says a turn was in flight
|
|
681
|
+
* (dispatched to the provider and not yet ended). The partial reply only ever
|
|
682
|
+
* lived in memory, so without this no client could be told how that turn
|
|
683
|
+
* ended. Appends a `result` carrying the `interrupted` turn outcome, the SAME
|
|
684
|
+
* marker path (`turnOutcome` on a `result`) a stopped or truncated turn uses.
|
|
685
|
+
*
|
|
686
|
+
* DELIVERY. A client's cursor comes from the previous process, and the state
|
|
687
|
+
* file's `historyLastSeq` can lag it without bound (the write is debounced and
|
|
688
|
+
* the debounce restarts on every append). What does not lag is the seq
|
|
689
|
+
* RESERVATION (see `_nextSeq`): it is persisted before any seq under it is
|
|
690
|
+
* issued, so `seqReservedThrough` is >= every seq the previous process gave a
|
|
691
|
+
* client. Restore moves the counter above it, so the marker is numbered strictly
|
|
692
|
+
* past every possible cursor: the delta replay (strictly newer than the cursor)
|
|
693
|
+
* honours the cursor and sends it. A state file without a reservation (written
|
|
694
|
+
* before this existed) falls back to `RESTART_SEQ_GAP`, best effort.
|
|
695
|
+
*
|
|
696
|
+
* The timestamp is clamped to one past the newest entry, like the synthetic
|
|
697
|
+
* tool_result of `sweepUnresolvedToolStarts`, so the marker never sorts before
|
|
698
|
+
* the entries it follows.
|
|
699
|
+
*
|
|
700
|
+
* PROVIDER RESUME. No provider continues a half-run turn after a restart: a
|
|
701
|
+
* restored session is a fresh idle provider that resumes the CONVERSATION
|
|
702
|
+
* (context), not the turn, so nothing completes the interrupted turn later.
|
|
703
|
+
* If one ever did, its completed result would simply follow this chip (a
|
|
704
|
+
* completed outcome adds no marker and does not remove one), which stays an
|
|
705
|
+
* honest record that the turn was cut off once.
|
|
706
|
+
*
|
|
707
|
+
* @param {string} sessionId
|
|
708
|
+
* @param {number} [now] - injectable for tests
|
|
709
|
+
* @returns {object} the appended entry
|
|
710
|
+
*/
|
|
711
|
+
recordInterruptedTurn(sessionId, now = Date.now()) {
|
|
712
|
+
if (!this._messageHistory.has(sessionId)) this._messageHistory.set(sessionId, [])
|
|
713
|
+
const history = this._messageHistory.get(sessionId)
|
|
714
|
+
let lastTs = 0
|
|
715
|
+
for (const e of history) {
|
|
716
|
+
if (e && Number.isFinite(e.timestamp) && e.timestamp > lastTs) lastTs = e.timestamp
|
|
717
|
+
}
|
|
718
|
+
// With a restored reservation the counter is already above it (restoreSeqReservation);
|
|
719
|
+
// only a pre-reservation state file needs the best-effort gap.
|
|
720
|
+
if (!this._seqReserved.has(sessionId)) {
|
|
721
|
+
this._seqCounters.set(sessionId, (this._seqCounters.get(sessionId) || 1) + RESTART_SEQ_GAP)
|
|
722
|
+
}
|
|
723
|
+
const marker = { type: 'result', turnOutcome: 'interrupted', timestamp: Math.max(now, lastTs + 1) }
|
|
724
|
+
this._pushHistory(history, marker, sessionId)
|
|
725
|
+
return marker
|
|
726
|
+
}
|
|
727
|
+
|
|
251
728
|
/**
|
|
252
729
|
* Record a user input message in the session's history ring buffer.
|
|
253
730
|
* On the first non-empty input, emits auto_label if the session qualifies.
|
|
@@ -261,8 +738,9 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
261
738
|
* `handlers/input-handlers.js::resolveUserInputId`) always resolves one
|
|
262
739
|
* before calling in, so replayed entries always carry an id in practice.
|
|
263
740
|
* See issue #2902.
|
|
741
|
+
* @param {'daemon'} [source] - #8301: marks a daemon-authored turn (the CI wake).
|
|
264
742
|
*/
|
|
265
|
-
recordUserInput(sessionId, text, sessionEntry, messageId) {
|
|
743
|
+
recordUserInput(sessionId, text, sessionEntry, messageId, source) {
|
|
266
744
|
if (sessionEntry) {
|
|
267
745
|
this._autoLabelSession(sessionId, text, sessionEntry)
|
|
268
746
|
}
|
|
@@ -274,6 +752,10 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
274
752
|
if (typeof messageId === 'string' && messageId.length > 0) {
|
|
275
753
|
entry.messageId = messageId
|
|
276
754
|
}
|
|
755
|
+
// #8301: `source: 'daemon'` marks a turn the daemon wrote (the CI wake), so a
|
|
756
|
+
// replaying client can tell it from something a person typed. Absent for
|
|
757
|
+
// typed input — an older client ignores the field either way.
|
|
758
|
+
if (source === 'daemon') entry.source = 'daemon'
|
|
277
759
|
this.recordHistory(sessionId, 'message', entry)
|
|
278
760
|
}
|
|
279
761
|
|
|
@@ -290,11 +772,19 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
290
772
|
}
|
|
291
773
|
const history = this._messageHistory.get(sessionId)
|
|
292
774
|
let persistNeeded = false
|
|
775
|
+
let completedAssistant
|
|
776
|
+
let assistantCompleted = false
|
|
293
777
|
|
|
294
778
|
switch (event) {
|
|
295
779
|
case 'stream_start': {
|
|
296
780
|
const key = `${sessionId}:${data.messageId}`
|
|
297
781
|
this._pendingStreams.set(key, '')
|
|
782
|
+
// #6630 / #8282: a reasoning stream must not be recorded as a reply.
|
|
783
|
+
if (data.thinking === true) {
|
|
784
|
+
this._streamKinds.set(key, 'thinking')
|
|
785
|
+
const thinkingPrecedes = boundedThinkingPrecedes(data.thinkingPrecedes)
|
|
786
|
+
if (thinkingPrecedes) this._streamPrecedes.set(key, thinkingPrecedes)
|
|
787
|
+
}
|
|
298
788
|
break
|
|
299
789
|
}
|
|
300
790
|
|
|
@@ -315,6 +805,13 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
315
805
|
}
|
|
316
806
|
return { persistNeeded: false, truncated: firstDrop }
|
|
317
807
|
}
|
|
808
|
+
// #9022: where the reply BEGINS is where its first text arrived, not where
|
|
809
|
+
// the stream opened. claude-tui and byok open the stream inside sendMessage,
|
|
810
|
+
// before the input is accepted and `user_input` recorded, so a start-time
|
|
811
|
+
// seq would put the reply above the prompt it answers.
|
|
812
|
+
if (data.delta.length > 0 && !this._streamStartSeqs.has(key)) {
|
|
813
|
+
this._streamStartSeqs.set(key, this._seqCounters.get(sessionId) || 1)
|
|
814
|
+
}
|
|
318
815
|
this._pendingStreams.set(key, existing + data.delta)
|
|
319
816
|
}
|
|
320
817
|
break
|
|
@@ -323,14 +820,46 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
323
820
|
case 'stream_end': {
|
|
324
821
|
const key = `${sessionId}:${data.messageId}`
|
|
325
822
|
const content = this._pendingStreams.get(key) || ''
|
|
823
|
+
const hadStream = this._pendingStreams.has(key)
|
|
824
|
+
const kind = this._streamKinds.get(key) || (data.thinking === true ? 'thinking' : undefined)
|
|
825
|
+
const thinkingPrecedes = kind === 'thinking' ? this._streamPrecedes.get(key) : undefined
|
|
326
826
|
this._pendingStreams.delete(key)
|
|
827
|
+
this._streamKinds.delete(key)
|
|
828
|
+
this._streamPrecedes.delete(key)
|
|
829
|
+
const wasTruncated = this._truncatedStreams.has(key)
|
|
830
|
+
this._streamStartSeqs.delete(key)
|
|
327
831
|
this._truncatedStreams.delete(key) // #6431 — release the once-per-stream guard
|
|
328
|
-
|
|
832
|
+
// A reasoning stream is recorded even with no text: current Claude models
|
|
833
|
+
// return the block with its signature only, so the SDK opens and closes a
|
|
834
|
+
// thinking stream that never carries a delta. Live, that is a "thought for
|
|
835
|
+
// Xs" bubble with an empty body; skipping it for want of text made the whole
|
|
836
|
+
// bubble vanish on replay. A reply with no text is still no entry, and so is
|
|
837
|
+
// a stream_end whose start this history never saw.
|
|
838
|
+
assistantCompleted = hadStream && kind !== 'thinking'
|
|
839
|
+
if (assistantCompleted && !wasTruncated && data.interrupted !== true) completedAssistant = content
|
|
840
|
+
if (content || (kind === 'thinking' && hadStream)) {
|
|
841
|
+
// #6630: a reasoning stream keeps what the live bubble shows -- that it
|
|
842
|
+
// IS reasoning (`kind`) and how long it took (`thinkingDurationMs`, the
|
|
843
|
+
// same bounded value the live `stream_end` frame carries). Without them
|
|
844
|
+
// a replay rebuilt it as a plain answer.
|
|
845
|
+
const thinkingDurationMs = kind === 'thinking'
|
|
846
|
+
? boundedNonNegInt(data.thinkingDurationMs, { max: MAX_SANE_DURATION_MS })
|
|
847
|
+
: undefined
|
|
848
|
+
// The live stream_end carries a token count when a provider separates one
|
|
849
|
+
// out (` · N tokens` in the footer); record it so a replay says the same.
|
|
850
|
+
const thinkingTokens = kind === 'thinking' ? boundedNonNegInt(data.thinkingTokens) : undefined
|
|
329
851
|
this._pushHistory(history, {
|
|
330
852
|
type: 'message',
|
|
331
853
|
messageType: 'response',
|
|
332
854
|
content,
|
|
333
855
|
messageId: data.messageId,
|
|
856
|
+
...(kind ? { kind } : {}),
|
|
857
|
+
...(thinkingDurationMs !== undefined ? { thinkingDurationMs } : {}),
|
|
858
|
+
...(thinkingTokens !== undefined ? { thinkingTokens } : {}),
|
|
859
|
+
// #8518: a block that reached the wire after the tool row / answer it
|
|
860
|
+
// belongs above keeps saying so, so a reload orders it the way the live
|
|
861
|
+
// client did. Absent for a block that arrived in order.
|
|
862
|
+
...(thinkingPrecedes ? { thinkingPrecedes } : {}),
|
|
334
863
|
timestamp: Date.now(),
|
|
335
864
|
}, sessionId)
|
|
336
865
|
}
|
|
@@ -339,21 +868,34 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
339
868
|
}
|
|
340
869
|
|
|
341
870
|
case 'message':
|
|
871
|
+
assistantCompleted = data.type === 'response' && data.kind !== 'thinking' && data.thinking !== true
|
|
872
|
+
if (assistantCompleted) completedAssistant = data.content
|
|
342
873
|
this._pushHistory(history, {
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
options: data.options,
|
|
874
|
+
// #6630: the SAME envelope the live frame is built from, so a field the
|
|
875
|
+
// live message carries (the compact_boundary / MCP-prompt-expansion
|
|
876
|
+
// markers) reaches the replay too.
|
|
877
|
+
...buildMessageWire(data),
|
|
348
878
|
// Carry through the stable messageId for user_input entries so
|
|
349
879
|
// clients can dedup rehydrated prompts against their own
|
|
350
880
|
// optimistic/live-echo copies (issue #2902).
|
|
351
881
|
...(data.messageId ? { messageId: data.messageId } : {}),
|
|
352
|
-
|
|
882
|
+
...(data.source === 'daemon' ? { source: 'daemon' } : {}),
|
|
353
883
|
}, sessionId)
|
|
354
884
|
persistNeeded = true
|
|
355
885
|
break
|
|
356
886
|
|
|
887
|
+
case 'error':
|
|
888
|
+
// #6630: an error is a chat bubble live (an error card, or a code-specific
|
|
889
|
+
// chip: stream stall, resume failure, auth required), so it is part of the
|
|
890
|
+
// transcript. It was not recorded at all, and so vanished on the first
|
|
891
|
+
// session switch or reload. Built by the live frame's own builder, so the
|
|
892
|
+
// `code` and the fields that select a chip travel with it. A malformed
|
|
893
|
+
// event with no message text is not a bubble live either.
|
|
894
|
+
if (!data || typeof data.message !== 'string') break
|
|
895
|
+
this._pushHistory(history, buildErrorWire(data), sessionId)
|
|
896
|
+
persistNeeded = true
|
|
897
|
+
break
|
|
898
|
+
|
|
357
899
|
case 'tool_start':
|
|
358
900
|
this._pushHistory(history, {
|
|
359
901
|
type: 'tool_start',
|
|
@@ -361,16 +903,49 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
361
903
|
toolUseId: data.toolUseId,
|
|
362
904
|
tool: data.tool,
|
|
363
905
|
input: data.input,
|
|
906
|
+
// #6630: the MCP server a tool belongs to labels its card; the live
|
|
907
|
+
// frame carries it, so the replay must.
|
|
908
|
+
...(typeof data.serverName === 'string' && data.serverName ? { serverName: data.serverName } : {}),
|
|
364
909
|
timestamp: Date.now(),
|
|
365
910
|
}, sessionId)
|
|
366
911
|
break
|
|
367
912
|
|
|
368
913
|
case 'tool_result':
|
|
914
|
+
// #7346: backfill the matching tool_start entry's `input` when the
|
|
915
|
+
// caller (tool-result.js's emitToolResults, via
|
|
916
|
+
// base-session.js's `_getTrackedToolInput`) attached the
|
|
917
|
+
// finalized input it captured at content_block_stop (CliSession)
|
|
918
|
+
// / from the full assistant block (SdkSession). tool_start is
|
|
919
|
+
// write-once (`_pushHistory` only ever appends), so without this
|
|
920
|
+
// the persisted entry stays `input: null` forever — the exact
|
|
921
|
+
// root cause of the "(no input)" placeholder surviving a session
|
|
922
|
+
// switch: a forceFull replay faithfully rebuilds from history,
|
|
923
|
+
// and history never had the input to rebuild WITH. Search
|
|
924
|
+
// backward (most turns have only a handful of recent entries,
|
|
925
|
+
// and the match is almost always near the end) rather than
|
|
926
|
+
// indexing by toolUseId, since tool_start entries are rare
|
|
927
|
+
// enough that a second Map isn't worth the bookkeeping.
|
|
928
|
+
//
|
|
929
|
+
// BYOK never sets `data.input` (its `_getTrackedToolInput` is
|
|
930
|
+
// never even reached — see tool-result.js), so this loop is a
|
|
931
|
+
// no-op for it and its tool_start entries are unchanged.
|
|
932
|
+
this.backfillToolInput(sessionId, data.toolUseId, data.input)
|
|
369
933
|
this._pushHistory(history, {
|
|
370
934
|
type: 'tool_result',
|
|
371
935
|
toolUseId: data.toolUseId,
|
|
372
936
|
result: data.result,
|
|
373
937
|
truncated: data.truncated,
|
|
938
|
+
// #7376: persist the failed / terminated markers, not just the text.
|
|
939
|
+
// This entry is what a reconnect or session switch replays raw.
|
|
940
|
+
// (Sync Full History PREFERS the native JSONL, whose parser keeps no
|
|
941
|
+
// tool results, so that path carries neither marker; the ring-buffer
|
|
942
|
+
// fallback still replays this entry.) Without them the live "turn
|
|
943
|
+
// terminated" (or "failed") state silently reverted to a plain green
|
|
944
|
+
// result on replay. Only the
|
|
945
|
+
// meaningful values are stored (`isError: true`, a string reason), so
|
|
946
|
+
// entries for ordinary successful results are byte-for-byte unchanged.
|
|
947
|
+
...(data.isError === true ? { isError: true } : {}),
|
|
948
|
+
...(typeof data.terminatedReason === 'string' ? { terminatedReason: data.terminatedReason } : {}),
|
|
374
949
|
timestamp: Date.now(),
|
|
375
950
|
}, sessionId)
|
|
376
951
|
break
|
|
@@ -381,22 +956,77 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
381
956
|
cost: data.cost,
|
|
382
957
|
duration: data.duration,
|
|
383
958
|
usage: data.usage,
|
|
959
|
+
// #7326: durable, so a session switch or reload re-shows the marker.
|
|
960
|
+
// Omitted when unknown, so ordinary entries are unchanged.
|
|
961
|
+
...turnOutcomeField(data.turnOutcome),
|
|
962
|
+
// #7326: a result that was stamped at emit keeps that stamp, so the
|
|
963
|
+
// replayed entry and the live frame share the marker's identity.
|
|
964
|
+
timestamp: Number.isFinite(data.timestamp) ? data.timestamp : Date.now(),
|
|
965
|
+
}, sessionId)
|
|
966
|
+
persistNeeded = true
|
|
967
|
+
break
|
|
968
|
+
|
|
969
|
+
case 'permission_outcome': {
|
|
970
|
+
// #8348 -- the durable record of how a permission prompt ended. The live
|
|
971
|
+
// `permission_request` / `permission_resolved` / `permission_expired`
|
|
972
|
+
// frames are transient (never in the ring buffer), so a full-rebuild
|
|
973
|
+
// replay (session switch, reload) cannot show a prompt that already
|
|
974
|
+
// expired or was answered; this entry is what it replays instead.
|
|
975
|
+
//
|
|
976
|
+
// ONE entry per requestId. SessionManager's request registry already
|
|
977
|
+
// makes a second call a no-op, but the entry must not depend on its
|
|
978
|
+
// caller for that: a duplicate here would put two records in the
|
|
979
|
+
// transcript, and the ring buffer is the only place both are visible.
|
|
980
|
+
if (!data || typeof data.requestId !== 'string' || data.requestId.length === 0) break
|
|
981
|
+
if (!PERMISSION_OUTCOMES.includes(data.outcome)) break
|
|
982
|
+
for (let i = history.length - 1; i >= 0; i--) {
|
|
983
|
+
const prior = history[i]
|
|
984
|
+
if (prior && prior.type === 'permission_outcome' && prior.requestId === data.requestId) {
|
|
985
|
+
return { persistNeeded: false }
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
this._pushHistory(history, {
|
|
989
|
+
type: 'permission_outcome',
|
|
990
|
+
requestId: data.requestId,
|
|
991
|
+
tool: clipRedacted(data.tool, PERMISSION_OUTCOME_TOOL_MAX),
|
|
992
|
+
description: clipRedacted(data.description, PERMISSION_OUTCOME_DESCRIPTION_MAX),
|
|
993
|
+
outcome: data.outcome,
|
|
994
|
+
// #8503: the tool input the clients were shown, so a replayed record
|
|
995
|
+
// and group read the same as a live one. Omitted when there is none,
|
|
996
|
+
// which is also every entry from before this field.
|
|
997
|
+
...inputField(boundPermissionOutcomeInput(data.input)),
|
|
998
|
+
// #8503: which allow it was (see PERMISSION_ALLOW_DECISIONS). Omitted for
|
|
999
|
+
// any other outcome and for an entry from before the field.
|
|
1000
|
+
...decisionField(permissionOutcomeDecision(data.outcome, data.decision)),
|
|
1001
|
+
// #8357: the tool-use id the prompt carried, so a replayed record still
|
|
1002
|
+
// pairs with its AskUserQuestion card. Omitted when there is none.
|
|
1003
|
+
...(typeof data.toolUseId === 'string' && data.toolUseId.length > 0 && data.toolUseId.length <= 200
|
|
1004
|
+
? { toolUseId: data.toolUseId }
|
|
1005
|
+
: {}),
|
|
384
1006
|
timestamp: Date.now(),
|
|
385
1007
|
}, sessionId)
|
|
386
1008
|
persistNeeded = true
|
|
387
1009
|
break
|
|
1010
|
+
}
|
|
388
1011
|
|
|
389
1012
|
case 'user_question':
|
|
390
1013
|
this._pushHistory(history, {
|
|
391
1014
|
type: 'user_question',
|
|
392
1015
|
toolUseId: data.toolUseId,
|
|
393
1016
|
questions: data.questions,
|
|
1017
|
+
// #8336: the provider's id for the AskUserQuestion tool call, when it
|
|
1018
|
+
// differs from `toolUseId` (the SDK and BYOK route the answer on a
|
|
1019
|
+
// chroxy-minted `ask-...` id). It is how the restore-time sweep finds
|
|
1020
|
+
// the `tool_start` this question belongs to.
|
|
1021
|
+
...(typeof data.sourceToolUseId === 'string' && data.sourceToolUseId.length > 0
|
|
1022
|
+
? { sourceToolUseId: data.sourceToolUseId }
|
|
1023
|
+
: {}),
|
|
394
1024
|
timestamp: Date.now(),
|
|
395
1025
|
}, sessionId)
|
|
396
1026
|
break
|
|
397
1027
|
}
|
|
398
1028
|
|
|
399
|
-
return { persistNeeded }
|
|
1029
|
+
return { persistNeeded, ...(assistantCompleted ? { assistantCompleted, completedAssistant } : {}) }
|
|
400
1030
|
}
|
|
401
1031
|
|
|
402
1032
|
/**
|
|
@@ -419,9 +1049,58 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
419
1049
|
}
|
|
420
1050
|
}
|
|
421
1051
|
|
|
1052
|
+
/**
|
|
1053
|
+
* #7346 / #8371: set the finalized `input` on the matching `tool_start`
|
|
1054
|
+
* entry. `tool_start` is write-once (`_pushHistory` only appends) and every
|
|
1055
|
+
* claude provider emits it with `input: null`, so without this a replay
|
|
1056
|
+
* rebuilds from history that never had the input to rebuild WITH.
|
|
1057
|
+
*
|
|
1058
|
+
* Two callers, one rule: `tool_result` (#7346, the input rode the result)
|
|
1059
|
+
* and `BaseSession._recordToolInput` via the session manager (#8371, the
|
|
1060
|
+
* moment the provider knows the input, which is BEFORE the tool runs -- a
|
|
1061
|
+
* replay during a still-running tool otherwise shows no INPUT). Both pass an
|
|
1062
|
+
* already-sanitised, size-capped value (`sanitizeToolInput`); this method
|
|
1063
|
+
* stores nothing else and applies no second copy of the redaction.
|
|
1064
|
+
*
|
|
1065
|
+
* Does not schedule a persist and returns no flag for one: `tool_start` and
|
|
1066
|
+
* `tool_result` themselves never set `persistNeeded` (the next message or
|
|
1067
|
+
* result persists the whole history, `truncateEntry` bounding the input).
|
|
1068
|
+
* Searches backward, so a repeated toolUseId backfills the most recent.
|
|
1069
|
+
*
|
|
1070
|
+
* @param {string} sessionId
|
|
1071
|
+
* @param {string} toolUseId
|
|
1072
|
+
* @param {unknown} input - sanitised input; `undefined` is ignored
|
|
1073
|
+
* @returns {boolean} true when a tool_start entry was updated
|
|
1074
|
+
*/
|
|
1075
|
+
backfillToolInput(sessionId, toolUseId, input) {
|
|
1076
|
+
if (input === undefined) return false
|
|
1077
|
+
const history = this._messageHistory.get(sessionId)
|
|
1078
|
+
if (!Array.isArray(history)) return false
|
|
1079
|
+
for (let i = history.length - 1; i >= 0; i--) {
|
|
1080
|
+
const entry = history[i]
|
|
1081
|
+
if (entry && entry.type === 'tool_start' && entry.toolUseId === toolUseId) {
|
|
1082
|
+
entry.input = input
|
|
1083
|
+
return true
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
return false
|
|
1087
|
+
}
|
|
1088
|
+
|
|
422
1089
|
/**
|
|
423
1090
|
* Shallow-clone and truncate a history entry for serialization.
|
|
424
1091
|
* Content/input fields >50KB are truncated to avoid bloated state files.
|
|
1092
|
+
*
|
|
1093
|
+
* #8136 (review on #7346): `input` on a `tool_start` entry used to be
|
|
1094
|
+
* `null` for every provider, so the string-only check below was dead
|
|
1095
|
+
* code for it. Since #7346's backfill, `input` is a PARSED OBJECT (the
|
|
1096
|
+
* tool's structured arguments, e.g. `{ file_path, content }` for
|
|
1097
|
+
* `Write`) — measured here by its SERIALIZED size, matching the string
|
|
1098
|
+
* branch's semantics rather than leaving objects uncapped entirely.
|
|
1099
|
+
* (In practice `base-session.js`'s `_recordToolInput` already runs
|
|
1100
|
+
* every captured input through `sanitizeToolInput`'s ~10KB broadcast
|
|
1101
|
+
* cap before it ever reaches history, so this branch is defense in
|
|
1102
|
+
* depth — a second, independent bound at the persistence boundary — not
|
|
1103
|
+
* the only thing standing between a huge input and the state file.)
|
|
425
1104
|
* @param {object} entry
|
|
426
1105
|
* @returns {object}
|
|
427
1106
|
*/
|
|
@@ -436,13 +1115,38 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
436
1115
|
}
|
|
437
1116
|
if (typeof clone.input === 'string' && clone.input.length > MAX) {
|
|
438
1117
|
clone.input = clone.input.slice(0, MAX) + '[truncated]'
|
|
1118
|
+
} else if (clone.input && typeof clone.input === 'object') {
|
|
1119
|
+
// #8136: object-shaped input (tool_start, since #7346's backfill) —
|
|
1120
|
+
// the string branch above never fires for it. Serialize to measure
|
|
1121
|
+
// its real on-disk size; a cyclic/unserializable value (shouldn't
|
|
1122
|
+
// happen for a JSON-sourced tool input, but defensive) falls back
|
|
1123
|
+
// to a safe marker rather than throwing out of a persist path.
|
|
1124
|
+
let serialized
|
|
1125
|
+
try {
|
|
1126
|
+
serialized = JSON.stringify(clone.input)
|
|
1127
|
+
} catch {
|
|
1128
|
+
serialized = null
|
|
1129
|
+
}
|
|
1130
|
+
if (typeof serialized !== 'string') {
|
|
1131
|
+
clone.input = { _truncated: true, summary: '[unserializable]' }
|
|
1132
|
+
} else if (serialized.length > MAX) {
|
|
1133
|
+
clone.input = { _truncated: true, summary: serialized.slice(0, MAX) + '... [truncated]' }
|
|
1134
|
+
}
|
|
439
1135
|
}
|
|
440
1136
|
return clone
|
|
441
1137
|
}
|
|
442
1138
|
|
|
443
1139
|
/**
|
|
444
1140
|
* Auto-label a session from the first user input if it still has a default name.
|
|
445
|
-
*
|
|
1141
|
+
*
|
|
1142
|
+
* Applies the word-boundary truncation label SYNCHRONOUSLY (via
|
|
1143
|
+
* `truncateTitle`) so a session is never left unnamed — this is the always-
|
|
1144
|
+
* available fallback. It also emits `auto_label` carrying the original first
|
|
1145
|
+
* message `text`, so a listener (SessionManager, #6764) can optionally fire an
|
|
1146
|
+
* asynchronous cheap-model call to UPGRADE the truncation to a short semantic
|
|
1147
|
+
* title. Firing only from here means the semantic path inherits this method's
|
|
1148
|
+
* once-per-session + default-name + manual-rename guards for free.
|
|
1149
|
+
*
|
|
446
1150
|
* @param {string} sessionId
|
|
447
1151
|
* @param {string} text
|
|
448
1152
|
* @param {object} sessionEntry - Must have { name, _autoLabeled } properties
|
|
@@ -463,18 +1167,12 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
463
1167
|
|
|
464
1168
|
sessionEntry._autoLabeled = true
|
|
465
1169
|
|
|
466
|
-
const
|
|
467
|
-
let label
|
|
468
|
-
if (trimmed.length <= MAX_LEN) {
|
|
469
|
-
label = trimmed
|
|
470
|
-
} else {
|
|
471
|
-
const cut = trimmed.lastIndexOf(' ', MAX_LEN)
|
|
472
|
-
label = (cut > 10 ? trimmed.slice(0, cut) : trimmed.slice(0, MAX_LEN)) + '...'
|
|
473
|
-
}
|
|
474
|
-
|
|
1170
|
+
const label = truncateTitle(trimmed)
|
|
475
1171
|
sessionEntry.name = label
|
|
476
1172
|
log.info(`Auto-labeled session ${sessionId} to "${label}"`)
|
|
477
|
-
|
|
1173
|
+
// `text` is the untruncated first message — the semantic-title upgrade path
|
|
1174
|
+
// needs the full source, not the already-truncated label.
|
|
1175
|
+
this.emit('auto_label', { sessionId, label, text: trimmed })
|
|
478
1176
|
}
|
|
479
1177
|
|
|
480
1178
|
/**
|
|
@@ -485,6 +1183,7 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
485
1183
|
this._messageHistory.delete(sessionId)
|
|
486
1184
|
this._historyTruncated.delete(sessionId)
|
|
487
1185
|
this._seqCounters.delete(sessionId)
|
|
1186
|
+
this._seqReserved.delete(sessionId)
|
|
488
1187
|
|
|
489
1188
|
// Clean up pending stream state (composite keys: `${sessionId}:messageId`)
|
|
490
1189
|
const prefix = sessionId + ':'
|
|
@@ -497,6 +1196,15 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
497
1196
|
for (const key of this._truncatedStreams) {
|
|
498
1197
|
if (key.startsWith(prefix)) this._truncatedStreams.delete(key)
|
|
499
1198
|
}
|
|
1199
|
+
for (const key of this._streamKinds.keys()) {
|
|
1200
|
+
if (key.startsWith(prefix)) this._streamKinds.delete(key)
|
|
1201
|
+
}
|
|
1202
|
+
for (const key of this._streamPrecedes.keys()) {
|
|
1203
|
+
if (key.startsWith(prefix)) this._streamPrecedes.delete(key)
|
|
1204
|
+
}
|
|
1205
|
+
for (const key of this._streamStartSeqs.keys()) {
|
|
1206
|
+
if (key.startsWith(prefix)) this._streamStartSeqs.delete(key)
|
|
1207
|
+
}
|
|
500
1208
|
}
|
|
501
1209
|
|
|
502
1210
|
/**
|
|
@@ -506,6 +1214,10 @@ export class SessionMessageHistory extends EventEmitter {
|
|
|
506
1214
|
this._messageHistory.clear()
|
|
507
1215
|
this._historyTruncated.clear()
|
|
508
1216
|
this._pendingStreams.clear()
|
|
1217
|
+
this._streamKinds.clear()
|
|
1218
|
+
this._streamPrecedes.clear()
|
|
1219
|
+
this._streamStartSeqs.clear()
|
|
509
1220
|
this._seqCounters.clear()
|
|
1221
|
+
this._seqReserved.clear()
|
|
510
1222
|
}
|
|
511
1223
|
}
|