@chroxy/server 0.11.0 → 0.11.11
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 +206 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- 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 +958 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +304 -0
- package/src/agent-control/client.js +1645 -0
- package/src/agent-control/events.js +551 -0
- package/src/agent-control/local-connection.js +293 -0
- package/src/agent-control/mcp-server.js +547 -0
- package/src/anthropic-compatible-config.js +30 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- 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 +1520 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +291 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- 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 +92 -7
- package/src/byok-mcp-config.js +633 -122
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +37 -23
- package/src/byok-session.js +707 -179
- package/src/byok-tool-executor.js +2742 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- 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-setting-sources.js +74 -0
- package/src/claude-stream-parser.js +53 -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 +215 -88
- 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 +3563 -284
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-cmd.js +236 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/connection-state.js +54 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/pages-cmd.js +6 -4
- package/src/cli/pair-code-cmd.js +7 -6
- package/src/cli/pair-discord-cmd.js +7 -6
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +91 -40
- package/src/cli/server-cmd.js +54 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1250 -126
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1517 -81
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-error-text.js +114 -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 +450 -27
- package/src/config-dir-migration.js +449 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +306 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +78 -23
- 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 +227 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +42 -39
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +28 -39
- package/src/credential-store.js +23 -19
- 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 +170 -182
- package/src/device-preferences.js +2 -2
- 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 +172 -3
- package/src/docker-session.js +294 -11
- package/src/doctor.js +781 -64
- package/src/durable-write.js +35 -0
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +101 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +186 -235
- package/src/folder-trust-wire.js +137 -0
- package/src/folder-trust-worker.js +17 -0
- package/src/folder-trust.js +1572 -0
- package/src/freshness/activity-meter.js +101 -0
- package/src/freshness/adapter.js +199 -0
- package/src/freshness/checks.js +239 -0
- package/src/freshness/config.js +98 -0
- package/src/freshness/core.js +185 -0
- package/src/freshness/derive.js +680 -0
- package/src/freshness/exchange.js +305 -0
- package/src/freshness/file-ledger.js +400 -0
- package/src/freshness/grade.js +81 -0
- package/src/freshness/hash.js +45 -0
- package/src/freshness/inbox.js +163 -0
- package/src/freshness/index.js +20 -0
- package/src/freshness/investigation.js +474 -0
- package/src/freshness/keys.js +177 -0
- package/src/freshness/ledger.js +122 -0
- package/src/freshness/outbox.js +131 -0
- package/src/freshness/policy.js +599 -0
- package/src/freshness/queue.js +843 -0
- package/src/freshness/read-errors.js +23 -0
- package/src/freshness/render.js +153 -0
- package/src/freshness/runtime.js +113 -0
- package/src/freshness/session-registry-adapter.js +161 -0
- package/src/freshness/state-file-adapter.js +167 -0
- package/src/freshness-runner/build-info.js +139 -0
- package/src/freshness-runner/cli.js +105 -0
- package/src/freshness-runner/run-tick.js +109 -0
- package/src/freshness-runner/stamp.js +57 -0
- package/src/freshness-sources/claude-transcript-adapter.js +211 -0
- package/src/freshness-sources/codex-transcript-adapter.js +33 -0
- package/src/freshness-sources/index.js +8 -0
- package/src/gemini-byok-session.js +292 -0
- package/src/gemini-credentials.js +67 -0
- package/src/gemini-key-safety.js +246 -0
- package/src/gemini-models.js +386 -0
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +540 -80
- package/src/handlers/checkpoint-handlers.js +47 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- 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 +57 -13
- package/src/handlers/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +714 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +92 -18
- package/src/handlers/session-handlers.js +551 -20
- 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 +372 -50
- package/src/handlers/skills-handlers.js +20 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +112 -0
- package/src/http-routes.js +127 -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 +378 -91
- package/src/jsonl-subprocess-session.js +96 -9
- package/src/keychain.js +1 -1
- package/src/logger.js +166 -30
- package/src/mailbox-route.js +113 -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 +27 -4
- 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 +64 -23
- 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 +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +112 -36
- package/src/orchestration/permission-gate.js +17 -2
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +185 -43
- package/src/orphan-reaper.js +470 -0
- package/src/outgoing-policy.js +189 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1410 -43
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +737 -89
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +126 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +315 -47
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/principal-audit.js +189 -0
- package/src/principal-binding.js +25 -0
- package/src/principal-brakes.js +21 -0
- package/src/principal-effect.js +101 -0
- package/src/principal-journal.js +905 -0
- package/src/principal-kill-switch.js +183 -0
- package/src/principal-label.js +5 -0
- package/src/principal-pending-permissions.js +177 -0
- package/src/principal-policy.js +1094 -0
- package/src/principal-sessions-snapshot.js +208 -0
- package/src/principal-store.js +488 -0
- package/src/principal-subscriptions.js +283 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +209 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +531 -20
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +330 -26
- package/src/scheduler.js +368 -11
- package/src/sdk-session.js +2114 -188
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +17 -3
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +553 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- 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 +1099 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +4062 -312
- package/src/session-message-history.js +841 -16
- package/src/session-name-allocator.js +685 -0
- 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-token-store.js +17 -8
- 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 +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +100 -29
- package/src/summarize-session.js +53 -4
- package/src/supervisor.js +22 -11
- 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/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +140 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +770 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +639 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +29 -0
- package/src/utils/bounded-regex.js +162 -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 +133 -37
- 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/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/pid-liveness.js +47 -0
- package/src/utils/preflight.js +360 -16
- 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 +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +297 -16
- package/src/worktree-gc.js +202 -6
- package/src/ws-auth.js +163 -31
- package/src/ws-broadcaster.js +49 -5
- package/src/ws-client-manager.js +24 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +363 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +349 -39
- package/src/ws-handler-context.js +88 -2
- package/src/ws-history.js +1010 -175
- package/src/ws-message-handlers.js +25 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +885 -98
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- 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/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
|
@@ -8,31 +8,76 @@
|
|
|
8
8
|
import { realpathSync } from 'fs'
|
|
9
9
|
import { scanConversations as defaultScanConversations } from '../conversation-scanner.js'
|
|
10
10
|
import { searchConversations as defaultSearchConversations } from '../conversation-search.js'
|
|
11
|
-
import {
|
|
11
|
+
import { readConversationTranscriptStrictAsync as defaultReadConversationTranscript, transcriptReadLimiter } from '../jsonl-reader.js'
|
|
12
|
+
import { resolveTranscriptSource } from '../transcript-sources.js'
|
|
13
|
+
import { projectSlug } from '../jsonl-reader.js'
|
|
12
14
|
import { validateCwdAllowed, broadcastFocusChanged, resolveSession, autoSubscribeOtherClients, buildSessionTokenMismatchPayload, sendSessionError } from '../handler-utils.js'
|
|
13
|
-
import { scopeConversationsToClient } from '../conversation-scope.js'
|
|
15
|
+
import { scopeConversationsToClient, boundConversationId } from '../conversation-scope.js'
|
|
16
|
+
import { isBoundClient, markConversationFrame } from '../environments/authority.js'
|
|
17
|
+
import { ReadLimitError, ReadCancelledError, admissionFor } from '../utils/read-limiter.js'
|
|
18
|
+
import { sendChunkedWithBackpressure, sendHistoryEntry } from '../ws-history.js'
|
|
14
19
|
import { createLogger, loggerForSession } from '../logger.js'
|
|
15
20
|
|
|
16
21
|
const log = createLogger('ws')
|
|
17
22
|
|
|
23
|
+
// Transcript reads are admitted through the one limiter that sits under every
|
|
24
|
+
// transcript reader (jsonl-reader.js `transcriptReadLimiter`).
|
|
25
|
+
const defaultTranscriptReadLimiter = transcriptReadLimiter
|
|
26
|
+
|
|
27
|
+
// An AbortSignal that fires when `ws` closes. `dispose` removes the listener.
|
|
28
|
+
function signalOnClose(ws) {
|
|
29
|
+
const ac = new AbortController()
|
|
30
|
+
if (ws?.readyState === 2 || ws?.readyState === 3) ac.abort()
|
|
31
|
+
const onClose = () => ac.abort()
|
|
32
|
+
if (typeof ws?.once === 'function') ws.once('close', onClose)
|
|
33
|
+
return {
|
|
34
|
+
signal: ac.signal,
|
|
35
|
+
dispose: () => { if (typeof ws?.removeListener === 'function') ws.removeListener('close', onClose) },
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
18
39
|
// UUID v4-ish shape guard shared by resume_conversation and the read-only
|
|
19
40
|
// transcript handler — rejects anything that isn't a canonical conversation id
|
|
20
41
|
// before it reaches the filesystem, closing path-traversal via the id segment.
|
|
21
42
|
const CONVERSATION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
22
43
|
|
|
44
|
+
// Prefer the provider-TAGGED sources (#7828) so every discovered conversation
|
|
45
|
+
// carries its provider; fall back to bare dirs (untagged), then the scanner
|
|
46
|
+
// default (~/.claude/projects).
|
|
47
|
+
function scanOptsFor(ctx) {
|
|
48
|
+
const tagged = ctx.runtime.transcriptSources
|
|
49
|
+
if (Array.isArray(tagged) && tagged.length > 0) return { projectsDirs: tagged }
|
|
50
|
+
return ctx.runtime.projectsDirs ? { projectsDirs: ctx.runtime.projectsDirs } : {}
|
|
51
|
+
}
|
|
52
|
+
|
|
23
53
|
async function handleListConversations(ws, client, msg, ctx) {
|
|
24
54
|
// ctx.scanConversations override allows tests to inject a stub and skip real fs.
|
|
25
55
|
const scan = ctx.scanConversations || defaultScanConversations
|
|
26
56
|
try {
|
|
27
|
-
// Pass provider-driven
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
57
|
+
// Pass provider-driven sources when available (#2965, #7828).
|
|
58
|
+
const scanOpts = scanOptsFor(ctx)
|
|
59
|
+
// Scanning reads the head of every transcript in the store, so it is admitted
|
|
60
|
+
// through the same limiter as every other transcript read.
|
|
61
|
+
const closing = signalOnClose(ws)
|
|
62
|
+
let all
|
|
63
|
+
try {
|
|
64
|
+
all = await (ctx.transcriptReadLimiter || defaultTranscriptReadLimiter).submit(
|
|
65
|
+
{ key: `scan\0${JSON.stringify(scanOpts)}`, ...admissionFor(client, isBoundClient), signal: closing.signal },
|
|
66
|
+
() => scan(scanOpts),
|
|
67
|
+
)
|
|
68
|
+
} finally {
|
|
69
|
+
closing.dispose()
|
|
70
|
+
}
|
|
31
71
|
// Adversary A8: scope results so a bound pairing-issued client
|
|
32
72
|
// cannot enumerate conversations outside its session cwd.
|
|
33
73
|
const conversations = scopeConversationsToClient(all, client, ctx)
|
|
34
74
|
ctx.transport.send(ws, { type: 'conversations_list', conversations })
|
|
35
75
|
} catch (err) {
|
|
76
|
+
if (err instanceof ReadCancelledError) return
|
|
77
|
+
if (err instanceof ReadLimitError) {
|
|
78
|
+
sendSessionError(ws, ctx, `${err.message}. Try again shortly.`)
|
|
79
|
+
return
|
|
80
|
+
}
|
|
36
81
|
log.warn(`Failed to scan conversations: ${err.message}`)
|
|
37
82
|
ctx.transport.send(ws, { type: 'conversations_list', conversations: [] })
|
|
38
83
|
}
|
|
@@ -41,16 +86,38 @@ async function handleListConversations(ws, client, msg, ctx) {
|
|
|
41
86
|
async function handleSearchConversations(ws, client, msg, ctx) {
|
|
42
87
|
const { query, maxResults } = msg
|
|
43
88
|
const search = ctx.searchConversations || defaultSearchConversations
|
|
89
|
+
const closing = signalOnClose(ws)
|
|
44
90
|
try {
|
|
45
|
-
|
|
46
|
-
//
|
|
47
|
-
//
|
|
48
|
-
|
|
91
|
+
// A session-scoped connection searches only the conversation its own session
|
|
92
|
+
// is running: the source is chosen BEFORE anything is read, ranked or
|
|
93
|
+
// truncated, so what other conversations contain cannot change the answer.
|
|
94
|
+
const scoped = isBoundClient(client)
|
|
95
|
+
const own = scoped ? boundConversationId(client, ctx) : null
|
|
96
|
+
const ownCwd = scoped ? ctx.sessions.sessionManager?.getSession?.(client.boundSessionId)?.cwd : null
|
|
97
|
+
// Source selection needs BOTH the conversation association and the project
|
|
98
|
+
// that association lives in (the daemon's own derivation from the session's cwd).
|
|
99
|
+
const searchOpts = scoped
|
|
100
|
+
? { maxResults, conversationId: own, projectDirName: typeof ownCwd === 'string' && ownCwd ? projectSlug(ownCwd) : null }
|
|
101
|
+
: { maxResults }
|
|
102
|
+
const all = scoped && (!own || !searchOpts.projectDirName)
|
|
103
|
+
? []
|
|
104
|
+
: await (ctx.transcriptReadLimiter || defaultTranscriptReadLimiter).submit(
|
|
105
|
+
{ key: `search\0${query}\0${maxResults ?? ''}\0${own ?? ''}`, ...admissionFor(client, isBoundClient), signal: closing.signal },
|
|
106
|
+
() => search(query, searchOpts),
|
|
107
|
+
)
|
|
108
|
+
// The cwd check still applies to what comes back.
|
|
49
109
|
const results = scopeConversationsToClient(all, client, ctx)
|
|
50
110
|
ctx.transport.send(ws, { type: 'search_results', query, results })
|
|
51
111
|
} catch (err) {
|
|
112
|
+
if (err instanceof ReadCancelledError) return
|
|
113
|
+
if (err instanceof ReadLimitError) {
|
|
114
|
+
sendSessionError(ws, ctx, `${err.message}. Try again shortly.`)
|
|
115
|
+
return
|
|
116
|
+
}
|
|
52
117
|
log.warn(`Failed to search conversations: ${err.message}`)
|
|
53
118
|
ctx.transport.send(ws, { type: 'search_results', query, results: [] })
|
|
119
|
+
} finally {
|
|
120
|
+
closing.dispose()
|
|
54
121
|
}
|
|
55
122
|
}
|
|
56
123
|
|
|
@@ -128,12 +195,14 @@ async function handleResumeConversation(ws, client, msg, ctx) {
|
|
|
128
195
|
* `capabilities.resume === false` (BYOK, Codex, Gemini, user-shell) for which
|
|
129
196
|
* `resume_conversation` is refused outright.
|
|
130
197
|
*
|
|
131
|
-
* Access follows the same
|
|
198
|
+
* Access follows the same scoping as `list_conversations`/`search_conversations`
|
|
132
199
|
* (`scopeConversationsToClient`): an UNBOUND client (primary token / dashboard)
|
|
133
|
-
* may read any conversation; a
|
|
134
|
-
*
|
|
135
|
-
*
|
|
136
|
-
*
|
|
200
|
+
* may read any conversation; a session-scoped client may read only the
|
|
201
|
+
* conversation its own session is running (conversation-scope.js) — anything
|
|
202
|
+
* else, or any case where the daemon does not know that association, is
|
|
203
|
+
* rejected. Reads go through a shared limiter (daemon-wide and per-connection
|
|
204
|
+
* caps, a bounded queue, coalescing of identical in-flight reads, and
|
|
205
|
+
* cancellation when the connection closes).
|
|
137
206
|
*
|
|
138
207
|
* The response reuses the existing `history_replay_start` / `message` /
|
|
139
208
|
* `history_replay_end` server→client frames (identical to `handleRequestFullHistory`,
|
|
@@ -142,6 +211,11 @@ async function handleResumeConversation(ws, client, msg, ctx) {
|
|
|
142
211
|
* is no live session, and a resumed session always gets a fresh id distinct from
|
|
143
212
|
* the conversationId, so this cannot collide with or clobber a live session's
|
|
144
213
|
* transcript.
|
|
214
|
+
*
|
|
215
|
+
* `history_replay_start` carries `truncated` for the slice actually sent (#7501),
|
|
216
|
+
* from the same meta reader `getFullHistoryAsync` uses — this path is subject to
|
|
217
|
+
* jsonl-reader's `MAX_MESSAGES` / `MAX_TRANSCRIPT_BYTES` caps exactly as the
|
|
218
|
+
* full-history path is, and used to omit the field entirely.
|
|
145
219
|
*/
|
|
146
220
|
async function handleRequestConversationTranscript(ws, client, msg, ctx) {
|
|
147
221
|
const { conversationId } = msg
|
|
@@ -155,28 +229,78 @@ async function handleRequestConversationTranscript(ws, client, msg, ctx) {
|
|
|
155
229
|
return
|
|
156
230
|
}
|
|
157
231
|
|
|
232
|
+
// Every failure from here on names the conversation it answers, with a
|
|
233
|
+
// stable code, so a viewer waiting on THIS conversation can settle on the
|
|
234
|
+
// reason instead of waiting out its inactivity timer.
|
|
235
|
+
const fail = (message) => ctx.transport.send(ws, {
|
|
236
|
+
type: 'session_error',
|
|
237
|
+
message,
|
|
238
|
+
code: 'TRANSCRIPT_UNAVAILABLE',
|
|
239
|
+
conversationId,
|
|
240
|
+
})
|
|
241
|
+
|
|
242
|
+
// A session-scoped connection may read only the conversation its own session
|
|
243
|
+
// is running. Decided from the daemon's association between the session and
|
|
244
|
+
// its conversation — before any scan or file access, and without consulting
|
|
245
|
+
// anything the client supplied. No known association means no access.
|
|
246
|
+
const scoped = isBoundClient(client)
|
|
247
|
+
if (scoped && conversationId !== boundConversationId(client, ctx)) {
|
|
248
|
+
fail('Not authorized to view this conversation')
|
|
249
|
+
return
|
|
250
|
+
}
|
|
251
|
+
|
|
158
252
|
// Resolve the conversation's recorded cwd authoritatively from the persisted
|
|
159
253
|
// store (the scanner reads the same JSONL layer list_conversations does). Only
|
|
160
254
|
// fall back to a client-provided cwd hint when the scan can't find it (e.g. a
|
|
161
255
|
// tiny conversation below the scanner's MIN_FILE_SIZE floor).
|
|
162
256
|
const scan = ctx.scanConversations || defaultScanConversations
|
|
163
|
-
|
|
257
|
+
//
|
|
258
|
+
// The same conversation id can exist under more than one provider's store.
|
|
259
|
+
// Collect EVERY match; the optional `provider` on the request selects one. An
|
|
260
|
+
// id that matches several providers with no selector is refused rather than
|
|
261
|
+
// resolved by whichever the scanner happened to list first (#7828).
|
|
262
|
+
let matches = []
|
|
164
263
|
try {
|
|
165
|
-
const
|
|
166
|
-
|
|
167
|
-
conv = Array.isArray(all) ? all.find((c) => c?.conversationId === conversationId) || null : null
|
|
264
|
+
const all = await scan(scanOptsFor(ctx))
|
|
265
|
+
matches = Array.isArray(all) ? all.filter((c) => c?.conversationId === conversationId) : []
|
|
168
266
|
} catch (err) {
|
|
169
267
|
// Scan failure is non-fatal — fall through to the client-provided cwd hint.
|
|
170
268
|
log.warn(`Transcript scan failed for ${conversationId}: ${err.message}`)
|
|
171
269
|
}
|
|
270
|
+
const wantedProvider = typeof msg.provider === 'string' && msg.provider ? msg.provider : null
|
|
271
|
+
// Authorization comes BEFORE any answer that depends on how many records
|
|
272
|
+
// exist or which providers hold them: a bound client is shown only the
|
|
273
|
+
// records it may see, and when every record is outside its scope it gets the
|
|
274
|
+
// same response a single out-of-scope record always got.
|
|
275
|
+
if (matches.length > 0) {
|
|
276
|
+
matches = scopeConversationsToClient(matches, client, ctx)
|
|
277
|
+
if (matches.length === 0) {
|
|
278
|
+
fail('Not authorized to view this conversation')
|
|
279
|
+
return
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
if (wantedProvider) matches = matches.filter((c) => c?.provider === wantedProvider)
|
|
283
|
+
if (matches.length > 1) {
|
|
284
|
+
const providers = new Set(matches.map((c) => c?.provider))
|
|
285
|
+
fail(providers.size > 1
|
|
286
|
+
? 'This conversation id exists under more than one provider and cannot be opened unambiguously from here. Open it from its provider\'s own session list.'
|
|
287
|
+
: 'Conversation id has more than one record for this provider, so it cannot be read unambiguously')
|
|
288
|
+
return
|
|
289
|
+
}
|
|
290
|
+
const conv = matches[0] || null
|
|
172
291
|
|
|
173
292
|
let cwd = conv?.cwd || null
|
|
174
|
-
if (!cwd &&
|
|
293
|
+
if (!cwd && scoped) {
|
|
294
|
+
// The directory comes from the daemon's own record of the session, never
|
|
295
|
+
// from the request.
|
|
296
|
+
const ownCwd = ctx.sessions.sessionManager?.getSession?.(client.boundSessionId)?.cwd
|
|
297
|
+
cwd = typeof ownCwd === 'string' && ownCwd ? ownCwd : null
|
|
298
|
+
} else if (!cwd && typeof msg.cwd === 'string' && msg.cwd) {
|
|
175
299
|
// Client-supplied fallback: validate it against the same path hygiene the
|
|
176
300
|
// create/resume paths enforce before trusting it to resolve a filesystem path.
|
|
177
301
|
const cwdError = validateCwdAllowed(msg.cwd, ctx.services.config)
|
|
178
302
|
if (cwdError) {
|
|
179
|
-
|
|
303
|
+
fail(cwdError)
|
|
180
304
|
return
|
|
181
305
|
}
|
|
182
306
|
// Defense-in-depth: validateCwdAllowed already resolved + vetted the realpath
|
|
@@ -186,51 +310,155 @@ async function handleRequestConversationTranscript(ws, client, msg, ctx) {
|
|
|
186
310
|
try {
|
|
187
311
|
cwd = realpathSync(msg.cwd)
|
|
188
312
|
} catch {
|
|
189
|
-
|
|
313
|
+
fail(`Cannot resolve path: ${msg.cwd}`)
|
|
190
314
|
return
|
|
191
315
|
}
|
|
192
316
|
}
|
|
193
317
|
|
|
194
318
|
if (!cwd) {
|
|
195
|
-
|
|
319
|
+
fail(`Conversation not found: ${conversationId}`)
|
|
196
320
|
return
|
|
197
321
|
}
|
|
198
322
|
|
|
199
323
|
// Scope enforcement — reuse the guard list_conversations/search_conversations
|
|
200
324
|
// use. A bound client that can't see this cwd gets an empty set → reject.
|
|
201
|
-
const
|
|
202
|
-
if (
|
|
203
|
-
|
|
325
|
+
const inScope = scopeConversationsToClient([{ conversationId, cwd }], client, ctx)
|
|
326
|
+
if (inScope.length === 0) {
|
|
327
|
+
fail('Not authorized to view this conversation')
|
|
204
328
|
return
|
|
205
329
|
}
|
|
206
330
|
|
|
207
331
|
// Read the transcript from disk. NO createSession, NO provider spawn. Reader is
|
|
208
332
|
// injectable for tests so the suite never touches the real ~/.claude/projects.
|
|
209
|
-
|
|
333
|
+
//
|
|
334
|
+
// #7501 — through the META reader, not the array-returning sibling one line
|
|
335
|
+
// away. This path is subject to jsonl-reader's OWN two caps (the 500
|
|
336
|
+
// most-recent `MAX_MESSAGES` window and the `MAX_TRANSCRIPT_BYTES` tail read),
|
|
337
|
+
// and the array alone cannot express either: 500 entries back is equally the
|
|
338
|
+
// shape of a complete 500-message conversation. This is the SAME reader
|
|
339
|
+
// `getFullHistoryAsync` uses for the full-history path (#7484) rather than a
|
|
340
|
+
// second meta implementation, so both replays report the same caps from one
|
|
341
|
+
// place and cannot drift apart.
|
|
342
|
+
//
|
|
343
|
+
// #7828 — the file is chosen by the conversation's OWN provider and locator,
|
|
344
|
+
// never by assuming Claude's layout. A refusal (unknown/unsupported provider,
|
|
345
|
+
// mismatched or escaping locator) is a session_error; nothing is retried
|
|
346
|
+
// against another provider's store.
|
|
347
|
+
const source = resolveTranscriptSource({
|
|
348
|
+
// A conversation the scan found carries its provider (absent => unknown).
|
|
349
|
+
// The cwd-hint path has no scan record and is Claude-only unless the
|
|
350
|
+
// request names another provider, which then reports its own refusal.
|
|
351
|
+
provider: conv ? conv.provider : (wantedProvider || 'claude'),
|
|
352
|
+
conversationId,
|
|
353
|
+
cwd,
|
|
354
|
+
sourceLocator: conv?.sourceLocator ?? null,
|
|
355
|
+
sources: ctx.runtime.transcriptSources,
|
|
356
|
+
})
|
|
357
|
+
if (!source.ok) {
|
|
358
|
+
fail(source.reason)
|
|
359
|
+
return
|
|
360
|
+
}
|
|
361
|
+
const readTranscript = ctx.readConversationTranscript || defaultReadConversationTranscript
|
|
210
362
|
let messages = []
|
|
363
|
+
let truncated = false
|
|
364
|
+
const limiter = ctx.transcriptReadLimiter || defaultTranscriptReadLimiter
|
|
365
|
+
const closing = signalOnClose(ws)
|
|
211
366
|
try {
|
|
212
|
-
|
|
367
|
+
// Duplicate in-flight requests for the same file share one read.
|
|
368
|
+
const readKey = `${source.path}\0${source.identity ? `${source.identity.dev}:${source.identity.ino}` : ''}`
|
|
369
|
+
const read = await limiter.submit(
|
|
370
|
+
{ key: readKey, ...admissionFor(client, isBoundClient), signal: closing.signal },
|
|
371
|
+
(signal) => readTranscript(source.path, undefined, { expectedIdentity: source.identity, signal, admitted: true }),
|
|
372
|
+
)
|
|
373
|
+
if (Array.isArray(read)) {
|
|
374
|
+
// The pre-#7501 reader shape. `ctx.readConversationTranscript` is a
|
|
375
|
+
// TEST-ONLY injection seam — nothing in production injects it, so this
|
|
376
|
+
// branch is unreachable outside the suite — and a legacy fixture still
|
|
377
|
+
// supplies a bare array, accepted and reported as untruncated rather than
|
|
378
|
+
// throwing on a shape that used to work. `false` over omitting the field:
|
|
379
|
+
// omitting it puts the frame back into the exact absent-vs-false ambiguity
|
|
380
|
+
// #7501 removes, and gives the wire two shapes to pin instead of one. Same
|
|
381
|
+
// posture handleRequestFullHistory takes toward a descriptor-less legacy
|
|
382
|
+
// manager.
|
|
383
|
+
messages = read
|
|
384
|
+
} else if (read && Array.isArray(read.messages)) {
|
|
385
|
+
messages = read.messages
|
|
386
|
+
// Strict boolean, matching how both clients read this family of field.
|
|
387
|
+
truncated = read.truncated === true
|
|
388
|
+
}
|
|
213
389
|
} catch (err) {
|
|
214
|
-
//
|
|
390
|
+
// The connection went away while the read waited or ran: nobody to answer.
|
|
391
|
+
if (err instanceof ReadCancelledError || err?.code === 'cancelled') return
|
|
392
|
+
if (err instanceof ReadLimitError) {
|
|
393
|
+
fail(`${err.message}. Try again shortly.`)
|
|
394
|
+
return
|
|
395
|
+
}
|
|
396
|
+
// #7828 — a missing/unreadable file or a corrupt record is a DATA error, not
|
|
397
|
+
// an empty successful transcript: say so, and send no replay frames.
|
|
215
398
|
log.warn(`Failed to read transcript for ${conversationId}: ${err.message}`)
|
|
216
|
-
|
|
399
|
+
fail(err?.name === 'TranscriptDataError' ? err.message : 'Transcript could not be read. Try again.')
|
|
400
|
+
return
|
|
401
|
+
} finally {
|
|
402
|
+
closing.dispose()
|
|
217
403
|
}
|
|
218
404
|
|
|
219
405
|
// Stream back using the SAME wire shape as request_full_history so existing
|
|
220
406
|
// renderers light up. `sessionId` carries the conversationId (read-only; no
|
|
221
407
|
// live session exists for a closed conversation).
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
408
|
+
//
|
|
409
|
+
// Route through ctx.transport so a method-style sender keeps its receiver;
|
|
410
|
+
// the shared loop only ever needs a (ws, payload) callable.
|
|
411
|
+
// Frames of this replay name the conversation in `sessionId`; the conversation
|
|
412
|
+
// was authorised above, so they are marked as conversation frames (see
|
|
413
|
+
// markConversationFrame) and the delivery rule for other-session tags skips them.
|
|
414
|
+
const send = (target, payload) => ctx.transport.send(target, markConversationFrame(payload))
|
|
415
|
+
|
|
416
|
+
// #7501 — `truncated` describes the collection ACTUALLY SENT, and is emitted
|
|
417
|
+
// unconditionally: absence reads to a client exactly like `truncated: false`,
|
|
418
|
+
// which is what let this path hand the viewer the last 500 messages of a
|
|
419
|
+
// 5,000-message conversation with nothing on the wire saying so.
|
|
420
|
+
send(ws, { type: 'history_replay_start', sessionId: conversationId, truncated, fullHistory: true, conversationId })
|
|
421
|
+
|
|
422
|
+
// #7480 — the THIRD path through the #4833 chunk-and-drain loop, and the
|
|
423
|
+
// second one that had no `bufferedAmount` check at all: it pushed the whole
|
|
424
|
+
// transcript onto the socket in one turn of the event loop.
|
|
425
|
+
// `MAX_TRANSCRIPT_BYTES` caps the transcript, not how much of it is buffered
|
|
426
|
+
// on the socket at once, so a large transcript on a slow link could still
|
|
427
|
+
// sail past the 1MB EVICT_THRESHOLD in ws-client-sender.js — which CLOSES
|
|
428
|
+
// the client. Measured on the pre-fix code, a 30-entry fat transcript peaked
|
|
429
|
+
// at 6,148,308 bytes buffered: 5.9x the eviction line.
|
|
430
|
+
sendChunkedWithBackpressure(ws, messages, {
|
|
431
|
+
emit: (entry) => {
|
|
432
|
+
send(ws, {
|
|
433
|
+
type: 'message',
|
|
434
|
+
messageType: entry.type,
|
|
435
|
+
content: entry.content,
|
|
436
|
+
tool: entry.tool,
|
|
437
|
+
timestamp: entry.timestamp,
|
|
438
|
+
sessionId: conversationId,
|
|
439
|
+
})
|
|
440
|
+
},
|
|
441
|
+
onDone: () => {
|
|
442
|
+
send(ws, { type: 'history_replay_end', sessionId: conversationId })
|
|
443
|
+
// #7340: defence-in-depth. The dashboard normally DIVERTS this frame — it
|
|
444
|
+
// routes `history_replay_start`/`message`/`history_replay_end` for a pending
|
|
445
|
+
// transcript id into the transcript viewer, which never touches
|
|
446
|
+
// `sessionStates`, so no wipe happens — and the mobile app has no transcript
|
|
447
|
+
// surface at all. This covers the fail-safe branch where the diversion is not
|
|
448
|
+
// armed (a raw client, or a frame that arrives without a pending request), in
|
|
449
|
+
// which case the client wipes its ACTIVE session's badge list because
|
|
450
|
+
// `conversationId` is a closed transcript with no live session behind it.
|
|
451
|
+
// Idempotent either way: both clients dedupe `agent_spawned` by `toolUseId`.
|
|
452
|
+
//
|
|
453
|
+
// The re-seed is CONDITIONAL, so it stays inside onDone rather than being
|
|
454
|
+
// hoisted out of the now-asynchronous loop: hoisting it would fire it
|
|
455
|
+
// before the replay frames it repairs, which is exactly the ordering the
|
|
456
|
+
// #7340 fix exists to establish.
|
|
457
|
+
if (client?.activeSessionId) {
|
|
458
|
+
ctx.transport.reseedActiveAgents(ws, client.activeSessionId)
|
|
459
|
+
}
|
|
460
|
+
},
|
|
461
|
+
})
|
|
234
462
|
}
|
|
235
463
|
|
|
236
464
|
async function handleRequestFullHistory(ws, client, msg, ctx) {
|
|
@@ -242,23 +470,208 @@ async function handleRequestFullHistory(ws, client, msg, ctx) {
|
|
|
242
470
|
sendSessionError(ws, ctx, message)
|
|
243
471
|
return
|
|
244
472
|
}
|
|
245
|
-
const
|
|
246
|
-
|
|
473
|
+
const sessionManager = ctx.sessions.sessionManager
|
|
474
|
+
// Same admission as the strict transcript endpoint: the read is capped
|
|
475
|
+
// daemon-wide and per connection, and stops when the connection closes.
|
|
476
|
+
const closing = signalOnClose(ws)
|
|
477
|
+
let history
|
|
478
|
+
try {
|
|
479
|
+
history = await sessionManager.getFullHistoryAsync(targetId, { ...admissionFor(client, isBoundClient), signal: closing.signal })
|
|
480
|
+
} catch (err) {
|
|
481
|
+
if (err instanceof ReadLimitError) {
|
|
482
|
+
sendSessionError(ws, ctx, `${err.message}. Try again shortly.`)
|
|
483
|
+
return
|
|
484
|
+
}
|
|
485
|
+
throw err
|
|
486
|
+
} finally {
|
|
487
|
+
closing.dispose()
|
|
488
|
+
}
|
|
489
|
+
if (closing.signal.aborted) return
|
|
490
|
+
// #7484 — `getFullHistoryAsync` returns a descriptor: WHICH source it read
|
|
491
|
+
// (the on-disk JSONL transcript or the ring buffer) alongside the entries and
|
|
492
|
+
// that source's own truncation. Both decisions below turn on it, and neither
|
|
493
|
+
// can be recovered from the entries: a JSONL slice and a ring slice are the
|
|
494
|
+
// same shape of array.
|
|
495
|
+
//
|
|
496
|
+
// A bare array is the pre-#7484 shape. Accepted, and read as the ring buffer
|
|
497
|
+
// it always was, so a legacy ctx fixture keeps replaying rather than throwing
|
|
498
|
+
// — the same posture as the `typeof === 'function'` probes below. The REAL
|
|
499
|
+
// manager's shape is pinned at the producer
|
|
500
|
+
// (tests/session-manager-full-history-source.test.js), because every test on
|
|
501
|
+
// this side stubs the manager and so cannot witness it.
|
|
502
|
+
const hasDescriptor = !!history && !Array.isArray(history) && Array.isArray(history.entries)
|
|
503
|
+
const fullHistory = hasDescriptor ? history.entries : (Array.isArray(history) ? history : [])
|
|
504
|
+
const source = hasDescriptor && history.source === 'jsonl' ? 'jsonl' : 'ring'
|
|
505
|
+
// Route through ctx.transport so a method-style sender keeps its receiver;
|
|
506
|
+
// the shared loop only ever needs a (ws, payload) callable.
|
|
507
|
+
const send = (target, payload) => ctx.transport.send(target, payload)
|
|
508
|
+
|
|
509
|
+
// #7460 — frame parity with replayHistory. `truncated` is how a client learns
|
|
510
|
+
// history was dropped on this replay.
|
|
511
|
+
//
|
|
512
|
+
// #7484 — and it must describe the collection ACTUALLY SENT. `isHistoryTruncated`
|
|
513
|
+
// reports the RING BUFFER's overflow, while this handler usually sends the JSONL
|
|
514
|
+
// transcript, which has its own entirely separate caps (500 most-recent
|
|
515
|
+
// messages / a 25MB tail read, jsonl-reader.js). So `truncated: false` could
|
|
516
|
+
// accompany a slice that silently dropped everything before the last 500.
|
|
517
|
+
// Sourced from the descriptor it follows the slice; the probe survives only for
|
|
518
|
+
// the legacy array shape, where the ring IS the slice.
|
|
519
|
+
const truncated = hasDescriptor && typeof history.truncated === 'boolean'
|
|
520
|
+
? history.truncated
|
|
521
|
+
: (typeof sessionManager.isHistoryTruncated === 'function'
|
|
522
|
+
? sessionManager.isHistoryTruncated(targetId)
|
|
523
|
+
: false)
|
|
524
|
+
// `latestSeq` must describe what THIS replay actually DELIVERS, not what the
|
|
525
|
+
// ring buffer happens to hold. `getFullHistoryAsync` PREFERS the JSONL
|
|
526
|
+
// transcript whenever `resumeSessionId` is set, and jsonl-reader.js emits only
|
|
527
|
+
// user_input/response/tool_use — none of which carry `_seq`. Sourcing the
|
|
528
|
+
// counter from the buffer there advertises a cursor the client never received:
|
|
529
|
+
// `reconcileReplayEnd` hands it to `recordHistorySeq`, so the NEXT reconnect
|
|
530
|
+
// resolves as already-current and replays NOTHING, stranding the client on the
|
|
531
|
+
// lossy JSONL rebuild. Derived from the entries themselves this is unchanged on
|
|
532
|
+
// the ring-buffer path — that slice is the whole buffer, so its max `_seq` IS
|
|
533
|
+
// `getLatestHistorySeq()` — and correctly advertises nothing on the JSONL path.
|
|
534
|
+
let latestSeq
|
|
247
535
|
for (const entry of fullHistory) {
|
|
248
|
-
if (entry.
|
|
249
|
-
|
|
250
|
-
type: 'message',
|
|
251
|
-
messageType: entry.type,
|
|
252
|
-
content: entry.content,
|
|
253
|
-
tool: entry.tool,
|
|
254
|
-
timestamp: entry.timestamp,
|
|
255
|
-
sessionId: targetId,
|
|
256
|
-
})
|
|
257
|
-
} else {
|
|
258
|
-
ctx.transport.send(ws, { ...entry, sessionId: targetId })
|
|
536
|
+
if (entry && typeof entry._seq === 'number' && (latestSeq === undefined || entry._seq > latestSeq)) {
|
|
537
|
+
latestSeq = entry._seq
|
|
259
538
|
}
|
|
260
539
|
}
|
|
261
|
-
|
|
540
|
+
// Omitted, never zeroed: absence means "this replay carried no cursor", while
|
|
541
|
+
// `latestSeq: 0` is a real seq the client would happily record.
|
|
542
|
+
const seqFrame = latestSeq === undefined ? {} : { latestSeq }
|
|
543
|
+
|
|
544
|
+
send(ws, { type: 'history_replay_start', sessionId: targetId, truncated, fullHistory: true, ...seqFrame })
|
|
545
|
+
|
|
546
|
+
// #7460 — the SAME chunk + bufferedAmount loop replayHistory uses, from the
|
|
547
|
+
// one implementation of it. Sending a 1000-entry ring buffer synchronously
|
|
548
|
+
// could push the socket past the 1MB EVICT_THRESHOLD in ws-client-sender.js
|
|
549
|
+
// and CLOSE the client: "Sync Full History" — the button a user presses
|
|
550
|
+
// BECAUSE the view looks wrong — was the action that could drop the
|
|
551
|
+
// connection.
|
|
552
|
+
// #8965: no synthesized agent_idle for a replayed result while the session runs.
|
|
553
|
+
const replayBusy = () => typeof sessionManager.isSessionBusy === 'function'
|
|
554
|
+
? sessionManager.isSessionBusy(targetId)
|
|
555
|
+
: false
|
|
556
|
+
sendChunkedWithBackpressure(ws, fullHistory, {
|
|
557
|
+
emit: (entry) => {
|
|
558
|
+
if (entry.type === 'user_input' || entry.type === 'response' || entry.type === 'tool_use') {
|
|
559
|
+
send(ws, {
|
|
560
|
+
type: 'message',
|
|
561
|
+
messageType: entry.type,
|
|
562
|
+
content: entry.content,
|
|
563
|
+
tool: entry.tool,
|
|
564
|
+
timestamp: entry.timestamp,
|
|
565
|
+
sessionId: targetId,
|
|
566
|
+
})
|
|
567
|
+
} else {
|
|
568
|
+
// This is the SECOND replay path, and both per-entry duties — the
|
|
569
|
+
// `_seq` → `historySeq` map (#7454) and the `result` → `agent_idle`
|
|
570
|
+
// synthesis (#7459 / #4628) — come from ws-history.js's shared emitter
|
|
571
|
+
// rather than a copy that can drift away from it again.
|
|
572
|
+
sendHistoryEntry(send, ws, targetId, entry, client, replayBusy)
|
|
573
|
+
}
|
|
574
|
+
},
|
|
575
|
+
onDone: () => {
|
|
576
|
+
// #7484 — the JSONL path's heal. `sendHistoryEntry` synthesizes
|
|
577
|
+
// `agent_idle` from a replayed `result`, and a JSONL slice has none:
|
|
578
|
+
// jsonl-reader.js emits user_input/response/tool_use only. Since
|
|
579
|
+
// `getFullHistoryAsync` PREFERS that transcript for any session with a
|
|
580
|
+
// `resumeSessionId` — the normal state of a live claude-family session —
|
|
581
|
+
// the #4628 heal could not fire on the source almost every "Sync Full
|
|
582
|
+
// History" press actually reads.
|
|
583
|
+
//
|
|
584
|
+
// The stale chip is CLIENT-side state: a live `tool_start` whose
|
|
585
|
+
// `tool_result` never arrived (a dropped PostToolUse hook).
|
|
586
|
+
// `history_replay_start` deliberately PRESERVES that set (#4466) and
|
|
587
|
+
// nothing in a JSONL slice can clear it — those entries rebuild as
|
|
588
|
+
// `message` frames, which touch no tool state. `agent_idle` is the only
|
|
589
|
+
// frame that clears it and is not replay-gated.
|
|
590
|
+
//
|
|
591
|
+
// ONE heal, at the end, rather than a per-entry synthesis: JSONL rows
|
|
592
|
+
// carry no dependable turn boundary to hang one on, and landing after the
|
|
593
|
+
// last entry is what makes it unable to wipe an activeTools set
|
|
594
|
+
// MID-replay. Before `history_replay_end`, so it stays inside the window
|
|
595
|
+
// where the #4466 reasoning holds.
|
|
596
|
+
//
|
|
597
|
+
// NOT while `isSessionBusy` reports the session LIVE. `agent_idle` sets
|
|
598
|
+
// isIdle, clears streamingMessageId (hiding the stop button) and clears
|
|
599
|
+
// activeTools — all true after a finished turn, and no `agent_busy` is
|
|
600
|
+
// coming to undo it before the next turn starts.
|
|
601
|
+
//
|
|
602
|
+
// #7507 — "live" here is deliberately WIDER than mid-turn, and the comment
|
|
603
|
+
// this replaced described only the narrow half. `isSessionBusy` is
|
|
604
|
+
// `entry.session.isRunning`, which BaseSession defines as
|
|
605
|
+
// `_isBusy || _backgroundShellTracker.size > 0`: a session whose turn has
|
|
606
|
+
// ENDED but which still holds an un-polled `Bash(run_in_background: true)`
|
|
607
|
+
// shell reads busy (#4307; the 60s advisory sweep must not flip liveness,
|
|
608
|
+
// #5247, so release comes only from BashOutput / destroy / the 4h hard
|
|
609
|
+
// quiesce). Do NOT "simplify" this to `_isBusy`.
|
|
610
|
+
//
|
|
611
|
+
// The reason is CONSISTENCY WITH THE SERVER'S SINGLE BUSY AUTHORITY, not
|
|
612
|
+
// mid-turn correctness. `listSessions()` publishes that same `isRunning` as
|
|
613
|
+
// each entry's `isBusy`, and BOTH clients re-derive `isIdle` from it on
|
|
614
|
+
// every `session_list` and `session_activity` (#4639 for the dashboard;
|
|
615
|
+
// #7518 gave the mobile app the same two paths, via the shared store-core
|
|
616
|
+
// `isIdlePatches` derivation and the shared `session_activity` dispatch
|
|
617
|
+
// entry). A narrower `_isBusy` guard would emit an `agent_idle` that the
|
|
618
|
+
// very next broadcast reverts — a flicker, not a heal, on either client.
|
|
619
|
+
// Pinned by behaviour in
|
|
620
|
+
// tests/conversation-full-history-replay.test.js (a real SessionManager +
|
|
621
|
+
// BaseSession) and at the producer in
|
|
622
|
+
// tests/session-manager-full-history-source.test.js.
|
|
623
|
+
//
|
|
624
|
+
// Until #7518 that argument held for the dashboard ALONE: the app had
|
|
625
|
+
// neither path, so the suppression was a pure false negative there — this
|
|
626
|
+
// synthesized `agent_idle` was the only thing that could clear a stale
|
|
627
|
+
// chip (#7479 N2), and a session holding an un-polled background shell
|
|
628
|
+
// kept one. That is why the fix went to the CLIENT rather than forking
|
|
629
|
+
// this guard per client, and why the guard did not change: with both
|
|
630
|
+
// clients consuming the same authority, one rule is now right on both.
|
|
631
|
+
//
|
|
632
|
+
// One consequence still worth recording:
|
|
633
|
+
// - The LIVE path is LESS conservative than this. event-normalizer.js
|
|
634
|
+
// appends `agent_idle` to every `result` unconditionally, without
|
|
635
|
+
// consulting `isRunning`; the replay heal mirrors that fan-out
|
|
636
|
+
// (ws-history.js) everywhere except this state.
|
|
637
|
+
//
|
|
638
|
+
// A manager that cannot answer is treated as idle: "cannot tell" must not
|
|
639
|
+
// silently become "never heal", which is the defect this fixes.
|
|
640
|
+
const busy = typeof sessionManager.isSessionBusy === 'function'
|
|
641
|
+
? sessionManager.isSessionBusy(targetId)
|
|
642
|
+
: false
|
|
643
|
+
if (source === 'jsonl' && !busy) {
|
|
644
|
+
send(ws, { type: 'agent_idle', sessionId: targetId })
|
|
645
|
+
}
|
|
646
|
+
send(ws, { type: 'history_replay_end', sessionId: targetId, ...seqFrame })
|
|
647
|
+
// #7340: same wipe, same repair — `request_full_history` targets a LIVE
|
|
648
|
+
// session, so its confirmed-backgrounded subagents must be re-asserted
|
|
649
|
+
// after the replay that cleared them.
|
|
650
|
+
ctx.transport.reseedActiveAgents(ws, targetId)
|
|
651
|
+
// #7457: same sweep, same repair. This end frame runs the client's
|
|
652
|
+
// unanswered-prompt sweep exactly as `replayHistory`'s does, so "Sync
|
|
653
|
+
// Full History" — the button a user presses BECAUSE the view looks
|
|
654
|
+
// wrong — would otherwise resolve the very question they are blocked on.
|
|
655
|
+
// The sibling `request_conversation_transcript` replay is exempt: its
|
|
656
|
+
// frames carry a conversationId in `sessionId`, which is never a live
|
|
657
|
+
// session id, so both clients' `updateSession` no-ops and the sweep
|
|
658
|
+
// touches nothing.
|
|
659
|
+
// #8357: PERMISSIONS FIRST, as `replayHistory`'s `finishReplay` does -- a
|
|
660
|
+
// question card is gated by its own permission, which the client must
|
|
661
|
+
// already hold when the question lands.
|
|
662
|
+
// #8340 / #8328: the permission card. `permission_request` is
|
|
663
|
+
// transient, so this full rebuild swaps the live Allow/Deny card away and
|
|
664
|
+
// the replay cannot restore it; `replayHistory` re-sends after its own end
|
|
665
|
+
// frame, and this path ends its own, so it must too. Same single
|
|
666
|
+
// implementation (ws-history's resendPendingPermissionsForSession), which
|
|
667
|
+
// keeps the #8342 session-bound-client guard.
|
|
668
|
+
try {
|
|
669
|
+
ctx.transport.resendPendingPermissions(ws, targetId)
|
|
670
|
+
} finally {
|
|
671
|
+
ctx.transport.resendPendingQuestions(ws, targetId)
|
|
672
|
+
}
|
|
673
|
+
},
|
|
674
|
+
})
|
|
262
675
|
}
|
|
263
676
|
|
|
264
677
|
async function handleRequestSessionContext(ws, client, msg, ctx) {
|