@chroxy/server 0.11.0 → 0.11.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +204 -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 +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 +1203 -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 +279 -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 +628 -121
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +3 -3
- package/src/byok-session.js +650 -175
- package/src/byok-tool-executor.js +2662 -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-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 +211 -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 +3513 -287
- package/src/claude-tui-tool-response.js +300 -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/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +68 -39
- package/src/cli/server-cmd.js +48 -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/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 +1066 -121
- package/src/cli.js +4 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1454 -79
- 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 +450 -27
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +286 -26
- 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 +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- 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 +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 +169 -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 +284 -10
- package/src/doctor.js +767 -61
- 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 +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 +151 -233
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +535 -68
- package/src/handlers/checkpoint-handlers.js +39 -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/input-handlers.js +685 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/scheduler-handlers.js +88 -14
- package/src/handlers/session-handlers.js +542 -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 +330 -42
- 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/health-proof.js +40 -0
- package/src/history-page.js +104 -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 +289 -82
- package/src/jsonl-subprocess-session.js +92 -8
- package/src/keychain.js +1 -1
- package/src/logger.js +63 -17
- 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 +12 -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 +80 -33
- package/src/orchestration/permission-gate.js +13 -1
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/turn-driver.js +44 -20
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -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 +1357 -42
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +712 -83
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +122 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +159 -43
- 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 +207 -4
- 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/scheduled-task-store.js +318 -26
- package/src/scheduler.js +73 -3
- package/src/sdk-session.js +2060 -187
- 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 +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +524 -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 +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3491 -312
- package/src/session-message-history.js +722 -16
- 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 +23 -11
- package/src/summarize-session.js +51 -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 +137 -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 +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 +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/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 +256 -16
- package/src/worktree-gc.js +7 -2
- 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 +331 -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 +329 -39
- package/src/ws-handler-context.js +70 -2
- package/src/ws-history.js +940 -172
- package/src/ws-message-handlers.js +17 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +643 -96
- 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
package/src/session-manager.js
CHANGED
|
@@ -1,23 +1,32 @@
|
|
|
1
1
|
import { EventEmitter } from 'events'
|
|
2
|
+
import { assertAuthorized } from './connection-authority.js'
|
|
3
|
+
import { DeclaredStatusInputSchema, DeclaredStatusSchema } from '@chroxy/protocol'
|
|
4
|
+
import { extractDeclaredStatus } from './declared-status.js'
|
|
2
5
|
import { randomBytes } from 'crypto'
|
|
3
|
-
import { statSync, mkdirSync, rmSync } from 'fs'
|
|
4
|
-
import { join, resolve, dirname } from 'path'
|
|
5
|
-
import { homedir } from 'os'
|
|
6
|
+
import { statSync, mkdirSync, rmSync, realpathSync } from 'fs'
|
|
7
|
+
import { join, resolve, dirname, basename, isAbsolute } from 'path'
|
|
6
8
|
import { execFileSync } from 'child_process'
|
|
9
|
+
import { USER_SHELL_PROVIDER } from '@chroxy/protocol'
|
|
7
10
|
import { getProvider, getProviderAuthInfo, DEFAULT_PROVIDER } from './providers.js'
|
|
8
|
-
import { isClaudeProvider } from './models.js'
|
|
11
|
+
import { isClaudeProvider, CLAUDE_NEW_SESSION_DEFAULT_MODEL } from './models.js'
|
|
12
|
+
import { classifyClaudeModelRequest } from './claude-model-request.js'
|
|
9
13
|
import { billingClassForProvider, BILLING_CLASSES } from './billing-class.js'
|
|
10
14
|
import { MonthlyProgrammaticBudgetManager } from './billing-budget.js'
|
|
11
|
-
import { runProviderPreflight, ProviderBinaryNotFoundError, ProviderBinaryQuarantinedError, ProviderBinaryProvenanceError, ProviderCredentialMissingError } from './utils/preflight.js'
|
|
15
|
+
import { runProviderPreflight, buildBinaryProvenanceOptions, ProviderBinaryNotFoundError, ProviderBinaryQuarantinedError, ProviderBinaryProvenanceError, ProviderBinaryUnsupportedError, ProviderBinaryVersionError, ProviderCredentialMissingError } from './utils/preflight.js'
|
|
12
16
|
import { GIT } from './git.js'
|
|
17
|
+
import { isGitRepoSync } from './utils/git-repo.js'
|
|
13
18
|
import { sweepOrphanChroxyWorktrees } from './worktree-gc.js'
|
|
14
|
-
import {
|
|
19
|
+
import { hasPersistedTranscript, readConversationHistoryWithMetaAsync } from './jsonl-reader.js'
|
|
20
|
+
import { resolveTranscriptSource } from './transcript-sources.js'
|
|
21
|
+
import { NATIVE_RESUME_DRIVER, nativeRestoreError } from './codex-native-resume.js'
|
|
22
|
+
import { buildContinuationSeed, coerceContinuationSeed, continuationSeedItem, sanitizeSeedText } from './archive-continuation.js'
|
|
15
23
|
import { readSessionContext } from './session-context.js'
|
|
16
24
|
import { parseDuration, isOperatorTimeoutInRange } from './duration.js'
|
|
17
25
|
import { SessionLockManager } from './session-lock.js'
|
|
18
26
|
import { CostBudgetManager } from './cost-budget-manager.js'
|
|
19
27
|
import { SessionStatePersistence } from './session-state-persistence.js'
|
|
20
28
|
import { SessionTimeoutManager, formatIdleDuration } from './session-timeout-manager.js'
|
|
29
|
+
import { ContainerLivenessMonitor } from './container-liveness-monitor.js'
|
|
21
30
|
import { SessionMessageHistory } from './session-message-history.js'
|
|
22
31
|
import { generateSessionTitle, DEFAULT_SEMANTIC_TITLE_MODEL, DEFAULT_SEMANTIC_TITLE_TIMEOUT_MS } from './session-title.js'
|
|
23
32
|
// NB: the default one-shot title runner (defaultRunOneShot) lives in
|
|
@@ -30,6 +39,7 @@ import { resolveSessionPreset, foldPreamble } from './session-preset.js'
|
|
|
30
39
|
import { SessionPresetTrustStore } from './session-preset-trust.js'
|
|
31
40
|
import { BinaryProvenanceLedger } from './binary-provenance-trust.js'
|
|
32
41
|
import { PermissionRuleStore } from './permission-rule-store.js'
|
|
42
|
+
import { permissionDecisionToken } from './permission-scope.js'
|
|
33
43
|
import { ScheduledTaskStore, defaultScheduledTasksPath } from './scheduled-task-store.js'
|
|
34
44
|
import { createLogger } from './logger.js'
|
|
35
45
|
import { ExternalSessionRegistry } from './external-session-registry.js'
|
|
@@ -37,19 +47,72 @@ import { metrics } from './metrics.js'
|
|
|
37
47
|
import { auditShellDestroy } from './shell-audit.js'
|
|
38
48
|
import { recordShell, forgetShell, reapOrphanShells } from './user-shell-registry.js'
|
|
39
49
|
import { getErrorMessage } from './utils/error-message.js'
|
|
50
|
+
import { claudeConfigDirCwdDenial } from './handler-utils.js'
|
|
51
|
+
import { assertProviderPermissionModeSupported, UnsupportedPermissionModeError } from './permission-mode-support.js'
|
|
40
52
|
import { toWireCount } from './utils/wire-counters.js'
|
|
53
|
+
import { assertSafeArgvValue } from './utils/argv-safety.js'
|
|
54
|
+
import { configPath } from './config-dir.js'
|
|
41
55
|
import {
|
|
42
56
|
forwardPerSessionSettingsToProviderOpts,
|
|
43
57
|
serializePerSessionSettings,
|
|
44
58
|
restorePerSessionSettings,
|
|
45
59
|
} from './per-session-settings.js'
|
|
60
|
+
import { AgentConnectionRegistry, createLegacyAgentConnection } from './agent-connections.js'
|
|
61
|
+
import { forgetSurveyKey } from './handlers/survey-throttle.js'
|
|
62
|
+
import { busyStateOf } from './session-busy-state.js'
|
|
63
|
+
import { pageHistory } from './history-page.js'
|
|
64
|
+
import { SessionArchive } from './session-archive.js'
|
|
65
|
+
import { stopClaudeModelRefresh, resumeClaudeModelRefresh } from './claude-model-refresh.js'
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Session events that `_wireSessionEvents` forwards to clients AND records to
|
|
69
|
+
* history (one listener per name). A provider's static `customEvents` must not
|
|
70
|
+
* repeat any of them: the transient listener it would add forwards each frame a
|
|
71
|
+
* second time (#8574). Exported so the overlap guard derives its expectation
|
|
72
|
+
* from this one list rather than copying it.
|
|
73
|
+
*/
|
|
74
|
+
export const PROXIED_SESSION_EVENTS = Object.freeze(['ready', 'stream_start', 'stream_delta', 'stream_end', 'message', 'tool_start', 'tool_result', 'result', 'error', 'user_question', 'background_tasks_changed'])
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Session events `_wireSessionEvents` forwards to clients as transient frames
|
|
78
|
+
* (not recorded, not replayed), beside each provider's own `customEvents`.
|
|
79
|
+
* Exported so the #8743 provider-activity classification can be checked against
|
|
80
|
+
* this list instead of a copy of it.
|
|
81
|
+
*/
|
|
82
|
+
export const BUILTIN_TRANSIENT_SESSION_EVENTS = Object.freeze(['permission_request', 'permission_resolved', 'permission_expired', 'agent_spawned', 'agent_completed', 'agent_event', 'plan_started', 'plan_ready', 'mcp_servers', 'skill_changed', 'skill_trust_request', 'skill_trust_granted', 'inactivity_warning', 'background_work_changed', 'stopped', 'activity_delta', 'activity_snapshot', 'message_queued', 'message_dequeued', 'busy_cleared', 'thinking_level_changed'])
|
|
83
|
+
|
|
84
|
+
function ownsDeclarationEvent(entry, data) {
|
|
85
|
+
if (entry?.session?.constructor?.declarationTurnOwnership !== true) return true
|
|
86
|
+
return typeof entry._declarationTurnId === 'string' && data?.declarationTurnId === entry._declarationTurnId
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function sessionHasCanonicalResponses(session) {
|
|
90
|
+
return session?.constructor?.canonicalAssistantResponses === true
|
|
91
|
+
}
|
|
46
92
|
|
|
47
93
|
const log = createLogger('session-manager')
|
|
48
|
-
|
|
94
|
+
/**
|
|
95
|
+
* The state file a SessionManager falls back to when no `stateFilePath` is
|
|
96
|
+
* injected — i.e. what the running daemon uses (server-cli.js passes none).
|
|
97
|
+
*
|
|
98
|
+
* Exported so the schedule CLI's drift guard can assert that its registry and
|
|
99
|
+
* the daemon's resolve to the same place without constructing a SessionManager
|
|
100
|
+
* (tests/schedule-cli.test.js). A `const` here would be frozen at import; see
|
|
101
|
+
* config-dir.js for why that is the whole of #7052.
|
|
102
|
+
*/
|
|
103
|
+
export function defaultStateFile() {
|
|
104
|
+
return configPath('session-state.json')
|
|
105
|
+
}
|
|
49
106
|
// #5982 — grace before auto-removing an exited user-shell session, so a live
|
|
50
107
|
// viewer sees the "[shell exited]" marker before the session vanishes.
|
|
51
108
|
const AUTO_REMOVE_ON_EXIT_DELAY_MS = 1500
|
|
52
109
|
|
|
110
|
+
// #8348 -- how many permission prompts SessionManager remembers (tool and
|
|
111
|
+
// description, by requestId) while they are open, so the outcome can be recorded
|
|
112
|
+
// when they end. A prompt leaves the registry the moment its outcome is recorded;
|
|
113
|
+
// the cap only bounds prompts that never end (a session that dies with one open).
|
|
114
|
+
const MAX_TRACKED_PERMISSION_REQUESTS = 256
|
|
115
|
+
|
|
53
116
|
/**
|
|
54
117
|
* Zero-initialized cumulative usage record (#4072). Lives on the session
|
|
55
118
|
* entry; increments on every priced `result` event. Field names are
|
|
@@ -147,7 +210,9 @@ export class ProviderModelNotSupportedError extends SessionError {
|
|
|
147
210
|
* Default base directory for session worktrees.
|
|
148
211
|
* @type {string}
|
|
149
212
|
*/
|
|
150
|
-
|
|
213
|
+
function defaultWorktreeBase() {
|
|
214
|
+
return configPath('worktrees')
|
|
215
|
+
}
|
|
151
216
|
|
|
152
217
|
/**
|
|
153
218
|
* Manages the lifecycle of multiple CLI sessions.
|
|
@@ -178,9 +243,10 @@ export { formatIdleDuration }
|
|
|
178
243
|
|
|
179
244
|
// Re-export preflight errors so call sites that catch createSession() failures
|
|
180
245
|
// can detect/branch on PROVIDER_BINARY_NOT_FOUND / PROVIDER_BINARY_QUARANTINED /
|
|
181
|
-
// PROVIDER_BINARY_PROVENANCE /
|
|
182
|
-
// separate dependency on utils/preflight.js.
|
|
183
|
-
export { ProviderBinaryNotFoundError, ProviderBinaryQuarantinedError, ProviderBinaryProvenanceError, ProviderCredentialMissingError }
|
|
246
|
+
// PROVIDER_BINARY_PROVENANCE / PROVIDER_BINARY_UNSUPPORTED / PROVIDER_BINARY_VERSION /
|
|
247
|
+
// PROVIDER_CREDENTIAL_MISSING without taking a separate dependency on utils/preflight.js.
|
|
248
|
+
export { ProviderBinaryNotFoundError, ProviderBinaryQuarantinedError, ProviderBinaryProvenanceError, ProviderBinaryUnsupportedError, ProviderBinaryVersionError, ProviderCredentialMissingError }
|
|
249
|
+
export { UnsupportedPermissionModeError }
|
|
184
250
|
|
|
185
251
|
/**
|
|
186
252
|
* @typedef {Object} SessionManagerConfig
|
|
@@ -215,6 +281,7 @@ export { ProviderBinaryNotFoundError, ProviderBinaryQuarantinedError, ProviderBi
|
|
|
215
281
|
* @property {string} [stateFilePath] - Path to session state JSON file (default: ~/.chroxy/session-state.json)
|
|
216
282
|
* @property {number} [stateTtlMs] - Max age of persisted state before discard (default: 24 hours)
|
|
217
283
|
* @property {number} [persistDebounceMs=2000] - Debounce interval for state file writes
|
|
284
|
+
* @property {number} [persistMaxWaitMs=10000] - Max time a continuous stream of appends may postpone a state write (#8954)
|
|
218
285
|
*
|
|
219
286
|
* Message history
|
|
220
287
|
* @property {number} [maxMessages=1000] - Max history messages per session (alias: maxHistory)
|
|
@@ -228,6 +295,182 @@ export { ProviderBinaryNotFoundError, ProviderBinaryQuarantinedError, ProviderBi
|
|
|
228
295
|
// "you have a bug" signal, not per-instance telemetry.
|
|
229
296
|
const warnedUnknownCtorOptKeys = new Set()
|
|
230
297
|
|
|
298
|
+
/**
|
|
299
|
+
* #2954 — how long a failed-restore entry is kept so the operator can act on it
|
|
300
|
+
* (and how long its history is preserved on disk). ONE definition: both
|
|
301
|
+
* `_pruneStaleFailedRestores` and the #7627 stale-entry sweep in `restoreState`
|
|
302
|
+
* bound against this, and a second copy is exactly how the 24h session filter
|
|
303
|
+
* came to silently override it.
|
|
304
|
+
*/
|
|
305
|
+
const FAILED_RESTORE_TTL_MS = 30 * 24 * 60 * 60 * 1000 // 30 days
|
|
306
|
+
// #8858 — cap on the error message persisted in a parked entry's `failedRestore` marker
|
|
307
|
+
const FAILED_RESTORE_MARKER_MAX_MESSAGE = 500
|
|
308
|
+
/**
|
|
309
|
+
* #8861 — how long `retryFailedRestore` waits for the provider's async start()
|
|
310
|
+
* to settle before it reports `ok: true` anyway. Long enough for a Codex
|
|
311
|
+
* thread/resume refusal or a claude-tui PTY death (seconds), short enough that a
|
|
312
|
+
* provider which never settles cannot leave the operator's Retry button spinning.
|
|
313
|
+
*/
|
|
314
|
+
const RETRY_RESTORE_SETTLE_TIMEOUT_MS = 30 * 1000
|
|
315
|
+
// #8866: how long an unsettled claim on a new-thread seed excludes a second input.
|
|
316
|
+
const CONTINUATION_CLAIM_TTL_MS = 2 * 60 * 1000
|
|
317
|
+
/**
|
|
318
|
+
* #8876 — how long a provider's async start() may stay unsettled before
|
|
319
|
+
* `createSession` treats it as failed. Without a bound, a start() that never
|
|
320
|
+
* settles leaves the session listed `starting` forever.
|
|
321
|
+
*
|
|
322
|
+
* Measured 2026-10-31: claude-tui's whole start (createSession -> warmup done)
|
|
323
|
+
* over 96 real daemon starts was median 1.1 s, p90 15.1 s, max 15.5 s — its
|
|
324
|
+
* warmup wait is itself capped at `SPAWN_WARMUP_MAX_MS` (15 s) and then
|
|
325
|
+
* proceeds. Codex app-server cold start was 0.2-0.9 s over 3 runs; it has no
|
|
326
|
+
* internal startup timeout, which is the wedge this covers. 60 s is ~4x the
|
|
327
|
+
* slowest healthy start observed. The measured starts were mostly one at a
|
|
328
|
+
* time; a boot restore starts every session at once, but claude-tui's start is
|
|
329
|
+
* bounded by its own caps (auth probe 5 s, hook-dir fs ops 2 s each, warmup
|
|
330
|
+
* 15 s), so a loaded boot still fits well inside the deadline.
|
|
331
|
+
*
|
|
332
|
+
* A provider class may override via `static get startDeadlineMs()` (a positive
|
|
333
|
+
* number, or `null` for no deadline). Interaction: `retryFailedRestore` reports
|
|
334
|
+
* `pending` after its own 30 s settle wait (`RETRY_RESTORE_SETTLE_TIMEOUT_MS`),
|
|
335
|
+
* and a deadline failure then arrives as `session_restore_failed` like any
|
|
336
|
+
* other rejection.
|
|
337
|
+
*/
|
|
338
|
+
export const PROVIDER_START_DEADLINE_MS = 60 * 1000
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* #8876 — resolve the start deadline for a provider instance. `undefined` ->
|
|
342
|
+
* the default; `null` -> no deadline; a finite number > 0 -> that value;
|
|
343
|
+
* anything else -> the default.
|
|
344
|
+
*/
|
|
345
|
+
function providerStartDeadlineMs(session) {
|
|
346
|
+
const declared = session?.constructor?.startDeadlineMs
|
|
347
|
+
if (declared === undefined) return PROVIDER_START_DEADLINE_MS
|
|
348
|
+
if (declared === null) return null
|
|
349
|
+
if (typeof declared === 'number' && Number.isFinite(declared) && declared > 0) return declared
|
|
350
|
+
return PROVIDER_START_DEADLINE_MS
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* #8348: the history outcome for a session's `permission_resolved` /
|
|
354
|
+
* `permission_expired` event, or null when it is not a permission prompt's end
|
|
355
|
+
* (an AskUserQuestion's resolution carries a `toolUseId`, not a `requestId`).
|
|
356
|
+
*
|
|
357
|
+
* `permission_resolved` also fires for prompts that ended with NO decision: the
|
|
358
|
+
* in-process providers resolve a timed-out, stopped or cleared prompt as a deny
|
|
359
|
+
* and say so only in `reason`. Those are `expired` (the tool call was dropped),
|
|
360
|
+
* not `denied` (nobody refused it) -- the distinction #8256 asks the clients for.
|
|
361
|
+
* A prompt the user cancelled with Stop (`reason: 'stopped'`) is `stopped`, not
|
|
362
|
+
* `expired`: nothing timed out, the person ended the turn (#8374). `aborted` is
|
|
363
|
+
* every OTHER abort of the turn's controller (a stalled stream, a dead provider
|
|
364
|
+
* process, a teardown) and stays `expired`.
|
|
365
|
+
*
|
|
366
|
+
* One system-made deny is recorded as `denied`, not `expired`: switching a session
|
|
367
|
+
* to auto mode while an MCP trust prompt is open resolves that prompt with
|
|
368
|
+
* `reason: 'auto_mode_mcp_trust_bypass'` and `decision: 'deny'`. The daemon
|
|
369
|
+
* refused the server spawn on purpose (trust is never granted by a bypass), so
|
|
370
|
+
* that is a refusal rather than a prompt that simply ran out.
|
|
371
|
+
*
|
|
372
|
+
* @param {'permission_resolved'|'permission_expired'} event
|
|
373
|
+
* @param {object} data
|
|
374
|
+
* @returns {'allowed'|'denied'|'expired'|'stopped'|null}
|
|
375
|
+
*/
|
|
376
|
+
function permissionOutcomeForEvent(event, data) {
|
|
377
|
+
if (!data || typeof data.requestId !== 'string' || !data.requestId) return null
|
|
378
|
+
if (event === 'permission_expired') return 'expired'
|
|
379
|
+
if (data.reason === 'stopped') return 'stopped'
|
|
380
|
+
if (data.reason === 'timeout' || data.reason === 'aborted' || data.reason === 'cleared') return 'expired'
|
|
381
|
+
return data.decision === 'deny' ? 'denied' : 'allowed'
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* #8348: the description the transcript keeps for a permission prompt.
|
|
386
|
+
*
|
|
387
|
+
* In order:
|
|
388
|
+
* 1. an AskUserQuestion prompt names the question that was asked;
|
|
389
|
+
* 2. `recordDescription`, the identifying field of the RAW input (command,
|
|
390
|
+
* file_path, ...) that the producer read before the input was shortened for
|
|
391
|
+
* broadcast and already redacted. A large input is broadcast as a truncation
|
|
392
|
+
* wrapper that has lost those fields, so only the producer can supply it;
|
|
393
|
+
* 3. the SANITIZED input, serialized: values under sensitive keys are masked in
|
|
394
|
+
* it. The truncation wrapper is never serialized: it carries nothing worth
|
|
395
|
+
* showing;
|
|
396
|
+
* 4. the producer's description, only when there is no input at all.
|
|
397
|
+
*
|
|
398
|
+
* @param {string|undefined} tool
|
|
399
|
+
* @param {string|undefined} description
|
|
400
|
+
* @param {object|undefined} input the sanitized tool input
|
|
401
|
+
* @param {string|undefined} recordDescription
|
|
402
|
+
* @returns {string}
|
|
403
|
+
*/
|
|
404
|
+
function describePermissionForOutcome(tool, description, input, recordDescription) {
|
|
405
|
+
if (tool === 'AskUserQuestion') {
|
|
406
|
+
const first = Array.isArray(input?.questions) ? input.questions[0] : null
|
|
407
|
+
const question = first && typeof first.question === 'string' ? first.question.trim() : ''
|
|
408
|
+
if (question) return question
|
|
409
|
+
}
|
|
410
|
+
if (typeof recordDescription === 'string' && recordDescription.length > 0) return recordDescription
|
|
411
|
+
const fallback = typeof description === 'string' ? description : ''
|
|
412
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) return fallback
|
|
413
|
+
if (input._truncated === true) return ''
|
|
414
|
+
const named = input.description || input.command || input.file_path || input.pattern || input.query
|
|
415
|
+
const source = named
|
|
416
|
+
|| (Object.keys(input).length > 0 ? JSON.stringify(input) : fallback)
|
|
417
|
+
return String(source)
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* #8348: fold the daemon's saved permission outcomes into a provider-transcript
|
|
422
|
+
* (JSONL) rebuild.
|
|
423
|
+
*
|
|
424
|
+
* A permission outcome is recorded only by the daemon, so it exists in the ring
|
|
425
|
+
* buffer and the state file and never in the provider's own transcript. "Sync
|
|
426
|
+
* Full History" replaces the client's transcript with the JSONL slice; without
|
|
427
|
+
* this the outcome records a session switch just showed would be erased by it.
|
|
428
|
+
*
|
|
429
|
+
* Ordered by timestamp into the slice (an outcome lands after any entry with the
|
|
430
|
+
* same or an earlier time), one per requestId, and, when the slice is the
|
|
431
|
+
* truncated tail of a longer transcript, only those no older than its first
|
|
432
|
+
* entry: an outcome for a call outside the window would sit at the top with
|
|
433
|
+
* nothing around it.
|
|
434
|
+
*
|
|
435
|
+
* The copies carry NO `_seq`. The full-history handler derives the reconnect
|
|
436
|
+
* cursor from the entries it sends, and a ring seq on an entry of a JSONL slice
|
|
437
|
+
* would advertise a cursor the client never received, stranding it on the lossy
|
|
438
|
+
* rebuild (#7484). Returns the input slice itself when there is nothing to add.
|
|
439
|
+
*
|
|
440
|
+
* @param {Array} transcript the JSONL entries
|
|
441
|
+
* @param {Array} ring the session's ring-buffer history
|
|
442
|
+
* @param {boolean} truncated whether the slice is a truncated tail
|
|
443
|
+
* @returns {Array}
|
|
444
|
+
*/
|
|
445
|
+
export function withRetainedPermissionOutcomes(transcript, ring, truncated) {
|
|
446
|
+
const seen = new Set()
|
|
447
|
+
let outcomes = []
|
|
448
|
+
for (const entry of ring) {
|
|
449
|
+
// #8259: an interrupted turn's marker is daemon-written too (the provider's own
|
|
450
|
+
// transcript never saw the turn end), so it is retained the same way.
|
|
451
|
+
const isInterrupted = !!entry && entry.type === 'result' && entry.turnOutcome === 'interrupted'
|
|
452
|
+
if (!entry || (entry.type !== 'permission_outcome' && !isInterrupted)) continue
|
|
453
|
+
const key = isInterrupted ? `interrupted:${entry.timestamp}` : entry.requestId
|
|
454
|
+
if (seen.has(key)) continue
|
|
455
|
+
seen.add(key)
|
|
456
|
+
const { _seq: _ringSeq, ...copy } = entry
|
|
457
|
+
outcomes.push(copy)
|
|
458
|
+
}
|
|
459
|
+
if (outcomes.length === 0) return transcript
|
|
460
|
+
const first = transcript[0]?.timestamp
|
|
461
|
+
if (truncated && typeof first === 'number') {
|
|
462
|
+
outcomes = outcomes.filter((o) => typeof o.timestamp === 'number' && o.timestamp >= first)
|
|
463
|
+
}
|
|
464
|
+
const merged = []
|
|
465
|
+
let next = 0
|
|
466
|
+
for (const entry of transcript) {
|
|
467
|
+
while (next < outcomes.length && outcomes[next].timestamp < entry.timestamp) merged.push(outcomes[next++])
|
|
468
|
+
merged.push(entry)
|
|
469
|
+
}
|
|
470
|
+
while (next < outcomes.length) merged.push(outcomes[next++])
|
|
471
|
+
return merged
|
|
472
|
+
}
|
|
473
|
+
|
|
231
474
|
export class SessionManager extends EventEmitter {
|
|
232
475
|
/**
|
|
233
476
|
* @param {SessionManagerConfig} opts
|
|
@@ -282,6 +525,8 @@ export class SessionManager extends EventEmitter {
|
|
|
282
525
|
// explicitly), but kept on the single source of truth so the fallback
|
|
283
526
|
// can't silently diverge from the server's default (#5819).
|
|
284
527
|
providerType = DEFAULT_PROVIDER,
|
|
528
|
+
agentConnections = [],
|
|
529
|
+
agentConnectionDeps = {},
|
|
285
530
|
|
|
286
531
|
// Session behavior
|
|
287
532
|
sessionTimeout,
|
|
@@ -341,6 +586,20 @@ export class SessionManager extends EventEmitter {
|
|
|
341
586
|
stateFilePath,
|
|
342
587
|
stateTtlMs,
|
|
343
588
|
persistDebounceMs = 2000,
|
|
589
|
+
persistMaxWaitMs = 10_000,
|
|
590
|
+
|
|
591
|
+
// Provider-neutral session archive: the chroxy-held history of a session
|
|
592
|
+
// that leaves the live set (closed, idle-timed-out, stale at boot, or a
|
|
593
|
+
// dismissed/expired failed restore) is kept in a compressed record so it
|
|
594
|
+
// stays readable. `sessionArchive` is the daemon config block
|
|
595
|
+
// (`{ enabled?, maxEntries?, maxAgeDays?, maxMegabytes? }`); the directory
|
|
596
|
+
// sits next to the session-state file, so a test's temp stateFilePath keeps
|
|
597
|
+
// it out of the real ~/.chroxy. Tests may inject `sessionArchiveStore`.
|
|
598
|
+
sessionArchive,
|
|
599
|
+
sessionArchiveStore,
|
|
600
|
+
// Interval (ms) of the background archive retention sweep. Default 6h; a
|
|
601
|
+
// test seam, not a config key. Non-positive / non-finite disables it.
|
|
602
|
+
sessionArchivePruneIntervalMs = 6 * 60 * 60 * 1000,
|
|
344
603
|
|
|
345
604
|
// #5554: per-skill usage recorder. Records which skills activate in each
|
|
346
605
|
// session, powering the Control Room Skills tab's "previously used" surface.
|
|
@@ -403,6 +662,11 @@ export class SessionManager extends EventEmitter {
|
|
|
403
662
|
// `AbortSignal.timeout(...)`; null → the DEFAULT_SEMANTIC_TITLE_TIMEOUT_MS.
|
|
404
663
|
semanticTitleTimeoutMs = null,
|
|
405
664
|
titleRunOneShot = null,
|
|
665
|
+
// #8030: test seam. Overrides the provider class `verifyOneShotExecutable()`
|
|
666
|
+
// re-verifies against (production default: `getProvider('claude-sdk')`) so
|
|
667
|
+
// tests can point the one-shot binary gate at a fixture class instead of
|
|
668
|
+
// spawning the real `claude` resolution.
|
|
669
|
+
oneShotProviderClass = null,
|
|
406
670
|
|
|
407
671
|
// #5859 (audit P1-7): opt-in boot-time sweep of orphaned chroxy session
|
|
408
672
|
// worktrees (dirs under the worktree base whose session id is no longer
|
|
@@ -410,6 +674,24 @@ export class SessionManager extends EventEmitter {
|
|
|
410
674
|
// mirroring the agent-worktree reaper's opt-in. Always clean-tree-guarded.
|
|
411
675
|
sweepOrphanWorktrees = false,
|
|
412
676
|
|
|
677
|
+
// #7552: the EnvironmentManager, so a session created with an
|
|
678
|
+
// `environmentId` is TAGGED onto that environment for its whole life and
|
|
679
|
+
// untagged the moment it leaves `_sessions`. Null whenever container
|
|
680
|
+
// environments are off (server-cli only constructs one when the feature is
|
|
681
|
+
// enabled), and every use below is `?.`-guarded. The coupling is the one
|
|
682
|
+
// `EnvironmentManager`'s own class doc already describes ("SessionManager
|
|
683
|
+
// uses EnvironmentManager … when creating sessions with an environmentId").
|
|
684
|
+
environmentManager = null,
|
|
685
|
+
|
|
686
|
+
// #7601: proactive container-liveness poll. `containerInspect` is a
|
|
687
|
+
// docker-agnostic `(containerId) => Promise<'running'|'gone'|'unknown'>`
|
|
688
|
+
// seam (server-cli wires it to a DockerBackend via inspectContainerLiveness;
|
|
689
|
+
// tests inject a fake). Null → the poll is not constructed, so a deployment
|
|
690
|
+
// that never wired it simply never polls. `containerLivenessIntervalMs`
|
|
691
|
+
// overrides the 30s default (tests drive it with fake timers).
|
|
692
|
+
containerInspect = null,
|
|
693
|
+
containerLivenessIntervalMs = undefined,
|
|
694
|
+
|
|
413
695
|
// Test-only: skip preflight checks (binary + credential). Production must
|
|
414
696
|
// leave this false so missing providers surface cleanly at createSession.
|
|
415
697
|
skipPreflight = false,
|
|
@@ -433,7 +715,7 @@ export class SessionManager extends EventEmitter {
|
|
|
433
715
|
// former is the createSession() option, the latter the ctor's). When only
|
|
434
716
|
// `provider` was supplied as a usable string, map it onto `providerType`
|
|
435
717
|
// so the caller gets the provider they intended rather than a silent
|
|
436
|
-
// DEFAULT_PROVIDER
|
|
718
|
+
// DEFAULT_PROVIDER spawn. If `providerType` was ALSO set
|
|
437
719
|
// explicitly, or `provider` is not a usable string (undefined/null/''),
|
|
438
720
|
// keep the resolved `providerType` and just warn that `provider` is
|
|
439
721
|
// ignored — never overwrite a good default with a bad alias value.
|
|
@@ -488,6 +770,15 @@ export class SessionManager extends EventEmitter {
|
|
|
488
770
|
this._port = port || null
|
|
489
771
|
this._apiToken = apiToken || null
|
|
490
772
|
this._skipPreflight = skipPreflight
|
|
773
|
+
// #8275: a new manager is a new daemon lifetime for the session-less model
|
|
774
|
+
// refresh. destroyAll() latches it off for shutdown; a manager built later in
|
|
775
|
+
// the same process (a test, an in-process restart) must be able to refresh.
|
|
776
|
+
resumeClaudeModelRefresh()
|
|
777
|
+
// Test seam: extra deps (queryFn, spawnFn, managedDir, now, ...) for that refresh.
|
|
778
|
+
this._modelRefreshDeps = opts.modelRefreshDeps ?? null
|
|
779
|
+
// #7552: null when container environments are disabled — every call site
|
|
780
|
+
// is optional-chained rather than branched.
|
|
781
|
+
this._environmentManager = environmentManager || null
|
|
491
782
|
|
|
492
783
|
// Session defaults
|
|
493
784
|
this.maxSessions = maxSessions
|
|
@@ -511,6 +802,11 @@ export class SessionManager extends EventEmitter {
|
|
|
511
802
|
this._userShellReapSeams = userShellReapSeams
|
|
512
803
|
this._sweepOrphanWorktrees = !!sweepOrphanWorktrees
|
|
513
804
|
this._providerType = providerType
|
|
805
|
+
this._agentConnectionRegistry = new AgentConnectionRegistry({
|
|
806
|
+
definitions: agentConnections,
|
|
807
|
+
getProvider,
|
|
808
|
+
...agentConnectionDeps,
|
|
809
|
+
})
|
|
514
810
|
|
|
515
811
|
// Session behavior
|
|
516
812
|
this._maxToolInput = maxToolInput || null
|
|
@@ -615,9 +911,10 @@ export class SessionManager extends EventEmitter {
|
|
|
615
911
|
|
|
616
912
|
// State persistence (delegated to SessionStatePersistence)
|
|
617
913
|
this._persistence = new SessionStatePersistence({
|
|
618
|
-
stateFilePath: stateFilePath ||
|
|
914
|
+
stateFilePath: stateFilePath || defaultStateFile(),
|
|
619
915
|
stateTtlMs,
|
|
620
916
|
persistDebounceMs,
|
|
917
|
+
persistMaxWaitMs,
|
|
621
918
|
})
|
|
622
919
|
// Backward-compatible accessors for tests that reference internal state
|
|
623
920
|
this._stateFilePath = this._persistence._stateFilePath
|
|
@@ -627,6 +924,27 @@ export class SessionManager extends EventEmitter {
|
|
|
627
924
|
this._stateTtlMs = this._persistence._stateTtlMs
|
|
628
925
|
this._persistDebounceMs = this._persistence._persistDebounceMs
|
|
629
926
|
|
|
927
|
+
// Only the four documented config keys are read (never `dir`, `now`, ...).
|
|
928
|
+
const archiveConfig = sessionArchive && typeof sessionArchive === 'object' && !Array.isArray(sessionArchive) ? sessionArchive : {}
|
|
929
|
+
this._sessionArchive = sessionArchiveStore || new SessionArchive({
|
|
930
|
+
dir: join(dirname(this._stateFilePath), 'archive'),
|
|
931
|
+
enabled: archiveConfig.enabled,
|
|
932
|
+
maxEntries: archiveConfig.maxEntries,
|
|
933
|
+
maxAgeDays: archiveConfig.maxAgeDays,
|
|
934
|
+
maxMegabytes: archiveConfig.maxMegabytes,
|
|
935
|
+
})
|
|
936
|
+
// Age retention must not depend on a new session ending or on a restart: a
|
|
937
|
+
// long-lived idle daemon would otherwise serve (and keep on disk) records
|
|
938
|
+
// past the retention it advertises. unref'd so it never holds the process.
|
|
939
|
+
this._archivePruneTimer = null
|
|
940
|
+
if (Number.isFinite(sessionArchivePruneIntervalMs) && sessionArchivePruneIntervalMs > 0) {
|
|
941
|
+
this._archivePruneTimer = setInterval(() => {
|
|
942
|
+
this._sessionArchive.prune?.()
|
|
943
|
+
this._retryUnarchivedStale()
|
|
944
|
+
}, sessionArchivePruneIntervalMs)
|
|
945
|
+
if (typeof this._archivePruneTimer.unref === 'function') this._archivePruneTimer.unref()
|
|
946
|
+
}
|
|
947
|
+
|
|
630
948
|
// #5554: usage recorder. Use the caller-supplied one (tests pin a temp
|
|
631
949
|
// path), else default to a file alongside the session-state file so a temp
|
|
632
950
|
// stateFilePath also redirects the usage log away from the real home — the
|
|
@@ -660,7 +978,7 @@ export class SessionManager extends EventEmitter {
|
|
|
660
978
|
this.binaryProvenanceLedger = binaryProvenanceLedger
|
|
661
979
|
|| new BinaryProvenanceLedger({ filePath: join(dirname(this._stateFilePath), 'binary-trust.json') })
|
|
662
980
|
// Config path the preset resolver reads the daemon override map from.
|
|
663
|
-
// Defaults to undefined → resolveSessionPreset uses its own
|
|
981
|
+
// Defaults to undefined → resolveSessionPreset uses its own defaultConfigPath().
|
|
664
982
|
this.presetConfigPath = typeof presetConfigPath === 'string' ? presetConfigPath : null
|
|
665
983
|
// #6771: durable per-project permission rule store. Same temp-redirect logic
|
|
666
984
|
// as the sidecars above — the default file sits next to the session-state
|
|
@@ -695,6 +1013,18 @@ export class SessionManager extends EventEmitter {
|
|
|
695
1013
|
|
|
696
1014
|
// Message history (delegated to SessionMessageHistory)
|
|
697
1015
|
this._history = new SessionMessageHistory({ maxMessages: maxMessages ?? maxHistory, maxToolInput })
|
|
1016
|
+
// #8259: persist a seq reservation synchronously, before a seq above the previous one
|
|
1017
|
+
// is issued (see SessionMessageHistory#_nextSeq). Not during teardown, nor while a
|
|
1018
|
+
// restore is still seeding sessions (a mid-restore write would drop the sessions not
|
|
1019
|
+
// yet restored); the restore's own final write carries the reservation.
|
|
1020
|
+
this._history.setSeqReservationHandler((sessionId) => {
|
|
1021
|
+
if (this._destroying || this._restoringHistory || !this._sessions.has(sessionId)) return
|
|
1022
|
+
this._flushPersistOrWarn(sessionId)
|
|
1023
|
+
})
|
|
1024
|
+
// #8348: open permission prompts, requestId -> { sessionId, tool, description }.
|
|
1025
|
+
// The end-of-prompt events carry only the requestId, so what the transcript
|
|
1026
|
+
// should say about the prompt is kept from the moment it was raised.
|
|
1027
|
+
this._permissionRequests = new Map()
|
|
698
1028
|
// Backward-compatible accessors for tests that reference internal state
|
|
699
1029
|
this._maxHistory = this._history.maxHistory
|
|
700
1030
|
this._messageHistory = this._history._messageHistory
|
|
@@ -718,6 +1048,9 @@ export class SessionManager extends EventEmitter {
|
|
|
718
1048
|
: DEFAULT_SEMANTIC_TITLE_TIMEOUT_MS
|
|
719
1049
|
// null → resolve the default SDK one-shot lazily on first use (see above).
|
|
720
1050
|
this._titleRunOneShot = typeof titleRunOneShot === 'function' ? titleRunOneShot : null
|
|
1051
|
+
// #8030: test seam — see the ctor opt above. null → verifyOneShotExecutable()
|
|
1052
|
+
// falls back to getProvider('claude-sdk').
|
|
1053
|
+
this._oneShotProviderClass = oneShotProviderClass || null
|
|
721
1054
|
|
|
722
1055
|
// Wire auto_label events from history to session_updated emissions. The
|
|
723
1056
|
// synchronous truncation label is broadcast immediately (never blocked), then
|
|
@@ -736,6 +1069,11 @@ export class SessionManager extends EventEmitter {
|
|
|
736
1069
|
this._mailboxEvents = [] // bounded ring buffer of recent mailbox deliveries (Control Room observability)
|
|
737
1070
|
this._externalSessions = new ExternalSessionRegistry() // #5969 — live external (/api/events) sessions for mission control
|
|
738
1071
|
this._sessionLastActivityAt = new Map() // sessionId -> last meaningful user/agent activity timestamp
|
|
1072
|
+
// #8301: sessions whose user pressed Stop and has not typed since — daemon turns are refused (see daemonTurnRefusal).
|
|
1073
|
+
this._userStopped = new Set()
|
|
1074
|
+
// #8866: sessionId -> { seed, claimed } — the archived-transcript seed of a session
|
|
1075
|
+
// continued as a NEW thread, held until the first accepted user input carries it.
|
|
1076
|
+
this._continuationSeeds = new Map()
|
|
739
1077
|
this._sessionCounter = 0 // monotonically incrementing; used for auto-naming
|
|
740
1078
|
this._locks = new SessionLockManager()
|
|
741
1079
|
|
|
@@ -745,6 +1083,12 @@ export class SessionManager extends EventEmitter {
|
|
|
745
1083
|
// back to disk unchanged — the user's history must not be dropped just
|
|
746
1084
|
// because the provider happened to be misconfigured at boot.
|
|
747
1085
|
this._failedRestores = new Map() // sessionId -> { saved, error }
|
|
1086
|
+
// Stale snapshots (the 24h filter's drops that would have restored fine)
|
|
1087
|
+
// whose ARCHIVE write failed. They are not failed restores and are never
|
|
1088
|
+
// restored: they are written back verbatim by serializeState() so every later
|
|
1089
|
+
// state write keeps them, the next boot sees them stale again and retries the
|
|
1090
|
+
// archive, and an entry leaves this map the moment its archive is satisfied.
|
|
1091
|
+
this._unarchivedStale = new Map() // key -> saved
|
|
748
1092
|
|
|
749
1093
|
// Set to true by destroyAll() so any subsequent persist call is a no-op
|
|
750
1094
|
// — prevents a duplicate shutdown pass writing 0 sessions over the good
|
|
@@ -780,7 +1124,7 @@ export class SessionManager extends EventEmitter {
|
|
|
780
1124
|
const friendly = formatIdleDuration(idleMs)
|
|
781
1125
|
log.info(`Session ${sessionId} timed out after ${friendly} idle`)
|
|
782
1126
|
this.emit('session_timeout', { sessionId, name: entry.name, idleMs })
|
|
783
|
-
this.destroySession(sessionId)
|
|
1127
|
+
this.destroySession(sessionId, { archiveReason: 'idle_timeout' })
|
|
784
1128
|
})
|
|
785
1129
|
|
|
786
1130
|
// Wire isRunning check so timeout manager can skip busy sessions
|
|
@@ -789,12 +1133,31 @@ export class SessionManager extends EventEmitter {
|
|
|
789
1133
|
return entry ? entry.session.isRunning : false
|
|
790
1134
|
})
|
|
791
1135
|
|
|
1136
|
+
// #7601: proactive container-liveness poll — surfaces CONTAINER_VANISHED on
|
|
1137
|
+
// an IDLE containerized session whose container was stopped externally
|
|
1138
|
+
// (a plain `docker stop` fires no chroxy event, so a poll is the only
|
|
1139
|
+
// detector). Constructed only when a `containerInspect` seam was wired
|
|
1140
|
+
// (production always does when environments/docker are in play); left null
|
|
1141
|
+
// otherwise so nothing polls. Started/stopped/destroyed alongside the
|
|
1142
|
+
// timeout manager.
|
|
1143
|
+
this._containerLivenessMonitor = containerInspect
|
|
1144
|
+
? new ContainerLivenessMonitor({
|
|
1145
|
+
enumerate: () => this._listContainerLivenessTargets(),
|
|
1146
|
+
inspect: containerInspect,
|
|
1147
|
+
// #7602: the live re-attach hangs off the poll's recovery edge — the
|
|
1148
|
+
// one moment we KNOW a vanished session's container is running again.
|
|
1149
|
+
onRecovered: ({ sessionId }) => this._reattachEnvironmentBoundSession(sessionId),
|
|
1150
|
+
...(containerLivenessIntervalMs != null ? { intervalMs: containerLivenessIntervalMs } : {}),
|
|
1151
|
+
})
|
|
1152
|
+
: null
|
|
1153
|
+
|
|
792
1154
|
// Validate provider exists at construction time for fail-fast behavior
|
|
793
1155
|
getProvider(this._providerType)
|
|
794
1156
|
}
|
|
795
1157
|
|
|
796
1158
|
/**
|
|
797
|
-
* Remove a session from all session-scoped maps and sets (#1204)
|
|
1159
|
+
* Remove a session from all session-scoped maps and sets (#1204), including
|
|
1160
|
+
* the survey-throttle record (#7450 / #8092).
|
|
798
1161
|
* Called by destroySession(), sync catch, and async .catch() paths.
|
|
799
1162
|
* @param {string} sessionId
|
|
800
1163
|
*/
|
|
@@ -803,11 +1166,39 @@ export class SessionManager extends EventEmitter {
|
|
|
803
1166
|
if (entry && entry.agentCommId) {
|
|
804
1167
|
this._agentCommIds.delete(entry.agentCommId)
|
|
805
1168
|
}
|
|
1169
|
+
// #7552: untag the container environment. This is deliberately HERE and not
|
|
1170
|
+
// on the `session_destroyed` EVENT: `_handleAsyncStartFailure`'s
|
|
1171
|
+
// restore-rebind branch removes a session from `_sessions` and emits
|
|
1172
|
+
// `session_restore_failed` INSTEAD of `session_destroyed`, so an event
|
|
1173
|
+
// listener would miss it and strand the id — and a stranded id makes the
|
|
1174
|
+
// environment permanently undestroyable, the exact inverse of the bug the
|
|
1175
|
+
// attach fixes. Every path out of `_sessions` runs this method (the sole
|
|
1176
|
+
// `_sessions.delete` site); `destroyAll()` is the one exception and untags
|
|
1177
|
+
// in its own loop. Both are pinned per-path in
|
|
1178
|
+
// tests/environment-session-wiring.test.js.
|
|
1179
|
+
if (entry?.environmentId) this._environmentManager?.removeSession(entry.environmentId, sessionId)
|
|
806
1180
|
this._sessions.delete(sessionId)
|
|
807
1181
|
this._sessionLastActivityAt.delete(sessionId)
|
|
808
1182
|
this._timeoutManager.removeSession(sessionId)
|
|
809
1183
|
this._history.cleanupSession(sessionId)
|
|
810
1184
|
this._costBudget.removeSession(sessionId)
|
|
1185
|
+
this._userStopped.delete(sessionId)
|
|
1186
|
+
this._continuationSeeds.delete(sessionId)
|
|
1187
|
+
for (const [requestId, pending] of this._permissionRequests) {
|
|
1188
|
+
if (pending.sessionId === sessionId) this._permissionRequests.delete(requestId)
|
|
1189
|
+
}
|
|
1190
|
+
// #8092: prune this session's survey-throttle record(s) for the SAME
|
|
1191
|
+
// reason the environment untag above lives here rather than on
|
|
1192
|
+
// `session_destroyed` — the restore-rebind branch of
|
|
1193
|
+
// `_handleAsyncStartFailure()` (and the sync/async start()-failure catch
|
|
1194
|
+
// paths above it) runs this method without ever emitting that event, so
|
|
1195
|
+
// an event-based prune (this PR's first attempt, #7450) silently missed
|
|
1196
|
+
// them. Hooking the removal itself, here, reaches every path out of
|
|
1197
|
+
// `_sessions` (this method IS that sole path, `destroyAll()` excepted —
|
|
1198
|
+
// see its own call below) rather than only the paths that happen to fire
|
|
1199
|
+
// a particular event — the general lesson this repo already learned once
|
|
1200
|
+
// for the environment tag.
|
|
1201
|
+
forgetSurveyKey(this, sessionId)
|
|
811
1202
|
}
|
|
812
1203
|
|
|
813
1204
|
/**
|
|
@@ -957,6 +1348,193 @@ export class SessionManager extends EventEmitter {
|
|
|
957
1348
|
return out
|
|
958
1349
|
}
|
|
959
1350
|
|
|
1351
|
+
// #8030 — three helpers that share the "opt-in provenance bag + re-verify a
|
|
1352
|
+
// binary before a spawn" logic that used to live inline at each call site:
|
|
1353
|
+
//
|
|
1354
|
+
// - `_binaryProvenanceOptions()` builds the `{ mode, signatureGate, ledger }`
|
|
1355
|
+
// bag `runProviderPreflight` expects (or null when the operator hasn't
|
|
1356
|
+
// opted in). Used at create-time preflight, inside the native
|
|
1357
|
+
// `connectionRuntimePreflight` closure, and by the two methods below —
|
|
1358
|
+
// one place to read `this._binaryProvenanceMode` / `this._binarySignatureGate`
|
|
1359
|
+
// / `this.binaryProvenanceLedger` instead of three copies drifting.
|
|
1360
|
+
// - `_verifyPinnedSpawn(ProviderClass, pinnedPath)` re-runs the FULL gate
|
|
1361
|
+
// against an EXACT path (no re-resolution) and fails closed — thrown
|
|
1362
|
+
// errors (e.g. `ProviderBinaryProvenanceError`) propagate as-is, and a
|
|
1363
|
+
// result whose `binaryPath` doesn't match `pinnedPath` is itself an
|
|
1364
|
+
// error. Wired as `providerOpts.spawnPreflight` (see createSession
|
|
1365
|
+
// below) so a per-turn provider can re-verify its pinned binary before
|
|
1366
|
+
// every spawn, not just once at session-create. #8035: BaseSession
|
|
1367
|
+
// stores this as `this._spawnPreflight` (not read by a subclass
|
|
1368
|
+
// directly), so every consumer that spawns more than once per session
|
|
1369
|
+
// shares it — the Agent SDK (#8030, execs a new process per turn) and
|
|
1370
|
+
// JsonlSubprocessSession's Gemini / Codex-exec subclasses (spawn once
|
|
1371
|
+
// per turn). #8038: claude-cli's `_spawnPersistentProcess`, claude-tui's
|
|
1372
|
+
// `_spawnPty` (non-native route; the native route's own
|
|
1373
|
+
// `connectionRuntimePreflight` re-check already counted) and codex
|
|
1374
|
+
// app-server's `start()` now call it too — every (re)spawn of every
|
|
1375
|
+
// provider that holds a `_spawnPreflight` is gated, not just the
|
|
1376
|
+
// per-turn ones.
|
|
1377
|
+
// - `verifyOneShotExecutable()` is the same idea for a one-shot call that
|
|
1378
|
+
// has NO create-time pin to reuse (the summarizer, the semantic-title
|
|
1379
|
+
// generator) — it re-resolves AND re-verifies fresh every call.
|
|
1380
|
+
|
|
1381
|
+
/**
|
|
1382
|
+
* Build the opt-in binary-provenance config bag for `runProviderPreflight`,
|
|
1383
|
+
* or null when the operator hasn't turned either gate on (mode 'off' AND no
|
|
1384
|
+
* signature gate) — passing null makes `runProviderPreflight` skip the step
|
|
1385
|
+
* entirely, byte-identical to pre-#6858 behaviour.
|
|
1386
|
+
*
|
|
1387
|
+
* @returns {{ mode: string, signatureGate: boolean, ledger: object|null }|null}
|
|
1388
|
+
*/
|
|
1389
|
+
_binaryProvenanceOptions() {
|
|
1390
|
+
// #8061: the bag-shape normalization itself lives in
|
|
1391
|
+
// `buildBinaryProvenanceOptions` (utils/preflight.js), shared with the
|
|
1392
|
+
// `chroxy resume` CLI gate — this stays a thin instance-field
|
|
1393
|
+
// reader so the two never drift on what counts as "off".
|
|
1394
|
+
return buildBinaryProvenanceOptions({
|
|
1395
|
+
mode: this._binaryProvenanceMode,
|
|
1396
|
+
signatureGate: this._binarySignatureGate,
|
|
1397
|
+
ledger: this.binaryProvenanceLedger,
|
|
1398
|
+
})
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
/**
|
|
1402
|
+
* #8030 / #8035 — re-verify an EXACT, already-resolved binary path before a
|
|
1403
|
+
* spawn. Used as the `spawnPreflight` seam a per-turn provider calls before
|
|
1404
|
+
* every spawn — SdkSession before every `query()` (the SDK execs a NEW
|
|
1405
|
+
* process per turn), JsonlSubprocessSession's Gemini/Codex-exec subclasses
|
|
1406
|
+
* before every child spawn — since a binary verified once at session-create
|
|
1407
|
+
* is not automatically still the same, still-healthy binary on turn two.
|
|
1408
|
+
* `pinnedPath` is the path THIS session verified at create time — passing
|
|
1409
|
+
* it as `options.pinnedPath` to
|
|
1410
|
+
* `runProviderPreflight` skips re-resolution entirely (a PATH change mid-
|
|
1411
|
+
* session can never redirect the spawn to a different binary) while still
|
|
1412
|
+
* re-running existence / quarantine / shim / provenance / version checks
|
|
1413
|
+
* against that exact path.
|
|
1414
|
+
*
|
|
1415
|
+
* Fails CLOSED: `runProviderPreflight` throws its normal typed errors
|
|
1416
|
+
* (`ProviderBinaryProvenanceError`, `ProviderBinaryQuarantinedError`, …) on
|
|
1417
|
+
* any gate failure, which propagate here unchanged. As a belt-and-braces
|
|
1418
|
+
* check, a successful call whose returned `binaryPath` somehow differs from
|
|
1419
|
+
* `pinnedPath` (it should not — verifying a pinned path always echoes it
|
|
1420
|
+
* back) also throws, rather than silently spawning whatever path preflight
|
|
1421
|
+
* returned.
|
|
1422
|
+
*
|
|
1423
|
+
* @param {Function} ProviderClass - the SAME class used to construct the session.
|
|
1424
|
+
* @param {string} pinnedPath - the create-time-verified path to re-verify.
|
|
1425
|
+
* @returns {string} `pinnedPath`, once re-verification passes.
|
|
1426
|
+
* @throws {Error} with `code = 'PROVIDER_BINARY_UNVERIFIED'` on a path
|
|
1427
|
+
* mismatch, or one of `runProviderPreflight`'s own typed errors otherwise.
|
|
1428
|
+
*/
|
|
1429
|
+
_verifyPinnedSpawn(ProviderClass, pinnedPath) {
|
|
1430
|
+
let result
|
|
1431
|
+
try {
|
|
1432
|
+
result = runProviderPreflight(ProviderClass, {
|
|
1433
|
+
provenance: this._binaryProvenanceOptions(),
|
|
1434
|
+
pinnedPath,
|
|
1435
|
+
// #8030: a per-turn re-verification must not re-log the #8031 soft-floor
|
|
1436
|
+
// advisory on every single turn — see runProviderPreflight's docblock.
|
|
1437
|
+
warnAdvisory: false,
|
|
1438
|
+
})
|
|
1439
|
+
} catch (err) {
|
|
1440
|
+
// The generic not-found text ("checked PATH and …") is wrong here: only
|
|
1441
|
+
// the pinned path was checked, and a session stays pinned to it, so the
|
|
1442
|
+
// remedy is a new session rather than an install.
|
|
1443
|
+
if (err?.code === 'PROVIDER_BINARY_NOT_FOUND') {
|
|
1444
|
+
const gone = new Error(`${err.provider}: the "${err.binary}" binary this session was verified with at ${pinnedPath} is no longer there or no longer executable — start a new session to use the currently installed one.`)
|
|
1445
|
+
gone.code = err.code
|
|
1446
|
+
gone.provider = err.provider
|
|
1447
|
+
gone.binary = err.binary
|
|
1448
|
+
gone.path = pinnedPath
|
|
1449
|
+
throw gone
|
|
1450
|
+
}
|
|
1451
|
+
throw err
|
|
1452
|
+
}
|
|
1453
|
+
if (result.binaryPath !== pinnedPath) {
|
|
1454
|
+
const err = new Error(`Provider binary at "${pinnedPath}" could not be re-verified for this spawn (preflight resolved a different or no path).`)
|
|
1455
|
+
err.code = 'PROVIDER_BINARY_UNVERIFIED'
|
|
1456
|
+
throw err
|
|
1457
|
+
}
|
|
1458
|
+
return result.binaryPath
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
/**
|
|
1462
|
+
* #8275 — once a USER-CREATED session of a provider that exposes
|
|
1463
|
+
* `refreshLiveModels` (claude-tui) has started, refresh the Claude picker from
|
|
1464
|
+
* the installed claude and announce it exactly as the SDK's in-session
|
|
1465
|
+
* `_fetchSupportedModels` does: a `models_updated` session event, which
|
|
1466
|
+
* ws-forwarding turns into the per-recipient `available_models` broadcast.
|
|
1467
|
+
* Fire-and-forget: it never delays or fails the session, and it is a no-op for
|
|
1468
|
+
* every other provider. The daemon never runs it on its own (boot, client
|
|
1469
|
+
* connect, restore); it rides on a launch the user asked for.
|
|
1470
|
+
*/
|
|
1471
|
+
_refreshLiveModelsAfterStart(sessionId, session, entry) {
|
|
1472
|
+
const ProviderClass = session?.constructor
|
|
1473
|
+
if (typeof ProviderClass?.refreshLiveModels !== 'function') return
|
|
1474
|
+
Promise.resolve()
|
|
1475
|
+
.then(() => ProviderClass.refreshLiveModels({
|
|
1476
|
+
bin: () => this.verifyOneShotExecutable(ProviderClass),
|
|
1477
|
+
...(this._modelRefreshDeps || {}),
|
|
1478
|
+
}))
|
|
1479
|
+
.then((models) => {
|
|
1480
|
+
if (!Array.isArray(models) || models.length === 0) return
|
|
1481
|
+
if (this._sessions.get(sessionId) !== entry || entry._destroying) return
|
|
1482
|
+
session.emit('models_updated', { models })
|
|
1483
|
+
})
|
|
1484
|
+
.catch((err) => log.debug(`Live model refresh after session start failed: ${getErrorMessage(err, 'unknown error')}`))
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
/**
|
|
1488
|
+
* #8030 — re-resolve AND re-verify the binary a one-shot model call (the
|
|
1489
|
+
* `summarize_session` handler, the semantic-title generator) is about to
|
|
1490
|
+
* spawn. Unlike a chat turn, a one-shot has no create-time session to pin a
|
|
1491
|
+
* path from, so this runs the FULL gate fresh every call: existence,
|
|
1492
|
+
* quarantine, the direct-exec shim refusal, the opt-in provenance gate, and
|
|
1493
|
+
* the version floor — exactly what `createSession` runs for a chat session,
|
|
1494
|
+
* so a `block`-mode hash mismatch refuses a one-shot exactly as it would
|
|
1495
|
+
* refuse a new chat session.
|
|
1496
|
+
*
|
|
1497
|
+
* `this._oneShotProviderClass` is a test seam (constructor opt
|
|
1498
|
+
* `oneShotProviderClass`); production defaults to resolving
|
|
1499
|
+
* `getProvider('claude-sdk')` — the summarizer / semantic-title one-shots
|
|
1500
|
+
* always spawn the Agent SDK regardless of which provider the CALLING
|
|
1501
|
+
* session uses (summarize-session.js's `defaultRunOneShot` is SDK-only).
|
|
1502
|
+
*
|
|
1503
|
+
* #8036 — GENERALIZED to take an explicit `ProviderClass` so a caller that
|
|
1504
|
+
* needs a DIFFERENT provider's one-shot spawn gated (the codex model-catalog
|
|
1505
|
+
* probe, which has no session either) can reuse this same verified resolver
|
|
1506
|
+
* instead of a second implementation. Passing no argument (or `undefined`)
|
|
1507
|
+
* preserves the exact #8030 default above; the ctor-time
|
|
1508
|
+
* `oneShotProviderClass` seam still wins over the built-in default when no
|
|
1509
|
+
* explicit class is passed at the call site.
|
|
1510
|
+
*
|
|
1511
|
+
* `this._skipPreflight` (test-only; see the ctor opt) returns the UNVERIFIED
|
|
1512
|
+
* resolved path with no gate at all — the same meaning `skipPreflight` has
|
|
1513
|
+
* everywhere else in this class.
|
|
1514
|
+
*
|
|
1515
|
+
* @param {Function} [ProviderClass] - #8036: the provider class to verify a
|
|
1516
|
+
* spawnable binary for. Defaults to `this._oneShotProviderClass ||
|
|
1517
|
+
* getProvider('claude-sdk')`, the original #8030 behaviour.
|
|
1518
|
+
* @returns {string} a verified, spawnable binary path.
|
|
1519
|
+
* @throws {Error} with `code = 'PROVIDER_BINARY_UNVERIFIED'` when preflight
|
|
1520
|
+
* resolves no usable path, or one of `runProviderPreflight`'s own typed
|
|
1521
|
+
* errors (e.g. `PROVIDER_BINARY_PROVENANCE`) on a gate failure.
|
|
1522
|
+
*/
|
|
1523
|
+
verifyOneShotExecutable(ProviderClass = this._oneShotProviderClass || getProvider('claude-sdk')) {
|
|
1524
|
+
if (this._skipPreflight) {
|
|
1525
|
+
// Test-only escape hatch — same unverified-path meaning as skipPreflight
|
|
1526
|
+
// everywhere else in this class. Production always leaves this false.
|
|
1527
|
+
return ProviderClass.resolvedBinary
|
|
1528
|
+
}
|
|
1529
|
+
const result = runProviderPreflight(ProviderClass, { provenance: this._binaryProvenanceOptions() })
|
|
1530
|
+
if (!result.binaryPath) {
|
|
1531
|
+
const err = new Error(`Could not verify a spawnable binary for provider "${ProviderClass.displayLabel || ProviderClass.name || 'claude-sdk'}".`)
|
|
1532
|
+
err.code = 'PROVIDER_BINARY_UNVERIFIED'
|
|
1533
|
+
throw err
|
|
1534
|
+
}
|
|
1535
|
+
return result.binaryPath
|
|
1536
|
+
}
|
|
1537
|
+
|
|
960
1538
|
/**
|
|
961
1539
|
* Resolve the validated "create plan" for a session (#6036 — the front-half
|
|
962
1540
|
* SRP extraction out of {@link SessionManager#createSession}). Owns exactly
|
|
@@ -993,7 +1571,7 @@ export class SessionManager extends EventEmitter {
|
|
|
993
1571
|
* effectiveSessionPreamble: (string|undefined),
|
|
994
1572
|
* }} the validated create plan.
|
|
995
1573
|
*/
|
|
996
|
-
_resolveCreateSessionPlan({ name, cwd, model, permissionMode, provider, worktree, restoreWorktreePath, restoreWorktreeRepoDir, sessionPreamble, preserveId, isRestore = false } = {}) {
|
|
1574
|
+
_resolveCreateSessionPlan({ name, cwd, model, permissionMode, provider, connectionId, restoredAgentConnection, worktree, restoreWorktreePath, restoreWorktreeRepoDir, sessionPreamble, preserveId, resumeSessionId, isRestore = false, modelSource = 'explicit' } = {}) {
|
|
997
1575
|
if (this._sessions.size >= this.maxSessions) {
|
|
998
1576
|
log.error(`Cannot create session: limit reached (${this._sessions.size}/${this.maxSessions})`)
|
|
999
1577
|
throw new SessionLimitError(this.maxSessions)
|
|
@@ -1015,7 +1593,12 @@ export class SessionManager extends EventEmitter {
|
|
|
1015
1593
|
let resolvedModel = model === undefined ? this._defaultModel : model
|
|
1016
1594
|
const resolvedPermissionMode = permissionMode || this._defaultPermissionMode
|
|
1017
1595
|
|
|
1018
|
-
// Validate cwd exists
|
|
1596
|
+
// Validate cwd exists. #8856: a restored worktree session's cwd IS its
|
|
1597
|
+
// worktree, which the agent inside it can delete (`git worktree remove`).
|
|
1598
|
+
// That one case is deferred to the rebind branch below, which can recreate
|
|
1599
|
+
// the worktree once the session id is known; it throws this same error
|
|
1600
|
+
// there whenever it cannot.
|
|
1601
|
+
let missingRestoreWorktree = false
|
|
1019
1602
|
try {
|
|
1020
1603
|
const stat = statSync(baseCwd)
|
|
1021
1604
|
if (!stat.isDirectory()) {
|
|
@@ -1023,11 +1606,24 @@ export class SessionManager extends EventEmitter {
|
|
|
1023
1606
|
}
|
|
1024
1607
|
} catch (err) {
|
|
1025
1608
|
if (err.code === 'ENOENT') {
|
|
1026
|
-
|
|
1609
|
+
if (restoreWorktreePath && resolve(baseCwd) === resolve(restoreWorktreePath)) {
|
|
1610
|
+
missingRestoreWorktree = true
|
|
1611
|
+
} else {
|
|
1612
|
+
throw new SessionDirectoryError(`Directory does not exist: ${baseCwd}`, baseCwd)
|
|
1613
|
+
}
|
|
1614
|
+
} else {
|
|
1615
|
+
throw err
|
|
1027
1616
|
}
|
|
1028
|
-
throw err
|
|
1029
1617
|
}
|
|
1030
1618
|
|
|
1619
|
+
// The configured Claude config directory is not a working directory. Checked
|
|
1620
|
+
// here, at the one boundary every creation shares (an omitted cwd, the
|
|
1621
|
+
// startup default, a restored session, a checkpoint branch), so none of
|
|
1622
|
+
// them can reach it. A restored session that now points into it is refused
|
|
1623
|
+
// like any other restore failure: logged, kept parked, not silently started.
|
|
1624
|
+
const baseDenial = claudeConfigDirCwdDenial(baseCwd)
|
|
1625
|
+
if (baseDenial) throw new SessionDirectoryError(baseDenial, baseCwd)
|
|
1626
|
+
|
|
1031
1627
|
// #4983 — preserve persisted ID on restoreState so dashboard's
|
|
1032
1628
|
// localStorage-cached activeSessionId still resolves after a daemon
|
|
1033
1629
|
// restart. Validate the format strictly (32 lower-case hex chars,
|
|
@@ -1051,8 +1647,26 @@ export class SessionManager extends EventEmitter {
|
|
|
1051
1647
|
// binary surfaces as an opaque ENOENT after the session has already
|
|
1052
1648
|
// appeared in the UI. Runs BEFORE worktree creation so a failed preflight
|
|
1053
1649
|
// doesn't leave an orphan worktree behind. (#2962)
|
|
1054
|
-
const
|
|
1650
|
+
const connectionResolution = connectionId
|
|
1651
|
+
? this._agentConnectionRegistry.resolve(connectionId, {
|
|
1652
|
+
provider,
|
|
1653
|
+
restoredSnapshot: restoredAgentConnection,
|
|
1654
|
+
model: resolvedModel,
|
|
1655
|
+
})
|
|
1656
|
+
: null
|
|
1657
|
+
const resolvedProviderType = connectionResolution?.definition.runtime || provider || this._providerType
|
|
1055
1658
|
const PreflightProviderClass = getProvider(resolvedProviderType)
|
|
1659
|
+
// Pin only an ordinary NEW Claude session with no configured/user choice.
|
|
1660
|
+
// Do this after connection resolution so another runtime never gets a
|
|
1661
|
+
// Claude model. Internal null, restored identity and resumed history retain
|
|
1662
|
+
// upstream policy; malformed/colliding preserve IDs still create fresh sessions.
|
|
1663
|
+
if (!isRestore && !resumeSessionId && !preserve && model === undefined && resolvedModel === null && isClaudeProvider(resolvedProviderType, PreflightProviderClass)) {
|
|
1664
|
+
resolvedModel = CLAUDE_NEW_SESSION_DEFAULT_MODEL
|
|
1665
|
+
}
|
|
1666
|
+
// #7825 — reject an adapter/mode combination before preflight, worktree
|
|
1667
|
+
// creation, provider construction, or turn start. This chokepoint is shared
|
|
1668
|
+
// by explicit create requests, configured defaults, boot restore, and retry.
|
|
1669
|
+
assertProviderPermissionModeSupported(PreflightProviderClass, resolvedPermissionMode, PreflightProviderClass.displayLabel || resolvedProviderType)
|
|
1056
1670
|
// #5985 (epic #5982): fail-closed gate for the embedded user-shell terminal.
|
|
1057
1671
|
// Enforced here (before any spawn) so it covers EVERY create path — WS
|
|
1058
1672
|
// create_session, restoreState, and internal callers — not just the WS
|
|
@@ -1063,18 +1677,12 @@ export class SessionManager extends EventEmitter {
|
|
|
1063
1677
|
if (PreflightProviderClass?.isUserShell === true && !this._userShellEnabled) {
|
|
1064
1678
|
throw new UserShellDisabledError()
|
|
1065
1679
|
}
|
|
1680
|
+
let providerPreflight = null
|
|
1066
1681
|
if (!this._skipPreflight) {
|
|
1067
|
-
// #6858: opt-in provenance gate.
|
|
1068
|
-
// operator opted in (mode
|
|
1069
|
-
//
|
|
1070
|
-
|
|
1071
|
-
? {
|
|
1072
|
-
mode: this._binaryProvenanceMode,
|
|
1073
|
-
signatureGate: this._binarySignatureGate,
|
|
1074
|
-
ledger: this.binaryProvenanceLedger,
|
|
1075
|
-
}
|
|
1076
|
-
: null
|
|
1077
|
-
runProviderPreflight(PreflightProviderClass, { provenance })
|
|
1682
|
+
// #6858: opt-in provenance gate. _binaryProvenanceOptions() returns null
|
|
1683
|
+
// when the operator hasn't opted in (mode 'off' AND no signature gate),
|
|
1684
|
+
// so runProviderPreflight skips the step entirely (unchanged behaviour).
|
|
1685
|
+
providerPreflight = runProviderPreflight(PreflightProviderClass, { provenance: this._binaryProvenanceOptions() })
|
|
1078
1686
|
}
|
|
1079
1687
|
// #6378: a provider opted into `config.providers.allowAnyModel` skips static
|
|
1080
1688
|
// allowlist validation entirely — the model id passes through verbatim and
|
|
@@ -1100,13 +1708,44 @@ export class SessionManager extends EventEmitter {
|
|
|
1100
1708
|
// SdkSession and CliSession treat as "use the upstream default")
|
|
1101
1709
|
// and log a warning so operators can spot the drift in logs (#3403).
|
|
1102
1710
|
if (isClaudeProvider(resolvedProviderType, PreflightProviderClass)) {
|
|
1103
|
-
|
|
1104
|
-
|
|
1711
|
+
// #7855: an off-roster id is NOT a stale one. A well-formed Claude id
|
|
1712
|
+
// the roster has not caught up with is forwarded verbatim (the CLI
|
|
1713
|
+
// resolves it; the running model is confirmed from the native journal).
|
|
1714
|
+
// Only an id that cannot be a Claude model at all is dropped, and only
|
|
1715
|
+
// when nobody asked for it by name (a restored snapshot or a configured
|
|
1716
|
+
// default, #3403). An explicit request for such an id is rejected
|
|
1717
|
+
// instead of silently starting another model.
|
|
1718
|
+
const request = classifyClaudeModelRequest(resolvedModel, providerAllowedModels)
|
|
1719
|
+
if (request.kind === 'native') {
|
|
1720
|
+
log.info(`Requested model '${resolvedModel}' is not in the current roster for provider '${resolvedProviderType}'; forwarding it verbatim to the native client`)
|
|
1721
|
+
} else if (typeof model === 'string' && !isRestore && modelSource !== 'replay') {
|
|
1722
|
+
throw new ProviderModelNotSupportedError({
|
|
1723
|
+
provider: resolvedProviderType,
|
|
1724
|
+
model: resolvedModel,
|
|
1725
|
+
supported: providerAllowedModels,
|
|
1726
|
+
})
|
|
1727
|
+
} else {
|
|
1728
|
+
log.warn(`Model '${resolvedModel}' is not a valid Claude model id for provider '${resolvedProviderType}' and was not explicitly requested; falling back to provider default. Supported: ${providerAllowedModels.slice(0, 8).join(', ')}${providerAllowedModels.length > 8 ? ', …' : ''}`)
|
|
1729
|
+
resolvedModel = null
|
|
1730
|
+
}
|
|
1105
1731
|
} else {
|
|
1106
|
-
// Non-Claude providers
|
|
1107
|
-
//
|
|
1108
|
-
// back would otherwise mask a real misconfiguration (e.g. a
|
|
1732
|
+
// Non-Claude providers reaching HERE published an authoritative,
|
|
1733
|
+
// non-empty allowlist — strict rejection still applies because
|
|
1734
|
+
// falling back would otherwise mask a real misconfiguration (e.g. a
|
|
1109
1735
|
// Claude model id sent to a Gemini session).
|
|
1736
|
+
//
|
|
1737
|
+
// "Authoritative" is not the same as "static" any more. Gemini and
|
|
1738
|
+
// DeepSeek publish a compiled-in list; codex (#7727) publishes the
|
|
1739
|
+
// ids its own binary answered `model/list` with, and publishes a
|
|
1740
|
+
// NON-ARRAY while it has no catalog — which this gate reads as
|
|
1741
|
+
// unrestricted a few lines above and never reaches this branch for.
|
|
1742
|
+
//
|
|
1743
|
+
// The `length > 0` guard above is why an empty array never gets
|
|
1744
|
+
// here: it is skipped, i.e. unvalidated. `handleSetModel`'s copy of
|
|
1745
|
+
// this gate does the opposite and treats `[]` as a deny-all. The
|
|
1746
|
+
// two disagree, so a provider must never return `[]` to mean
|
|
1747
|
+
// "nothing to say" — #7727 documents that on getAllowedModels and
|
|
1748
|
+
// tests/codex-model-validation.test.js pins the asymmetry.
|
|
1110
1749
|
throw new ProviderModelNotSupportedError({
|
|
1111
1750
|
provider: resolvedProviderType,
|
|
1112
1751
|
model: resolvedModel,
|
|
@@ -1128,10 +1767,13 @@ export class SessionManager extends EventEmitter {
|
|
|
1128
1767
|
// entry carries worktreePath:null and never GCs the dir on destroy
|
|
1129
1768
|
// (orphan accrual) and reports isolation:'none'. The original repo dir
|
|
1130
1769
|
// can't be derived from the persisted cwd (which IS the worktree), so it
|
|
1131
|
-
// is persisted + threaded through here for `git worktree remove`.
|
|
1132
|
-
//
|
|
1133
|
-
// the
|
|
1134
|
-
//
|
|
1770
|
+
// is persisted + threaded through here for `git worktree remove`.
|
|
1771
|
+
//
|
|
1772
|
+
// #8856: if the worktree dir was deleted out from under us (the agent
|
|
1773
|
+
// removed its own cwd, or `chroxy worktree gc`), it is recreated below
|
|
1774
|
+
// from worktreeRepoDir. Failing instead parked the session as a failed
|
|
1775
|
+
// restore whose Retry could never succeed, because nothing put the
|
|
1776
|
+
// directory back.
|
|
1135
1777
|
//
|
|
1136
1778
|
// SECURITY (#5310 review): restoreWorktreePath is read from the on-disk
|
|
1137
1779
|
// state file and later becomes a recursive-deletion target in
|
|
@@ -1142,39 +1784,32 @@ export class SessionManager extends EventEmitter {
|
|
|
1142
1784
|
// restored path that doesn't resolve to exactly that is rejected: we
|
|
1143
1785
|
// safe-degrade to a non-worktree session (worktreePath stays null ⇒ no
|
|
1144
1786
|
// deletion target) and log loudly, rather than rebind an unsafe path.
|
|
1145
|
-
const expectedWorktreeDir = resolve(join(this._worktreeBase ||
|
|
1787
|
+
const expectedWorktreeDir = resolve(join(this._worktreeBase || defaultWorktreeBase(), sessionId))
|
|
1146
1788
|
if (resolve(restoreWorktreePath) === expectedWorktreeDir) {
|
|
1147
|
-
|
|
1789
|
+
if (missingRestoreWorktree) {
|
|
1790
|
+
this._recreateMissingWorktree(expectedWorktreeDir, restoreWorktreeRepoDir, sessionId)
|
|
1791
|
+
}
|
|
1792
|
+
// Bind the canonical path, not the persisted spelling: they are equal
|
|
1793
|
+
// only lexically, and a spelling like `<base>/gone/../<id>` resolves
|
|
1794
|
+
// here but fails on disk, so the provider would get a dead cwd.
|
|
1795
|
+
worktreePath = expectedWorktreeDir
|
|
1148
1796
|
worktreeRepoDir = restoreWorktreeRepoDir || null
|
|
1149
|
-
resolvedCwd =
|
|
1797
|
+
resolvedCwd = expectedWorktreeDir
|
|
1150
1798
|
} else {
|
|
1799
|
+
if (missingRestoreWorktree) {
|
|
1800
|
+
// Never recreate at a path the #5310 guard rejects: fail exactly as
|
|
1801
|
+
// the existence check above did before #8856.
|
|
1802
|
+
throw new SessionDirectoryError(`Directory does not exist: ${baseCwd}`, baseCwd)
|
|
1803
|
+
}
|
|
1151
1804
|
log.warn(`Restored worktreePath "${restoreWorktreePath}" for session ${sessionId} does not match the expected per-session worktree dir "${expectedWorktreeDir}" — ignoring the rebind (treating as non-worktree) so a corrupted state file can't make destroySession() delete an arbitrary path`)
|
|
1152
1805
|
}
|
|
1153
1806
|
} else if (worktree) {
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
} catch {
|
|
1161
|
-
throw new WorktreeError(`Not a git repository: ${baseCwd}`)
|
|
1162
|
-
}
|
|
1163
|
-
|
|
1164
|
-
// Create worktree directory
|
|
1165
|
-
const worktreeBase = this._worktreeBase || DEFAULT_WORKTREE_BASE
|
|
1166
|
-
const worktreeDir = join(worktreeBase, sessionId)
|
|
1167
|
-
mkdirSync(worktreeBase, { recursive: true })
|
|
1168
|
-
|
|
1169
|
-
try {
|
|
1170
|
-
execFileSync(GIT, ['-C', baseCwd, 'worktree', 'add', '--detach', worktreeDir, 'HEAD'], {
|
|
1171
|
-
stdio: ['pipe', 'pipe', 'pipe'],
|
|
1172
|
-
encoding: 'utf-8',
|
|
1173
|
-
})
|
|
1174
|
-
} catch (err) {
|
|
1175
|
-
const msg = err?.stderr?.trim() || err?.message || String(err)
|
|
1176
|
-
throw new WorktreeError(`Failed to create worktree: ${msg}`)
|
|
1177
|
-
}
|
|
1807
|
+
const worktreeDir = join(this._worktreeBase || defaultWorktreeBase(), sessionId)
|
|
1808
|
+
// The session's cwd becomes the worktree: judge it before anything is created.
|
|
1809
|
+
// (A restored worktree, rebound or recreated below, is at the path checked above.)
|
|
1810
|
+
const worktreeDenial = claudeConfigDirCwdDenial(worktreeDir)
|
|
1811
|
+
if (worktreeDenial) throw new SessionDirectoryError(worktreeDenial, worktreeDir)
|
|
1812
|
+
this._addDetachedWorktree(baseCwd, worktreeDir)
|
|
1178
1813
|
|
|
1179
1814
|
resolvedCwd = worktreeDir
|
|
1180
1815
|
worktreePath = worktreeDir
|
|
@@ -1250,6 +1885,14 @@ export class SessionManager extends EventEmitter {
|
|
|
1250
1885
|
worktreeRepoDir,
|
|
1251
1886
|
presetDescriptor,
|
|
1252
1887
|
effectiveSessionPreamble,
|
|
1888
|
+
connectionResolution,
|
|
1889
|
+
// #8030: renamed from connectionVerifiedBinary — this is the create-time
|
|
1890
|
+
// preflight-verified path for ANY provider (connection-resolved or not),
|
|
1891
|
+
// not only the agent-connection case the old name implied. Still
|
|
1892
|
+
// forwarded to providerOpts.connectionVerifiedBinary unchanged (below)
|
|
1893
|
+
// for the agent-connection consumers that already read that key; ALSO
|
|
1894
|
+
// now drives providerOpts.spawnPreflight for every provider (see below).
|
|
1895
|
+
verifiedBinary: providerPreflight?.binaryPath || null,
|
|
1253
1896
|
}
|
|
1254
1897
|
}
|
|
1255
1898
|
|
|
@@ -1278,7 +1921,7 @@ export class SessionManager extends EventEmitter {
|
|
|
1278
1921
|
* skills text). Trimmed + capped to SESSION_PREAMBLE_MAX_LENGTH by
|
|
1279
1922
|
* BaseSession. Persisted across reconnects.
|
|
1280
1923
|
* @param {string} [options.promptEvaluatorSkipPattern] - Per-session regex source
|
|
1281
|
-
* string consulted by `
|
|
1924
|
+
* string consulted by `shouldSkipEvaluatorAsync` BEFORE the server-wide
|
|
1282
1925
|
* `config.promptEvaluatorSkipPattern` (the global knob landed in #3187;
|
|
1283
1926
|
* this per-session override lands here in #3639). Pairs with the
|
|
1284
1927
|
* per-session promptEvaluator toggle so different sessions can use
|
|
@@ -1298,6 +1941,11 @@ export class SessionManager extends EventEmitter {
|
|
|
1298
1941
|
* `msg-{N+1}` instead of restarting from `msg-1` and colliding with messages
|
|
1299
1942
|
* the dashboard cached from the previous process (#3700). Non-finite or
|
|
1300
1943
|
* negative values ignored.
|
|
1944
|
+
* @param {boolean} [options.conversationPersisted] - Internal/restore-only (#8418):
|
|
1945
|
+
* the previous run's "claude has saved a conversation for `resumeSessionId`" bit,
|
|
1946
|
+
* handed to a provider that tracks one (claude-tui) so a restart can tell a session
|
|
1947
|
+
* that never completed a turn from one whose transcript has since been removed.
|
|
1948
|
+
* Only `true` is forwarded; providers that do not read it ignore it.
|
|
1301
1949
|
* @param {boolean} [options.skipPersist] - Internal: skip the sync persist flush. Used by
|
|
1302
1950
|
* `restoreState()`, which must seed history and budget after createSession before the
|
|
1303
1951
|
* state file is rewritten; otherwise each flush would overwrite the on-disk file with
|
|
@@ -1313,6 +1961,10 @@ export class SessionManager extends EventEmitter {
|
|
|
1313
1961
|
* so callers can safely pass any value. Primary use: `restoreState` reusing the
|
|
1314
1962
|
* persisted id so dashboard's localStorage-cached `activeSessionId` still resolves
|
|
1315
1963
|
* after a daemon restart (#4983).
|
|
1964
|
+
* @param {'explicit'|'replay'} [options.modelSource] - #7855: `replay` marks `model` as
|
|
1965
|
+
* read back from saved state (an archive, a scheduled task) rather than asked for now.
|
|
1966
|
+
* An unusable replayed id falls back to the provider default instead of failing create.
|
|
1967
|
+
* Omitted means `explicit`.
|
|
1316
1968
|
* @param {boolean} [options.isRestore] - Internal (#5316): marks a session created by
|
|
1317
1969
|
* `restoreState()`. When a provider's start() rejects ASYNCHRONOUSLY, the rejection
|
|
1318
1970
|
* handler preserves the restored history + worktree (registers a failed-restore)
|
|
@@ -1326,7 +1978,7 @@ export class SessionManager extends EventEmitter {
|
|
|
1326
1978
|
* it (#6743).
|
|
1327
1979
|
* @returns {string} sessionId
|
|
1328
1980
|
*/
|
|
1329
|
-
createSession({ name, cwd, model, permissionMode, resumeSessionId, provider, worktree, restoreWorktreePath, restoreWorktreeRepoDir, sandbox, codexSandbox, containerId, containerUser, containerCliPath, promptEvaluator, promptEvaluatorSkipPattern, chroxyContextHint, sessionPreamble, stdinForwardingDisabled, disabledMcpServers, bootedModel, messageCounter, skipPermissions, agentCommId, metadata = null, skipPersist = false, preserveId, isRestore = false } = {}) {
|
|
1981
|
+
createSession({ name, cwd, model, permissionMode, resumeSessionId, nativeResume, conversationPersisted, provider, connectionId, restoredAgentConnection, worktree, restoreWorktreePath, restoreWorktreeRepoDir, sandbox, codexSandbox, environmentId, containerId, containerUser, containerCliPath, promptEvaluator, promptEvaluatorSkipPattern, chroxyContextHint, sessionPreamble, stdinForwardingDisabled, disabledMcpServers, bootedModel, messageCounter, skipPermissions, agentCommId, metadata = null, skipPersist = false, preserveId, isRestore = false, modelSource } = {}) {
|
|
1330
1982
|
// #6036 — front-half SRP extraction: preflight + isolation + provider/preset
|
|
1331
1983
|
// resolution (incl. the limit guard, cwd check, id/name, #2962 preflight,
|
|
1332
1984
|
// #5985 user-shell gate, #3403 model fallback, worktree create/restore, and
|
|
@@ -1341,12 +1993,16 @@ export class SessionManager extends EventEmitter {
|
|
|
1341
1993
|
model,
|
|
1342
1994
|
permissionMode,
|
|
1343
1995
|
provider,
|
|
1996
|
+
connectionId,
|
|
1997
|
+
restoredAgentConnection,
|
|
1344
1998
|
worktree,
|
|
1345
1999
|
restoreWorktreePath,
|
|
1346
2000
|
restoreWorktreeRepoDir,
|
|
1347
2001
|
sessionPreamble,
|
|
1348
2002
|
preserveId,
|
|
2003
|
+
resumeSessionId,
|
|
1349
2004
|
isRestore,
|
|
2005
|
+
modelSource,
|
|
1350
2006
|
})
|
|
1351
2007
|
const {
|
|
1352
2008
|
sessionId,
|
|
@@ -1360,8 +2016,16 @@ export class SessionManager extends EventEmitter {
|
|
|
1360
2016
|
worktreeRepoDir,
|
|
1361
2017
|
presetDescriptor,
|
|
1362
2018
|
effectiveSessionPreamble,
|
|
2019
|
+
connectionResolution,
|
|
2020
|
+
verifiedBinary,
|
|
1363
2021
|
} = plan
|
|
1364
2022
|
|
|
2023
|
+
if (nativeResume && (!isRestore || ProviderClass.nativeResumeDriver !== NATIVE_RESUME_DRIVER)) {
|
|
2024
|
+
throw nativeRestoreError('DRIVER_INCOMPATIBLE', 'saved native state cannot be routed into another provider or driver')
|
|
2025
|
+
}
|
|
2026
|
+
if (isRestore && resolvedProvider === 'codex' && ProviderClass.nativeResumeDriver !== NATIVE_RESUME_DRIVER && !resumeSessionId) {
|
|
2027
|
+
throw nativeRestoreError('LOCATOR_MISSING', 'this saved Codex state has no native resume identity; create a new session explicitly')
|
|
2028
|
+
}
|
|
1365
2029
|
const providerOpts = {
|
|
1366
2030
|
cwd: resolvedCwd,
|
|
1367
2031
|
model: resolvedModel,
|
|
@@ -1369,12 +2033,63 @@ export class SessionManager extends EventEmitter {
|
|
|
1369
2033
|
port: this._port,
|
|
1370
2034
|
apiToken: this._apiToken,
|
|
1371
2035
|
resumeSessionId: resumeSessionId || null,
|
|
2036
|
+
...(ProviderClass.nativeResumeDriver === NATIVE_RESUME_DRIVER ? {
|
|
2037
|
+
nativeResume: isRestore ? nativeResume || null : null,
|
|
2038
|
+
isRestore,
|
|
2039
|
+
nativeResumePersist: () => this._flushPersistOrWarn(sessionId),
|
|
2040
|
+
} : {}),
|
|
1372
2041
|
transforms: this._transforms,
|
|
1373
2042
|
// Provider id flows into BaseSession so the skills loader can apply
|
|
1374
2043
|
// the `providers:` filter (#3198) and pick a per-provider injection
|
|
1375
2044
|
// default (#3200). Same string SessionManager uses to pick the
|
|
1376
2045
|
// ProviderClass via getProvider() — the registry key.
|
|
1377
2046
|
provider: resolvedProvider,
|
|
2047
|
+
// #7835: production-created API BYOK sessions compile the authored
|
|
2048
|
+
// project chain. Direct unit constructors remain explicit via their
|
|
2049
|
+
// injectable loader seam and never touch a developer's real machine root.
|
|
2050
|
+
loadProjectInstructions: true,
|
|
2051
|
+
}
|
|
2052
|
+
if (connectionResolution) {
|
|
2053
|
+
providerOpts.connectionAuthRoute = connectionResolution.definition.authRoute
|
|
2054
|
+
if (connectionResolution.childEnv) providerOpts.connectionChildEnv = connectionResolution.childEnv
|
|
2055
|
+
// #8030: renamed from connectionVerifiedBinary on the plan object, but
|
|
2056
|
+
// still forwarded under the SAME providerOpts key — every existing
|
|
2057
|
+
// consumer of `opts.connectionVerifiedBinary` is unaffected.
|
|
2058
|
+
if (verifiedBinary) providerOpts.connectionVerifiedBinary = verifiedBinary
|
|
2059
|
+
if (connectionResolution.definition.authRoute === 'native' && verifiedBinary) {
|
|
2060
|
+
providerOpts.connectionRuntimePreflight = () => {
|
|
2061
|
+
const repeated = runProviderPreflight(ProviderClass, {
|
|
2062
|
+
provenance: this._binaryProvenanceOptions(),
|
|
2063
|
+
})
|
|
2064
|
+
if (repeated.binaryPath !== verifiedBinary) {
|
|
2065
|
+
const err = new Error('The verified provider binary path changed before the explicit native route could start.')
|
|
2066
|
+
err.code = 'NATIVE_RUNTIME_UNVERIFIED'
|
|
2067
|
+
throw err
|
|
2068
|
+
}
|
|
2069
|
+
return repeated.binaryPath
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
// #8030: per-spawn re-verification, wired for EVERY provider (not just an
|
|
2074
|
+
// agent-connection session) whenever create-time preflight ran and gave us
|
|
2075
|
+
// a path — `verifiedBinary` is null when preflight was skipped
|
|
2076
|
+
// (this._skipPreflight, test-only) or the provider is containerised
|
|
2077
|
+
// (runProviderPreflight returns binaryPath:null for those; the binary
|
|
2078
|
+
// lives inside the container, unreachable to a host-side re-verify).
|
|
2079
|
+
// #8035: `spawnPreflight` is a BaseSession opt now (stored as
|
|
2080
|
+
// `this._spawnPreflight`, forwarded to every picker subclass via
|
|
2081
|
+
// `BASE_SESSION_OPT_KEYS` — see base-session.js), so SdkSession AND
|
|
2082
|
+
// JsonlSubprocessSession's Gemini / Codex-exec subclasses both consume it
|
|
2083
|
+
// per spawn (each execs a NEW process every turn, so "verified once at
|
|
2084
|
+
// create" doesn't cover turn two onward). #8038: claude-cli, claude-tui
|
|
2085
|
+
// and codex app-server's default route also call `_gatedSpawnBinary` now
|
|
2086
|
+
// — every (re)spawn on every route (first start, model switch,
|
|
2087
|
+
// permission-mode change, post-Stop revival, crash respawn, PTY respawn,
|
|
2088
|
+
// app-server's one-shot `start()`) re-verifies against this exact pinned
|
|
2089
|
+
// path. A refusal on a respawn does not burn that provider's respawn
|
|
2090
|
+
// budget — see `_refuseSpawn` on BaseSession.
|
|
2091
|
+
if (verifiedBinary) {
|
|
2092
|
+
providerOpts.spawnPreflight = () => this._verifyPinnedSpawn(ProviderClass, verifiedBinary)
|
|
1378
2093
|
}
|
|
1379
2094
|
// #6638: per-session codex sandbox mode (read-only / workspace-write /
|
|
1380
2095
|
// danger-full-access). Codex-specific opt read directly by CodexAppServerSession;
|
|
@@ -1456,6 +2171,12 @@ export class SessionManager extends EventEmitter {
|
|
|
1456
2171
|
if (stdinForwardingDisabled === true) {
|
|
1457
2172
|
providerOpts.stdinForwardingDisabled = true
|
|
1458
2173
|
}
|
|
2174
|
+
// #8418: the restored "claude saved a conversation for this id" bit. Only
|
|
2175
|
+
// `true` is forwarded: absent / false / malformed is the pre-#8418 meaning
|
|
2176
|
+
// ("nothing known"), which is what a provider's own default already is.
|
|
2177
|
+
if (conversationPersisted === true) {
|
|
2178
|
+
providerOpts.conversationPersisted = true
|
|
2179
|
+
}
|
|
1459
2180
|
// #6824: per-session parked (disabled) MCP server names. Byok-local opt —
|
|
1460
2181
|
// forwarded only when it's a non-empty array of strings so non-BYOK
|
|
1461
2182
|
// providers (which ignore the unknown key via the opt picker) never see a
|
|
@@ -1488,6 +2209,24 @@ export class SessionManager extends EventEmitter {
|
|
|
1488
2209
|
// forwarded via BASE_SESSION_OPT_KEYS.
|
|
1489
2210
|
providerOpts.permissionRuleStore = this.permissionRuleStore
|
|
1490
2211
|
const session = new ProviderClass(providerOpts)
|
|
2212
|
+
const agentConnection = connectionResolution
|
|
2213
|
+
? {
|
|
2214
|
+
...connectionResolution.descriptor,
|
|
2215
|
+
model: {
|
|
2216
|
+
requested: typeof model === 'string' && model.length > 0 ? model : null,
|
|
2217
|
+
resolved: null,
|
|
2218
|
+
},
|
|
2219
|
+
}
|
|
2220
|
+
: createLegacyAgentConnection({
|
|
2221
|
+
runtime: resolvedProvider,
|
|
2222
|
+
ProviderClass,
|
|
2223
|
+
model: resolvedModel,
|
|
2224
|
+
authInfo: getProviderAuthInfo(resolvedProvider, ProviderClass),
|
|
2225
|
+
})
|
|
2226
|
+
// This snapshot is deliberately descriptor-only. Secret material used to
|
|
2227
|
+
// construct a child environment stays in providerOpts and is never attached
|
|
2228
|
+
// to the session entry, persistence payload, events, or logs.
|
|
2229
|
+
session.agentConnection = agentConnection
|
|
1491
2230
|
// Pre-seed `bootedModel` from a restored snapshot so the dashboard can
|
|
1492
2231
|
// surface the session's actual model immediately on reconnect, without
|
|
1493
2232
|
// waiting for the next CLI init event to repopulate it (#3700b). Only
|
|
@@ -1516,6 +2255,7 @@ export class SessionManager extends EventEmitter {
|
|
|
1516
2255
|
name: sessionName,
|
|
1517
2256
|
cwd: resolvedCwd,
|
|
1518
2257
|
provider: resolvedProvider,
|
|
2258
|
+
agentConnection,
|
|
1519
2259
|
createdAt: Date.now(),
|
|
1520
2260
|
worktreePath,
|
|
1521
2261
|
// Original repo dir needed for `git worktree remove` during cleanup.
|
|
@@ -1547,9 +2287,37 @@ export class SessionManager extends EventEmitter {
|
|
|
1547
2287
|
// orchestrationRole } for the session-list badges). In-memory only in v1 —
|
|
1548
2288
|
// not persisted; a restart-reconcile re-establishes it (E-3 part 3).
|
|
1549
2289
|
metadata: metadata || null,
|
|
2290
|
+
// #7552: the container environment this session was created INTO, or null.
|
|
2291
|
+
// The untag side is `_cleanupSessionMaps`, the single funnel every session
|
|
2292
|
+
// takes out of `_sessions`.
|
|
2293
|
+
//
|
|
2294
|
+
// #7561: this and the three container fields below are now PERSISTED
|
|
2295
|
+
// (`_serializeSessionEntry`) and re-resolved on restore
|
|
2296
|
+
// (`_resolveRestoredContainerBinding`). They were in-memory only, which
|
|
2297
|
+
// meant a restored `docker-sdk` session came back with no containerId —
|
|
2298
|
+
// and `DockerSdkSession` reads that absence as "I own the container", so
|
|
2299
|
+
// `start()` launched a BRAND NEW default `node:22-slim` container instead
|
|
2300
|
+
// of re-entering the operator's configured one. Not a host escape, but an
|
|
2301
|
+
// escape from the containment the operator configured (image, devcontainer
|
|
2302
|
+
// mounts, sanitised env, resource limits), which is why the binding has to
|
|
2303
|
+
// round-trip.
|
|
2304
|
+
environmentId: (typeof environmentId === 'string' && environmentId.length > 0) ? environmentId : null,
|
|
2305
|
+
// The resolved container this session talks to. Recorded as PASSED (not
|
|
2306
|
+
// read back off the provider, whose `_containerId` is mutated at runtime
|
|
2307
|
+
// when it owns the container) so the persisted shape says what the session
|
|
2308
|
+
// was created against.
|
|
2309
|
+
containerId: (typeof containerId === 'string' && containerId.length > 0) ? containerId : null,
|
|
2310
|
+
containerUser: (typeof containerUser === 'string' && containerUser.length > 0) ? containerUser : null,
|
|
2311
|
+
containerCliPath: (typeof containerCliPath === 'string' && containerCliPath.length > 0) ? containerCliPath : null,
|
|
1550
2312
|
}
|
|
1551
2313
|
|
|
1552
2314
|
this._sessions.set(sessionId, entry)
|
|
2315
|
+
// #7552: TAG the environment as soon as the entry is live — paired with the
|
|
2316
|
+
// untag in `_cleanupSessionMaps`, the single funnel every session takes out
|
|
2317
|
+
// of `_sessions`. Attaching here rather than after `start()` keeps the pair
|
|
2318
|
+
// symmetric: a start() failure (sync throw or async rejection) runs that
|
|
2319
|
+
// same cleanup, so the tag is removed on the failure paths too.
|
|
2320
|
+
if (entry.environmentId) this._environmentManager?.addSession(entry.environmentId, sessionId)
|
|
1553
2321
|
// Mailbox (#5914 follow-up): auto-register the session's AGENT_COMM_ID so the
|
|
1554
2322
|
// live-interrupt route resolves agent -> session WITHOUT a separate POST
|
|
1555
2323
|
// /api/mailbox/register. registerAgentCommId is the authoritative validator
|
|
@@ -1566,8 +2334,85 @@ export class SessionManager extends EventEmitter {
|
|
|
1566
2334
|
// claude-tui's start() spawns its PTY asynchronously and (as of #5316)
|
|
1567
2335
|
// REJECTS when the PTY fails to come up, so this is the primary failure
|
|
1568
2336
|
// signal for that provider.
|
|
1569
|
-
if (result && typeof result.
|
|
1570
|
-
|
|
2337
|
+
if (result && typeof result.then === 'function') {
|
|
2338
|
+
// #8861: keep a SETTLE handle on the entry. `_handleAsyncStartFailure`
|
|
2339
|
+
// still runs on every rejection exactly as the bare `.catch` did (fresh
|
|
2340
|
+
// AND restored sessions); the handle only lets a caller that needs to
|
|
2341
|
+
// know how the start ended (retryFailedRestore) await it. It never
|
|
2342
|
+
// rejects, so it adds no unhandled rejection of its own — and a throw
|
|
2343
|
+
// inside `_handleAsyncStartFailure` is logged rather than escaping, the
|
|
2344
|
+
// same place it would otherwise have surfaced as an unhandled one. A
|
|
2345
|
+
// sync start() (sdk-session) leaves no handle.
|
|
2346
|
+
//
|
|
2347
|
+
// #8872: until the start settles the session is in `_sessions` but not
|
|
2348
|
+
// yet usable — and, for a restore, may still be re-parked. `listSessions`
|
|
2349
|
+
// reports it as `starting` so no client offers it as openable, and the
|
|
2350
|
+
// success branch announces the change so every client's list refreshes.
|
|
2351
|
+
// The rejection branch needs no announcement of its own: the restore
|
|
2352
|
+
// path emits `session_restore_failed` and the fresh path emits
|
|
2353
|
+
// `session_create_failed`, and the ws-forwarding listener for each
|
|
2354
|
+
// queues the refreshed `session_list` (queueStartOutcomeSessionList).
|
|
2355
|
+
// `session_destroyed` itself announces nothing.
|
|
2356
|
+
//
|
|
2357
|
+
// #8876: the wait is bounded. A start() that never settles (Codex
|
|
2358
|
+
// app-server has no startup timeout of its own) is rejected with
|
|
2359
|
+
// START_TIMEOUT after `providerStartDeadlineMs`, so it runs the same
|
|
2360
|
+
// `_handleAsyncStartFailure` path as any other rejection. A late
|
|
2361
|
+
// settlement of the underlying start is ignored, so it can neither
|
|
2362
|
+
// double-announce nor surface as an unhandled rejection.
|
|
2363
|
+
entry._starting = true
|
|
2364
|
+
const deadlineMs = providerStartDeadlineMs(session)
|
|
2365
|
+
const onOk = () => {
|
|
2366
|
+
entry._starting = false
|
|
2367
|
+
// Only for the entry that is still live: a session destroyed (or
|
|
2368
|
+
// re-created under the same id) before its start resolved has
|
|
2369
|
+
// nothing to announce.
|
|
2370
|
+
if (this._sessions.get(sessionId) === entry && !entry._destroying) {
|
|
2371
|
+
this.emit('session_start_settled', { sessionId })
|
|
2372
|
+
if (!isRestore) this._refreshLiveModelsAfterStart(sessionId, session, entry)
|
|
2373
|
+
}
|
|
2374
|
+
return { ok: true }
|
|
2375
|
+
}
|
|
2376
|
+
const onErr = (err) => {
|
|
2377
|
+
entry._starting = false
|
|
2378
|
+
// Only for the entry that is still live: with a deadline, a timer
|
|
2379
|
+
// from a session that was destroyed and re-created under the same
|
|
2380
|
+
// id (a failed-restore retry reuses the id) would otherwise tear
|
|
2381
|
+
// down the NEW entry.
|
|
2382
|
+
if (this._sessions.get(sessionId) === entry) {
|
|
2383
|
+
try {
|
|
2384
|
+
this._handleAsyncStartFailure(sessionId, err)
|
|
2385
|
+
} catch (handlerErr) {
|
|
2386
|
+
log.error(`Async start() failure handler threw for session ${sessionId}: ${handlerErr?.stack || handlerErr}`)
|
|
2387
|
+
}
|
|
2388
|
+
}
|
|
2389
|
+
return { ok: false, error: err }
|
|
2390
|
+
}
|
|
2391
|
+
// The handlers run DIRECTLY off the provider's promise (one microtask
|
|
2392
|
+
// hop, as before the deadline existed). `done` makes the first of
|
|
2393
|
+
// {settlement, deadline} the only one handled. Usually a late one would
|
|
2394
|
+
// find its entry gone anyway, but not when the failure path threw
|
|
2395
|
+
// before the entry left `_sessions` (a throwing listener): without the
|
|
2396
|
+
// flag a late resolve would then announce a timed-out session as
|
|
2397
|
+
// settled.
|
|
2398
|
+
entry._startSettled = new Promise((resolve) => {
|
|
2399
|
+
let done = false
|
|
2400
|
+
let timer = null
|
|
2401
|
+
const finish = (handler) => (arg) => {
|
|
2402
|
+
if (done) return
|
|
2403
|
+
done = true
|
|
2404
|
+
if (timer) clearTimeout(timer)
|
|
2405
|
+
resolve(handler(arg))
|
|
2406
|
+
}
|
|
2407
|
+
if (deadlineMs !== null) {
|
|
2408
|
+
timer = setTimeout(() => finish(onErr)(Object.assign(
|
|
2409
|
+
new Error(`Provider did not finish starting within ${Math.round(deadlineMs / 1000)}s`),
|
|
2410
|
+
{ code: 'START_TIMEOUT' },
|
|
2411
|
+
)), deadlineMs)
|
|
2412
|
+
timer.unref?.()
|
|
2413
|
+
}
|
|
2414
|
+
result.then(finish(onOk), finish(onErr))
|
|
2415
|
+
})
|
|
1571
2416
|
}
|
|
1572
2417
|
} catch (err) {
|
|
1573
2418
|
// Clean up phantom session on start() failure (Guardian FM-03)
|
|
@@ -1584,8 +2429,8 @@ export class SessionManager extends EventEmitter {
|
|
|
1584
2429
|
// on a restore-rebind, worktreePath points at a PRE-EXISTING worktree
|
|
1585
2430
|
// (with possibly uncommitted work) that we must NOT delete just because
|
|
1586
2431
|
// the provider's start() failed — destroying it would lose the user's
|
|
1587
|
-
// work
|
|
1588
|
-
//
|
|
2432
|
+
// work, and the retry #2954 preserves could only recreate a fresh
|
|
2433
|
+
// checkout of the repo's HEAD in its place (#8856). Only the fresh-create
|
|
1589
2434
|
// branch should roll back its own creation. Use worktreeRepoDir (the
|
|
1590
2435
|
// original repo) for the remove, consistent with the destroy paths.
|
|
1591
2436
|
if (worktreePath && !restoreWorktreePath) {
|
|
@@ -1674,7 +2519,9 @@ export class SessionManager extends EventEmitter {
|
|
|
1674
2519
|
// Full teardown (removes the freshly-created worktree). The emit above
|
|
1675
2520
|
// ran synchronously, so subscribers received the error while the session
|
|
1676
2521
|
// was still mapped, before this broadcasts `session_destroyed`.
|
|
1677
|
-
|
|
2522
|
+
// Not archived: a session whose start() never succeeded has no history
|
|
2523
|
+
// worth keeping (the "no history worth preserving" note above).
|
|
2524
|
+
this.destroySession(sessionId, { archive: false })
|
|
1678
2525
|
return
|
|
1679
2526
|
}
|
|
1680
2527
|
|
|
@@ -1718,6 +2565,222 @@ export class SessionManager extends EventEmitter {
|
|
|
1718
2565
|
this._flushPersist()
|
|
1719
2566
|
}
|
|
1720
2567
|
|
|
2568
|
+
/**
|
|
2569
|
+
* Create a detached git worktree of `repoDir` at `worktreeDir`.
|
|
2570
|
+
* Shared by worktree session creation and #8856's restore-time recreation.
|
|
2571
|
+
* @param {string} repoDir - The git repository to branch the worktree from
|
|
2572
|
+
* @param {string} worktreeDir - Absolute path of the new worktree
|
|
2573
|
+
* @param {{ force?: boolean, commit?: string, noHooks?: boolean }} [opts]
|
|
2574
|
+
* `force` lets git reuse a path that is still registered as a worktree of
|
|
2575
|
+
* `repoDir` but missing on disk (a dir deleted without `git worktree
|
|
2576
|
+
* remove`); without it git refuses the add. `commit` is what to check out
|
|
2577
|
+
* (default `HEAD`). `noHooks` stops git running the repository's hooks.
|
|
2578
|
+
* @throws {WorktreeError} when repoDir is not a git repository or the add fails
|
|
2579
|
+
*/
|
|
2580
|
+
_addDetachedWorktree(repoDir, worktreeDir, { force = false, commit = 'HEAD', noHooks = false } = {}) {
|
|
2581
|
+
assertSafeArgvValue(commit, 'worktree commit')
|
|
2582
|
+
if (!isGitRepoSync(repoDir)) {
|
|
2583
|
+
throw new WorktreeError(`Not a git repository: ${repoDir}`)
|
|
2584
|
+
}
|
|
2585
|
+
|
|
2586
|
+
mkdirSync(dirname(worktreeDir), { recursive: true })
|
|
2587
|
+
|
|
2588
|
+
const addArgs = []
|
|
2589
|
+
if (noHooks) addArgs.push('-c', 'core.hooksPath=/dev/null')
|
|
2590
|
+
addArgs.push('-C', repoDir, 'worktree', 'add')
|
|
2591
|
+
if (force) addArgs.push('--force')
|
|
2592
|
+
addArgs.push('--detach', worktreeDir, commit)
|
|
2593
|
+
try {
|
|
2594
|
+
execFileSync(GIT, addArgs, {
|
|
2595
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
2596
|
+
encoding: 'utf-8',
|
|
2597
|
+
})
|
|
2598
|
+
} catch (err) {
|
|
2599
|
+
const msg = err?.stderr?.trim() || err?.message || String(err)
|
|
2600
|
+
throw new WorktreeError(`Failed to create worktree: ${msg}`)
|
|
2601
|
+
}
|
|
2602
|
+
}
|
|
2603
|
+
|
|
2604
|
+
/**
|
|
2605
|
+
* #8856: recreate a restored session's chroxy-managed worktree that was
|
|
2606
|
+
* deleted while the daemon was down or under a live session (typically by
|
|
2607
|
+
* the agent inside it removing its own cwd). The caller has already checked
|
|
2608
|
+
* that `worktreeDir` is exactly this session's `<worktreeBase>/<id>` (#5310),
|
|
2609
|
+
* so this never creates a checkout anywhere else.
|
|
2610
|
+
*
|
|
2611
|
+
* What is checked out depends on how the worktree went, and nothing that
|
|
2612
|
+
* still references the session's commits is replaced before they are pinned:
|
|
2613
|
+
* - Removed with `git worktree remove`: no registration is left, so a plain
|
|
2614
|
+
* (non-force) add succeeds with a fresh detached checkout of the repo's
|
|
2615
|
+
* HEAD. Commits made only on the old detached HEAD were already
|
|
2616
|
+
* unreferenced by that removal. A plain add cannot replace anything.
|
|
2617
|
+
* - Deleted without git (`rm -rf`): git still has it registered, with the
|
|
2618
|
+
* HEAD it last had, so the plain add fails. That HEAD is read back, pinned
|
|
2619
|
+
* under `refs/chroxy/worktree-recovery/<id>`, and only then is the stale
|
|
2620
|
+
* registration replaced (`--force`) by a checkout of that commit. If the
|
|
2621
|
+
* HEAD cannot be read with certainty the restore fails and nothing is
|
|
2622
|
+
* replaced. If the forced add fails, the pin stays and the next attempt
|
|
2623
|
+
* (Retry) checks it out; it is dropped once a checkout references it.
|
|
2624
|
+
* A pin is deliberately never removed anywhere else (not on destroy or
|
|
2625
|
+
* dismiss): keeping one commit reachable is the point of it.
|
|
2626
|
+
* Either way uncommitted work from the deleted worktree is gone; that is
|
|
2627
|
+
* logged loudly. Without the recreation the session could only ever be
|
|
2628
|
+
* parked as a failed restore whose Retry runs this same path and fails again.
|
|
2629
|
+
*
|
|
2630
|
+
* `repoDir` comes from the state file, so it is held to an absolute path and
|
|
2631
|
+
* the repository's hooks are not run. Writing that file already takes the
|
|
2632
|
+
* daemon user's own access, and the restored `cwd` it carries is where the
|
|
2633
|
+
* agent then runs, so this adds no authority beyond that. Disabling hooks
|
|
2634
|
+
* is the cheap part of the containment, not all of it: commands the
|
|
2635
|
+
* repository's own config defines (checkout filters, `core.fsmonitor`)
|
|
2636
|
+
* still run, as they do for any git operation in that repository.
|
|
2637
|
+
*
|
|
2638
|
+
* @param {string} worktreeDir - The session's expected worktree dir (missing)
|
|
2639
|
+
* @param {string|undefined} repoDir - The persisted worktreeRepoDir
|
|
2640
|
+
* @param {string} sessionId - Used for log messages only
|
|
2641
|
+
* @throws {SessionDirectoryError} when the repo dir is unknown, relative,
|
|
2642
|
+
* missing or not a git repository, or the worktree cannot be recreated
|
|
2643
|
+
* without risking its commits — the restore then fails and is parked
|
|
2644
|
+
*/
|
|
2645
|
+
_recreateMissingWorktree(worktreeDir, repoDir, sessionId) {
|
|
2646
|
+
const missing = (reason) => new SessionDirectoryError(
|
|
2647
|
+
`Directory does not exist: ${worktreeDir} (the session's worktree was deleted and cannot be recreated: ${reason})`,
|
|
2648
|
+
worktreeDir,
|
|
2649
|
+
)
|
|
2650
|
+
// Never let an absent or relative repoDir reach `git -C`, which would
|
|
2651
|
+
// resolve it against the daemon's own cwd. A missing or non-git repoDir
|
|
2652
|
+
// fails the rev-parse inside _addDetachedWorktree, whose error names it.
|
|
2653
|
+
if (typeof repoDir !== 'string' || repoDir.length === 0) {
|
|
2654
|
+
throw missing('no repository is recorded for it')
|
|
2655
|
+
}
|
|
2656
|
+
if (!isAbsolute(repoDir)) {
|
|
2657
|
+
throw missing(`its recorded repository ${repoDir} is not an absolute path`)
|
|
2658
|
+
}
|
|
2659
|
+
const recoveryRef = `refs/chroxy/worktree-recovery/${basename(worktreeDir)}`
|
|
2660
|
+
assertSafeArgvValue(recoveryRef, 'recovery ref')
|
|
2661
|
+
let commit = this._readGitCommit(repoDir, recoveryRef)
|
|
2662
|
+
if (commit) {
|
|
2663
|
+
// A pin left by an earlier attempt must not replace a registration that
|
|
2664
|
+
// has since moved on (the session committed again and was deleted
|
|
2665
|
+
// again): forcing the old commit would drop the newer one's only ref.
|
|
2666
|
+
const registered = this._registeredWorktreeHead(repoDir, worktreeDir)
|
|
2667
|
+
if (registered === undefined) {
|
|
2668
|
+
throw missing(`git's worktree registrations could not be read, so the commit pinned at ${recoveryRef} cannot be checked against them`)
|
|
2669
|
+
}
|
|
2670
|
+
if (registered && registered !== commit) {
|
|
2671
|
+
throw missing(`git still registers it at ${registered}, which differs from the commit pinned at ${recoveryRef} (${commit}); resolve that by hand`)
|
|
2672
|
+
}
|
|
2673
|
+
} else {
|
|
2674
|
+
try {
|
|
2675
|
+
this._addDetachedWorktree(repoDir, worktreeDir, { noHooks: true })
|
|
2676
|
+
log.warn(`Recreated the deleted worktree for session ${sessionId} at ${worktreeDir} as a fresh detached checkout of ${repoDir} HEAD; uncommitted work from the deleted worktree is not recoverable (#8856)`)
|
|
2677
|
+
return
|
|
2678
|
+
} catch (plainErr) {
|
|
2679
|
+
commit = this._registeredWorktreeHead(repoDir, worktreeDir)
|
|
2680
|
+
if (!commit) throw missing(plainErr?.message || String(plainErr))
|
|
2681
|
+
}
|
|
2682
|
+
assertSafeArgvValue(commit, 'worktree commit')
|
|
2683
|
+
const pinArgs = ['-c', 'core.hooksPath=/dev/null', '-C', repoDir, 'update-ref', recoveryRef, commit]
|
|
2684
|
+
try {
|
|
2685
|
+
execFileSync(GIT, pinArgs, { stdio: ['pipe', 'pipe', 'pipe'], encoding: 'utf-8' })
|
|
2686
|
+
} catch (err) {
|
|
2687
|
+
throw missing(`could not pin its last HEAD ${commit}: ${err?.stderr?.trim() || err?.message || err}`)
|
|
2688
|
+
}
|
|
2689
|
+
}
|
|
2690
|
+
try {
|
|
2691
|
+
this._addDetachedWorktree(repoDir, worktreeDir, { force: true, commit, noHooks: true })
|
|
2692
|
+
} catch (err) {
|
|
2693
|
+
throw missing(`${err?.message || err}; its last HEAD stays pinned at ${recoveryRef}`)
|
|
2694
|
+
}
|
|
2695
|
+
const unpinArgs = ['-c', 'core.hooksPath=/dev/null', '-C', repoDir, 'update-ref', '-d', recoveryRef]
|
|
2696
|
+
try {
|
|
2697
|
+
execFileSync(GIT, unpinArgs, { stdio: ['pipe', 'pipe', 'pipe'], encoding: 'utf-8' })
|
|
2698
|
+
} catch (err) {
|
|
2699
|
+
log.warn(`Could not drop ${recoveryRef} in ${repoDir} after recreating the worktree: ${err?.stderr?.trim() || err?.message || err}`)
|
|
2700
|
+
}
|
|
2701
|
+
log.warn(`Recreated the deleted worktree for session ${sessionId} at ${worktreeDir} as a detached checkout of its last HEAD ${commit}; uncommitted work from the deleted worktree is not recoverable (#8856)`)
|
|
2702
|
+
}
|
|
2703
|
+
|
|
2704
|
+
/**
|
|
2705
|
+
* The commit `ref` names in `repoDir`, or null when it does not exist or
|
|
2706
|
+
* does not peel to a commit.
|
|
2707
|
+
* @param {string} repoDir
|
|
2708
|
+
* @param {string} ref
|
|
2709
|
+
* @returns {string|null}
|
|
2710
|
+
*/
|
|
2711
|
+
_readGitCommit(repoDir, ref) {
|
|
2712
|
+
const commitRef = `${ref}^{commit}`
|
|
2713
|
+
assertSafeArgvValue(commitRef, 'git ref')
|
|
2714
|
+
try {
|
|
2715
|
+
const out = execFileSync(GIT, ['-C', repoDir, 'rev-parse', '--verify', '--quiet', commitRef], {
|
|
2716
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
2717
|
+
encoding: 'utf-8',
|
|
2718
|
+
}).trim()
|
|
2719
|
+
return /^([0-9a-f]{40}|[0-9a-f]{64})$/.test(out) ? out : null
|
|
2720
|
+
} catch {
|
|
2721
|
+
return null
|
|
2722
|
+
}
|
|
2723
|
+
}
|
|
2724
|
+
|
|
2725
|
+
/**
|
|
2726
|
+
* The HEAD commit git still records for `worktreeDir` as a worktree of
|
|
2727
|
+
* `repoDir`; null when it is not registered; undefined when the
|
|
2728
|
+
* registrations could not be read at all. Neither falsy result may
|
|
2729
|
+
* authorise replacing anything. Read NUL-delimited so no path spelling can
|
|
2730
|
+
* split a record, and compared against the path canonicalised the way git
|
|
2731
|
+
* stores it: resolved through the nearest ancestor that still exists (the
|
|
2732
|
+
* whole worktree base may be gone, under a symlinked prefix such as macOS
|
|
2733
|
+
* /var), with both realpath flavours (the native one expands Windows 8.3
|
|
2734
|
+
* short names), and on Windows with git's forward slashes and any letter
|
|
2735
|
+
* case folded by resolve() and toLowerCase().
|
|
2736
|
+
* @param {string} repoDir
|
|
2737
|
+
* @param {string} worktreeDir
|
|
2738
|
+
* @returns {string|null|undefined}
|
|
2739
|
+
*/
|
|
2740
|
+
_registeredWorktreeHead(repoDir, worktreeDir) {
|
|
2741
|
+
const norm = (p) => (process.platform === 'win32' ? resolve(p).toLowerCase() : resolve(p))
|
|
2742
|
+
const candidates = new Set([norm(worktreeDir)])
|
|
2743
|
+
let dir = resolve(worktreeDir)
|
|
2744
|
+
const rest = []
|
|
2745
|
+
for (;;) {
|
|
2746
|
+
let found = false
|
|
2747
|
+
for (const real of [realpathSync, realpathSync.native]) {
|
|
2748
|
+
try {
|
|
2749
|
+
candidates.add(norm(join(real(dir), ...rest)))
|
|
2750
|
+
found = true
|
|
2751
|
+
} catch { /* try the parent */ }
|
|
2752
|
+
}
|
|
2753
|
+
if (found) break
|
|
2754
|
+
const parent = dirname(dir)
|
|
2755
|
+
if (parent === dir) break
|
|
2756
|
+
rest.unshift(basename(dir))
|
|
2757
|
+
dir = parent
|
|
2758
|
+
}
|
|
2759
|
+
let out
|
|
2760
|
+
try {
|
|
2761
|
+
out = execFileSync(GIT, ['-C', repoDir, 'worktree', 'list', '--porcelain', '-z'], {
|
|
2762
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
2763
|
+
encoding: 'utf-8',
|
|
2764
|
+
})
|
|
2765
|
+
} catch {
|
|
2766
|
+
return undefined
|
|
2767
|
+
}
|
|
2768
|
+
let path = null
|
|
2769
|
+
let head = null
|
|
2770
|
+
for (const field of `${out}\0`.split('\0')) {
|
|
2771
|
+
if (field === '') {
|
|
2772
|
+
if (path !== null && head !== null && candidates.has(norm(path))) return head
|
|
2773
|
+
path = null
|
|
2774
|
+
head = null
|
|
2775
|
+
} else if (field.startsWith('worktree ')) {
|
|
2776
|
+
path = field.slice('worktree '.length)
|
|
2777
|
+
} else if (/^HEAD ([0-9a-f]{40}|[0-9a-f]{64})$/.test(field)) {
|
|
2778
|
+
head = field.slice('HEAD '.length)
|
|
2779
|
+
}
|
|
2780
|
+
}
|
|
2781
|
+
return null
|
|
2782
|
+
}
|
|
2783
|
+
|
|
1721
2784
|
/**
|
|
1722
2785
|
* Remove a git worktree, logging errors non-fatally.
|
|
1723
2786
|
* @param {string} worktreePath - Absolute path to the worktree directory
|
|
@@ -1848,7 +2911,7 @@ export class SessionManager extends EventEmitter {
|
|
|
1848
2911
|
|
|
1849
2912
|
/**
|
|
1850
2913
|
* List all sessions with summary info.
|
|
1851
|
-
* @returns {Array<{ sessionId, name, cwd, model, permissionMode, isBusy, createdAt, lastActivityAt, stdinForwardingDisabled, stdinDroppedBytes, stdinDroppedCount }>}
|
|
2914
|
+
* @returns {Array<{ sessionId, name, cwd, model, permissionMode, isBusy, busyReason, backgroundShellCount, createdAt, lastActivityAt, stdinForwardingDisabled, stdinDroppedBytes, stdinDroppedCount }>}
|
|
1852
2915
|
*/
|
|
1853
2916
|
listSessions() {
|
|
1854
2917
|
const list = []
|
|
@@ -1862,24 +2925,30 @@ export class SessionManager extends EventEmitter {
|
|
|
1862
2925
|
// round-trip as `0` — matching the strict-boolean pattern used by
|
|
1863
2926
|
// `stdinForwardingDisabled` so reconnecting clients see a stable
|
|
1864
2927
|
// numeric shape regardless of provider.
|
|
2928
|
+
const decisionActivity = entry.session.getDecisionActivityState?.()
|
|
1865
2929
|
const totals = entry.session.stdinDroppedTotals
|
|
1866
2930
|
const stdinDroppedBytes = totals && Number.isFinite(totals.bytes) ? totals.bytes : 0
|
|
1867
2931
|
const stdinDroppedCount = totals && Number.isFinite(totals.count) ? totals.count : 0
|
|
1868
2932
|
const resolvedProvider = entry.provider || this._providerType
|
|
1869
|
-
//
|
|
2933
|
+
// Explicit connection routes are immutable session state. Historical
|
|
2934
|
+
// usage must never be relabelled by a later process.env/store change.
|
|
1870
2935
|
// Prefer the provider's live resolveAuth().billingClass (it already folds
|
|
1871
2936
|
// in the era gate + the claude-sdk/claude-cli explicit-key refinement);
|
|
1872
2937
|
// fall back to billingClassForProvider() for any provider whose
|
|
1873
2938
|
// resolveAuth predates the field. Wrapped defensively so a misbehaving
|
|
1874
2939
|
// custom provider's resolveAuth can't crash the snapshot.
|
|
1875
|
-
let billingClass
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
2940
|
+
let billingClass = entry.agentConnection?.entitlement?.route === 'api'
|
|
2941
|
+
? BILLING_CLASSES.API_KEY
|
|
2942
|
+
: entry.agentConnection?.entitlement?.route === 'subscription'
|
|
2943
|
+
? BILLING_CLASSES.SUBSCRIPTION
|
|
2944
|
+
: undefined
|
|
2945
|
+
if (!billingClass && entry.agentConnection?.provenance?.source === 'legacy') {
|
|
2946
|
+
try {
|
|
2947
|
+
billingClass = getProviderAuthInfo(resolvedProvider, ProviderClass)?.billingClass
|
|
2948
|
+
} catch {
|
|
2949
|
+
billingClass = undefined
|
|
2950
|
+
}
|
|
2951
|
+
if (!billingClass) billingClass = billingClassForProvider(resolvedProvider, Date.now())
|
|
1883
2952
|
}
|
|
1884
2953
|
list.push({
|
|
1885
2954
|
sessionId,
|
|
@@ -1895,7 +2964,19 @@ export class SessionManager extends EventEmitter {
|
|
|
1895
2964
|
// CLI default") across restarts.
|
|
1896
2965
|
model: entry.session.model || entry.session.bootedModel || null,
|
|
1897
2966
|
permissionMode: entry.session.permissionMode || 'approve',
|
|
2967
|
+
// #8872: the provider's async start() has not settled yet, so the
|
|
2968
|
+
// session is not openable — and a restore may still be re-parked. A
|
|
2969
|
+
// strict boolean so every row carries the same shape.
|
|
2970
|
+
starting: entry._starting === true,
|
|
1898
2971
|
isBusy: entry.session.isRunning,
|
|
2972
|
+
...(entry.declaredStatus ? { declaredStatus: { ...entry.declaredStatus } } : {}),
|
|
2973
|
+
...(decisionActivity ? { decisionActivity } : {}),
|
|
2974
|
+
// #8302: WHY it is busy, beside the unchanged boolean. `isBusy` merges
|
|
2975
|
+
// "mid-turn" with "idle but a background shell is still tracked"; a
|
|
2976
|
+
// client needs to tell them apart to say "waiting on N shells" instead
|
|
2977
|
+
// of "Working". `backgroundShellCount` is the tracker's size (quiesced
|
|
2978
|
+
// shells included), so it can be > 0 while pendingBackgroundShells is [].
|
|
2979
|
+
...busyStateOf(entry.session),
|
|
1899
2980
|
createdAt: entry.createdAt,
|
|
1900
2981
|
lastActivityAt: this._sessionLastActivityAt.get(sessionId) || entry.createdAt,
|
|
1901
2982
|
conversationId: entry.session.resumeSessionId || null,
|
|
@@ -1904,7 +2985,11 @@ export class SessionManager extends EventEmitter {
|
|
|
1904
2985
|
// cost row per class (api-key → "Cost (BYOK)", programmatic-credit →
|
|
1905
2986
|
// "Credit spend", subscription → "Included (subscription)").
|
|
1906
2987
|
billingClass,
|
|
1907
|
-
|
|
2988
|
+
agentConnection: entry.agentConnection,
|
|
2989
|
+
capabilities: {
|
|
2990
|
+
...(ProviderClass.capabilities || {}),
|
|
2991
|
+
...(ProviderClass.nativeResumeDriver === NATIVE_RESUME_DRIVER ? { resume: entry.session.providerRuntimeCapabilities?.nativeResume === true } : {}),
|
|
2992
|
+
},
|
|
1908
2993
|
worktree: entry.worktreePath != null,
|
|
1909
2994
|
repoCwd: entry.worktreeRepoDir || null,
|
|
1910
2995
|
isolation: entry.isolation || 'none',
|
|
@@ -2032,27 +3117,62 @@ export class SessionManager extends EventEmitter {
|
|
|
2032
3117
|
* Rename a session with mutation lock.
|
|
2033
3118
|
* @returns {Promise<boolean>}
|
|
2034
3119
|
*/
|
|
2035
|
-
async renameSessionLocked(sessionId, name) {
|
|
3120
|
+
async renameSessionLocked(sessionId, name, { isAuthorized } = {}) {
|
|
2036
3121
|
const release = await this._locks.acquire(sessionId)
|
|
2037
3122
|
try {
|
|
3123
|
+
assertAuthorized(isAuthorized)
|
|
2038
3124
|
return this.renameSession(sessionId, name)
|
|
2039
3125
|
} finally {
|
|
2040
3126
|
release()
|
|
2041
3127
|
}
|
|
2042
3128
|
}
|
|
2043
3129
|
|
|
3130
|
+
/**
|
|
3131
|
+
* Undo the "going away" mark of a destroy that did not finish (refused, or
|
|
3132
|
+
* threw before the entry left the map), so the session is visible again and
|
|
3133
|
+
* can be destroyed again. Stays marked while another destroy of it is queued.
|
|
3134
|
+
* @param {string} sessionId
|
|
3135
|
+
* @param {boolean} [counted] true when this destroy bumped `_pendingDestroys`
|
|
3136
|
+
*/
|
|
3137
|
+
_releaseDestroyMark(sessionId, counted = false) {
|
|
3138
|
+
const live = this._sessions.get(sessionId)
|
|
3139
|
+
if (!live) return
|
|
3140
|
+
if (counted) live._pendingDestroys = Math.max(0, (live._pendingDestroys || 1) - 1)
|
|
3141
|
+
if (!live._pendingDestroys) live._destroying = false
|
|
3142
|
+
}
|
|
3143
|
+
|
|
2044
3144
|
/**
|
|
2045
3145
|
* Destroy a session with mutation lock.
|
|
2046
3146
|
* Sets _destroying immediately (before lock acquisition) so concurrent
|
|
2047
3147
|
* getSession() calls see the session as unavailable right away.
|
|
3148
|
+
* @param {string} sessionId
|
|
3149
|
+
* @param {{ archiveReason?: string, archive?: boolean }} [opts] see destroySession
|
|
2048
3150
|
* @returns {Promise<boolean>}
|
|
2049
3151
|
*/
|
|
2050
|
-
async destroySessionLocked(sessionId) {
|
|
3152
|
+
async destroySessionLocked(sessionId, opts) {
|
|
3153
|
+
const { isAuthorized, ...destroyOpts } = opts || {}
|
|
2051
3154
|
const entry = this._sessions.get(sessionId)
|
|
2052
|
-
if (entry)
|
|
3155
|
+
if (entry) {
|
|
3156
|
+
entry._destroying = true
|
|
3157
|
+
entry._pendingDestroys = (entry._pendingDestroys || 0) + 1
|
|
3158
|
+
}
|
|
2053
3159
|
const release = await this._locks.acquire(sessionId)
|
|
2054
3160
|
try {
|
|
2055
|
-
|
|
3161
|
+
try {
|
|
3162
|
+
assertAuthorized(isAuthorized)
|
|
3163
|
+
} catch (err) {
|
|
3164
|
+
// Not destroyed after all: the session must not stay marked as going away -
|
|
3165
|
+
// unless another destroy of it is still queued behind this one.
|
|
3166
|
+
this._releaseDestroyMark(sessionId, true)
|
|
3167
|
+
throw err
|
|
3168
|
+
}
|
|
3169
|
+
try {
|
|
3170
|
+
return this.destroySession(sessionId, opts === undefined ? undefined : destroyOpts)
|
|
3171
|
+
} catch (err) {
|
|
3172
|
+
// #9034: a failed destroy must not strand the entry as going away.
|
|
3173
|
+
this._releaseDestroyMark(sessionId, true)
|
|
3174
|
+
throw err
|
|
3175
|
+
}
|
|
2056
3176
|
} finally {
|
|
2057
3177
|
release()
|
|
2058
3178
|
}
|
|
@@ -2121,9 +3241,35 @@ export class SessionManager extends EventEmitter {
|
|
|
2121
3241
|
// Default runner is the SDK one-shot shared with the #5547 summarizer; loaded
|
|
2122
3242
|
// lazily so the SDK stays out of SessionManager's static import graph. Tests
|
|
2123
3243
|
// inject `titleRunOneShot`, short-circuiting the import entirely.
|
|
2124
|
-
const
|
|
3244
|
+
const baseRunner = this._titleRunOneShot
|
|
2125
3245
|
|| (await import('./summarize-session.js')).defaultRunOneShot
|
|
2126
3246
|
|
|
3247
|
+
// #8030: the one-shot title spawn goes through the same binary gate a
|
|
3248
|
+
// fresh chat session would (verifyOneShotExecutable — re-resolve AND
|
|
3249
|
+
// re-verify, since a title call has no create-time session to pin a
|
|
3250
|
+
// path from). Wrapping here (rather than changing baseRunner's own
|
|
3251
|
+
// signature) keeps this seam identical for both the real
|
|
3252
|
+
// defaultRunOneShot AND an injected `titleRunOneShot` test double —
|
|
3253
|
+
// both now receive `resolveExecutable` in their args.
|
|
3254
|
+
//
|
|
3255
|
+
// generateSessionTitle wraps its runOneShot call in a bare try/catch and
|
|
3256
|
+
// fails open to the truncation label on ANY throw (by design — a failed
|
|
3257
|
+
// title call must never leave a session unnamed). That means a gate
|
|
3258
|
+
// refusal here is otherwise SILENT: log it before rethrowing, so a
|
|
3259
|
+
// block-mode mismatch on the title path leaves a trace instead of
|
|
3260
|
+
// vanishing into the fallback.
|
|
3261
|
+
const runOneShot = (args) => baseRunner({
|
|
3262
|
+
...args,
|
|
3263
|
+
resolveExecutable: () => {
|
|
3264
|
+
try {
|
|
3265
|
+
return this.verifyOneShotExecutable()
|
|
3266
|
+
} catch (err) {
|
|
3267
|
+
log.warn(`Semantic title spawn refused by the binary gate for ${sessionId}: ${getErrorMessage(err, 'unknown error')}`)
|
|
3268
|
+
throw err
|
|
3269
|
+
}
|
|
3270
|
+
},
|
|
3271
|
+
})
|
|
3272
|
+
|
|
2127
3273
|
// Hard-bound the fire-and-forget call: AbortSignal.timeout fires after
|
|
2128
3274
|
// _semanticTitleTimeoutMs, which threads to defaultRunOneShot →
|
|
2129
3275
|
// query({ abortController }) so a stalled provider stream is torn down (not
|
|
@@ -2176,14 +3322,28 @@ export class SessionManager extends EventEmitter {
|
|
|
2176
3322
|
* Destroy a specific session.
|
|
2177
3323
|
* Sets _destroying = true at the start so concurrent getSession() calls
|
|
2178
3324
|
* treat the session as unavailable while cleanup is in progress.
|
|
3325
|
+
*
|
|
3326
|
+
* Unless `archive` is false (or the session is a user shell, which has no
|
|
3327
|
+
* transcript), the session's persisted-shape snapshot is written to the
|
|
3328
|
+
* session archive FIRST, before the teardown below drops its history, so what
|
|
3329
|
+
* chroxy holds stays readable after the session is gone. Archiving never
|
|
3330
|
+
* throws and never blocks the teardown.
|
|
3331
|
+
*
|
|
3332
|
+
* @param {string} sessionId
|
|
3333
|
+
* @param {{ archiveReason?: string, archive?: boolean }} [opts]
|
|
3334
|
+
* `archiveReason` labels the archive row (default 'closed'); `archive: false`
|
|
3335
|
+
* skips archiving (a session that never started has nothing worth keeping).
|
|
2179
3336
|
* @returns {boolean}
|
|
2180
3337
|
*/
|
|
2181
|
-
destroySession(sessionId) {
|
|
3338
|
+
destroySession(sessionId, { archiveReason = 'closed', archive = true } = {}) {
|
|
2182
3339
|
const entry = this._sessions.get(sessionId)
|
|
2183
3340
|
if (!entry) {
|
|
2184
3341
|
log.error(`Cannot destroy: session ${sessionId} not found`)
|
|
2185
3342
|
return false
|
|
2186
3343
|
}
|
|
3344
|
+
if (archive !== false && entry.session?.constructor?.isUserShell !== true) {
|
|
3345
|
+
this._queueLiveEntryForArchive(sessionId, entry, archiveReason)
|
|
3346
|
+
}
|
|
2187
3347
|
// Mark as destroying immediately — getSession() will return null from here on
|
|
2188
3348
|
entry._destroying = true
|
|
2189
3349
|
metrics.inc('sessions.destroyed')
|
|
@@ -2192,16 +3352,28 @@ export class SessionManager extends EventEmitter {
|
|
|
2192
3352
|
// Prevent unhandled 'error' throw if session emits error during destroy
|
|
2193
3353
|
entry.session.on('error', () => {})
|
|
2194
3354
|
// Emit synthetic stream_end for any in-flight streams so clients see termination
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
3355
|
+
// A failure here (history, or a session_event listener) must not abort the
|
|
3356
|
+
// teardown and strand the entry as going away (#9034).
|
|
3357
|
+
try {
|
|
3358
|
+
const closedMessageIds = this._history.closePendingStreams(sessionId)
|
|
3359
|
+
for (const messageId of closedMessageIds) {
|
|
3360
|
+
this.emit('session_event', { sessionId, event: 'stream_end', data: { messageId } })
|
|
3361
|
+
}
|
|
3362
|
+
} catch (streamErr) {
|
|
3363
|
+
log.error(`Error closing pending streams for session ${sessionId} "${entry.name}": ${streamErr?.stack || streamErr}`)
|
|
2198
3364
|
}
|
|
2199
3365
|
try {
|
|
2200
3366
|
entry.session.destroy()
|
|
2201
3367
|
} catch (destroyErr) {
|
|
2202
3368
|
log.error(`Error destroying session ${sessionId} "${entry.name}": ${destroyErr?.stack || destroyErr}`)
|
|
2203
3369
|
}
|
|
2204
|
-
|
|
3370
|
+
try {
|
|
3371
|
+
this._cleanupSessionMaps(sessionId)
|
|
3372
|
+
} catch (err) {
|
|
3373
|
+
// Still in the map: leave it visible and destroyable rather than invisible.
|
|
3374
|
+
this._releaseDestroyMark(sessionId)
|
|
3375
|
+
throw err
|
|
3376
|
+
}
|
|
2205
3377
|
if (entry.worktreePath) {
|
|
2206
3378
|
this._removeWorktree(entry.worktreePath, entry.worktreeRepoDir, sessionId)
|
|
2207
3379
|
}
|
|
@@ -2273,6 +3445,21 @@ export class SessionManager extends EventEmitter {
|
|
|
2273
3445
|
*/
|
|
2274
3446
|
destroyAll() {
|
|
2275
3447
|
this.stopSessionTimeouts()
|
|
3448
|
+
// #8275: the session-less Claude model refresh owns a child `claude` that no
|
|
3449
|
+
// session tracks. Every shutdown path ends here, so cancel it (SIGKILL, and a
|
|
3450
|
+
// latch against a client connecting mid-shutdown) before the process exits.
|
|
3451
|
+
// Fire-and-forget: destroyAll is synchronous and the kill is already sent.
|
|
3452
|
+
stopClaudeModelRefresh().catch(() => {})
|
|
3453
|
+
// #8348: a permission prompt still open at shutdown can never be answered --
|
|
3454
|
+
// its hook is denied and its in-process request is cleared -- and the sessions
|
|
3455
|
+
// are about to be serialized and torn down with their listeners removed, so
|
|
3456
|
+
// nothing later would journal it. Record it as expired NOW, ahead of the final
|
|
3457
|
+
// write below, so a client that reconnects to the restarted daemon is shown
|
|
3458
|
+
// the dropped call instead of finding the card silently gone (or, on a delta
|
|
3459
|
+
// replay, still offering a dead Allow).
|
|
3460
|
+
for (const requestId of [...this._permissionRequests.keys()]) {
|
|
3461
|
+
this.recordPermissionOutcome(requestId, 'expired')
|
|
3462
|
+
}
|
|
2276
3463
|
this._persistence.cancelPersist()
|
|
2277
3464
|
try {
|
|
2278
3465
|
this.serializeState()
|
|
@@ -2313,12 +3500,30 @@ export class SessionManager extends EventEmitter {
|
|
|
2313
3500
|
reason: entry.session._exitReason ?? 'shutdown',
|
|
2314
3501
|
})
|
|
2315
3502
|
}
|
|
3503
|
+
// #7552: destroyAll() clears `_sessions` wholesale instead of going
|
|
3504
|
+
// through `_cleanupSessionMaps`, so it is the ONE path that has to untag
|
|
3505
|
+
// for itself. Shutdown makes this belt-and-braces — the next boot's
|
|
3506
|
+
// `EnvironmentManager.reconnect()` clears `env.sessions` unconditionally —
|
|
3507
|
+
// but leaving it out would mean the environments file is written with
|
|
3508
|
+
// session ids that are already dead, and "correct only because something
|
|
3509
|
+
// else cleans up later" is the shape that rots.
|
|
3510
|
+
if (entry.environmentId) this._environmentManager?.removeSession(entry.environmentId, sessionId)
|
|
3511
|
+
// #8092: same reasoning as the environment untag immediately above —
|
|
3512
|
+
// destroyAll() bypasses `_cleanupSessionMaps()` entirely, so it is the
|
|
3513
|
+
// one path that has to prune the survey-throttle record for itself too.
|
|
3514
|
+
forgetSurveyKey(this, sessionId)
|
|
2316
3515
|
this.emit('session_destroyed', { sessionId })
|
|
2317
3516
|
}
|
|
2318
3517
|
this._sessions.clear()
|
|
2319
3518
|
this._timeoutManager.destroy()
|
|
3519
|
+
this._containerLivenessMonitor?.destroy()
|
|
3520
|
+
// Finish any just-closed session still compressing, so a clean exit does not
|
|
3521
|
+
// lose its archive, then stop the retention sweep.
|
|
3522
|
+
try { this._sessionArchive.drainSync?.() } catch (err) { log.warn(`session archive drain failed (non-fatal): ${getErrorMessage(err, 'unknown error')}`) }
|
|
3523
|
+
if (this._archivePruneTimer) { clearInterval(this._archivePruneTimer); this._archivePruneTimer = null }
|
|
2320
3524
|
this._history.clear()
|
|
2321
3525
|
this._costBudget.clear()
|
|
3526
|
+
this._userStopped.clear()
|
|
2322
3527
|
// #5554: persist any pending usage records on shutdown (best-effort).
|
|
2323
3528
|
try { this.skillsUsageRecorder?.flush() } catch { /* non-fatal */ }
|
|
2324
3529
|
}
|
|
@@ -2367,7 +3572,7 @@ export class SessionManager extends EventEmitter {
|
|
|
2367
3572
|
* has already run — late callers (duplicate shutdown handler, stray
|
|
2368
3573
|
* session event) cannot overwrite the on-disk state (#3697).
|
|
2369
3574
|
*/
|
|
2370
|
-
serializeState() {
|
|
3575
|
+
serializeState({ durable = false } = {}) {
|
|
2371
3576
|
// After destroyAll() has cleared the in-memory Map, any further write
|
|
2372
3577
|
// would persist 0 sessions and overwrite the good state already on disk.
|
|
2373
3578
|
// Skip silently — the destroyAll() call did the final write itself
|
|
@@ -2388,7 +3593,19 @@ export class SessionManager extends EventEmitter {
|
|
|
2388
3593
|
// user's history is permanently lost. We write them back exactly as
|
|
2389
3594
|
// they were loaded so a retry (after the user sets the missing env var
|
|
2390
3595
|
// and restarts) can fully re-hydrate history.
|
|
2391
|
-
|
|
3596
|
+
// #8858 — stamp each with `failedRestore: { code, message }`. The entry is
|
|
3597
|
+
// otherwise byte-identical to an ordinary session, so the next boot's 24h
|
|
3598
|
+
// staleness filter could not tell a PARKED entry from one that merely aged
|
|
3599
|
+
// out, and dropped it when its container binding resolved. The marker is
|
|
3600
|
+
// what lets `restoreState` keep it parked until Retry, Dismiss or the
|
|
3601
|
+
// failed-restore TTL. An older file has no marker and behaves as before.
|
|
3602
|
+
for (const [, { saved, error }] of this._failedRestores) {
|
|
3603
|
+
state.sessions.push({ ...saved, failedRestore: this._failedRestoreMarker(error) })
|
|
3604
|
+
}
|
|
3605
|
+
|
|
3606
|
+
// Stale snapshots whose archive failed: written back verbatim (NOT stamped
|
|
3607
|
+
// as failed restores) so the next boot sees them stale and retries.
|
|
3608
|
+
for (const saved of this._unarchivedStale.values()) {
|
|
2392
3609
|
state.sessions.push(saved)
|
|
2393
3610
|
}
|
|
2394
3611
|
|
|
@@ -2399,7 +3616,7 @@ export class SessionManager extends EventEmitter {
|
|
|
2399
3616
|
state.budgetExceeded = budgetState.budgetExceeded
|
|
2400
3617
|
state.budgetPaused = budgetState.budgetPaused
|
|
2401
3618
|
|
|
2402
|
-
return this._persistence.serializeState(state)
|
|
3619
|
+
return this._persistence.serializeState(state, { durable })
|
|
2403
3620
|
}
|
|
2404
3621
|
|
|
2405
3622
|
/**
|
|
@@ -2415,10 +3632,26 @@ export class SessionManager extends EventEmitter {
|
|
|
2415
3632
|
*/
|
|
2416
3633
|
_serializeSessionEntry(id, entry) {
|
|
2417
3634
|
const history = this._history.getHistory(id).map(e => this._history.truncateEntry(e))
|
|
3635
|
+
const decisionActivity = entry.session.getDecisionActivityState?.()
|
|
2418
3636
|
return {
|
|
2419
3637
|
id,
|
|
3638
|
+
...(entry.declaredStatus ? { declaredStatus: { ...entry.declaredStatus } } : {}),
|
|
3639
|
+
...(decisionActivity ? { decisionActivity } : {}),
|
|
2420
3640
|
sdkSessionId: (typeof entry.session.resumeSessionId !== 'undefined' ? entry.session.resumeSessionId : null),
|
|
2421
3641
|
conversationId: entry.session.resumeSessionId || null,
|
|
3642
|
+
nativeResume: entry.session.nativeResumeState || null,
|
|
3643
|
+
...(typeof entry.session.getCodexSandbox === 'function' ? { codexSandbox: entry.session.getCodexSandbox() } : {}),
|
|
3644
|
+
// #8418: has the provider's conversation ever been SAVED (claude-tui: a
|
|
3645
|
+
// turn completed, or the transcript was seen on disk)? `sdkSessionId`
|
|
3646
|
+
// alone cannot say: claude-tui mints and serializes its id before claude
|
|
3647
|
+
// has written anything, so an untouched session and one whose transcript
|
|
3648
|
+
// was later wiped look identical on restore. Only providers that track it
|
|
3649
|
+
// report a boolean; for the rest the key is omitted, and a state file
|
|
3650
|
+
// without it restores exactly as before (an older build reading one
|
|
3651
|
+
// ignores the unknown key: restore copies named fields only).
|
|
3652
|
+
...(typeof entry.session.conversationPersisted === 'boolean'
|
|
3653
|
+
? { conversationPersisted: entry.session.conversationPersisted }
|
|
3654
|
+
: {}),
|
|
2422
3655
|
cwd: entry.cwd,
|
|
2423
3656
|
model: entry.session.model,
|
|
2424
3657
|
// Persist the model the underlying CLI actually booted with (#3700b).
|
|
@@ -2439,6 +3672,10 @@ export class SessionManager extends EventEmitter {
|
|
|
2439
3672
|
messageCounter: entry.session._messageCounter || 0,
|
|
2440
3673
|
permissionMode: entry.session.permissionMode,
|
|
2441
3674
|
provider: entry.provider || null,
|
|
3675
|
+
// Persist the route that actually created the session. Restore compares
|
|
3676
|
+
// descriptor version, stable id, runtime id, and requested auth route
|
|
3677
|
+
// with current host config and fails closed when that identity changes.
|
|
3678
|
+
agentConnection: entry.agentConnection || null,
|
|
2442
3679
|
name: entry.name,
|
|
2443
3680
|
// #5310 (WP-0.4) — persist the worktree binding so a restored session
|
|
2444
3681
|
// rebinds to its existing worktree (rather than losing it). worktreePath
|
|
@@ -2448,6 +3685,21 @@ export class SessionManager extends EventEmitter {
|
|
|
2448
3685
|
// (pre-#5310) restore as null → treated as a non-worktree session.
|
|
2449
3686
|
worktreePath: entry.worktreePath || null,
|
|
2450
3687
|
worktreeRepoDir: entry.worktreeRepoDir || null,
|
|
3688
|
+
// #7561: persist the container binding so an environment-backed session
|
|
3689
|
+
// rebinds to ITS container on restore instead of silently launching a
|
|
3690
|
+
// fresh default one (see the entry comment in createSession, and
|
|
3691
|
+
// `_resolveRestoredContainerBinding` for what restore does with these).
|
|
3692
|
+
// `environmentId` is the authority when present — the restore path
|
|
3693
|
+
// re-resolves the container off the LIVE EnvironmentManager, because the
|
|
3694
|
+
// environment may have been rebuilt while the daemon was down — and the
|
|
3695
|
+
// three container fields carry the binding for a session created with a
|
|
3696
|
+
// bare containerId and no environment. Null for every non-container
|
|
3697
|
+
// session; older state files (no fields) restore as null, which is the
|
|
3698
|
+
// pre-#7561 behaviour for exactly the sessions that had no binding.
|
|
3699
|
+
environmentId: entry.environmentId || null,
|
|
3700
|
+
containerId: entry.containerId || null,
|
|
3701
|
+
containerUser: entry.containerUser || null,
|
|
3702
|
+
containerCliPath: entry.containerCliPath || null,
|
|
2451
3703
|
// Mailbox (#5914 follow-up): persist the registered AGENT_COMM_ID so a
|
|
2452
3704
|
// session keeps its mailbox identity across a daemon restart (re-applied
|
|
2453
3705
|
// via createSession on restore below). Null when the session never
|
|
@@ -2455,6 +3707,26 @@ export class SessionManager extends EventEmitter {
|
|
|
2455
3707
|
agentCommId: entry.agentCommId || null,
|
|
2456
3708
|
lastActivityAt: this._sessionLastActivityAt.get(id) || entry.createdAt,
|
|
2457
3709
|
history,
|
|
3710
|
+
// #8866: a session continued as a NEW thread from the archive that has not
|
|
3711
|
+
// had its first message yet still owes the model its transcript seed; it
|
|
3712
|
+
// must survive a daemon restart in that window. Absent otherwise.
|
|
3713
|
+
// `claimed` records that the first input is IN FLIGHT: after a crash that
|
|
3714
|
+
// seed is dropped, not re-sent (see coerceContinuationSeed).
|
|
3715
|
+
...(this._continuationSeeds.has(id)
|
|
3716
|
+
? { continuationSeed: { ...this._continuationSeeds.get(id).seed, ...(this._continuationSeeds.get(id).claimed ? { claimed: true } : {}) } }
|
|
3717
|
+
: {}),
|
|
3718
|
+
// #8336: the highest history seq this run handed out. The ring buffer's
|
|
3719
|
+
// `_seq` stamps are server-internal and stripped from `history` above,
|
|
3720
|
+
// but a reconnecting client keeps its cursor across a restart; restore
|
|
3721
|
+
// keeps numbering past this value so that cursor still means what it did
|
|
3722
|
+
// (see SessionMessageHistory#setHistory). Absent on older state files.
|
|
3723
|
+
historyLastSeq: this._history.getLastIssuedSeq(id),
|
|
3724
|
+
// #8259: highest seq this run may issue; persisted BEFORE any seq under it is
|
|
3725
|
+
// handed out, so a restart numbers past every cursor a client could hold.
|
|
3726
|
+
...(this._history.getSeqReservedThrough(id) > 0 ? { seqReservedThrough: this._history.getSeqReservedThrough(id) } : {}),
|
|
3727
|
+
// #8259: a turn was dispatched to the provider and has not ended. Written only
|
|
3728
|
+
// when true (absent otherwise), so ordinary state files are unchanged.
|
|
3729
|
+
...(entry.turnInFlight === true ? { turnInFlight: true } : {}),
|
|
2458
3730
|
// #4664: persist per-session toggle/string settings via the
|
|
2459
3731
|
// shared registry — each entry's coerce produces the same
|
|
2460
3732
|
// strict-boolean/string-default shape the pre-refactor per-knob
|
|
@@ -2510,7 +3782,396 @@ export class SessionManager extends EventEmitter {
|
|
|
2510
3782
|
}
|
|
2511
3783
|
|
|
2512
3784
|
/**
|
|
2513
|
-
*
|
|
3785
|
+
* #7561 — resolve the container binding a persisted session must come back
|
|
3786
|
+
* with, or REFUSE the restore.
|
|
3787
|
+
*
|
|
3788
|
+
* The security property this enforces: **a session the operator created
|
|
3789
|
+
* INSIDE a container must never come back running anywhere else.** Before
|
|
3790
|
+
* this, the binding was not persisted at all, so a restored `docker-sdk`
|
|
3791
|
+
* session had `containerId: null` — and `DockerSdkSession`'s constructor
|
|
3792
|
+
* reads that as `_containerOwned = true`, so `start()` launched a fresh
|
|
3793
|
+
* default `node:22-slim` container with the session's cwd bind-mounted,
|
|
3794
|
+
* discarding the environment's image, its devcontainer mounts
|
|
3795
|
+
* (`validateMounts`), its sanitised env (`sanitizeContainerEnv`) and its
|
|
3796
|
+
* memory/cpu limits. Silent, and strictly weaker than what the operator asked
|
|
3797
|
+
* for.
|
|
3798
|
+
*
|
|
3799
|
+
* The three outcomes:
|
|
3800
|
+
*
|
|
3801
|
+
* 1. Nothing persisted → `{}`. Non-container sessions and every state file
|
|
3802
|
+
* written before #7561 take the unchanged path.
|
|
3803
|
+
* 2. `environmentId` persisted → the LIVE EnvironmentManager is the
|
|
3804
|
+
* authority. `getContainerInfo()` re-resolves the container and throws
|
|
3805
|
+
* when the environment is gone or not running. #7619: the re-resolved id
|
|
3806
|
+
* is then COMPARED against the persisted one, and a REBUILT container is
|
|
3807
|
+
* refused too — the same situation the live path refuses as
|
|
3808
|
+
* `container_replaced`, since a rebuilt container carries none of the
|
|
3809
|
+
* in-container `claude` install or the SDK transcript and would resume
|
|
3810
|
+
* the conversation blank. Every one of those THROWS, which lands the
|
|
3811
|
+
* session in the #2954 failed-restore path: history is preserved on disk
|
|
3812
|
+
* and `session_restore_failed` fires. Loud beats a silent respawn.
|
|
3813
|
+
*
|
|
3814
|
+
* Retryability differs by arm, and the rebuilt-container one is the odd
|
|
3815
|
+
* one out. Gone / stopped / disabled all clear when the operator brings
|
|
3816
|
+
* the environment back, and the next boot restores. A REBUILT container
|
|
3817
|
+
* never does: the environment is already back and running, and its id
|
|
3818
|
+
* will not match the persisted one again, so that session stays in the
|
|
3819
|
+
* needs-attention list until `_pruneStaleFailedRestores` drops it after
|
|
3820
|
+
* the TTL. `clearFailedRestore` exists for a user-driven dismiss but has
|
|
3821
|
+
* no caller yet, so there is currently no in-product way to act on it —
|
|
3822
|
+
* see #7625.
|
|
3823
|
+
*
|
|
3824
|
+
* The one accepted-but-unverifiable case: a state file written before
|
|
3825
|
+
* #7561 persisted no `containerId`, so there is nothing to compare. That
|
|
3826
|
+
* restores (refusing would strand every session that upgraded across that
|
|
3827
|
+
* boundary) but WARNS, so "cannot verify" is never silently recorded as
|
|
3828
|
+
* "nothing to verify".
|
|
3829
|
+
* 3. Only a bare `containerId` persisted (no environment — an internal
|
|
3830
|
+
* caller, never the wire) → forwarded verbatim. There is no registry to
|
|
3831
|
+
* revalidate against; `DockerSdkSession._verifyContainer` is the runtime
|
|
3832
|
+
* check and fails the session loudly if the container is gone. The
|
|
3833
|
+
* important part is that `containerId` is non-null, so the session cannot
|
|
3834
|
+
* take the `_containerOwned` spawn branch.
|
|
3835
|
+
*
|
|
3836
|
+
* Note the deliberate asymmetry with #7552's "restore must not half-tag" rule:
|
|
3837
|
+
* that held while the binding was NOT persisted. With it persisted, a
|
|
3838
|
+
* successful restore SHOULD re-tag — and does, via `createSession`'s existing
|
|
3839
|
+
* `addSession` call, because `environmentId` is forwarded below.
|
|
3840
|
+
*
|
|
3841
|
+
* @param {object} saved - the persisted session payload
|
|
3842
|
+
* @returns {{environmentId?: string, containerId?: string, containerUser?: string, containerCliPath?: string}}
|
|
3843
|
+
* @throws {Error & {code: 'ENVIRONMENT_UNAVAILABLE'}} when a persisted environment cannot be re-entered
|
|
3844
|
+
* @private
|
|
3845
|
+
*/
|
|
3846
|
+
_resolveRestoredContainerBinding(saved) {
|
|
3847
|
+
const str = (v) => (typeof v === 'string' && v.length > 0 ? v : undefined)
|
|
3848
|
+
const environmentId = str(saved?.environmentId)
|
|
3849
|
+
const containerId = str(saved?.containerId)
|
|
3850
|
+
|
|
3851
|
+
if (!environmentId) {
|
|
3852
|
+
if (!containerId) return {}
|
|
3853
|
+
return {
|
|
3854
|
+
containerId,
|
|
3855
|
+
containerUser: str(saved?.containerUser),
|
|
3856
|
+
containerCliPath: str(saved?.containerCliPath),
|
|
3857
|
+
}
|
|
3858
|
+
}
|
|
3859
|
+
|
|
3860
|
+
const fail = (reason) => {
|
|
3861
|
+
const err = new Error(
|
|
3862
|
+
`Session was created inside container environment "${environmentId}", which cannot be re-entered: ${reason}. ` +
|
|
3863
|
+
`Refusing to restore it outside that environment.`,
|
|
3864
|
+
)
|
|
3865
|
+
err.code = 'ENVIRONMENT_UNAVAILABLE'
|
|
3866
|
+
throw err
|
|
3867
|
+
}
|
|
3868
|
+
|
|
3869
|
+
if (!this._environmentManager || typeof this._environmentManager.getContainerInfo !== 'function') {
|
|
3870
|
+
// Container environments were turned off (or this daemon never had them)
|
|
3871
|
+
// since the session was created. Restoring would run it on the host side
|
|
3872
|
+
// of the boundary it was created behind.
|
|
3873
|
+
fail('container environments are not enabled on this server')
|
|
3874
|
+
}
|
|
3875
|
+
|
|
3876
|
+
let info
|
|
3877
|
+
try {
|
|
3878
|
+
info = this._environmentManager.getContainerInfo(environmentId)
|
|
3879
|
+
} catch (err) {
|
|
3880
|
+
// Covers both "no such environment" and "not running (status: stopped |
|
|
3881
|
+
// error)" — getContainerInfo throws for each.
|
|
3882
|
+
fail(err?.message || String(err))
|
|
3883
|
+
}
|
|
3884
|
+
if (!info || typeof info.containerId !== 'string' || info.containerId.length === 0) {
|
|
3885
|
+
fail('the environment reports no container')
|
|
3886
|
+
}
|
|
3887
|
+
|
|
3888
|
+
// #7619 — a REBUILT container is refused here exactly as the live path
|
|
3889
|
+
// (`_reattachEnvironmentBoundSession`, reason `container_replaced`) refuses
|
|
3890
|
+
// it. Both entry points see one underlying situation — the environment's
|
|
3891
|
+
// container was replaced while this session was bound to the old one — and
|
|
3892
|
+
// before this they disagreed: live surfaced a visible refusal, boot silently
|
|
3893
|
+
// rebound. The silent rebind is the WORSE half, because a rebuilt container
|
|
3894
|
+
// carries none of the in-container `claude` install or the SDK transcript,
|
|
3895
|
+
// so the "restored" session comes back knowing nothing — precisely the
|
|
3896
|
+
// blank-session outcome the live refusal exists to prevent. A restored
|
|
3897
|
+
// session having no in-memory turn state does not change that: what the user
|
|
3898
|
+
// sees is a conversation that silently lost its history either way.
|
|
3899
|
+
if (containerId && info.containerId !== containerId) {
|
|
3900
|
+
fail(
|
|
3901
|
+
`the environment now runs a different container (${info.containerId.slice(0, 12)}), ` +
|
|
3902
|
+
`not the one this session was created in (${containerId.slice(0, 12)})`,
|
|
3903
|
+
)
|
|
3904
|
+
}
|
|
3905
|
+
if (!containerId) {
|
|
3906
|
+
// Nothing was persisted to compare against. The expected cause is a state
|
|
3907
|
+
// file written before #7561 added the binding, but it is not the only one
|
|
3908
|
+
// that reaches here — an incomplete or hand-edited state file lands in the
|
|
3909
|
+
// same branch — so the log reports the OBSERVATION and names that cause as
|
|
3910
|
+
// expected rather than certain. Refusing every one of these would strand
|
|
3911
|
+
// sessions that merely upgraded across that boundary, so it is accepted.
|
|
3912
|
+
// But "cannot verify" is recorded rather than silently treated as
|
|
3913
|
+
// "nothing to verify", which is the defect class this guard belongs to.
|
|
3914
|
+
log.warn(
|
|
3915
|
+
`Restored session in environment "${environmentId}" has no persisted container id; ` +
|
|
3916
|
+
`cannot verify the environment's current container is the one it was created in ` +
|
|
3917
|
+
`(expected for a state file written before #7561 — otherwise the persisted state is incomplete).`,
|
|
3918
|
+
)
|
|
3919
|
+
}
|
|
3920
|
+
|
|
3921
|
+
return {
|
|
3922
|
+
environmentId,
|
|
3923
|
+
containerId: info.containerId,
|
|
3924
|
+
containerUser: str(info.containerUser),
|
|
3925
|
+
containerCliPath: str(info.containerCliPath),
|
|
3926
|
+
}
|
|
3927
|
+
}
|
|
3928
|
+
|
|
3929
|
+
/**
|
|
3930
|
+
* Restore ONE saved session: resolve its container binding, create the
|
|
3931
|
+
* session, then re-seed everything createSession does NOT (usage counters,
|
|
3932
|
+
* the auto-name counter, message history, lastActivityAt).
|
|
3933
|
+
*
|
|
3934
|
+
* Extracted from restoreState()'s loop by #7625 so the boot path and the
|
|
3935
|
+
* operator-triggered retry drive the SAME recipe. Keeping two copies was the
|
|
3936
|
+
* alternative and it is the defect class this repo already carries a lint
|
|
3937
|
+
* for after three recurrences (scripts/lint-session-opt-forwarding.sh): a
|
|
3938
|
+
* ~100-line option-forwarding list, hand-maintained twice, drifts. The
|
|
3939
|
+
* extraction was a verbatim move — the block was asserted byte-identical
|
|
3940
|
+
* after re-indenting, not retyped.
|
|
3941
|
+
*
|
|
3942
|
+
* THROWS on a SYNCHRONOUS failure (container binding refused, preflight,
|
|
3943
|
+
* SessionLimitError, a sync start() rejection re-thrown by createSession).
|
|
3944
|
+
* The caller owns the failed-restore bookkeeping, because the two callers
|
|
3945
|
+
* want different things: boot collects them, retry re-parks one.
|
|
3946
|
+
*
|
|
3947
|
+
* An ASYNCHRONOUS start() rejection is NOT raised here and must not be
|
|
3948
|
+
* handled by the caller either — createSession wires it to
|
|
3949
|
+
* _handleAsyncStartFailure, which re-parks an `isRestore` session on its
|
|
3950
|
+
* own. That is why `isRestore: true` below is load-bearing for the retry
|
|
3951
|
+
* path and not merely inherited from the boot path.
|
|
3952
|
+
*
|
|
3953
|
+
* @param {object} saved A serialized entry (see _serializeSessionEntry).
|
|
3954
|
+
* @param {boolean} seedHistory Seed saved.history onto the ring buffer.
|
|
3955
|
+
* False only for a legacy v0 state file, which carries no history.
|
|
3956
|
+
* @returns {string} The new session id.
|
|
3957
|
+
*/
|
|
3958
|
+
_attemptRestoreOne(saved, seedHistory) {
|
|
3959
|
+
// #7561: resolve (and re-validate) the container binding FIRST, so a
|
|
3960
|
+
// session whose environment is gone / stopped / disabled throws into the
|
|
3961
|
+
// failed-restore catch below instead of being created host-side or into
|
|
3962
|
+
// a freshly-spawned ad-hoc container. Nothing has been constructed at
|
|
3963
|
+
// this point, which is what makes the refusal total.
|
|
3964
|
+
const containerBinding = this._resolveRestoredContainerBinding(saved)
|
|
3965
|
+
// skipPersist: we rewrite the state file once at the end of
|
|
3966
|
+
// restoreState, after history and cost budget have been reseeded.
|
|
3967
|
+
// Flushing per-session here would overwrite the on-disk file with
|
|
3968
|
+
// empty history for all not-yet-processed sessions, erasing the
|
|
3969
|
+
// data we're trying to restore.
|
|
3970
|
+
const sessionId = this.createSession({
|
|
3971
|
+
// #4983 — reuse the persisted ID so dashboard's localStorage-
|
|
3972
|
+
// cached activeSessionId still resolves after a daemon restart.
|
|
3973
|
+
// createSession validates the format (32-char lower-case hex);
|
|
3974
|
+
// a malformed or duplicate id falls back to randomBytes so the
|
|
3975
|
+
// call still succeeds. The dashboard's #4982 SESSION_NOT_FOUND
|
|
3976
|
+
// chip is the safety net for the malformed/missing/cross-host
|
|
3977
|
+
// cases that this preservation can't help with.
|
|
3978
|
+
preserveId: saved.id,
|
|
3979
|
+
name: saved.name,
|
|
3980
|
+
cwd: saved.cwd,
|
|
3981
|
+
model: saved.model,
|
|
3982
|
+
permissionMode: saved.permissionMode,
|
|
3983
|
+
resumeSessionId: saved.sdkSessionId,
|
|
3984
|
+
nativeResume: saved.nativeResume || null,
|
|
3985
|
+
codexSandbox: saved.codexSandbox || undefined,
|
|
3986
|
+
// #8418: only a literal `true` counts; a hand-edited or older file restores
|
|
3987
|
+
// as "unknown", exactly as before this field existed.
|
|
3988
|
+
conversationPersisted: saved.conversationPersisted === true ? true : undefined,
|
|
3989
|
+
provider: saved.provider || undefined,
|
|
3990
|
+
connectionId: typeof saved.agentConnection?.id === 'string' && saved.agentConnection.provenance?.source === 'configured'
|
|
3991
|
+
? saved.agentConnection.id
|
|
3992
|
+
: undefined,
|
|
3993
|
+
restoredAgentConnection: saved.agentConnection?.provenance?.source === 'configured'
|
|
3994
|
+
? saved.agentConnection
|
|
3995
|
+
: undefined,
|
|
3996
|
+
// #5310 (WP-0.4) — rebind to the existing worktree (don't recreate).
|
|
3997
|
+
// Only string paths flow through; non-worktree sessions and older
|
|
3998
|
+
// state files (no field) pass undefined and take the normal path.
|
|
3999
|
+
restoreWorktreePath: typeof saved.worktreePath === 'string' && saved.worktreePath.length > 0
|
|
4000
|
+
? saved.worktreePath
|
|
4001
|
+
: undefined,
|
|
4002
|
+
restoreWorktreeRepoDir: typeof saved.worktreeRepoDir === 'string' && saved.worktreeRepoDir.length > 0
|
|
4003
|
+
? saved.worktreeRepoDir
|
|
4004
|
+
: undefined,
|
|
4005
|
+
// #4664: restore per-session toggle/string settings via the
|
|
4006
|
+
// shared registry. Each registry entry's `acceptFromConstructor`
|
|
4007
|
+
// predicate drops malformed values to `undefined` so
|
|
4008
|
+
// createSession applies BaseSession's default — exact match for
|
|
4009
|
+
// the pre-refactor per-knob behaviour, and older state files
|
|
4010
|
+
// (without these fields) round-trip cleanly.
|
|
4011
|
+
...restorePerSessionSettings(saved),
|
|
4012
|
+
// #3639: forward the persisted skip-pattern source. Non-string /
|
|
4013
|
+
// empty values are dropped (createSession ignores them) so older
|
|
4014
|
+
// state files restore as null. Kept out of the registry because
|
|
4015
|
+
// the empty-string-as-null wire shape doesn't fit the
|
|
4016
|
+
// boolean/string factory.
|
|
4017
|
+
promptEvaluatorSkipPattern: typeof saved.promptEvaluatorSkipPattern === 'string' && saved.promptEvaluatorSkipPattern.length > 0
|
|
4018
|
+
? saved.promptEvaluatorSkipPattern
|
|
4019
|
+
: undefined,
|
|
4020
|
+
// #3540: forward the persisted stdin_disabled latch. Only
|
|
4021
|
+
// truthy values flip the flag; pre-#3540 state files (no
|
|
4022
|
+
// field) restore as `false`. The SdkSession constructor
|
|
4023
|
+
// initialises `_stdinForwardingDisabled` from this opt and
|
|
4024
|
+
// the existing `_attachSidecarProcessListeners` short-circuit
|
|
4025
|
+
// ensures no warn/error is re-emitted on restore — clients
|
|
4026
|
+
// observe the disabled state via session_list metadata.
|
|
4027
|
+
stdinForwardingDisabled: saved.stdinForwardingDisabled === true ? true : undefined,
|
|
4028
|
+
// #6824: forward the persisted parked MCP server set so the respawned
|
|
4029
|
+
// BYOK fleet skips starting them. Non-array / empty values are
|
|
4030
|
+
// dropped (createSession only forwards a non-empty string array), so
|
|
4031
|
+
// older state files restore with nothing parked.
|
|
4032
|
+
disabledMcpServers: Array.isArray(saved.disabledMcpServers) && saved.disabledMcpServers.length > 0
|
|
4033
|
+
? saved.disabledMcpServers.filter((n) => typeof n === 'string')
|
|
4034
|
+
: undefined,
|
|
4035
|
+
// Restore the previously-booted model (#3700b) so the dashboard
|
|
4036
|
+
// dropdown shows the real model on reconnect, not the registry
|
|
4037
|
+
// fallback. createSession() ignores non-string / empty values so
|
|
4038
|
+
// older state files (pre-#3700b) restore cleanly as null.
|
|
4039
|
+
bootedModel: typeof saved.bootedModel === 'string' && saved.bootedModel.length > 0
|
|
4040
|
+
? saved.bootedModel
|
|
4041
|
+
: undefined,
|
|
4042
|
+
// Restore the messageId counter so new turns don't reuse old IDs
|
|
4043
|
+
// and collide with dashboard-cached messages (#3700).
|
|
4044
|
+
messageCounter: typeof saved.messageCounter === 'number' && Number.isFinite(saved.messageCounter) && saved.messageCounter >= 0
|
|
4045
|
+
? saved.messageCounter
|
|
4046
|
+
: undefined,
|
|
4047
|
+
// Mailbox (#5914 follow-up): re-register the persisted AGENT_COMM_ID so
|
|
4048
|
+
// a restored session is reachable by the live-interrupt route again.
|
|
4049
|
+
// createSession validates it (drops bad values to a no-op); older
|
|
4050
|
+
// state files (no field) restore with no mailbox identity.
|
|
4051
|
+
agentCommId: typeof saved.agentCommId === 'string' && saved.agentCommId.length > 0
|
|
4052
|
+
? saved.agentCommId
|
|
4053
|
+
: undefined,
|
|
4054
|
+
// #7561: environmentId + containerId/containerUser/containerCliPath,
|
|
4055
|
+
// re-resolved above. Empty for a non-container session, so this spread
|
|
4056
|
+
// is a no-op on every path that had one before. Forwarding
|
|
4057
|
+
// `environmentId` is also what re-tags `env.sessions` — createSession's
|
|
4058
|
+
// existing `addSession` call does it, so the environment's live-session
|
|
4059
|
+
// set (and the #7562 destroy guard that reads it) is true again after a
|
|
4060
|
+
// restart.
|
|
4061
|
+
...containerBinding,
|
|
4062
|
+
skipPersist: true,
|
|
4063
|
+
// #5316 (WP-2.2) — mark this as a restore so an ASYNC provider
|
|
4064
|
+
// start() rejection (claude-tui PTY warmup death) preserves the
|
|
4065
|
+
// restored history + worktree instead of destroying them.
|
|
4066
|
+
isRestore: true,
|
|
4067
|
+
})
|
|
4068
|
+
try {
|
|
4069
|
+
// #4089 / #4124: restore the per-session running totals + the
|
|
4070
|
+
// threshold-notified latch onto the freshly-created entry. We do
|
|
4071
|
+
// this AFTER createSession so the entry exists, and BEFORE
|
|
4072
|
+
// history replay so a synthetic result event during replay
|
|
4073
|
+
// (unlikely but defensive) doesn't double-count. Validate shape:
|
|
4074
|
+
// missing / corrupt cumulativeUsage falls back to all-zero;
|
|
4075
|
+
// non-boolean costThresholdNotified falls back to false.
|
|
4076
|
+
//
|
|
4077
|
+
// Per-field clamps:
|
|
4078
|
+
// - Token counts + turnsBilled are monotonic counters; corrupt
|
|
4079
|
+
// state with negatives clamps to 0.
|
|
4080
|
+
// - costUsd accepts negatives per #4099 (refund / credit
|
|
4081
|
+
// adjustments). Only non-finite values fall back to 0.
|
|
4082
|
+
const restoredEntry = this._sessions.get(sessionId)
|
|
4083
|
+
// #7082: the restore path reads ~/.chroxy/session-state.json, so a hand-edited
|
|
4084
|
+
// or corrupt file can carry a fractional / past-2^53 / negative counter straight
|
|
4085
|
+
// into the live snapshot. Same coercion as the accumulate path above.
|
|
4086
|
+
if (restoredEntry) {
|
|
4087
|
+
const status = DeclaredStatusSchema.safeParse(saved.declaredStatus)
|
|
4088
|
+
if (status.success) {
|
|
4089
|
+
restoredEntry.declaredStatus = status.data
|
|
4090
|
+
}
|
|
4091
|
+
restoredEntry.session.restoreDeclaredStatusActivity?.(status.success ? status.data : null, saved.decisionActivity)
|
|
4092
|
+
if (saved.cumulativeUsage && typeof saved.cumulativeUsage === 'object') {
|
|
4093
|
+
const u = saved.cumulativeUsage
|
|
4094
|
+
restoredEntry.cumulativeUsage = {
|
|
4095
|
+
inputTokens: toWireCount(u.inputTokens),
|
|
4096
|
+
outputTokens: toWireCount(u.outputTokens),
|
|
4097
|
+
cacheReadTokens: toWireCount(u.cacheReadTokens),
|
|
4098
|
+
cacheCreationTokens: toWireCount(u.cacheCreationTokens),
|
|
4099
|
+
// costUsd is NOT coerced: `z.number().finite()` with no `.int()`, and
|
|
4100
|
+
// legitimately negative for a refund / credit adjustment (#4099).
|
|
4101
|
+
costUsd: Number.isFinite(u.costUsd) ? u.costUsd : 0,
|
|
4102
|
+
turnsBilled: toWireCount(u.turnsBilled),
|
|
4103
|
+
}
|
|
4104
|
+
}
|
|
4105
|
+
if (saved.costThresholdNotified === true) {
|
|
4106
|
+
restoredEntry.costThresholdNotified = true
|
|
4107
|
+
}
|
|
4108
|
+
}
|
|
4109
|
+
// Keep _sessionCounter ahead of any restored "Session N" names so the
|
|
4110
|
+
// first new auto-named session after restore never collides (#2338).
|
|
4111
|
+
this._advanceSessionCounterPast(saved.name)
|
|
4112
|
+
// Restore message history if present (v1+).
|
|
4113
|
+
// Sweep any `tool_start` that lacks a matching `tool_result` and
|
|
4114
|
+
// splice in a synthetic interrupted result (#4617) BEFORE seeding
|
|
4115
|
+
// history so the subsequent dashboard history replay never sees a
|
|
4116
|
+
// dangling tool_start. Without this, an unresolved tool_use from
|
|
4117
|
+
// before shutdown re-enters `activeTools` on replay and never gets
|
|
4118
|
+
// cleared — the footer shows "Running X · Nh Mm" forever.
|
|
4119
|
+
if (seedHistory && Array.isArray(saved.history) && saved.history.length > 0) {
|
|
4120
|
+
const swept = SessionMessageHistory.sweepUnresolvedToolStarts(saved.history)
|
|
4121
|
+
// #8336: carry the previous run's numbering across the restart. The
|
|
4122
|
+
// persisted entries were contiguous and ended at `historyLastSeq`, so the
|
|
4123
|
+
// first one had `historyLastSeq - length + 1`; a state file without the
|
|
4124
|
+
// field (or one that contradicts itself) restarts at 1, as before.
|
|
4125
|
+
const lastSeq = saved.historyLastSeq
|
|
4126
|
+
const firstSeq = Number.isSafeInteger(lastSeq) && lastSeq >= saved.history.length
|
|
4127
|
+
? lastSeq - saved.history.length + 1
|
|
4128
|
+
: undefined
|
|
4129
|
+
this._history.setHistory(sessionId, swept, { firstSeq })
|
|
4130
|
+
}
|
|
4131
|
+
// #8259: close a turn the previous process was running when it went down. Driven
|
|
4132
|
+
// by the persisted in-flight flag (set when a turn is dispatched to the
|
|
4133
|
+
// provider, cleared when it ends), NOT by the shape of the history: a queued
|
|
4134
|
+
// follow-up, an evaluator-held draft, an errored turn and a cap-evicted prompt
|
|
4135
|
+
// all defeat any reading of the history. The flag was cleared on the live
|
|
4136
|
+
// entry by createSession, so the next serialize records it as handled and a
|
|
4137
|
+
// second restart adds nothing.
|
|
4138
|
+
this._restoringHistory = (this._restoringHistory || 0) + 1
|
|
4139
|
+
try {
|
|
4140
|
+
this._history.restoreSeqReservation(sessionId, saved.seqReservedThrough)
|
|
4141
|
+
if (saved.turnInFlight === true) {
|
|
4142
|
+
this._history.recordInterruptedTurn(sessionId)
|
|
4143
|
+
}
|
|
4144
|
+
} finally {
|
|
4145
|
+
this._restoringHistory -= 1
|
|
4146
|
+
}
|
|
4147
|
+
if (typeof saved.lastActivityAt === 'number' && Number.isFinite(saved.lastActivityAt) && saved.lastActivityAt > 0) {
|
|
4148
|
+
this._sessionLastActivityAt.set(sessionId, saved.lastActivityAt)
|
|
4149
|
+
}
|
|
4150
|
+
// #8866: an unconsumed new-thread seed (state file: untrusted, re-bounded).
|
|
4151
|
+
const continuationSeed = coerceContinuationSeed(saved.continuationSeed)
|
|
4152
|
+
if (continuationSeed) this._continuationSeeds.set(sessionId, { seed: continuationSeed, claimed: false, claimedAt: 0, token: null })
|
|
4153
|
+
} catch (err) {
|
|
4154
|
+
// The TAIL threw, after createSession() already returned — so a live but
|
|
4155
|
+
// half-seeded session exists and must not be left behind.
|
|
4156
|
+
//
|
|
4157
|
+
// Tear down `sessionId`, NOT `saved.id`. createSession falls back to a
|
|
4158
|
+
// random id when `preserveId` is malformed or collides with a live
|
|
4159
|
+
// session (see its `preserve` guard), and `saved.id` comes off disk, so
|
|
4160
|
+
// the two genuinely can differ. An earlier version tore down the parked
|
|
4161
|
+
// id in the CALLER and would have missed the orphan entirely in that
|
|
4162
|
+
// case, leaving a live session AND a re-parked entry for the same
|
|
4163
|
+
// restore (Copilot, #7630 review).
|
|
4164
|
+
//
|
|
4165
|
+
// Doing it here rather than in each caller also covers the boot path,
|
|
4166
|
+
// whose catch re-parks without any orphan check of its own.
|
|
4167
|
+
this._teardownHalfSeededSession(sessionId)
|
|
4168
|
+
throw err
|
|
4169
|
+
}
|
|
4170
|
+
return sessionId
|
|
4171
|
+
}
|
|
4172
|
+
|
|
4173
|
+
/**
|
|
4174
|
+
* Restore session state from disk after a restart.
|
|
2514
4175
|
* Creates new sessions using saved parameters. SdkSession can resume
|
|
2515
4176
|
* via resumeSessionId; CliSession starts fresh (process state is ephemeral).
|
|
2516
4177
|
* @returns {string|null} The first restored session ID, or null
|
|
@@ -2537,6 +4198,15 @@ export class SessionManager extends EventEmitter {
|
|
|
2537
4198
|
log.warn(`user-shell orphan reaper failed (non-fatal): ${err?.message || err}`)
|
|
2538
4199
|
}
|
|
2539
4200
|
|
|
4201
|
+
// Age out expired archive records on EVERY boot (even with archiving turned
|
|
4202
|
+
// off, and before the no-prior-state early return): retention must not
|
|
4203
|
+
// depend on a new session ending. Best-effort — never affects boot.
|
|
4204
|
+
try {
|
|
4205
|
+
this._sessionArchive.prune()
|
|
4206
|
+
} catch (err) {
|
|
4207
|
+
log.warn(`session archive prune failed (non-fatal): ${getErrorMessage(err, 'unknown error')}`)
|
|
4208
|
+
}
|
|
4209
|
+
|
|
2540
4210
|
const state = this._persistence.restoreState()
|
|
2541
4211
|
if (!state) return null
|
|
2542
4212
|
|
|
@@ -2545,151 +4215,14 @@ export class SessionManager extends EventEmitter {
|
|
|
2545
4215
|
let firstId = null
|
|
2546
4216
|
let anyFailure = false
|
|
2547
4217
|
const oldToNew = new Map() // old serialized session ID → new session ID
|
|
4218
|
+
// #8259: no seq-reservation write while sessions are still being restored (it would
|
|
4219
|
+
// drop the ones not yet restored); the flush after the loop carries the reservations.
|
|
4220
|
+
this._restoringHistory = (this._restoringHistory || 0) + 1
|
|
4221
|
+
try {
|
|
2548
4222
|
for (const saved of state.sessions) {
|
|
2549
4223
|
try {
|
|
2550
|
-
|
|
2551
|
-
// restoreState, after history and cost budget have been reseeded.
|
|
2552
|
-
// Flushing per-session here would overwrite the on-disk file with
|
|
2553
|
-
// empty history for all not-yet-processed sessions, erasing the
|
|
2554
|
-
// data we're trying to restore.
|
|
2555
|
-
const sessionId = this.createSession({
|
|
2556
|
-
// #4983 — reuse the persisted ID so dashboard's localStorage-
|
|
2557
|
-
// cached activeSessionId still resolves after a daemon restart.
|
|
2558
|
-
// createSession validates the format (32-char lower-case hex);
|
|
2559
|
-
// a malformed or duplicate id falls back to randomBytes so the
|
|
2560
|
-
// call still succeeds. The dashboard's #4982 SESSION_NOT_FOUND
|
|
2561
|
-
// chip is the safety net for the malformed/missing/cross-host
|
|
2562
|
-
// cases that this preservation can't help with.
|
|
2563
|
-
preserveId: saved.id,
|
|
2564
|
-
name: saved.name,
|
|
2565
|
-
cwd: saved.cwd,
|
|
2566
|
-
model: saved.model,
|
|
2567
|
-
permissionMode: saved.permissionMode,
|
|
2568
|
-
resumeSessionId: saved.sdkSessionId,
|
|
2569
|
-
provider: saved.provider || undefined,
|
|
2570
|
-
// #5310 (WP-0.4) — rebind to the existing worktree (don't recreate).
|
|
2571
|
-
// Only string paths flow through; non-worktree sessions and older
|
|
2572
|
-
// state files (no field) pass undefined and take the normal path.
|
|
2573
|
-
restoreWorktreePath: typeof saved.worktreePath === 'string' && saved.worktreePath.length > 0
|
|
2574
|
-
? saved.worktreePath
|
|
2575
|
-
: undefined,
|
|
2576
|
-
restoreWorktreeRepoDir: typeof saved.worktreeRepoDir === 'string' && saved.worktreeRepoDir.length > 0
|
|
2577
|
-
? saved.worktreeRepoDir
|
|
2578
|
-
: undefined,
|
|
2579
|
-
// #4664: restore per-session toggle/string settings via the
|
|
2580
|
-
// shared registry. Each registry entry's `acceptFromConstructor`
|
|
2581
|
-
// predicate drops malformed values to `undefined` so
|
|
2582
|
-
// createSession applies BaseSession's default — exact match for
|
|
2583
|
-
// the pre-refactor per-knob behaviour, and older state files
|
|
2584
|
-
// (without these fields) round-trip cleanly.
|
|
2585
|
-
...restorePerSessionSettings(saved),
|
|
2586
|
-
// #3639: forward the persisted skip-pattern source. Non-string /
|
|
2587
|
-
// empty values are dropped (createSession ignores them) so older
|
|
2588
|
-
// state files restore as null. Kept out of the registry because
|
|
2589
|
-
// the empty-string-as-null wire shape doesn't fit the
|
|
2590
|
-
// boolean/string factory.
|
|
2591
|
-
promptEvaluatorSkipPattern: typeof saved.promptEvaluatorSkipPattern === 'string' && saved.promptEvaluatorSkipPattern.length > 0
|
|
2592
|
-
? saved.promptEvaluatorSkipPattern
|
|
2593
|
-
: undefined,
|
|
2594
|
-
// #3540: forward the persisted stdin_disabled latch. Only
|
|
2595
|
-
// truthy values flip the flag; pre-#3540 state files (no
|
|
2596
|
-
// field) restore as `false`. The SdkSession constructor
|
|
2597
|
-
// initialises `_stdinForwardingDisabled` from this opt and
|
|
2598
|
-
// the existing `_attachSidecarProcessListeners` short-circuit
|
|
2599
|
-
// ensures no warn/error is re-emitted on restore — clients
|
|
2600
|
-
// observe the disabled state via session_list metadata.
|
|
2601
|
-
stdinForwardingDisabled: saved.stdinForwardingDisabled === true ? true : undefined,
|
|
2602
|
-
// #6824: forward the persisted parked MCP server set so the respawned
|
|
2603
|
-
// BYOK fleet skips starting them. Non-array / empty values are
|
|
2604
|
-
// dropped (createSession only forwards a non-empty string array), so
|
|
2605
|
-
// older state files restore with nothing parked.
|
|
2606
|
-
disabledMcpServers: Array.isArray(saved.disabledMcpServers) && saved.disabledMcpServers.length > 0
|
|
2607
|
-
? saved.disabledMcpServers.filter((n) => typeof n === 'string')
|
|
2608
|
-
: undefined,
|
|
2609
|
-
// Restore the previously-booted model (#3700b) so the dashboard
|
|
2610
|
-
// dropdown shows the real model on reconnect, not the registry
|
|
2611
|
-
// fallback. createSession() ignores non-string / empty values so
|
|
2612
|
-
// older state files (pre-#3700b) restore cleanly as null.
|
|
2613
|
-
bootedModel: typeof saved.bootedModel === 'string' && saved.bootedModel.length > 0
|
|
2614
|
-
? saved.bootedModel
|
|
2615
|
-
: undefined,
|
|
2616
|
-
// Restore the messageId counter so new turns don't reuse old IDs
|
|
2617
|
-
// and collide with dashboard-cached messages (#3700).
|
|
2618
|
-
messageCounter: typeof saved.messageCounter === 'number' && Number.isFinite(saved.messageCounter) && saved.messageCounter >= 0
|
|
2619
|
-
? saved.messageCounter
|
|
2620
|
-
: undefined,
|
|
2621
|
-
// Mailbox (#5914 follow-up): re-register the persisted AGENT_COMM_ID so
|
|
2622
|
-
// a restored session is reachable by the live-interrupt route again.
|
|
2623
|
-
// createSession validates it (drops bad values to a no-op); older
|
|
2624
|
-
// state files (no field) restore with no mailbox identity.
|
|
2625
|
-
agentCommId: typeof saved.agentCommId === 'string' && saved.agentCommId.length > 0
|
|
2626
|
-
? saved.agentCommId
|
|
2627
|
-
: undefined,
|
|
2628
|
-
skipPersist: true,
|
|
2629
|
-
// #5316 (WP-2.2) — mark this as a restore so an ASYNC provider
|
|
2630
|
-
// start() rejection (claude-tui PTY warmup death) preserves the
|
|
2631
|
-
// restored history + worktree instead of destroying them.
|
|
2632
|
-
isRestore: true,
|
|
2633
|
-
})
|
|
4224
|
+
const sessionId = this._attemptRestoreOne(saved, hasVersion)
|
|
2634
4225
|
if (saved.id) oldToNew.set(saved.id, sessionId)
|
|
2635
|
-
// #4089 / #4124: restore the per-session running totals + the
|
|
2636
|
-
// threshold-notified latch onto the freshly-created entry. We do
|
|
2637
|
-
// this AFTER createSession so the entry exists, and BEFORE
|
|
2638
|
-
// history replay so a synthetic result event during replay
|
|
2639
|
-
// (unlikely but defensive) doesn't double-count. Validate shape:
|
|
2640
|
-
// missing / corrupt cumulativeUsage falls back to all-zero;
|
|
2641
|
-
// non-boolean costThresholdNotified falls back to false.
|
|
2642
|
-
//
|
|
2643
|
-
// Per-field clamps:
|
|
2644
|
-
// - Token counts + turnsBilled are monotonic counters; corrupt
|
|
2645
|
-
// state with negatives clamps to 0.
|
|
2646
|
-
// - costUsd accepts negatives per #4099 (refund / credit
|
|
2647
|
-
// adjustments). Only non-finite values fall back to 0.
|
|
2648
|
-
const restoredEntry = this._sessions.get(sessionId)
|
|
2649
|
-
// #7082: the restore path reads ~/.chroxy/session-state.json, so a hand-edited
|
|
2650
|
-
// or corrupt file can carry a fractional / past-2^53 / negative counter straight
|
|
2651
|
-
// into the live snapshot. Same coercion as the accumulate path above.
|
|
2652
|
-
if (restoredEntry) {
|
|
2653
|
-
if (saved.cumulativeUsage && typeof saved.cumulativeUsage === 'object') {
|
|
2654
|
-
const u = saved.cumulativeUsage
|
|
2655
|
-
restoredEntry.cumulativeUsage = {
|
|
2656
|
-
inputTokens: toWireCount(u.inputTokens),
|
|
2657
|
-
outputTokens: toWireCount(u.outputTokens),
|
|
2658
|
-
cacheReadTokens: toWireCount(u.cacheReadTokens),
|
|
2659
|
-
cacheCreationTokens: toWireCount(u.cacheCreationTokens),
|
|
2660
|
-
// costUsd is NOT coerced: `z.number().finite()` with no `.int()`, and
|
|
2661
|
-
// legitimately negative for a refund / credit adjustment (#4099).
|
|
2662
|
-
costUsd: Number.isFinite(u.costUsd) ? u.costUsd : 0,
|
|
2663
|
-
turnsBilled: toWireCount(u.turnsBilled),
|
|
2664
|
-
}
|
|
2665
|
-
}
|
|
2666
|
-
if (saved.costThresholdNotified === true) {
|
|
2667
|
-
restoredEntry.costThresholdNotified = true
|
|
2668
|
-
}
|
|
2669
|
-
}
|
|
2670
|
-
// Keep _sessionCounter ahead of any restored "Session N" names so the
|
|
2671
|
-
// first new auto-named session after restore never collides (#2338).
|
|
2672
|
-
if (saved.name) {
|
|
2673
|
-
const match = saved.name.match(/^Session (\d+)$/)
|
|
2674
|
-
if (match) {
|
|
2675
|
-
const n = parseInt(match[1], 10)
|
|
2676
|
-
if (n > this._sessionCounter) this._sessionCounter = n
|
|
2677
|
-
}
|
|
2678
|
-
}
|
|
2679
|
-
// Restore message history if present (v1+).
|
|
2680
|
-
// Sweep any `tool_start` that lacks a matching `tool_result` and
|
|
2681
|
-
// splice in a synthetic interrupted result (#4617) BEFORE seeding
|
|
2682
|
-
// history so the subsequent dashboard history replay never sees a
|
|
2683
|
-
// dangling tool_start. Without this, an unresolved tool_use from
|
|
2684
|
-
// before shutdown re-enters `activeTools` on replay and never gets
|
|
2685
|
-
// cleared — the footer shows "Running X · Nh Mm" forever.
|
|
2686
|
-
if (hasVersion && Array.isArray(saved.history) && saved.history.length > 0) {
|
|
2687
|
-
const swept = SessionMessageHistory.sweepUnresolvedToolStarts(saved.history)
|
|
2688
|
-
this._history.setHistory(sessionId, swept)
|
|
2689
|
-
}
|
|
2690
|
-
if (typeof saved.lastActivityAt === 'number' && Number.isFinite(saved.lastActivityAt) && saved.lastActivityAt > 0) {
|
|
2691
|
-
this._sessionLastActivityAt.set(sessionId, saved.lastActivityAt)
|
|
2692
|
-
}
|
|
2693
4226
|
if (!firstId) firstId = sessionId
|
|
2694
4227
|
log.info(`Restored session "${saved.name}" (SDK resume: ${saved.sdkSessionId || 'none'})`)
|
|
2695
4228
|
} catch (err) {
|
|
@@ -2701,14 +4234,100 @@ export class SessionManager extends EventEmitter {
|
|
|
2701
4234
|
// Advance _sessionCounter past failed "Session N" names too, so any
|
|
2702
4235
|
// new sessions created during this boot don't collide with the name
|
|
2703
4236
|
// still occupying disk state.
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
2708
|
-
|
|
2709
|
-
|
|
4237
|
+
this._advanceSessionCounterPast(saved.name)
|
|
4238
|
+
log.error(`Failed to restore session ${JSON.stringify(String(saved.name))} (${saved.provider || 'default'}): ${err.message}`)
|
|
4239
|
+
this.emit('session_restore_failed', {
|
|
4240
|
+
sessionId: failedId,
|
|
4241
|
+
name: saved.name,
|
|
4242
|
+
provider: saved.provider || this._providerType,
|
|
4243
|
+
cwd: saved.cwd,
|
|
4244
|
+
model: saved.model || null,
|
|
4245
|
+
permissionMode: saved.permissionMode || null,
|
|
4246
|
+
errorCode: err?.code || 'RESTORE_FAILED',
|
|
4247
|
+
errorMessage: err?.message || String(err),
|
|
4248
|
+
originalHistoryPreserved: true,
|
|
4249
|
+
historyLength: Array.isArray(saved.history) ? saved.history.length : 0,
|
|
4250
|
+
})
|
|
4251
|
+
}
|
|
4252
|
+
}
|
|
4253
|
+
} finally {
|
|
4254
|
+
this._restoringHistory -= 1
|
|
4255
|
+
}
|
|
4256
|
+
|
|
4257
|
+
// #7627 — the sessions the 24h staleness filter set aside. They are NOT
|
|
4258
|
+
// restored: that policy is unchanged, and a stale session that would come
|
|
4259
|
+
// back fine is still dropped here by simply not being touched. But a stale
|
|
4260
|
+
// session whose restore would REFUSE is a different thing — #2954 promises
|
|
4261
|
+
// its history is preserved for the operator, and deleting it unseen made
|
|
4262
|
+
// that promise false for anything last active more than 24h ago, which is
|
|
4263
|
+
// the ordinary "daemon was down overnight" case. Resolving the binding is
|
|
4264
|
+
// cheap and constructs nothing, so ask, and register the refusals.
|
|
4265
|
+
let droppedStale = 0
|
|
4266
|
+
for (const saved of Array.isArray(state.staleSessions) ? state.staleSessions : []) {
|
|
4267
|
+
// Bounded by the failed-restore TTL, not resurrected forever: past that
|
|
4268
|
+
// horizon the entry is dropped exactly as before. The worktree exemption
|
|
4269
|
+
// mirrors `_pruneStaleFailedRestores` deliberately — #2954 keeps a
|
|
4270
|
+
// worktree-backed entry at ANY age, because dropping its id exposes the
|
|
4271
|
+
// worktree to the orphan sweep, whose clean-tree guard cannot see
|
|
4272
|
+
// committed-but-unreachable `--detach` commits. Both bounds must agree or
|
|
4273
|
+
// one of them silently overrides the other, which is this whole issue.
|
|
4274
|
+
const last = (typeof saved?.lastActivityAt === 'number' && saved.lastActivityAt > 0)
|
|
4275
|
+
? saved.lastActivityAt
|
|
4276
|
+
: (typeof saved?.createdAt === 'number' && saved.createdAt > 0 ? saved.createdAt : null)
|
|
4277
|
+
const pastTtl = last !== null && Number.isFinite(last) && Date.now() - last > FAILED_RESTORE_TTL_MS
|
|
4278
|
+
if (pastTtl && !saved?.worktreePath) {
|
|
4279
|
+
// Dropped for good past the failed-restore TTL: keep what chroxy held. If
|
|
4280
|
+
// the archive write FAILED the entry is dropped anyway (bounded, as
|
|
4281
|
+
// before the archive existed), loudly.
|
|
4282
|
+
if (this._archiveSaved(saved, 'stale') === 'failed') {
|
|
4283
|
+
log.warn(`Stale session ${JSON.stringify(String(saved?.name))} is past the failed-restore TTL and could not be archived; dropping it`)
|
|
4284
|
+
}
|
|
4285
|
+
droppedStale++
|
|
4286
|
+
continue
|
|
4287
|
+
}
|
|
4288
|
+
// #8858 — an entry that was ALREADY parked by an earlier boot stays parked.
|
|
4289
|
+
// Its restore failed, usually for a reason this method cannot see (missing
|
|
4290
|
+
// cwd, deleted worktree, no native locator), so "the container binding
|
|
4291
|
+
// resolves" says nothing about whether it would restore. Re-register it
|
|
4292
|
+
// with its persisted error instead of letting the clause below drop it.
|
|
4293
|
+
const parked = this._parkedMarker(saved)
|
|
4294
|
+
if (parked) {
|
|
4295
|
+
anyFailure = true
|
|
4296
|
+
const err = Object.assign(new Error(parked.message), { code: parked.code })
|
|
4297
|
+
const failedId = this._registerFailedRestore(saved, err)
|
|
4298
|
+
this._advanceSessionCounterPast(saved.name)
|
|
4299
|
+
log.warn(`Stale session ${JSON.stringify(String(saved.name))} stays parked as a failed restore: ${err.message}`)
|
|
4300
|
+
this.emit('session_restore_failed', {
|
|
4301
|
+
sessionId: failedId,
|
|
4302
|
+
name: saved.name,
|
|
4303
|
+
provider: saved.provider || this._providerType,
|
|
4304
|
+
cwd: saved.cwd,
|
|
4305
|
+
model: saved.model || null,
|
|
4306
|
+
permissionMode: saved.permissionMode || null,
|
|
4307
|
+
errorCode: err.code,
|
|
4308
|
+
errorMessage: err.message,
|
|
4309
|
+
originalHistoryPreserved: true,
|
|
4310
|
+
historyLength: Array.isArray(saved.history) ? saved.history.length : 0,
|
|
4311
|
+
})
|
|
4312
|
+
continue
|
|
4313
|
+
}
|
|
4314
|
+
try {
|
|
4315
|
+
this._resolveRestoredContainerBinding(saved)
|
|
4316
|
+
// It would have restored fine — it is merely stale. Not restored and
|
|
4317
|
+
// not parked, and dropped from disk on the next write — but its history
|
|
4318
|
+
// is archived first, so it stays readable (archive-before-flush).
|
|
4319
|
+
// If the archive write FAILED, the snapshot is retained (see
|
|
4320
|
+
// `_unarchivedStale`) so no later state write can drop the only copy.
|
|
4321
|
+
if (this._archiveSaved(saved, 'stale') === 'failed') {
|
|
4322
|
+
this._unarchivedStale.set(this._unarchivedStaleKey(saved), saved)
|
|
4323
|
+
log.warn(`Stale session ${JSON.stringify(String(saved?.name))} could not be archived; keeping it in the state file and retrying`)
|
|
2710
4324
|
}
|
|
2711
|
-
|
|
4325
|
+
droppedStale++
|
|
4326
|
+
} catch (err) {
|
|
4327
|
+
anyFailure = true
|
|
4328
|
+
const failedId = this._registerFailedRestore(saved, err)
|
|
4329
|
+
this._advanceSessionCounterPast(saved.name)
|
|
4330
|
+
log.warn(`Stale session ${JSON.stringify(String(saved.name))} cannot be restored and was kept for review: ${err.message}`)
|
|
2712
4331
|
this.emit('session_restore_failed', {
|
|
2713
4332
|
sessionId: failedId,
|
|
2714
4333
|
name: saved.name,
|
|
@@ -2724,6 +4343,34 @@ export class SessionManager extends EventEmitter {
|
|
|
2724
4343
|
}
|
|
2725
4344
|
}
|
|
2726
4345
|
|
|
4346
|
+
// #7627 — a boot with nothing restored AND nothing registered must return
|
|
4347
|
+
// here, exactly as it did when persistence returned null for an all-stale
|
|
4348
|
+
// file. Everything below is the tail that runs for a boot that produced
|
|
4349
|
+
// something, and letting it run on an empty one changed behaviour unrelated
|
|
4350
|
+
// to this fix: `_costBudget.restore` re-loads the cost map of sessions just
|
|
4351
|
+
// dropped, and an all-stale boot with no refusal is the only occasion those
|
|
4352
|
+
// dead entries are collected — every other boot round-trips them.
|
|
4353
|
+
//
|
|
4354
|
+
// Note what this does NOT restore: once a refusal is preserved, its frozen
|
|
4355
|
+
// `lastActivityAt` keeps `anyFailure` true on every later boot, so that
|
|
4356
|
+
// collection occasion is disabled for as long as the entry lives. Pre-existing
|
|
4357
|
+
// — base behaves the same for any sub-24h reboot cadence, since the collection
|
|
4358
|
+
// only ever happened on a boot that restored nothing at all — but the cost map
|
|
4359
|
+
// is not self-collecting while a needs-attention entry exists, and that is
|
|
4360
|
+
// worth knowing before treating this early return as a complete answer.
|
|
4361
|
+
//
|
|
4362
|
+
// One exception, for the session archive: when archiving is on and stale
|
|
4363
|
+
// entries were dropped, write the state now. A boot that restored nothing
|
|
4364
|
+
// would otherwise leave them in the state file until some later write, so
|
|
4365
|
+
// every such boot would archive them again, including after the user deleted
|
|
4366
|
+
// the archived copy or retention aged it out. The write is the same one the
|
|
4367
|
+
// next session mutation would make: no sessions, and a cost map without the
|
|
4368
|
+
// dead entries (the collection described above, done now).
|
|
4369
|
+
if (!firstId && !anyFailure) {
|
|
4370
|
+
if (droppedStale > 0 && this._sessionArchive.retentionPolicy().enabled) this._flushPersist()
|
|
4371
|
+
return null
|
|
4372
|
+
}
|
|
4373
|
+
|
|
2727
4374
|
// Restore cost tracking data (v1+), remapping old IDs to new IDs.
|
|
2728
4375
|
this._costBudget.restore(state, oldToNew.size > 0 ? oldToNew : null)
|
|
2729
4376
|
|
|
@@ -2760,7 +4407,7 @@ export class SessionManager extends EventEmitter {
|
|
|
2760
4407
|
// retained sessions are ever swept.
|
|
2761
4408
|
const liveSessionIds = new Set([...this._sessions.keys(), ...this._failedRestores.keys()])
|
|
2762
4409
|
const report = sweepOrphanChroxyWorktrees({
|
|
2763
|
-
worktreeBase: this._worktreeBase ||
|
|
4410
|
+
worktreeBase: this._worktreeBase || defaultWorktreeBase(),
|
|
2764
4411
|
liveSessionIds,
|
|
2765
4412
|
})
|
|
2766
4413
|
if (report.removed.length || report.skippedDirty.length || report.skippedError.length) {
|
|
@@ -2782,6 +4429,70 @@ export class SessionManager extends EventEmitter {
|
|
|
2782
4429
|
* @returns {string} sessionId
|
|
2783
4430
|
* @private
|
|
2784
4431
|
*/
|
|
4432
|
+
/**
|
|
4433
|
+
* Tear down a session that was CREATED but could not be fully re-seeded, so
|
|
4434
|
+
* its parked entry can be restored verbatim (#7625 review).
|
|
4435
|
+
*
|
|
4436
|
+
* The window this closes: `_attemptRestoreOne` calls createSession() and then
|
|
4437
|
+
* re-seeds usage counters, the name counter, history and lastActivityAt. A
|
|
4438
|
+
* throw in that TAIL leaves a live-but-half-seeded session in `_sessions` —
|
|
4439
|
+
* with NO history, because the seed never ran, and with a lastActivityAt of
|
|
4440
|
+
* `now` from createSession's own touchActivity rather than the frozen value
|
|
4441
|
+
* #7627 depends on.
|
|
4442
|
+
*
|
|
4443
|
+
* The first version of the retry treated that as "keep the live session, it
|
|
4444
|
+
* is usable" and flushed it. Review reproduced what that costs: the preserved
|
|
4445
|
+
* conversation is gone, the freeze is thawed, and the loss is written to disk
|
|
4446
|
+
* immediately — on the one feature whose entire purpose is that a failed
|
|
4447
|
+
* restore loses nothing. Keeping the half-seeded session is the wrong trade.
|
|
4448
|
+
*
|
|
4449
|
+
* So: detach and destroy ONLY the live provider and drop the in-process maps,
|
|
4450
|
+
* exactly as `_handleAsyncStartFailure` does. The WORKTREE is deliberately
|
|
4451
|
+
* left intact — that is what makes the next retry able to succeed — and the
|
|
4452
|
+
* caller re-parks the ORIGINAL `saved`, which still holds the history and the
|
|
4453
|
+
* frozen timestamp.
|
|
4454
|
+
*
|
|
4455
|
+
* @param {string} sessionId
|
|
4456
|
+
*/
|
|
4457
|
+
_teardownHalfSeededSession(sessionId) {
|
|
4458
|
+
const entry = this._sessions.get(sessionId)
|
|
4459
|
+
if (!entry) return
|
|
4460
|
+
try {
|
|
4461
|
+
entry.session?.removeAllListeners?.()
|
|
4462
|
+
entry.session?.on?.('error', () => {}) // swallow a stray error during destroy
|
|
4463
|
+
entry.session?.destroy?.()
|
|
4464
|
+
} catch (destroyErr) {
|
|
4465
|
+
log.error(`Failed to destroy provider for half-seeded restore ${sessionId}: ${destroyErr?.stack || destroyErr}`)
|
|
4466
|
+
}
|
|
4467
|
+
this._cleanupSessionMaps(sessionId)
|
|
4468
|
+
}
|
|
4469
|
+
|
|
4470
|
+
/**
|
|
4471
|
+
* #8858 — the durable "this entry is parked" marker `serializeState` writes.
|
|
4472
|
+
* Code and message only (message capped), so the Control Room row reads the
|
|
4473
|
+
* same after a restart that skipped the live attempt.
|
|
4474
|
+
* @private
|
|
4475
|
+
*/
|
|
4476
|
+
_failedRestoreMarker(err) {
|
|
4477
|
+
return {
|
|
4478
|
+
code: err?.code || 'RESTORE_FAILED',
|
|
4479
|
+
message: String(err?.message || err || 'restore failed').slice(0, FAILED_RESTORE_MARKER_MAX_MESSAGE),
|
|
4480
|
+
}
|
|
4481
|
+
}
|
|
4482
|
+
|
|
4483
|
+
/**
|
|
4484
|
+
* #8858 — read the marker back from a persisted entry. Returns null for an
|
|
4485
|
+
* entry without a well-formed marker (an older state file, or one hand-edited
|
|
4486
|
+
* into nonsense) so such an entry follows the pre-existing path.
|
|
4487
|
+
* @private
|
|
4488
|
+
*/
|
|
4489
|
+
_parkedMarker(saved) {
|
|
4490
|
+
const m = saved?.failedRestore
|
|
4491
|
+
if (!m || typeof m !== 'object') return null
|
|
4492
|
+
if (typeof m.code !== 'string' || m.code === '' || typeof m.message !== 'string') return null
|
|
4493
|
+
return { code: m.code, message: m.message.slice(0, FAILED_RESTORE_MARKER_MAX_MESSAGE) }
|
|
4494
|
+
}
|
|
4495
|
+
|
|
2785
4496
|
_registerFailedRestore(saved, err) {
|
|
2786
4497
|
// Reuse the saved id when present so the client-visible identity is
|
|
2787
4498
|
// stable across restart attempts; fall back to a random id otherwise.
|
|
@@ -2790,6 +4501,24 @@ export class SessionManager extends EventEmitter {
|
|
|
2790
4501
|
return sessionId
|
|
2791
4502
|
}
|
|
2792
4503
|
|
|
4504
|
+
/**
|
|
4505
|
+
* Keep `_sessionCounter` ahead of any "Session N" name still occupying disk
|
|
4506
|
+
* state, so the first new auto-named session after a restore cannot collide
|
|
4507
|
+
* (#2338). Every restore outcome must call this — a restored session, a fresh
|
|
4508
|
+
* failure, and a #7627 preserved stale refusal all leave a name on disk, and a
|
|
4509
|
+
* path that skips it makes a needs-attention entry indistinguishable from a
|
|
4510
|
+
* live session. It was three copies of this regex before #7627 added a fourth
|
|
4511
|
+
* caller; one definition now.
|
|
4512
|
+
* @private
|
|
4513
|
+
*/
|
|
4514
|
+
_advanceSessionCounterPast(name) {
|
|
4515
|
+
if (!name) return
|
|
4516
|
+
const match = String(name).match(/^Session (\d+)$/)
|
|
4517
|
+
if (!match) return
|
|
4518
|
+
const n = parseInt(match[1], 10)
|
|
4519
|
+
if (n > this._sessionCounter) this._sessionCounter = n
|
|
4520
|
+
}
|
|
4521
|
+
|
|
2793
4522
|
/**
|
|
2794
4523
|
* Drop failed-restore entries whose session has been inactive longer than the
|
|
2795
4524
|
* TTL, so a chronically-failing session can't grow _failedRestores +
|
|
@@ -2804,7 +4533,7 @@ export class SessionManager extends EventEmitter {
|
|
|
2804
4533
|
* @returns {number} count pruned
|
|
2805
4534
|
*/
|
|
2806
4535
|
_pruneStaleFailedRestores(now = Date.now()) {
|
|
2807
|
-
const TTL_MS =
|
|
4536
|
+
const TTL_MS = FAILED_RESTORE_TTL_MS
|
|
2808
4537
|
let pruned = 0
|
|
2809
4538
|
for (const [sessionId, entry] of this._failedRestores) {
|
|
2810
4539
|
const saved = entry?.saved
|
|
@@ -2819,50 +4548,787 @@ export class SessionManager extends EventEmitter {
|
|
|
2819
4548
|
? saved.lastActivityAt
|
|
2820
4549
|
: (typeof saved?.createdAt === 'number' && saved.createdAt > 0 ? saved.createdAt : null)
|
|
2821
4550
|
if (last !== null && Number.isFinite(last) && now - last > TTL_MS) {
|
|
4551
|
+
// Archive BEFORE the entry is dropped (and before the flush that removes
|
|
4552
|
+
// it from disk), so a crash leaves a duplicate the archive dedupes. If the
|
|
4553
|
+
// archive write FAILED the entry stays: #2954 promises its history is
|
|
4554
|
+
// preserved, and this is the only copy. It is retried on the next boot.
|
|
4555
|
+
if (this._archiveSaved(saved, 'failed_restore_expired') === 'failed') {
|
|
4556
|
+
log.warn(`Kept stale failed-restore ${JSON.stringify(String(saved?.name || sessionId))}: it could not be archived first (retried next boot)`)
|
|
4557
|
+
continue
|
|
4558
|
+
}
|
|
2822
4559
|
this._failedRestores.delete(sessionId)
|
|
2823
4560
|
pruned++
|
|
2824
4561
|
log.info(`Pruned stale failed-restore "${saved?.name || sessionId}" (inactive since ${new Date(last).toISOString()})`)
|
|
2825
4562
|
}
|
|
2826
4563
|
}
|
|
2827
|
-
if (pruned > 0) log.info(`Pruned ${pruned} stale failed-restore session(s) (inactive > 30d)`)
|
|
2828
|
-
return pruned
|
|
2829
|
-
}
|
|
4564
|
+
if (pruned > 0) log.info(`Pruned ${pruned} stale failed-restore session(s) (inactive > 30d)`)
|
|
4565
|
+
return pruned
|
|
4566
|
+
}
|
|
4567
|
+
|
|
4568
|
+
/**
|
|
4569
|
+
* Return the list of sessions that failed to restore at startup.
|
|
4570
|
+
* UI uses this to show a "needs attention" state with a retry affordance.
|
|
4571
|
+
* @returns {Array<{ sessionId, name, provider, errorCode, errorMessage, needsAttention, historyLength }>}
|
|
4572
|
+
*/
|
|
4573
|
+
getFailedRestores() {
|
|
4574
|
+
const list = []
|
|
4575
|
+
for (const [sessionId, { saved, error }] of this._failedRestores) {
|
|
4576
|
+
list.push({
|
|
4577
|
+
sessionId,
|
|
4578
|
+
name: saved.name,
|
|
4579
|
+
provider: saved.provider || this._providerType,
|
|
4580
|
+
agentConnection: saved.agentConnection || undefined,
|
|
4581
|
+
cwd: saved.cwd,
|
|
4582
|
+
model: saved.model || null,
|
|
4583
|
+
permissionMode: saved.permissionMode || null,
|
|
4584
|
+
errorCode: error?.code || 'RESTORE_FAILED',
|
|
4585
|
+
errorMessage: error?.message || String(error),
|
|
4586
|
+
needsAttention: true,
|
|
4587
|
+
historyLength: Array.isArray(saved.history) ? saved.history.length : 0,
|
|
4588
|
+
})
|
|
4589
|
+
}
|
|
4590
|
+
return list
|
|
4591
|
+
}
|
|
4592
|
+
|
|
4593
|
+
/**
|
|
4594
|
+
* Archive a saved session entry SYNCHRONOUSLY and report the outcome. NEVER
|
|
4595
|
+
* throws. The callers that are about to DROP the only copy of a session (the
|
|
4596
|
+
* failed-restore TTL prune, a dismissed failed restore, a stale boot entry)
|
|
4597
|
+
* use the status: on 'failed' they keep the source where they have a choice.
|
|
4598
|
+
* @param {object} saved - a serialized session entry
|
|
4599
|
+
* @param {string} reason
|
|
4600
|
+
* @returns {'archived'|'duplicate'|'skipped'|'failed'}
|
|
4601
|
+
*/
|
|
4602
|
+
_archiveSaved(saved, reason) {
|
|
4603
|
+
try {
|
|
4604
|
+
const status = this._sessionArchive.archiveOutcome(saved, reason)?.status
|
|
4605
|
+
return status === 'archived' || status === 'duplicate' || status === 'skipped' ? status : 'failed'
|
|
4606
|
+
} catch (err) {
|
|
4607
|
+
log.warn(`Session archive failed (${reason}): ${getErrorMessage(err, 'unknown error')}`)
|
|
4608
|
+
return 'failed'
|
|
4609
|
+
}
|
|
4610
|
+
}
|
|
4611
|
+
|
|
4612
|
+
_unarchivedStaleKey(saved) {
|
|
4613
|
+
return typeof saved?.id === 'string' && saved.id ? saved.id : `unarchived-${this._unarchivedStale.size}-${Date.now()}`
|
|
4614
|
+
}
|
|
4615
|
+
|
|
4616
|
+
/**
|
|
4617
|
+
* Retry the archive of the retained stale snapshots; each one whose archive is
|
|
4618
|
+
* now satisfied (archived, duplicate or skipped) leaves the map and the state
|
|
4619
|
+
* file. Runs on the retention timer.
|
|
4620
|
+
*/
|
|
4621
|
+
_retryUnarchivedStale() {
|
|
4622
|
+
if (this._unarchivedStale.size === 0) return
|
|
4623
|
+
let changed = false
|
|
4624
|
+
for (const [key, saved] of [...this._unarchivedStale]) {
|
|
4625
|
+
if (this._archiveSaved(saved, 'stale') === 'failed') continue
|
|
4626
|
+
this._unarchivedStale.delete(key)
|
|
4627
|
+
changed = true
|
|
4628
|
+
}
|
|
4629
|
+
if (changed) this._flushPersist()
|
|
4630
|
+
}
|
|
4631
|
+
|
|
4632
|
+
/**
|
|
4633
|
+
* Snapshot a LIVE entry (before its history is dropped) and hand it to the
|
|
4634
|
+
* archive's off-event-loop queue. The snapshot and its JSON are taken
|
|
4635
|
+
* synchronously here (the cost the state persist already pays); compression
|
|
4636
|
+
* and the write happen later, so closing a session never stalls the daemon.
|
|
4637
|
+
* A failure is logged and never blocks the teardown, which proceeds exactly as
|
|
4638
|
+
* it did before the archive existed.
|
|
4639
|
+
*/
|
|
4640
|
+
_queueLiveEntryForArchive(sessionId, entry, reason) {
|
|
4641
|
+
try {
|
|
4642
|
+
const saved = this._serializeSessionEntry(sessionId, entry)
|
|
4643
|
+
if (saved && saved.createdAt == null && typeof entry.createdAt === 'number') saved.createdAt = entry.createdAt
|
|
4644
|
+
const status = this._sessionArchive.enqueue(saved, reason)?.status
|
|
4645
|
+
if (status === 'failed') log.warn(`Session ${sessionId} was closed but could not be archived`)
|
|
4646
|
+
return status
|
|
4647
|
+
} catch (err) {
|
|
4648
|
+
log.warn(`Could not snapshot session ${sessionId} for the archive: ${getErrorMessage(err, 'unknown error')}`)
|
|
4649
|
+
return 'failed'
|
|
4650
|
+
}
|
|
4651
|
+
}
|
|
4652
|
+
|
|
4653
|
+
/** Resolves once every just-closed session has been written to the archive. */
|
|
4654
|
+
async whenArchiveIdle() {
|
|
4655
|
+
await this._sessionArchive.whenIdle?.()
|
|
4656
|
+
}
|
|
4657
|
+
|
|
4658
|
+
/**
|
|
4659
|
+
* The archive roster, newest first, plus the retention policy that governs it.
|
|
4660
|
+
* @returns {{ policy: object, sessions: object[] }}
|
|
4661
|
+
*/
|
|
4662
|
+
listArchivedSessions() {
|
|
4663
|
+
const sessions = this._sessionArchive.list().map((row) => {
|
|
4664
|
+
const { locator, ...wire } = row
|
|
4665
|
+
return { ...wire, restore: this._archiveRestoreOptions(row, locator) }
|
|
4666
|
+
})
|
|
4667
|
+
return { policy: this._sessionArchive.retentionPolicy(), sessions }
|
|
4668
|
+
}
|
|
4669
|
+
|
|
4670
|
+
/**
|
|
4671
|
+
* #8866: what "continue" can mean for one archived session, from CHEAP checks
|
|
4672
|
+
* only (provider registered, a locator was recorded, the directory exists), so
|
|
4673
|
+
* the roster can enable or grey the two actions. It is advisory: the click
|
|
4674
|
+
* re-checks authoritatively (`restoreArchivedSession`), including that the
|
|
4675
|
+
* provider transcript is still on disk.
|
|
4676
|
+
*
|
|
4677
|
+
* native resume the SAME conversation (the boot / retry recipe)
|
|
4678
|
+
* newThread a brand-new session in the archived directory, seeded with the
|
|
4679
|
+
* archived transcript on its first message
|
|
4680
|
+
*
|
|
4681
|
+
* @param {{ provider: string|null, cwd: string|null }} meta
|
|
4682
|
+
* @param {boolean|null} locator - whether a provider conversation was recorded (`null` = unknown)
|
|
4683
|
+
* @returns {{ native: boolean, nativeReason?: string, newThread: boolean, newThreadReason?: string }}
|
|
4684
|
+
* @private
|
|
4685
|
+
*/
|
|
4686
|
+
_archiveRestoreOptions(meta, locator) {
|
|
4687
|
+
const providerName = meta.provider || this._providerType
|
|
4688
|
+
let ProviderClass = null
|
|
4689
|
+
try { ProviderClass = getProvider(providerName) } catch { /* unregistered: reported below */ }
|
|
4690
|
+
const common = this._archiveCommonRefusal(ProviderClass, providerName, meta.cwd)
|
|
4691
|
+
const out = { native: false, newThread: false }
|
|
4692
|
+
if (common) {
|
|
4693
|
+
out.nativeReason = common.message
|
|
4694
|
+
out.newThreadReason = common.message
|
|
4695
|
+
return out
|
|
4696
|
+
}
|
|
4697
|
+
out.newThread = true
|
|
4698
|
+
const nativeRefusal = this._archiveNativeRefusal(ProviderClass, providerName, locator)
|
|
4699
|
+
if (nativeRefusal) out.nativeReason = nativeRefusal.message
|
|
4700
|
+
else out.native = true
|
|
4701
|
+
return out
|
|
4702
|
+
}
|
|
4703
|
+
|
|
4704
|
+
/** Refusals that apply to BOTH modes. @returns {{code: string, message: string}|null} @private */
|
|
4705
|
+
_archiveCommonRefusal(ProviderClass, providerName, cwd) {
|
|
4706
|
+
if (!ProviderClass) {
|
|
4707
|
+
return { code: 'ARCHIVE_RESTORE_PROVIDER_UNAVAILABLE', message: `The "${providerName}" provider is not available on this server.` }
|
|
4708
|
+
}
|
|
4709
|
+
if (ProviderClass.isUserShell === true || providerName === USER_SHELL_PROVIDER) {
|
|
4710
|
+
return { code: 'ARCHIVE_RESTORE_FORBIDDEN_USER_SHELL', message: 'A user-shell session has no conversation to continue.' }
|
|
4711
|
+
}
|
|
4712
|
+
if (typeof cwd !== 'string' || cwd.length === 0 || !this._isDirectory(cwd)) {
|
|
4713
|
+
return { code: 'ARCHIVE_RESTORE_CWD_MISSING', message: 'The directory this session ran in no longer exists.' }
|
|
4714
|
+
}
|
|
4715
|
+
return null
|
|
4716
|
+
}
|
|
4717
|
+
|
|
4718
|
+
/** @returns {{code: string, message: string}|null} @private */
|
|
4719
|
+
_archiveNativeRefusal(ProviderClass, providerName, locator) {
|
|
4720
|
+
const resumable = ProviderClass.nativeResumeDriver === NATIVE_RESUME_DRIVER || ProviderClass.capabilities?.resume === true
|
|
4721
|
+
if (!resumable) {
|
|
4722
|
+
return { code: 'ARCHIVE_RESTORE_NATIVE_UNSUPPORTED', message: `The ${ProviderClass.displayLabel || providerName} provider cannot resume a conversation; continue it as a new thread instead.` }
|
|
4723
|
+
}
|
|
4724
|
+
if (locator === false) {
|
|
4725
|
+
return { code: 'ARCHIVE_RESTORE_LOCATOR_MISSING', message: 'This session recorded no provider conversation to resume; continue it as a new thread instead.' }
|
|
4726
|
+
}
|
|
4727
|
+
// A worktree session's cwd IS its worktree (destroySession removes it), so
|
|
4728
|
+
// the directory check in _archiveCommonRefusal already covers that case.
|
|
4729
|
+
return null
|
|
4730
|
+
}
|
|
4731
|
+
|
|
4732
|
+
/** @private */
|
|
4733
|
+
_isDirectory(path) {
|
|
4734
|
+
try { return statSync(path).isDirectory() } catch { return false }
|
|
4735
|
+
}
|
|
4736
|
+
|
|
4737
|
+
/** Does the provider transcript a Claude-family locator names still exist? (test seam) @private */
|
|
4738
|
+
_claudeTranscriptExists(cwd, conversationId) {
|
|
4739
|
+
// Honours CLAUDE_CONFIG_DIR and answers true when it cannot check (S2).
|
|
4740
|
+
return hasPersistedTranscript(cwd, conversationId)
|
|
4741
|
+
}
|
|
4742
|
+
|
|
4743
|
+
/**
|
|
4744
|
+
* #8866: is the conversation `saved` names already held by a live session or a
|
|
4745
|
+
* parked failed restore? Matches the saved session id, the Claude conversation
|
|
4746
|
+
* id, or the Codex native thread id.
|
|
4747
|
+
* @returns {{ sessionId: string, name: string|null, parked: boolean }|null}
|
|
4748
|
+
* @private
|
|
4749
|
+
*/
|
|
4750
|
+
_findConversationOwner(saved) {
|
|
4751
|
+
const str = (v) => (typeof v === 'string' && v.length > 0 ? v : null)
|
|
4752
|
+
const savedId = str(saved?.id)
|
|
4753
|
+
const conversationId = str(saved?.sdkSessionId)
|
|
4754
|
+
const threadId = str(saved?.nativeResume?.threadId)
|
|
4755
|
+
const matches = (id, conv, thread) =>
|
|
4756
|
+
(savedId && id === savedId) || (conversationId && conv === conversationId) || (threadId && thread === threadId)
|
|
4757
|
+
for (const [id, entry] of this._sessions) {
|
|
4758
|
+
const s = entry.session
|
|
4759
|
+
if (matches(id, str(s?.resumeSessionId), str(s?.nativeResumeState?.threadId))) {
|
|
4760
|
+
return { sessionId: id, name: entry.name ?? null, parked: false }
|
|
4761
|
+
}
|
|
4762
|
+
}
|
|
4763
|
+
for (const [id, parked] of this._failedRestores) {
|
|
4764
|
+
const p = parked?.saved
|
|
4765
|
+
if (matches(id, str(p?.sdkSessionId), str(p?.nativeResume?.threadId))) {
|
|
4766
|
+
return { sessionId: id, name: str(p?.name), parked: true }
|
|
4767
|
+
}
|
|
4768
|
+
}
|
|
4769
|
+
return null
|
|
4770
|
+
}
|
|
4771
|
+
|
|
4772
|
+
/**
|
|
4773
|
+
* #8866 — bring an archived session back, because the user asked to.
|
|
4774
|
+
*
|
|
4775
|
+
* `mode: 'native'` resumes the SAME conversation through exactly the recipe
|
|
4776
|
+
* boot and `retryFailedRestore` use (`_attemptRestoreOne(saved, true)`, so an
|
|
4777
|
+
* ASYNC start failure re-parks it in the failed restores with its history).
|
|
4778
|
+
* It needs a recorded locator whose provider transcript / thread still exists
|
|
4779
|
+
* and a directory that still exists. When it works the record LEAVES the
|
|
4780
|
+
* archive (`release`, no tombstone): the session is live again, closing it
|
|
4781
|
+
* later re-archives it, and a tombstone would make that archive (or a dismissed
|
|
4782
|
+
* failed restore of the same snapshot) dedupe to `duplicate` and lose the only
|
|
4783
|
+
* copy. The release happens synchronously right after the sync attempt and
|
|
4784
|
+
* the state flush, under a lock keyed on the archiveId, so a double click gets
|
|
4785
|
+
* `ARCHIVED_SESSION_NOT_FOUND` rather than a second live copy.
|
|
4786
|
+
*
|
|
4787
|
+
* `mode: 'new_thread'` starts a NEW session (new id, `isRestore` false) in the
|
|
4788
|
+
* archived directory with the archived provider and model, and keeps the
|
|
4789
|
+
* container binding or refuses (never a silent move to the host). It carries
|
|
4790
|
+
* NO authority from the old session: not permissionMode (the provider default
|
|
4791
|
+
* applies), not codexSandbox, not the native locator, not a worktree. The
|
|
4792
|
+
* record STAYS in the archive, because the old thread is not live again. The
|
|
4793
|
+
* model gets the archived transcript with the first message the user sends
|
|
4794
|
+
* (see `claimContinuationSeed`); the new session's history opens with a system
|
|
4795
|
+
* line saying so.
|
|
4796
|
+
*
|
|
4797
|
+
* @param {string} archiveId
|
|
4798
|
+
* @param {'native'|'new_thread'} mode
|
|
4799
|
+
* @param {{ settleTimeoutMs?: number }} [opts]
|
|
4800
|
+
* @returns {Promise<{ok: true, mode: string, sessionId: string, seed?: {messagesIncluded: number, messagesTotal: number, bytes: number}} | {ok: false, mode: string, code: string, message: string, sessionId?: string}>}
|
|
4801
|
+
*/
|
|
4802
|
+
async restoreArchivedSession(archiveId, mode, { settleTimeoutMs = RETRY_RESTORE_SETTLE_TIMEOUT_MS, isAuthorized } = {}) {
|
|
4803
|
+
const fail = (code, message, extra = {}) => ({ ok: false, mode, code, message, ...extra })
|
|
4804
|
+
if (mode !== 'native' && mode !== 'new_thread') {
|
|
4805
|
+
return fail('ARCHIVE_RESTORE_INVALID', 'mode must be "native" or "new_thread"')
|
|
4806
|
+
}
|
|
4807
|
+
let release = await this._locks.acquire(`archive-restore:${archiveId}`)
|
|
4808
|
+
const releaseOnce = () => {
|
|
4809
|
+
if (!release) return
|
|
4810
|
+
const r = release
|
|
4811
|
+
release = null
|
|
4812
|
+
r()
|
|
4813
|
+
}
|
|
4814
|
+
let awaitStart = null
|
|
4815
|
+
try {
|
|
4816
|
+
assertAuthorized(isAuthorized)
|
|
4817
|
+
const read = await this._sessionArchive.getSaved?.(archiveId)
|
|
4818
|
+
assertAuthorized(isAuthorized)
|
|
4819
|
+
if (!read) return fail('ARCHIVED_SESSION_NOT_FOUND', 'No archived session with that id')
|
|
4820
|
+
if (!read.ok) return fail(read.code, read.message)
|
|
4821
|
+
const { saved, meta } = read
|
|
4822
|
+
|
|
4823
|
+
const providerName = saved.provider || this._providerType
|
|
4824
|
+
let ProviderClass = null
|
|
4825
|
+
try { ProviderClass = getProvider(providerName) } catch { /* reported by the refusal */ }
|
|
4826
|
+
const refusal = this._archiveCommonRefusal(ProviderClass, providerName, saved.cwd)
|
|
4827
|
+
if (refusal) return fail(refusal.code, refusal.message)
|
|
4828
|
+
|
|
4829
|
+
if (mode === 'native') {
|
|
4830
|
+
const nativeRefusal = this._archiveNativeRefusal(ProviderClass, providerName, meta.locator)
|
|
4831
|
+
if (nativeRefusal) return fail(nativeRefusal.code, nativeRefusal.message)
|
|
4832
|
+
// The same conversation must never be live twice (two writers on one
|
|
4833
|
+
// transcript / native thread). Also covers "resumed elsewhere first" and a
|
|
4834
|
+
// restore whose archive record was kept because the state flush failed.
|
|
4835
|
+
const owner = this._findConversationOwner(saved)
|
|
4836
|
+
if (owner) {
|
|
4837
|
+
return fail(
|
|
4838
|
+
'ARCHIVE_RESTORE_ALREADY_LIVE',
|
|
4839
|
+
owner.parked
|
|
4840
|
+
? 'This conversation is already restored and parked in Failed restores; use Retry there.'
|
|
4841
|
+
: `This conversation is already live as "${owner.name}"; switch to it instead of resuming it again.`,
|
|
4842
|
+
{ sessionId: owner.sessionId },
|
|
4843
|
+
)
|
|
4844
|
+
}
|
|
4845
|
+
if (ProviderClass.nativeResumeDriver === NATIVE_RESUME_DRIVER) {
|
|
4846
|
+
if (!saved.nativeResume || typeof saved.nativeResume !== 'object') {
|
|
4847
|
+
return fail('ARCHIVE_RESTORE_LOCATOR_MISSING', 'This session recorded no native Codex thread to resume; continue it as a new thread instead.')
|
|
4848
|
+
}
|
|
4849
|
+
} else if (typeof saved.sdkSessionId !== 'string' || saved.sdkSessionId.length === 0 || saved.conversationPersisted === false) {
|
|
4850
|
+
return fail('ARCHIVE_RESTORE_LOCATOR_MISSING', 'This session recorded no provider conversation to resume; continue it as a new thread instead.')
|
|
4851
|
+
} else if (!this._claudeTranscriptExists(saved.cwd, saved.sdkSessionId)) {
|
|
4852
|
+
return fail('ARCHIVE_RESTORE_LOCATOR_MISSING', 'The provider transcript for this session is no longer on disk; continue it as a new thread instead.')
|
|
4853
|
+
}
|
|
4854
|
+
try {
|
|
4855
|
+
const restoredId = this._attemptRestoreOne(saved, true)
|
|
4856
|
+
// CONFIRMED durable (file AND directory entry fsync'd): the archive copy is
|
|
4857
|
+
// released next, so the state file must really hold the restored session
|
|
4858
|
+
// before the record goes.
|
|
4859
|
+
const flushed = this._flushPersistConfirmedDurable(restoredId)
|
|
4860
|
+
// Grab the settle handle NOW, while the entry is still mapped (see
|
|
4861
|
+
// retryFailedRestore): a rejected start re-parks it and drops the entry.
|
|
4862
|
+
awaitStart = { restoredId, settled: this._awaitStartSettled(restoredId, settleTimeoutMs), saved }
|
|
4863
|
+
// Only a session that is on disk may take the archive copy with it.
|
|
4864
|
+
// Synchronous with the attempt: no await between them.
|
|
4865
|
+
if (flushed) {
|
|
4866
|
+
const released = this._sessionArchive.release(archiveId)
|
|
4867
|
+
if (released !== 'released') log.warn(`Restored archived session ${restoredId} but its archive record was not released (${released})`)
|
|
4868
|
+
} else {
|
|
4869
|
+
log.warn(`Restored archived session ${restoredId} but state could not be saved; keeping its archive record`)
|
|
4870
|
+
}
|
|
4871
|
+
} catch (err) {
|
|
4872
|
+
log.error(`Archive restore failed for ${JSON.stringify(String(saved.name))}: ${err?.message || err}`)
|
|
4873
|
+
return fail(err?.code || 'ARCHIVE_RESTORE_FAILED', err?.message || String(err))
|
|
4874
|
+
}
|
|
4875
|
+
} else {
|
|
4876
|
+
let containerBinding
|
|
4877
|
+
try {
|
|
4878
|
+
containerBinding = this._resolveRestoredContainerBinding(saved)
|
|
4879
|
+
} catch (err) {
|
|
4880
|
+
return fail(err?.code || 'ENVIRONMENT_UNAVAILABLE', err?.message || String(err))
|
|
4881
|
+
}
|
|
4882
|
+
const seed = buildContinuationSeed(saved.history, { omittedOldest: meta.omittedOldest })
|
|
4883
|
+
const baseName = typeof saved.name === 'string' && saved.name.trim() ? saved.name.trim() : 'Archived session'
|
|
4884
|
+
let newId
|
|
4885
|
+
try {
|
|
4886
|
+
newId = this.createSession({
|
|
4887
|
+
name: `${baseName} (continued)`,
|
|
4888
|
+
cwd: saved.cwd,
|
|
4889
|
+
model: saved.model || undefined,
|
|
4890
|
+
// #7855: a model read back from a saved record is a replay, not a request
|
|
4891
|
+
// someone just made; a since-retired id degrades to the default (#3403).
|
|
4892
|
+
modelSource: 'replay',
|
|
4893
|
+
provider: saved.provider || undefined,
|
|
4894
|
+
connectionId: typeof saved.agentConnection?.id === 'string' && saved.agentConnection.provenance?.source === 'configured'
|
|
4895
|
+
? saved.agentConnection.id
|
|
4896
|
+
: undefined,
|
|
4897
|
+
restoredAgentConnection: saved.agentConnection?.provenance?.source === 'configured'
|
|
4898
|
+
? saved.agentConnection
|
|
4899
|
+
: undefined,
|
|
4900
|
+
...containerBinding,
|
|
4901
|
+
// One flush below, after the seed and the opening line exist.
|
|
4902
|
+
skipPersist: true,
|
|
4903
|
+
})
|
|
4904
|
+
if (seed) {
|
|
4905
|
+
this._continuationSeeds.set(newId, {
|
|
4906
|
+
seed: { ...seed, name: sanitizeSeedText(baseName).slice(0, 256), archivedAt: typeof meta.archivedAt === 'number' ? meta.archivedAt : null },
|
|
4907
|
+
claimed: false,
|
|
4908
|
+
claimedAt: 0,
|
|
4909
|
+
token: null,
|
|
4910
|
+
})
|
|
4911
|
+
}
|
|
4912
|
+
const omitted = seed ? seed.messagesTotal - seed.messagesIncluded : 0
|
|
4913
|
+
this._recordHistory(newId, 'message', {
|
|
4914
|
+
type: 'system',
|
|
4915
|
+
content: seed
|
|
4916
|
+
? `Continued as a NEW thread from the archived session "${baseName}". The model does not have that conversation natively: ` +
|
|
4917
|
+
`a transcript of ${seed.messagesIncluded} of ${seed.messagesTotal} messages${omitted > 0 ? ` (the ${omitted} oldest left out)` : ''} ` +
|
|
4918
|
+
'will be sent with your first message. Tool calls, file contents and approvals from it are not included.'
|
|
4919
|
+
: `Continued as a NEW thread from the archived session "${baseName}". It had no conversation text to carry over, so the model starts with no earlier context.`,
|
|
4920
|
+
timestamp: Date.now(),
|
|
4921
|
+
})
|
|
4922
|
+
this._flushPersistOrWarn(newId)
|
|
4923
|
+
awaitStart = {
|
|
4924
|
+
restoredId: newId,
|
|
4925
|
+
settled: this._awaitStartSettled(newId, settleTimeoutMs),
|
|
4926
|
+
saved,
|
|
4927
|
+
seed: seed ? { messagesIncluded: seed.messagesIncluded, messagesTotal: seed.messagesTotal, bytes: seed.bytes } : null,
|
|
4928
|
+
}
|
|
4929
|
+
} catch (err) {
|
|
4930
|
+
if (newId && this._sessions.has(newId)) this.destroySession(newId, { archive: false })
|
|
4931
|
+
log.error(`Continue-as-new-thread failed for ${JSON.stringify(String(saved.name))}: ${err?.message || err}`)
|
|
4932
|
+
return fail(err?.code || 'ARCHIVE_RESTORE_FAILED', err?.message || String(err))
|
|
4933
|
+
}
|
|
4934
|
+
}
|
|
4935
|
+
} finally {
|
|
4936
|
+
releaseOnce()
|
|
4937
|
+
}
|
|
4938
|
+
|
|
4939
|
+
if (!awaitStart) throw new Error('restoreArchivedSession: unreachable — every non-awaiting path returns')
|
|
4940
|
+
const { restoredId, settled, saved } = awaitStart
|
|
4941
|
+
const outcome = await settled
|
|
4942
|
+
if (!outcome.ok) {
|
|
4943
|
+
const err = outcome.error
|
|
4944
|
+
const message = err?.message || String(err)
|
|
4945
|
+
log.error(`Archive restore's provider start failed for ${JSON.stringify(String(saved.name))}: ${message}`)
|
|
4946
|
+
return fail(err?.code || 'START_FAILED', message, mode === 'native' ? { sessionId: restoredId } : {})
|
|
4947
|
+
}
|
|
4948
|
+
log.info(`Archive ${mode === 'native' ? 'restored' : 'continued as a new thread'}: ${JSON.stringify(String(saved.name))} (${saved.provider || 'default'})`)
|
|
4949
|
+
return { ok: true, mode, sessionId: restoredId, ...(awaitStart.seed ? { seed: awaitStart.seed } : {}) }
|
|
4950
|
+
}
|
|
4951
|
+
|
|
4952
|
+
/**
|
|
4953
|
+
* #8866: take the pending archived-transcript seed of a session continued as a
|
|
4954
|
+
* NEW thread, as the one_turn text context item `prepareInputContext` merges
|
|
4955
|
+
* into the first message.
|
|
4956
|
+
*
|
|
4957
|
+
* const claim = sm.claimContinuationSeed(id)
|
|
4958
|
+
* // null no seed (nothing owed)
|
|
4959
|
+
* // { busy: true } another input holds the claim and has not been
|
|
4960
|
+
* // settled: the caller must REFUSE this input, or it
|
|
4961
|
+
* // could become the first delivered input without
|
|
4962
|
+
* // the transcript
|
|
4963
|
+
* // { unpersisted: true } the claim could not be confirmed durable; the
|
|
4964
|
+
* // caller must REFUSE this input (retry-safe)
|
|
4965
|
+
* // { token, item } claimed; settle with the token
|
|
4966
|
+
* sm.settleContinuationSeed(id, token, consumed)
|
|
4967
|
+
*
|
|
4968
|
+
* The claim is persisted (fsync'd) BEFORE the caller dispatches, so a crash
|
|
4969
|
+
* mid-dispatch records the seed as in flight and restore drops it rather than
|
|
4970
|
+
* re-sending it. A claim older than CONTINUATION_CLAIM_TTL_MS that was never
|
|
4971
|
+
* settled counts as CONSUMED (never reclaimable: re-injecting the transcript
|
|
4972
|
+
* twice is worse than losing it once), and says so in the log.
|
|
4973
|
+
* @param {string} sessionId
|
|
4974
|
+
* @returns {null | { busy: true } | { unpersisted: true } | { token: string, item: object }}
|
|
4975
|
+
*/
|
|
4976
|
+
claimContinuationSeed(sessionId) {
|
|
4977
|
+
const held = this._continuationSeeds.get(sessionId)
|
|
4978
|
+
if (!held) return null
|
|
4979
|
+
const now = Date.now()
|
|
4980
|
+
if (held.claimed) {
|
|
4981
|
+
if (now - held.claimedAt < CONTINUATION_CLAIM_TTL_MS) return { busy: true }
|
|
4982
|
+
log.warn(`Continuation seed for session ${sessionId} was claimed ${now - held.claimedAt}ms ago and never settled; counting it as consumed`)
|
|
4983
|
+
this._continuationSeeds.delete(sessionId)
|
|
4984
|
+
this._flushPersistOrWarn(sessionId, null, { durable: true })
|
|
4985
|
+
return null
|
|
4986
|
+
}
|
|
4987
|
+
held.claimed = true
|
|
4988
|
+
held.claimedAt = now
|
|
4989
|
+
held.token = randomBytes(8).toString('hex')
|
|
4990
|
+
if (!this._flushPersistConfirmedDurable(sessionId)) {
|
|
4991
|
+
// Disk may still say "unclaimed": dispatching now could replay the
|
|
4992
|
+
// transcript after a crash. Back out, leave the seed pending, and tell the
|
|
4993
|
+
// caller to refuse the input (retry-safe).
|
|
4994
|
+
held.claimed = false
|
|
4995
|
+
held.token = null
|
|
4996
|
+
log.warn(`Continuation seed claim for session ${sessionId} could not be confirmed durable; refusing the input rather than risk a replay`)
|
|
4997
|
+
this._flushPersistOrWarn(sessionId) // best effort: put the unclaimed state back on disk
|
|
4998
|
+
return { unpersisted: true }
|
|
4999
|
+
}
|
|
5000
|
+
return { token: held.token, item: continuationSeedItem(held.seed) }
|
|
5001
|
+
}
|
|
5002
|
+
|
|
5003
|
+
/**
|
|
5004
|
+
* @param {string} sessionId
|
|
5005
|
+
* @param {string} token - the claim's token; a stale or foreign one is ignored
|
|
5006
|
+
* @param {boolean} consumed - true once the provider ADMITTED the input (or its
|
|
5007
|
+
* admission is uncertain, which counts as consumed); false returns the seed
|
|
5008
|
+
* to pending after a definite rejection
|
|
5009
|
+
*/
|
|
5010
|
+
settleContinuationSeed(sessionId, token, consumed) {
|
|
5011
|
+
const held = this._continuationSeeds.get(sessionId)
|
|
5012
|
+
if (!held || !held.claimed || held.token !== token) return
|
|
5013
|
+
if (consumed) {
|
|
5014
|
+
this._continuationSeeds.delete(sessionId)
|
|
5015
|
+
// Immediately, not on the debounce: a crash right after delivery must not
|
|
5016
|
+
// bring the transcript back.
|
|
5017
|
+
this._flushPersistOrWarn(sessionId, null, { durable: true })
|
|
5018
|
+
} else {
|
|
5019
|
+
held.claimed = false
|
|
5020
|
+
held.token = null
|
|
5021
|
+
// Immediately: the file says claimed:true, and a crash before the debounce
|
|
5022
|
+
// would drop a seed that was never sent.
|
|
5023
|
+
this._flushPersistOrWarn(sessionId)
|
|
5024
|
+
}
|
|
5025
|
+
}
|
|
5026
|
+
|
|
5027
|
+
/**
|
|
5028
|
+
* One page of an archived session's history (oldest first).
|
|
5029
|
+
* @param {string} archiveId
|
|
5030
|
+
* @param {{ offset?: number, limit?: number }} [opts]
|
|
5031
|
+
* @returns {Promise<object>}
|
|
5032
|
+
*/
|
|
5033
|
+
async getArchivedSessionHistory(archiveId, opts) {
|
|
5034
|
+
return this._sessionArchive.getHistoryPage(archiveId, opts)
|
|
5035
|
+
}
|
|
5036
|
+
|
|
5037
|
+
/** @returns {'deleted'|'not_found'|'failed'} */
|
|
5038
|
+
deleteArchivedSession(archiveId) {
|
|
5039
|
+
return this._sessionArchive.delete(archiveId)
|
|
5040
|
+
}
|
|
5041
|
+
|
|
5042
|
+
/**
|
|
5043
|
+
* Apply a validated retention policy to the running archive and prune now.
|
|
5044
|
+
* @returns {object|null} the applied policy, or null when the archive store
|
|
5045
|
+
* does not support a runtime policy update (an injected test store)
|
|
5046
|
+
*/
|
|
5047
|
+
setArchiveRetentionPolicy(policy) {
|
|
5048
|
+
return typeof this._sessionArchive.setRetentionPolicy === 'function'
|
|
5049
|
+
? this._sessionArchive.setRetentionPolicy(policy)
|
|
5050
|
+
: null
|
|
5051
|
+
}
|
|
5052
|
+
|
|
5053
|
+
/** @returns {{ deleted: number, failed: number }} */
|
|
5054
|
+
deleteAllArchivedSessions() {
|
|
5055
|
+
return this._sessionArchive.deleteAll()
|
|
5056
|
+
}
|
|
5057
|
+
|
|
5058
|
+
/**
|
|
5059
|
+
* One page of a parked failed restore's PRESERVED history (#8860), oldest
|
|
5060
|
+
* first. Read-only: it resumes, rebuilds and creates nothing, so the
|
|
5061
|
+
* fail-closed native resume (docs/providers.md "Native restart continuity")
|
|
5062
|
+
* is untouched. It exists because a session parked for a missing native
|
|
5063
|
+
* locator can never be restored, and the roster publishes only a count.
|
|
5064
|
+
*
|
|
5065
|
+
* Each entry is shaped by `historyWireEntry` (history-page.js: the persistence
|
|
5066
|
+
* boundary's `truncateEntry`, replay's server-only field strip, and a display
|
|
5067
|
+
* cap for an oversized entry), and the page stops early once its serialized
|
|
5068
|
+
* size would pass HISTORY_PAGE_BYTES, so `entries` can be
|
|
5069
|
+
* shorter than `limit`. `limit` is clamped to 1..MAX (default 50) and
|
|
5070
|
+
* `offset` to >= 0, whatever the caller sent; a non-numeric value takes the
|
|
5071
|
+
* default rather than propagating NaN into `slice`.
|
|
5072
|
+
*
|
|
5073
|
+
* Takes no lock: `retryFailedRestore` removes the entry before it attempts
|
|
5074
|
+
* anything, so a read racing it sees either the whole entry or none.
|
|
5075
|
+
*
|
|
5076
|
+
* @param {string} sessionId
|
|
5077
|
+
* @param {{ offset?: number, limit?: number }} [opts]
|
|
5078
|
+
* @returns {{ok: true, total: number, offset: number, entries: object[]} | {ok: false, code: string, message: string}}
|
|
5079
|
+
*/
|
|
5080
|
+
getFailedRestoreHistory(sessionId, { offset, limit } = {}) {
|
|
5081
|
+
const parked = this._failedRestores.get(sessionId)
|
|
5082
|
+
if (!parked) {
|
|
5083
|
+
return {
|
|
5084
|
+
ok: false,
|
|
5085
|
+
code: 'FAILED_RESTORE_NOT_FOUND',
|
|
5086
|
+
message: `No failed-restore entry for session ${sessionId}`,
|
|
5087
|
+
}
|
|
5088
|
+
}
|
|
5089
|
+
return { ok: true, ...pageHistory(parked.saved?.history, { offset, limit }, this._history) }
|
|
5090
|
+
}
|
|
5091
|
+
|
|
5092
|
+
/**
|
|
5093
|
+
* Clear a failed-restore entry when the user dismisses the failed session so
|
|
5094
|
+
* it stops reappearing. Its preserved history is archived first
|
|
5095
|
+
* ('failed_restore_dismissed'), so dismissing no longer destroys the only
|
|
5096
|
+
* copy of a session that can never be resumed.
|
|
5097
|
+
* @param {string} sessionId
|
|
5098
|
+
* @returns {boolean} true if an entry was cleared
|
|
5099
|
+
*/
|
|
5100
|
+
clearFailedRestore(sessionId) {
|
|
5101
|
+
if (!this._failedRestores.has(sessionId)) return false
|
|
5102
|
+
// Dismissing a failed restore drops its preserved history; archive it first,
|
|
5103
|
+
// and keep the entry if that failed — dismissing must not destroy the only copy.
|
|
5104
|
+
if (this._archiveSaved(this._failedRestores.get(sessionId)?.saved, 'failed_restore_dismissed') === 'failed') {
|
|
5105
|
+
log.warn(`Failed restore ${sessionId} was NOT dismissed: its history could not be archived first`)
|
|
5106
|
+
return false
|
|
5107
|
+
}
|
|
5108
|
+
this._failedRestores.delete(sessionId)
|
|
5109
|
+
this._flushPersist()
|
|
5110
|
+
return true
|
|
5111
|
+
}
|
|
5112
|
+
|
|
5113
|
+
/**
|
|
5114
|
+
* Retry a parked failed restore (#7625) — the operator-triggered second
|
|
5115
|
+
* attempt at a session the boot restore could not bring back.
|
|
5116
|
+
*
|
|
5117
|
+
* This is the caller `clearFailedRestore` never had. The dominant real case
|
|
5118
|
+
* is an environment that was down at boot and is back now (a host reboot,
|
|
5119
|
+
* since the `docker run` args carry no `--restart` policy), so the retry is
|
|
5120
|
+
* non-destructive by design: nothing is discarded on failure, the entry is
|
|
5121
|
+
* simply re-parked with the history and worktree it already had.
|
|
5122
|
+
*
|
|
5123
|
+
* ORDERING IS LOAD-BEARING, in three places:
|
|
5124
|
+
*
|
|
5125
|
+
* 1. The entry is removed from `_failedRestores` BEFORE the attempt, and
|
|
5126
|
+
* removing it AT ALL is what the tests actually pin. `serializeState()`
|
|
5127
|
+
* writes one entry per `_sessions` id AND, in a separate unguarded loop,
|
|
5128
|
+
* one per `_failedRestores` entry, so an entry left parked after a
|
|
5129
|
+
* successful retry puts the id on disk TWICE — and the next boot's
|
|
5130
|
+
* `preserveId` path treats a duplicate as malformed and silently mints a
|
|
5131
|
+
* random id instead, giving the operator a phantom second session.
|
|
5132
|
+
*
|
|
5133
|
+
* Doing it BEFORE rather than after is defence-in-depth, and the honest
|
|
5134
|
+
* scope is narrower than it looks: mutation-testing this method showed
|
|
5135
|
+
* that moving the delete after the attempt — with or without
|
|
5136
|
+
* `skipPersist` — is NOT observable, because the success path flushes
|
|
5137
|
+
* again after the delete and overwrites any bad intermediate write. What
|
|
5138
|
+
* delete-first buys is that the two maps are never simultaneously live
|
|
5139
|
+
* for this id, so a crash inside that window cannot leave a duplicate on
|
|
5140
|
+
* disk, and the invariant survives `skipPersist` being dropped later.
|
|
5141
|
+
*
|
|
5142
|
+
* 2. The flush happens only AFTER a successful attempt.
|
|
5143
|
+
* `_attemptRestoreOne` passes `skipPersist: true` for the reason
|
|
5144
|
+
* createSession's own comment gives: flushing inside createSession runs
|
|
5145
|
+
* BEFORE history is re-seeded and would write EMPTY history over the very
|
|
5146
|
+
* data being restored. Flushing here instead is what makes that safe.
|
|
5147
|
+
* The failure path deliberately does NOT flush — delete-then-re-register
|
|
5148
|
+
* leaves `_failedRestores` byte-identical, so there is nothing to write.
|
|
5149
|
+
*
|
|
5150
|
+
* 3. The whole thing runs under the per-session lock, so two operators (or a
|
|
5151
|
+
* double-tapped button) cannot interleave a delete against an attempt.
|
|
5152
|
+
*
|
|
5153
|
+
* A SECOND async start() rejection needs no handling HERE for the re-park:
|
|
5154
|
+
* `_attemptRestoreOne` passes `isRestore: true`, so `_handleAsyncStartFailure`
|
|
5155
|
+
* re-parks it (and emits `session_restore_failed`) exactly as it does on the
|
|
5156
|
+
* boot path. What this method adds (#8861) is that it WAITS for that outcome:
|
|
5157
|
+
* provider start() is async, and returning at the sync boundary reported
|
|
5158
|
+
* success for a session that was about to be re-parked, so the client had
|
|
5159
|
+
* already listed it as live. The contract is now:
|
|
5160
|
+
*
|
|
5161
|
+
* - `ok: true` — the provider's start() settled successfully, or is STILL
|
|
5162
|
+
* PENDING after `settleTimeoutMs` (default 30s; the session is live and
|
|
5163
|
+
* a later rejection re-parks it through the normal path). Neither means
|
|
5164
|
+
* the session has proven healthy.
|
|
5165
|
+
* - `ok: false` — the sync attempt threw, OR start() rejected within the
|
|
5166
|
+
* window. In the latter case the entry is already re-parked and
|
|
5167
|
+
* `session_restore_failed` already emitted by `_handleAsyncStartFailure`;
|
|
5168
|
+
* this method neither re-registers nor emits again.
|
|
5169
|
+
*
|
|
5170
|
+
* The per-session lock covers the delete → attempt → flush sequence and is
|
|
5171
|
+
* RELEASED before the settle wait: provider IO must not be held under the
|
|
5172
|
+
* mutation lock a concurrent rename/destroy of the restored session needs.
|
|
5173
|
+
*
|
|
5174
|
+
* @param {string} sessionId The parked session's id.
|
|
5175
|
+
* @param {{ settleTimeoutMs?: number }} [opts]
|
|
5176
|
+
* @returns {Promise<{ok: true, sessionId: string} | {ok: false, sessionId?: string, code: string, message: string}>}
|
|
5177
|
+
* `sessionId` on an `ok: false` reply is set only when a start() rejection
|
|
5178
|
+
* re-parked the session, and names the id it was re-parked under.
|
|
5179
|
+
*/
|
|
5180
|
+
async retryFailedRestore(sessionId, { settleTimeoutMs = RETRY_RESTORE_SETTLE_TIMEOUT_MS, isAuthorized } = {}) {
|
|
5181
|
+
let release = await this._locks.acquire(sessionId)
|
|
5182
|
+
// Idempotent: the lock is released early on the success path (before the
|
|
5183
|
+
// settle wait) and by the `finally` on every other path.
|
|
5184
|
+
const releaseOnce = () => {
|
|
5185
|
+
if (!release) return
|
|
5186
|
+
const r = release
|
|
5187
|
+
release = null
|
|
5188
|
+
r()
|
|
5189
|
+
}
|
|
5190
|
+
// Set only by the success path, which wants to await the start outside the
|
|
5191
|
+
// lock. Declared out here so the `finally` can run before the await.
|
|
5192
|
+
let awaitStart = null
|
|
5193
|
+
try {
|
|
5194
|
+
assertAuthorized(isAuthorized)
|
|
5195
|
+
const parked = this._failedRestores.get(sessionId)
|
|
5196
|
+
if (!parked) {
|
|
5197
|
+
// Distinguishable from a failed attempt: the caller needs to tell "your
|
|
5198
|
+
// button is stale, this entry is gone" (a concurrent retry won the race,
|
|
5199
|
+
// or _pruneStaleFailedRestores dropped it at its TTL) from "the retry
|
|
5200
|
+
// ran and failed again".
|
|
5201
|
+
return {
|
|
5202
|
+
ok: false,
|
|
5203
|
+
code: 'FAILED_RESTORE_NOT_FOUND',
|
|
5204
|
+
message: `No failed-restore entry for session ${sessionId}`,
|
|
5205
|
+
}
|
|
5206
|
+
}
|
|
5207
|
+
const { saved } = parked
|
|
5208
|
+
|
|
5209
|
+
// A user-shell session has no resumable state, and re-spawning one would
|
|
5210
|
+
// bypass the `userShell.enabled` gate if it was since turned off (#5983).
|
|
5211
|
+
//
|
|
5212
|
+
// REACHABILITY — corrected by review, because the first version of this
|
|
5213
|
+
// comment claimed the state was unreachable and that was too strong. The
|
|
5214
|
+
// daemon's own paths cannot park one: serializeState() skips
|
|
5215
|
+
// `isUserShell` so one is never persisted, and _handleAsyncStartFailure's
|
|
5216
|
+
// re-park branch requires `entry._isRestore`, which a fresh user-shell
|
|
5217
|
+
// session never has. But restoreState() reads
|
|
5218
|
+
// ~/.chroxy/session-state.json and parks whatever fails, so a
|
|
5219
|
+
// hand-edited or corrupted state file carrying a user-shell entry reaches
|
|
5220
|
+
// _registerFailedRestore through the ordinary boot path — and this file
|
|
5221
|
+
// already treats that file as untrusted input elsewhere (#7082 coerces
|
|
5222
|
+
// corrupt counters out of it). So this is a live guard, not dead code.
|
|
5223
|
+
//
|
|
5224
|
+
// It lives in SessionManager rather than the WS handler so it covers
|
|
5225
|
+
// every caller: the strict-primary user-shell gate exists only in
|
|
5226
|
+
// handleCreateSession, so a retry driven from anywhere else bypasses it.
|
|
5227
|
+
// Resolved from the provider REGISTRY and checked on the class, matching
|
|
5228
|
+
// every other user-shell gate in this file (`constructor.isUserShell`).
|
|
5229
|
+
// A saved entry carries only a provider NAME, so the name comparison is
|
|
5230
|
+
// kept as the fallback for a provider that is not registered in this
|
|
5231
|
+
// process — but the class check is what actually decides when it can.
|
|
5232
|
+
const SavedProviderClass = getProvider(saved.provider)
|
|
5233
|
+
if (SavedProviderClass?.isUserShell === true || saved.provider === USER_SHELL_PROVIDER) {
|
|
5234
|
+
return {
|
|
5235
|
+
ok: false,
|
|
5236
|
+
code: 'RETRY_FORBIDDEN_USER_SHELL',
|
|
5237
|
+
message: 'A user-shell session cannot be restored — it has no resumable state and re-spawning one would bypass the userShell.enabled gate.',
|
|
5238
|
+
}
|
|
5239
|
+
}
|
|
5240
|
+
|
|
5241
|
+
this._failedRestores.delete(sessionId)
|
|
5242
|
+
|
|
5243
|
+
try {
|
|
5244
|
+
const restoredId = this._attemptRestoreOne(saved, true)
|
|
5245
|
+
this._flushPersistOrWarn(restoredId)
|
|
5246
|
+
// Grab the settle promise NOW, synchronously, while the entry is still
|
|
5247
|
+
// mapped: a start() that rejects re-parks the session and drops it from
|
|
5248
|
+
// `_sessions`, after which there would be no handle left to look up.
|
|
5249
|
+
awaitStart = { restoredId, settled: this._awaitStartSettled(restoredId, settleTimeoutMs), saved }
|
|
5250
|
+
} catch (err) {
|
|
5251
|
+
// No orphan check here on purpose. `_attemptRestoreOne` tears down any
|
|
5252
|
+
// half-seeded session it created before it rethrows, and it is the only
|
|
5253
|
+
// scope that knows which id createSession actually used — `saved.id`
|
|
5254
|
+
// can differ from it when preserveId is malformed or collides. A check
|
|
5255
|
+
// at this level would be keyed on the wrong id in exactly the case that
|
|
5256
|
+
// matters (Copilot, #7630 review).
|
|
5257
|
+
//
|
|
5258
|
+
// Re-park with the SAME `saved` object. #7627: a failed restore's
|
|
5259
|
+
// lastActivityAt is frozen at the value it had when first parked, and
|
|
5260
|
+
// re-using `saved` rather than re-serializing is what keeps it frozen —
|
|
5261
|
+
// re-stamping it here would push the entry's 30-day TTL out on every
|
|
5262
|
+
// retry, so a chronically-failing session could never age out.
|
|
5263
|
+
this._registerFailedRestore(saved, err)
|
|
5264
|
+
this._advanceSessionCounterPast(saved.name)
|
|
5265
|
+
log.error(`Retry failed to restore session ${JSON.stringify(String(saved.name))}: ${err?.message || err}`)
|
|
5266
|
+
this.emit('session_restore_failed', {
|
|
5267
|
+
sessionId,
|
|
5268
|
+
name: saved.name,
|
|
5269
|
+
provider: saved.provider || this._providerType,
|
|
5270
|
+
cwd: saved.cwd,
|
|
5271
|
+
model: saved.model || null,
|
|
5272
|
+
permissionMode: saved.permissionMode || null,
|
|
5273
|
+
errorCode: err?.code || 'RESTORE_FAILED',
|
|
5274
|
+
errorMessage: err?.message || String(err),
|
|
5275
|
+
originalHistoryPreserved: true,
|
|
5276
|
+
historyLength: Array.isArray(saved.history) ? saved.history.length : 0,
|
|
5277
|
+
})
|
|
5278
|
+
return {
|
|
5279
|
+
ok: false,
|
|
5280
|
+
code: err?.code || 'RESTORE_FAILED',
|
|
5281
|
+
message: err?.message || String(err),
|
|
5282
|
+
}
|
|
5283
|
+
}
|
|
5284
|
+
} finally {
|
|
5285
|
+
releaseOnce()
|
|
5286
|
+
}
|
|
2830
5287
|
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
const list = []
|
|
2838
|
-
for (const [sessionId, { saved, error }] of this._failedRestores) {
|
|
2839
|
-
list.push({
|
|
2840
|
-
sessionId,
|
|
2841
|
-
name: saved.name,
|
|
2842
|
-
provider: saved.provider || this._providerType,
|
|
2843
|
-
cwd: saved.cwd,
|
|
2844
|
-
model: saved.model || null,
|
|
2845
|
-
permissionMode: saved.permissionMode || null,
|
|
2846
|
-
errorCode: error?.code || 'RESTORE_FAILED',
|
|
2847
|
-
errorMessage: error?.message || String(error),
|
|
2848
|
-
needsAttention: true,
|
|
2849
|
-
historyLength: Array.isArray(saved.history) ? saved.history.length : 0,
|
|
2850
|
-
})
|
|
5288
|
+
if (!awaitStart) throw new Error('retryFailedRestore: unreachable — every non-awaiting path returns')
|
|
5289
|
+
const { restoredId, settled, saved } = awaitStart
|
|
5290
|
+
const outcome = await settled
|
|
5291
|
+
if (outcome.ok && outcome.pending) {
|
|
5292
|
+
log.warn(`Retry restored session ${JSON.stringify(String(saved.name))} but its provider start has not settled after ${settleTimeoutMs}ms; reporting ok (a later rejection re-parks it)`)
|
|
5293
|
+
return { ok: true, sessionId: restoredId }
|
|
2851
5294
|
}
|
|
2852
|
-
|
|
5295
|
+
if (outcome.ok) {
|
|
5296
|
+
log.info(`Retry restored session ${JSON.stringify(String(saved.name))} (${saved.provider || 'default'})`)
|
|
5297
|
+
return { ok: true, sessionId: restoredId }
|
|
5298
|
+
}
|
|
5299
|
+
// `_handleAsyncStartFailure` already re-parked the entry and emitted
|
|
5300
|
+
// `session_restore_failed`; doing either again would double-announce.
|
|
5301
|
+
const err = outcome.error
|
|
5302
|
+
const message = err?.message || String(err)
|
|
5303
|
+
log.error(`Retry's provider start failed for session ${JSON.stringify(String(saved.name))}: ${message}`)
|
|
5304
|
+
// `restoredId`, not the requested id: createSession falls back to a random
|
|
5305
|
+
// id when preserveId is malformed or collides, and the re-park is keyed on
|
|
5306
|
+
// the id it actually used, so that is the row the client must find.
|
|
5307
|
+
return { ok: false, sessionId: restoredId, code: err?.code || 'START_FAILED', message }
|
|
2853
5308
|
}
|
|
2854
5309
|
|
|
2855
5310
|
/**
|
|
2856
|
-
*
|
|
2857
|
-
* the
|
|
5311
|
+
* #8861: resolve how a session's provider start() ended, without ever
|
|
5312
|
+
* rejecting. Reads the handle `createSession` left on the entry, so it must be
|
|
5313
|
+
* CALLED synchronously after the session was created (the entry is dropped
|
|
5314
|
+
* from `_sessions` when a rejected restore is re-parked).
|
|
5315
|
+
*
|
|
2858
5316
|
* @param {string} sessionId
|
|
2859
|
-
* @
|
|
5317
|
+
* @param {number} timeoutMs
|
|
5318
|
+
* @returns {Promise<{ok: true} | {ok: false, error: any} | {ok: true, pending: true}>}
|
|
5319
|
+
* `{ ok: true }` for a settled start OR a sync start (no handle);
|
|
5320
|
+
* `{ ok: true, pending: true }` when it has not settled within `timeoutMs`.
|
|
5321
|
+
* @private
|
|
2860
5322
|
*/
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
5323
|
+
_awaitStartSettled(sessionId, timeoutMs) {
|
|
5324
|
+
const handle = this._sessions.get(sessionId)?._startSettled
|
|
5325
|
+
if (!handle) return Promise.resolve({ ok: true })
|
|
5326
|
+
let timer
|
|
5327
|
+
const timeout = new Promise((resolve) => {
|
|
5328
|
+
timer = setTimeout(() => resolve({ ok: true, pending: true }), timeoutMs)
|
|
5329
|
+
timer.unref?.()
|
|
5330
|
+
})
|
|
5331
|
+
return Promise.race([handle, timeout]).finally(() => clearTimeout(timer))
|
|
2866
5332
|
}
|
|
2867
5333
|
|
|
2868
5334
|
/**
|
|
@@ -2885,6 +5351,14 @@ export class SessionManager extends EventEmitter {
|
|
|
2885
5351
|
return this._history.getHistory(sessionId)
|
|
2886
5352
|
}
|
|
2887
5353
|
|
|
5354
|
+
/**
|
|
5355
|
+
* #9022 -- reply text streamed so far for a still-open stream; see
|
|
5356
|
+
* SessionMessageHistory#getPendingResponseStreams.
|
|
5357
|
+
*/
|
|
5358
|
+
getPendingResponseStreams(sessionId) {
|
|
5359
|
+
return this._history.getPendingResponseStreams(sessionId)
|
|
5360
|
+
}
|
|
5361
|
+
|
|
2888
5362
|
/**
|
|
2889
5363
|
* Get the count of messages in the ring buffer for a session.
|
|
2890
5364
|
* @param {string} sessionId
|
|
@@ -2937,25 +5411,107 @@ export class SessionManager extends EventEmitter {
|
|
|
2937
5411
|
* Get full conversation history asynchronously by reading the JSONL file.
|
|
2938
5412
|
* Avoids blocking the event loop for large files (use in WS handlers).
|
|
2939
5413
|
* Falls back to the ring buffer if JSONL is unavailable.
|
|
2940
|
-
*
|
|
5414
|
+
*
|
|
5415
|
+
* #7484 — returns a DESCRIPTOR, not a bare array, because the two sources are
|
|
5416
|
+
* not interchangeable and the caller has no other way to tell them apart:
|
|
5417
|
+
*
|
|
5418
|
+
* - `source: 'jsonl'` is the common case for a live claude-family session (a
|
|
5419
|
+
* `resumeSessionId` plus a readable transcript). Its entries are
|
|
5420
|
+
* user_input/response/tool_use only — no `result`, no `_seq` — so a replay
|
|
5421
|
+
* of them carries neither a turn boundary nor a cursor.
|
|
5422
|
+
* - `source: 'ring'` is the fallback, and the only slice whose truncation
|
|
5423
|
+
* `isHistoryTruncated()` describes.
|
|
5424
|
+
* - `truncated` always describes THIS slice: the ring buffer's overflow flag
|
|
5425
|
+
* for `'ring'`, the transcript reader's own MAX_MESSAGES/byte caps for
|
|
5426
|
+
* `'jsonl'`. Reporting the ring's flag next to a JSONL slice is a statement
|
|
5427
|
+
* about a collection the caller never received.
|
|
5428
|
+
*
|
|
5429
|
+
* #8348 — the daemon's saved `permission_outcome` records are folded into a
|
|
5430
|
+
* `'jsonl'` slice (they exist only in the ring buffer and the state file, never
|
|
5431
|
+
* in the provider's transcript), without their ring `_seq`, so the slice still
|
|
5432
|
+
* advertises no cursor.
|
|
5433
|
+
*
|
|
5434
|
+
* @returns {Promise<{ entries: Array<{ type, content, tool?, timestamp, messageId? }>, source: 'jsonl'|'ring', truncated: boolean }>}
|
|
2941
5435
|
*/
|
|
2942
|
-
async getFullHistoryAsync(sessionId) {
|
|
5436
|
+
async getFullHistoryAsync(sessionId, readOpts = {}) {
|
|
2943
5437
|
const entry = this._sessions.get(sessionId)
|
|
2944
|
-
|
|
5438
|
+
// No session (or one being torn down) read NEITHER source. Labelled 'ring'
|
|
5439
|
+
// because that is the slice a caller would have got — an empty one — and
|
|
5440
|
+
// the label must never imply a transcript was consulted.
|
|
5441
|
+
if (!entry || entry._destroying) return { entries: [], source: 'ring', truncated: false }
|
|
2945
5442
|
|
|
2946
5443
|
const conversationId = entry.session.resumeSessionId
|
|
2947
|
-
if (conversationId) {
|
|
5444
|
+
if (conversationId && entry.session.constructor.nativeResumeDriver !== NATIVE_RESUME_DRIVER) {
|
|
2948
5445
|
try {
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
|
|
5446
|
+
// Resolved inside the provider store with real-path containment and the
|
|
5447
|
+
// file's identity, like every other transcript read; the reader then
|
|
5448
|
+
// admits it through the shared limiter and checks the opened descriptor.
|
|
5449
|
+
const src = resolveTranscriptSource({ provider: 'claude', conversationId, cwd: entry.cwd })
|
|
5450
|
+
if (!src.ok) throw new Error(src.reason)
|
|
5451
|
+
const { messages, truncated } = await readConversationHistoryWithMetaAsync(src.path, undefined, {
|
|
5452
|
+
expectedIdentity: src.identity,
|
|
5453
|
+
clientKey: readOpts.clientKey,
|
|
5454
|
+
restricted: readOpts.restricted,
|
|
5455
|
+
signal: readOpts.signal,
|
|
5456
|
+
})
|
|
5457
|
+
if (messages.length > 0) {
|
|
5458
|
+
return {
|
|
5459
|
+
entries: withRetainedPermissionOutcomes(messages, this.getHistory(sessionId), truncated),
|
|
5460
|
+
source: 'jsonl',
|
|
5461
|
+
truncated,
|
|
5462
|
+
}
|
|
5463
|
+
}
|
|
2952
5464
|
} catch (err) {
|
|
5465
|
+
// Too many reads in flight: tell the caller, do not substitute the ring buffer.
|
|
5466
|
+
if (err?.name === 'ReadLimitError') throw err
|
|
2953
5467
|
log.error(`Failed to read JSONL history for session ${sessionId}: ${err?.message || err}`)
|
|
2954
5468
|
}
|
|
2955
5469
|
}
|
|
2956
5470
|
|
|
2957
5471
|
// Fallback to ring buffer
|
|
2958
|
-
return
|
|
5472
|
+
return {
|
|
5473
|
+
entries: this.getHistory(sessionId),
|
|
5474
|
+
source: 'ring',
|
|
5475
|
+
truncated: this.isHistoryTruncated(sessionId),
|
|
5476
|
+
}
|
|
5477
|
+
}
|
|
5478
|
+
|
|
5479
|
+
/**
|
|
5480
|
+
* Is this session LIVE right now — mid-turn, OR still waiting on background
|
|
5481
|
+
* work? (#7484; the name's "busy" is corrected to liveness here by #7507.)
|
|
5482
|
+
*
|
|
5483
|
+
* The full-history replay needs this to decide whether a synthesized
|
|
5484
|
+
* `agent_idle` would be TRUE. `agent_idle` sets `isIdle`, clears
|
|
5485
|
+
* `streamingMessageId` (hiding the stop button) and clears `activeTools` —
|
|
5486
|
+
* all correct after a finished turn, all wrong while the session is live.
|
|
5487
|
+
*
|
|
5488
|
+
* This is `entry.session.isRunning`, and that is deliberately WIDER than
|
|
5489
|
+
* "mid-turn": BaseSession defines it as
|
|
5490
|
+
* `_isBusy || _backgroundShellTracker.size > 0`, so a session whose turn has
|
|
5491
|
+
* ENDED but which still holds an un-polled `Bash(run_in_background: true)`
|
|
5492
|
+
* shell reads busy here (#4307 — `_clearMessageState` preserves that map by
|
|
5493
|
+
* design, and the 60s advisory sweep must not flip liveness, #5247).
|
|
5494
|
+
*
|
|
5495
|
+
* Do NOT narrow it to `_isBusy`. `listSessions()` publishes this very same
|
|
5496
|
+
* `isRunning` as each entry's `isBusy`, and the dashboard re-derives `isIdle`
|
|
5497
|
+
* from that on every `session_list` / `session_activity` broadcast (#4639).
|
|
5498
|
+
* Two readings of one authority that disagree means whichever side this method
|
|
5499
|
+
* feeds gets reverted by the next broadcast. Pinned in
|
|
5500
|
+
* tests/session-manager-full-history-source.test.js against a REAL BaseSession,
|
|
5501
|
+
* because a stub with an own `isRunning` property cannot tell the two apart.
|
|
5502
|
+
*
|
|
5503
|
+
* `_destroying` entries are skipped, matching `getSession()` and
|
|
5504
|
+
* `listSessions()` (#7507 N1). Unreachable from the current call site, which
|
|
5505
|
+
* gates on `resolveSession` → `getSession()`, but a session being torn down is
|
|
5506
|
+
* not one any future caller should be answered about.
|
|
5507
|
+
*
|
|
5508
|
+
* @param {string} sessionId
|
|
5509
|
+
* @returns {boolean}
|
|
5510
|
+
*/
|
|
5511
|
+
isSessionBusy(sessionId) {
|
|
5512
|
+
const entry = this._sessions.get(sessionId)
|
|
5513
|
+
if (!entry || entry._destroying) return false
|
|
5514
|
+
return !!(entry.session && entry.session.isRunning)
|
|
2959
5515
|
}
|
|
2960
5516
|
|
|
2961
5517
|
/**
|
|
@@ -2977,11 +5533,168 @@ export class SessionManager extends EventEmitter {
|
|
|
2977
5533
|
}
|
|
2978
5534
|
|
|
2979
5535
|
/**
|
|
2980
|
-
*
|
|
2981
|
-
*
|
|
5536
|
+
* #8362: the server accepted an answer to a `user_question`. Records it on the
|
|
5537
|
+
* history entry (so the restore-time sweep does not call it interrupted) and
|
|
5538
|
+
* schedules a persist, since a restart can follow immediately and the question
|
|
5539
|
+
* entry was written to the state file before it was answered.
|
|
5540
|
+
*
|
|
5541
|
+
* @param {string} sessionId
|
|
5542
|
+
* @param {string} [toolUseId] - the question's id; omitted by clients that send none
|
|
5543
|
+
*/
|
|
5544
|
+
recordQuestionAnswered(sessionId, toolUseId) {
|
|
5545
|
+
if (this._history.markQuestionAnswered(sessionId, toolUseId)) {
|
|
5546
|
+
this._schedulePersist()
|
|
5547
|
+
}
|
|
5548
|
+
}
|
|
5549
|
+
|
|
5550
|
+
/**
|
|
5551
|
+
* #8301: a person expressed intent to work with this session — they typed a chat
|
|
5552
|
+
* input or submitted a line in its terminal pane. Clears the "user stopped"
|
|
5553
|
+
* state (see `recordUserInterrupt`) and does nothing else: no history, no
|
|
5554
|
+
* activity touch, no label.
|
|
5555
|
+
*
|
|
5556
|
+
* Called at RECEIPT of the input, synchronously, by the input handlers — NOT
|
|
5557
|
+
* from `recordUserInput`, which runs at admission. For correlated input that is
|
|
5558
|
+
* later than the person's act: a provider that admits after awaiting its
|
|
5559
|
+
* transport would let an input sent BEFORE a Stop clear that Stop when it was
|
|
5560
|
+
* finally admitted. `recordDaemonUserInput` and the daemon's PTY wake never come
|
|
5561
|
+
* through here, so a wake can never re-enable wakes.
|
|
5562
|
+
*
|
|
5563
|
+
* @param {string} sessionId
|
|
5564
|
+
*/
|
|
5565
|
+
recordUserIntent(sessionId) {
|
|
5566
|
+
this._userStopped.delete(sessionId)
|
|
5567
|
+
}
|
|
5568
|
+
|
|
5569
|
+
/**
|
|
5570
|
+
* #8301: the user pressed Stop on this session. Until they next type into it,
|
|
5571
|
+
* daemon-authored turns (the CI wake) are refused: a Stop is the user saying
|
|
5572
|
+
* "stop", and a wake that lands right after it would start the very work they
|
|
5573
|
+
* just halted. Called from the interrupt handler; not from scheduler/orchestration
|
|
5574
|
+
* interrupts, which are not the user's word.
|
|
5575
|
+
*
|
|
5576
|
+
* @param {string} sessionId
|
|
5577
|
+
*/
|
|
5578
|
+
recordUserInterrupt(sessionId) {
|
|
5579
|
+
if (this._sessions.has(sessionId)) this._userStopped.add(sessionId)
|
|
5580
|
+
}
|
|
5581
|
+
|
|
5582
|
+
/**
|
|
5583
|
+
* #8301: THE refusal seam for a daemon-authored turn — one answer, asked both
|
|
5584
|
+
* before dispatch and again when a queued wake is about to flush. Returns why
|
|
5585
|
+
* the session must not be handed one right now, or `null` when it may.
|
|
5586
|
+
*
|
|
5587
|
+
* - `'no-session'` the session is gone or being torn down
|
|
5588
|
+
* - `'budget-paused'` the cost budget pause (typed input is refused for this)
|
|
5589
|
+
* - `'user-stopped'` the user pressed Stop and has not typed since
|
|
5590
|
+
* - otherwise the provider's own reason (`session.daemonTurnRefusal()`): a
|
|
5591
|
+
* state in which its `sendMessage` would respawn, error, or discard the
|
|
5592
|
+
* user's queued follow-ups
|
|
5593
|
+
*
|
|
5594
|
+
* A provider hook that throws refuses (fail safe): not being able to tell is
|
|
5595
|
+
* not a reason to wake.
|
|
5596
|
+
*
|
|
5597
|
+
* NOT covered: a session another driver occupies (orchestration TurnDriver /
|
|
5598
|
+
* scheduler). Each driver keeps its occupancy in its own private set, so there
|
|
5599
|
+
* is nothing cheap to ask here; building a registry for it is its own change.
|
|
5600
|
+
*
|
|
5601
|
+
* @param {string} sessionId
|
|
5602
|
+
* @returns {string|null}
|
|
5603
|
+
*/
|
|
5604
|
+
daemonTurnRefusal(sessionId) {
|
|
5605
|
+
const entry = this._sessions.get(sessionId)
|
|
5606
|
+
if (!entry || entry._destroying) return 'no-session'
|
|
5607
|
+
if (this._costBudget.isPaused(sessionId)) return 'budget-paused'
|
|
5608
|
+
if (this._userStopped.has(sessionId)) return 'user-stopped'
|
|
5609
|
+
try {
|
|
5610
|
+
const reason = entry.session?.daemonTurnRefusal?.()
|
|
5611
|
+
return typeof reason === 'string' && reason.length > 0 ? reason : null
|
|
5612
|
+
} catch (err) {
|
|
5613
|
+
log.warn(`daemonTurnRefusal threw for session ${sessionId}; refusing: ${err?.message || err}`)
|
|
5614
|
+
return 'refusal-check-failed'
|
|
5615
|
+
}
|
|
5616
|
+
}
|
|
5617
|
+
|
|
5618
|
+
/**
|
|
5619
|
+
* #8301: make a DAEMON-authored turn visible the way a typed one is. The CI
|
|
5620
|
+
* wake travels the provider's `sendMessage` seam as an ordinary user turn, but
|
|
5621
|
+
* `input-handlers.js` is the only thing that records a user turn to history
|
|
5622
|
+
* and echoes it to clients — and it only runs for a websocket `input`. So this
|
|
5623
|
+
* is the non-ws equivalent of its `commitForwardedEffects`: the history entry
|
|
5624
|
+
* (a reconnecting client replays it), `touchActivity`, and a `user_input`
|
|
5625
|
+
* session event that `ws-forwarding.js` broadcasts to the session's viewers.
|
|
5626
|
+
*
|
|
5627
|
+
* Deliberately NOT `recordUserInput`'s auto-label path: the first input of a
|
|
5628
|
+
* session names it, and a daemon line ("CI finished on PR #N…") must never be
|
|
5629
|
+
* what a session is called. No `clientId` goes out — there is no sender, so
|
|
5630
|
+
* every viewer renders it (a client skips only the `user_input` it sent).
|
|
5631
|
+
*
|
|
5632
|
+
* Call it only once the provider has ADMITTED the line (dispatched or queued).
|
|
5633
|
+
* Nothing is recorded for a session that no longer exists.
|
|
5634
|
+
*
|
|
5635
|
+
* @param {string} sessionId
|
|
5636
|
+
* @param {string} text - the exact line the provider was given.
|
|
5637
|
+
* @param {string} messageId - stable id (matches the provider's queue mirror).
|
|
5638
|
+
* @returns {boolean} true when recorded and broadcast.
|
|
2982
5639
|
*/
|
|
5640
|
+
recordDaemonUserInput(sessionId, text, messageId) {
|
|
5641
|
+
const entry = this._sessions.get(sessionId)
|
|
5642
|
+
if (!entry || entry._destroying) return false
|
|
5643
|
+
// `source: 'daemon'` rides on the history entry and the broadcast so a client
|
|
5644
|
+
// can tell this from something a person typed.
|
|
5645
|
+
this._history.recordUserInput(sessionId, text, undefined, messageId, 'daemon')
|
|
5646
|
+
this.touchActivity(sessionId)
|
|
5647
|
+
this.emit('session_event', {
|
|
5648
|
+
sessionId,
|
|
5649
|
+
event: 'user_input',
|
|
5650
|
+
data: { text, messageId, timestamp: Date.now(), source: 'daemon' },
|
|
5651
|
+
})
|
|
5652
|
+
return true
|
|
5653
|
+
}
|
|
5654
|
+
|
|
5655
|
+
/** Update durable declared intent without changing provider activity. */
|
|
5656
|
+
setDeclaredStatus(sessionId, input, source = 'api') {
|
|
5657
|
+
const entry = this._sessions.get(sessionId)
|
|
5658
|
+
if (!entry || entry._destroying) return null
|
|
5659
|
+
const parsed = DeclaredStatusInputSchema.safeParse(input)
|
|
5660
|
+
if (!parsed.success || !['marker', 'api', 'hook'].includes(source)) return null
|
|
5661
|
+
const declaration = parsed.data
|
|
5662
|
+
const decision = declaration.decision === undefined
|
|
5663
|
+
? entry.declaredStatus?.decision
|
|
5664
|
+
: (/^none$/i.test(declaration.decision) ? undefined : declaration.decision)
|
|
5665
|
+
const status = { ...declaration, source, updatedAt: Date.now() }
|
|
5666
|
+
delete status.decision
|
|
5667
|
+
if (decision) status.decision = decision
|
|
5668
|
+
// Repeat complete messages/replays do not produce duplicate declarations.
|
|
5669
|
+
const previous = entry.declaredStatus
|
|
5670
|
+
if (previous && ['state', 'summary', 'next', 'blockedOn', 'etaMinutes', 'decision', 'source'].every((field) => previous[field] === status[field])) return { ...previous }
|
|
5671
|
+
entry.declaredStatus = status
|
|
5672
|
+
entry.session.setDeclaredStatusActivity?.(status)
|
|
5673
|
+
this._schedulePersist()
|
|
5674
|
+
this.emit('session_event', { sessionId, event: 'session_status', data: { declaredStatus: { ...status } } })
|
|
5675
|
+
return { ...status }
|
|
5676
|
+
}
|
|
5677
|
+
|
|
5678
|
+
/** Record provider output and accept intent only after normal completion. */
|
|
2983
5679
|
_recordHistory(sessionId, event, data) {
|
|
2984
|
-
const { persistNeeded, truncated } = this._history.recordHistory(sessionId, event, data)
|
|
5680
|
+
const { persistNeeded, truncated, completedAssistant, assistantCompleted } = this._history.recordHistory(sessionId, event, data)
|
|
5681
|
+
const entry = this._sessions.get(sessionId)
|
|
5682
|
+
if (entry && assistantCompleted && sessionHasCanonicalResponses(entry.session) !== true) {
|
|
5683
|
+
// The latest completed assistant response supersedes an intermediate
|
|
5684
|
+
// response even when it carries no usable declaration. Never retain text:
|
|
5685
|
+
// only a bounded parsed candidate waits for the turn's normal result.
|
|
5686
|
+
entry._pendingDeclaredStatus = typeof completedAssistant === 'string' ? extractDeclaredStatus(completedAssistant) : null
|
|
5687
|
+
}
|
|
5688
|
+
if (event === 'result' && entry && ownsDeclarationEvent(entry, data)) {
|
|
5689
|
+
const pending = entry._pendingDeclaredStatus
|
|
5690
|
+
delete entry._pendingDeclaredStatus
|
|
5691
|
+
const eligible = sessionHasCanonicalResponses(entry.session) ? data?.declarationEligible === true : data?.declarationEligible !== false
|
|
5692
|
+
if (pending && eligible && data?.interrupted !== true && (!data?.turnOutcome || data.turnOutcome === 'completed')) {
|
|
5693
|
+
this.setDeclaredStatus(sessionId, pending, 'marker')
|
|
5694
|
+
}
|
|
5695
|
+
} else if (event === 'error' && data?.recoverable !== true && entry && ownsDeclarationEvent(entry, data)) {
|
|
5696
|
+
delete entry._pendingDeclaredStatus
|
|
5697
|
+
}
|
|
2985
5698
|
if (persistNeeded) {
|
|
2986
5699
|
this._schedulePersist()
|
|
2987
5700
|
}
|
|
@@ -3006,6 +5719,89 @@ export class SessionManager extends EventEmitter {
|
|
|
3006
5719
|
}
|
|
3007
5720
|
}
|
|
3008
5721
|
|
|
5722
|
+
/**
|
|
5723
|
+
* #8348: remember an open permission prompt so its outcome can be recorded.
|
|
5724
|
+
*
|
|
5725
|
+
* Two feeders, one per pipeline: the session's own `permission_request` event
|
|
5726
|
+
* (the in-process providers, via `_wireSessionEvents`) and ws-permissions.js
|
|
5727
|
+
* (the hook-routed providers, whose prompts never pass through a session
|
|
5728
|
+
* event). Only what the clients were already shown is kept: the tool, the
|
|
5729
|
+
* description they received (clipped by the history layer on recording) and, since
|
|
5730
|
+
* #8503, the sanitized `input` the `permission_request` carried.
|
|
5731
|
+
*
|
|
5732
|
+
* @param {string} sessionId
|
|
5733
|
+
* @param {{ requestId?: string, tool?: string, description?: string, input?: object }} request
|
|
5734
|
+
*/
|
|
5735
|
+
notePermissionRequest(sessionId, request) {
|
|
5736
|
+
const requestId = request?.requestId
|
|
5737
|
+
if (typeof sessionId !== 'string' || !sessionId) return
|
|
5738
|
+
if (typeof requestId !== 'string' || !requestId) return
|
|
5739
|
+
// Re-noting an id moves it to the Map's tail, so the cap evicts the stalest.
|
|
5740
|
+
this._permissionRequests.delete(requestId)
|
|
5741
|
+
this._permissionRequests.set(requestId, {
|
|
5742
|
+
sessionId,
|
|
5743
|
+
tool: typeof request.tool === 'string' ? request.tool : '',
|
|
5744
|
+
description: describePermissionForOutcome(request.tool, request.description, request.input, request.recordDescription),
|
|
5745
|
+
// #8503: the input the clients were shown, held by reference (it is the
|
|
5746
|
+
// sanitized copy the broadcast carries, never the raw one) so the outcome
|
|
5747
|
+
// can journal it. The history layer bounds and re-checks it on recording.
|
|
5748
|
+
input: request.input,
|
|
5749
|
+
// #8357: the provider's tool-use id, so a replayed AskUserQuestion record
|
|
5750
|
+
// still pairs with its question. Absent for every other prompt.
|
|
5751
|
+
...(typeof request.toolUseId === 'string' && request.toolUseId ? { toolUseId: request.toolUseId } : {}),
|
|
5752
|
+
})
|
|
5753
|
+
while (this._permissionRequests.size > MAX_TRACKED_PERMISSION_REQUESTS) {
|
|
5754
|
+
const oldest = this._permissionRequests.keys().next().value
|
|
5755
|
+
if (oldest === undefined) break
|
|
5756
|
+
this._permissionRequests.delete(oldest)
|
|
5757
|
+
}
|
|
5758
|
+
}
|
|
5759
|
+
|
|
5760
|
+
/**
|
|
5761
|
+
* #8348: record how a permission prompt ended, in the session's history, so a
|
|
5762
|
+
* full-rebuild replay (session switch, reload) can show it. The live
|
|
5763
|
+
* `permission_*` frames are transient and are not replayed.
|
|
5764
|
+
*
|
|
5765
|
+
* ONE outcome per requestId: the registry entry is consumed here, so a second
|
|
5766
|
+
* ending for the same prompt (the hook path can report both a user answer and
|
|
5767
|
+
* the turn's death) finds nothing and records nothing. A prompt this manager
|
|
5768
|
+
* never saw raised records nothing either -- there is no tool or description
|
|
5769
|
+
* to show, and the clients were never shown the prompt.
|
|
5770
|
+
*
|
|
5771
|
+
* Never throws: it is called from inside a session's event emission and from
|
|
5772
|
+
* the permission response paths, and a failure to journal an outcome must not
|
|
5773
|
+
* take either down.
|
|
5774
|
+
*
|
|
5775
|
+
* @param {string} requestId
|
|
5776
|
+
* @param {'allowed'|'denied'|'expired'|'stopped'} outcome
|
|
5777
|
+
* @param {string} [decision] #8503: the decision token the prompt was answered with
|
|
5778
|
+
* (`allow` / `allowSession` / `allowAlways`); kept only on an `allowed` outcome
|
|
5779
|
+
* @returns {boolean} true when an entry was recorded
|
|
5780
|
+
*/
|
|
5781
|
+
recordPermissionOutcome(requestId, outcome, decision) {
|
|
5782
|
+
try {
|
|
5783
|
+
if (typeof requestId !== 'string' || !requestId) return false
|
|
5784
|
+
const pending = this._permissionRequests.get(requestId)
|
|
5785
|
+
if (!pending) return false
|
|
5786
|
+
this._permissionRequests.delete(requestId)
|
|
5787
|
+
const entry = this._sessions.get(pending.sessionId)
|
|
5788
|
+
if (!entry || entry._destroying) return false
|
|
5789
|
+
this._recordHistory(pending.sessionId, 'permission_outcome', {
|
|
5790
|
+
requestId,
|
|
5791
|
+
tool: pending.tool,
|
|
5792
|
+
description: pending.description,
|
|
5793
|
+
outcome,
|
|
5794
|
+
input: pending.input,
|
|
5795
|
+
decision,
|
|
5796
|
+
toolUseId: pending.toolUseId,
|
|
5797
|
+
})
|
|
5798
|
+
return true
|
|
5799
|
+
} catch (err) {
|
|
5800
|
+
log.warn(`Failed to record permission outcome for ${requestId}: ${err?.message || err}`)
|
|
5801
|
+
return false
|
|
5802
|
+
}
|
|
5803
|
+
}
|
|
5804
|
+
|
|
3009
5805
|
/**
|
|
3010
5806
|
* Push an entry to the history array, trimming to max size.
|
|
3011
5807
|
* Backward-compatible delegate to SessionMessageHistory._pushHistory.
|
|
@@ -3018,7 +5814,7 @@ export class SessionManager extends EventEmitter {
|
|
|
3018
5814
|
}
|
|
3019
5815
|
|
|
3020
5816
|
/**
|
|
3021
|
-
* Schedule a debounced persist
|
|
5817
|
+
* Schedule a debounced persist (trailing debounce with a max-wait, #8954).
|
|
3022
5818
|
* No-op once `destroyAll()` has run — see `serializeState()` (#3697).
|
|
3023
5819
|
*/
|
|
3024
5820
|
_schedulePersist() {
|
|
@@ -3032,8 +5828,29 @@ export class SessionManager extends EventEmitter {
|
|
|
3032
5828
|
* shutdown erases a user's session. History/budget updates should keep
|
|
3033
5829
|
* using the debounced path to avoid write amplification.
|
|
3034
5830
|
*/
|
|
3035
|
-
_flushPersist() {
|
|
3036
|
-
return this._persistence.flushPersist(() => this.serializeState())
|
|
5831
|
+
_flushPersist({ durable = false } = {}) {
|
|
5832
|
+
return this._persistence.flushPersist(() => this.serializeState({ durable }))
|
|
5833
|
+
}
|
|
5834
|
+
|
|
5835
|
+
/**
|
|
5836
|
+
* #8866: a durable flush whose verdict is CONFIRMED. `writeFileRestricted`
|
|
5837
|
+
* does not throw when only the post-rename directory fsync fails (the file is
|
|
5838
|
+
* live, its durability unproven), so a bare durable flush can "succeed"
|
|
5839
|
+
* without proving anything. A caller about to drop its only other copy of the
|
|
5840
|
+
* data must use this and treat `false` as "keep the copy".
|
|
5841
|
+
* Once `destroyAll()` has run, `serializeState` writes nothing and the flush
|
|
5842
|
+
* still reports success, so that state is never "confirmed".
|
|
5843
|
+
* @returns {boolean} true only when the write succeeded AND its durability is confirmed
|
|
5844
|
+
*/
|
|
5845
|
+
_flushPersistConfirmedDurable(sessionId, name = null) {
|
|
5846
|
+
if (this._destroying) return false
|
|
5847
|
+
if (!this._flushPersistOrWarn(sessionId, name, { durable: true })) return false
|
|
5848
|
+
const unconfirmed = this._persistence.lastDurabilityUnconfirmed
|
|
5849
|
+
if (unconfirmed) {
|
|
5850
|
+
log.error(`Session state for ${sessionId} was written but its durability is unconfirmed (${unconfirmed})`)
|
|
5851
|
+
return false
|
|
5852
|
+
}
|
|
5853
|
+
return true
|
|
3037
5854
|
}
|
|
3038
5855
|
|
|
3039
5856
|
/**
|
|
@@ -3052,25 +5869,64 @@ export class SessionManager extends EventEmitter {
|
|
|
3052
5869
|
* be nameless). Omit to look it up from `_sessions`.
|
|
3053
5870
|
* @returns {boolean} true if the write succeeded.
|
|
3054
5871
|
*/
|
|
3055
|
-
_flushPersistOrWarn(sessionId, name = null) {
|
|
3056
|
-
if (this._flushPersist()) return true
|
|
5872
|
+
_flushPersistOrWarn(sessionId, name = null, { durable = false } = {}) {
|
|
5873
|
+
if (this._flushPersist({ durable })) return true
|
|
3057
5874
|
const resolvedName = name || this._sessions.get(sessionId)?.name || null
|
|
3058
5875
|
log.error(`Session state for ${sessionId}${resolvedName ? ` ("${resolvedName}")` : ''} was NOT persisted — it may be lost on restart. Check disk space and write permissions for ${this._stateFilePath}.`)
|
|
3059
5876
|
this.emit('session_persist_failed', { sessionId, name: resolvedName })
|
|
3060
5877
|
return false
|
|
3061
5878
|
}
|
|
3062
5879
|
|
|
5880
|
+
/**
|
|
5881
|
+
* #8259: set or clear the persisted "a turn is in flight" flag and persist it at
|
|
5882
|
+
* once (not on the debounce), so a crash right after either edge leaves the state
|
|
5883
|
+
* file telling the truth.
|
|
5884
|
+
*
|
|
5885
|
+
* CONTRACT: the flag means "input was accepted and has not been answered". It is
|
|
5886
|
+
* set when a provider marks the session busy for a turn, which for claude-tui is
|
|
5887
|
+
* before it awaits prompt readiness and for byok before MCP prompt expansion, so a
|
|
5888
|
+
* restart in those awaits marks input that never reached the model. That is
|
|
5889
|
+
* accurate from the user's side (they sent input and got no answer; sending again
|
|
5890
|
+
* is the right advice) and is accepted. A turn typed directly into the claude-tui
|
|
5891
|
+
* terminal never sets busy and is not covered.
|
|
5892
|
+
*
|
|
5893
|
+
* Ignored during teardown: a session being destroyed flips busy off, and that is
|
|
5894
|
+
* not its turn ending.
|
|
5895
|
+
*/
|
|
5896
|
+
_setTurnInFlight(sessionId, session, next) {
|
|
5897
|
+
const entry = this._sessions.get(sessionId)
|
|
5898
|
+
if (!entry || entry.session !== session || this._destroying || entry._destroying) return
|
|
5899
|
+
if ((entry.turnInFlight === true) === next) return
|
|
5900
|
+
entry.turnInFlight = next
|
|
5901
|
+
this._flushPersistOrWarn(sessionId)
|
|
5902
|
+
}
|
|
5903
|
+
|
|
5904
|
+
/** #8259: the turn's terminal outcome (result, error, stopped) was emitted. */
|
|
5905
|
+
_noteTurnEnded(sessionId, session) {
|
|
5906
|
+
this._setTurnInFlight(sessionId, session, false)
|
|
5907
|
+
}
|
|
5908
|
+
|
|
3063
5909
|
/**
|
|
3064
5910
|
* Wire session events to unified session_event emission.
|
|
3065
5911
|
* Handles both CliSession and PtySession events.
|
|
3066
5912
|
*/
|
|
3067
5913
|
_wireSessionEvents(sessionId, session) {
|
|
5914
|
+
session.on('declaration_turn', (data) => {
|
|
5915
|
+
const entry = this._sessions.get(sessionId)
|
|
5916
|
+
if (!entry || entry._destroying || typeof data?.declarationTurnId !== 'string') return
|
|
5917
|
+
entry._declarationTurnId = data.declarationTurnId
|
|
5918
|
+
delete entry._pendingDeclaredStatus
|
|
5919
|
+
})
|
|
5920
|
+
session.on('assistant_response', (response) => {
|
|
5921
|
+
const entry = this._sessions.get(sessionId)
|
|
5922
|
+
if (entry && !entry._destroying && ownsDeclarationEvent(entry, response)) entry._pendingDeclaredStatus = extractDeclaredStatus(response?.text)
|
|
5923
|
+
})
|
|
3068
5924
|
// #5431: background_tasks_changed — claude-tui's idle transcript re-scan
|
|
3069
5925
|
// reporting that outstanding background work changed (a task-notification
|
|
3070
5926
|
// landed or a wakeup fired while no turn was running). Deliberately NOT
|
|
3071
5927
|
// an ACTIVITY_EVENT: the session is idle by definition when it fires, so
|
|
3072
5928
|
// it must not reset the idle timeout.
|
|
3073
|
-
const PROXIED_EVENTS =
|
|
5929
|
+
const PROXIED_EVENTS = PROXIED_SESSION_EVENTS
|
|
3074
5930
|
// Events that indicate meaningful activity (reset idle timeout)
|
|
3075
5931
|
const ACTIVITY_EVENTS = new Set(['message', 'stream_start', 'tool_start', 'result', 'user_question'])
|
|
3076
5932
|
// Session-scoped logger — entries are tagged with sessionId for per-session routing
|
|
@@ -3128,10 +5984,51 @@ export class SessionManager extends EventEmitter {
|
|
|
3128
5984
|
})
|
|
3129
5985
|
}
|
|
3130
5986
|
|
|
5987
|
+
// #8259: BaseSession's `_isBusy` accessor reports a turn starting (input dispatched
|
|
5988
|
+
// to the provider, including a queued follow-up when it flushes) and ending
|
|
5989
|
+
// (result, error, stop, abort: every end reaches the same clear). Persist both
|
|
5990
|
+
// edges at once rather than on the 2 s debounce, so a crash right after either
|
|
5991
|
+
// leaves the state file saying the truth. Ignored during teardown: a session
|
|
5992
|
+
// being destroyed flips busy off, and that is not its turn ending.
|
|
5993
|
+
session.on('turn_state', ({ active } = {}) => {
|
|
5994
|
+
if (active === true) {
|
|
5995
|
+
const entry = this._sessions.get(sessionId)
|
|
5996
|
+
if (entry) delete entry._pendingDeclaredStatus
|
|
5997
|
+
}
|
|
5998
|
+
this._setTurnInFlight(sessionId, session, active === true)
|
|
5999
|
+
})
|
|
6000
|
+
// A user Stop is a terminal outcome too (cli/tui emit it instead of a result).
|
|
6001
|
+
session.on('stopped', (data) => {
|
|
6002
|
+
const entry = this._sessions.get(sessionId)
|
|
6003
|
+
if (entry && ownsDeclarationEvent(entry, data)) {
|
|
6004
|
+
delete entry._pendingDeclaredStatus
|
|
6005
|
+
this._noteTurnEnded(sessionId, session)
|
|
6006
|
+
}
|
|
6007
|
+
})
|
|
6008
|
+
|
|
3131
6009
|
for (const event of PROXIED_EVENTS) {
|
|
3132
|
-
session.on(event, (
|
|
3133
|
-
|
|
6010
|
+
session.on(event, (emitted) => {
|
|
6011
|
+
// #6630: an `error` carries no time of its own, and its wire frame and its
|
|
6012
|
+
// history entry each used to stamp one. A client that held the live bubble
|
|
6013
|
+
// and then took a cursor replay compares them to dedup (an error has no
|
|
6014
|
+
// message id), and two stamps a millisecond apart read as two errors.
|
|
6015
|
+
// Stamp ONCE, here, and let both consumers read it.
|
|
6016
|
+
const data = event === 'error' && emitted && typeof emitted === 'object' && !Number.isFinite(emitted.timestamp)
|
|
6017
|
+
? { ...emitted, timestamp: Date.now() }
|
|
6018
|
+
: emitted
|
|
6019
|
+
// #7393: a `late` thinking frame is a finished turn being decorated, not
|
|
6020
|
+
// activity: it must not push the idle timeout back.
|
|
6021
|
+
if (ACTIVITY_EVENTS.has(event) && data?.late !== true) this.touchActivity(sessionId)
|
|
3134
6022
|
this._recordHistory(sessionId, event, data)
|
|
6023
|
+
// #8259: the turn's terminal outcome has been emitted. Clear the persisted
|
|
6024
|
+
// in-flight flag HERE, whatever the provider process does next: a subprocess
|
|
6025
|
+
// provider emits its result and keeps `_isBusy` true until the child closes,
|
|
6026
|
+
// and a restart in that window must not call a finished turn interrupted. Every
|
|
6027
|
+
// provider's outcome passes this listener. A recoverable error (a rejected
|
|
6028
|
+
// follow-up, say) does not end the turn.
|
|
6029
|
+
if ((event === 'result' || (event === 'error' && data?.recoverable !== true)) && ownsDeclarationEvent(this._sessions.get(sessionId), data)) {
|
|
6030
|
+
this._noteTurnEnded(sessionId, session)
|
|
6031
|
+
}
|
|
3135
6032
|
this.emit('session_event', { sessionId, event, data })
|
|
3136
6033
|
if (LOGGED_EVENTS.has(event)) {
|
|
3137
6034
|
const detail = event === 'error' ? `: ${data?.message || ''}` : ''
|
|
@@ -3269,15 +6166,64 @@ export class SessionManager extends EventEmitter {
|
|
|
3269
6166
|
// store-core follow-up (#5937). Until then a client that reconnects
|
|
3270
6167
|
// mid-queue won't see the pre-existing queued items — acceptable for the
|
|
3271
6168
|
// foundation slice, tracked in #5937.
|
|
3272
|
-
const builtinTransient =
|
|
3273
|
-
const
|
|
6169
|
+
const builtinTransient = BUILTIN_TRANSIENT_SESSION_EVENTS
|
|
6170
|
+
const declaredCustomEvents = Array.isArray(session.constructor.customEvents) ? session.constructor.customEvents : []
|
|
6171
|
+
// #8574: a name that is already PROXIED has its listener (above); a second
|
|
6172
|
+
// transient one would forward every frame to the client twice. Every
|
|
6173
|
+
// in-repo provider is held to this by tests/provider-custom-events-overlap.test.js;
|
|
6174
|
+
// this covers a provider registered from outside the repo, and says so
|
|
6175
|
+
// rather than hiding the provider's mistake.
|
|
6176
|
+
const overlapping = declaredCustomEvents.filter((e) => PROXIED_EVENTS.includes(e))
|
|
6177
|
+
if (overlapping.length > 0) {
|
|
6178
|
+
sessionLog.warn(`[customEvents] ${session.constructor.name} lists proxied event(s) ${overlapping.join(', ')} in customEvents; ignoring the duplicate (they are already forwarded)`)
|
|
6179
|
+
}
|
|
6180
|
+
const customEvents = declaredCustomEvents.filter((e) => !PROXIED_EVENTS.includes(e))
|
|
3274
6181
|
const TRANSIENT_EVENTS = [...new Set([...builtinTransient, ...customEvents])]
|
|
3275
6182
|
for (const event of TRANSIENT_EVENTS) {
|
|
3276
6183
|
session.on(event, (data) => {
|
|
6184
|
+
// #8700: a level the SESSION changed or learned (a model switch, the
|
|
6185
|
+
// effort Claude Code reported at turn start) is logged here, under the
|
|
6186
|
+
// Chroxy session id an operator greps for, in the same summary format
|
|
6187
|
+
// the `set_thinking_level` handler prints.
|
|
6188
|
+
if (event === 'thinking_level_changed') {
|
|
6189
|
+
const described = typeof session.describeThinkingLevel === 'function'
|
|
6190
|
+
? session.describeThinkingLevel()
|
|
6191
|
+
: `requested=${session.thinkingLevel || 'default'}`
|
|
6192
|
+
sessionLog.info(`Thinking level on session ${sessionId}: ${described}${data?.reason ? ` — ${data.reason}` : ''}`)
|
|
6193
|
+
}
|
|
6194
|
+
// #8348: journal the prompt's lifecycle BEFORE it is announced, so a
|
|
6195
|
+
// client that sees it end can always find the durable record. The
|
|
6196
|
+
// frames themselves stay transient; only the outcome is kept.
|
|
6197
|
+
if (event === 'permission_request') {
|
|
6198
|
+
this.notePermissionRequest(sessionId, data)
|
|
6199
|
+
} else if (event === 'permission_resolved' || event === 'permission_expired') {
|
|
6200
|
+
const outcome = permissionOutcomeForEvent(event, data)
|
|
6201
|
+
if (outcome) this.recordPermissionOutcome(data.requestId, outcome, event === 'permission_resolved' ? permissionDecisionToken(data.decision, data.scope) : undefined)
|
|
6202
|
+
// #8470: a question a newer one replaced has no requestId, so the outcome
|
|
6203
|
+
// journal above never sees it. Its verdict is recorded on the question's
|
|
6204
|
+
// own history entry instead.
|
|
6205
|
+
if (event === 'permission_resolved' && data?.reason === 'superseded' && typeof data.toolUseId === 'string') {
|
|
6206
|
+
if (this._history.markQuestionSuperseded(sessionId, data.toolUseId)) this._schedulePersist()
|
|
6207
|
+
}
|
|
6208
|
+
}
|
|
6209
|
+
// Not journaled yet: a BYOK Task subagent's prompts, which reach this
|
|
6210
|
+
// session wrapped in `agent_event { type, payload }`. The client holds such
|
|
6211
|
+
// a prompt inside the Task bubble's `childAgentEvents`, not as a top-level
|
|
6212
|
+
// prompt message, so it cannot yet reconcile a recorded outcome with it: it
|
|
6213
|
+
// would show the nested prompt and a second standalone record. Until it can
|
|
6214
|
+
// (a follow-up), child prompts keep their transient, live-only behaviour.
|
|
3277
6215
|
this.emit('session_event', { sessionId, event, data })
|
|
3278
6216
|
})
|
|
3279
6217
|
}
|
|
3280
6218
|
|
|
6219
|
+
// #8371: a tracked tool's sanitised input is known before the tool runs.
|
|
6220
|
+
// Backfill the `tool_start` history entry now so a replay during the
|
|
6221
|
+
// running tool carries the INPUT. History only: nothing is sent to clients
|
|
6222
|
+
// (the live view already got it as `tool_input_delta`).
|
|
6223
|
+
session.on('tool_input_recorded', (data) => {
|
|
6224
|
+
this._history.backfillToolInput(sessionId, data?.toolUseId, data?.input)
|
|
6225
|
+
})
|
|
6226
|
+
|
|
3281
6227
|
// models_updated is global (not per-session) — forward as transient event
|
|
3282
6228
|
session.on('models_updated', (data) => {
|
|
3283
6229
|
this.emit('session_event', { sessionId, event: 'models_updated', data })
|
|
@@ -3295,7 +6241,7 @@ export class SessionManager extends EventEmitter {
|
|
|
3295
6241
|
session.on('respawn_exhausted', (data) => {
|
|
3296
6242
|
if (!this._sessions.has(sessionId)) return
|
|
3297
6243
|
sessionLog.error(`[respawn_exhausted] ${data?.reason || 'pty respawn gave up'} — destroying session`)
|
|
3298
|
-
this.destroySession(sessionId)
|
|
6244
|
+
this.destroySession(sessionId, { archiveReason: 'respawn_exhausted' })
|
|
3299
6245
|
})
|
|
3300
6246
|
}
|
|
3301
6247
|
|
|
@@ -3431,19 +6377,25 @@ export class SessionManager extends EventEmitter {
|
|
|
3431
6377
|
// Resolved the same way as listSessions; defensive so a misbehaving
|
|
3432
6378
|
// provider can't break the usage broadcast.
|
|
3433
6379
|
const usageProvider = entry.provider || this._providerType
|
|
3434
|
-
let billingClass
|
|
3435
|
-
|
|
3436
|
-
|
|
3437
|
-
|
|
3438
|
-
|
|
6380
|
+
let billingClass = entry.agentConnection?.entitlement?.route === 'api'
|
|
6381
|
+
? BILLING_CLASSES.API_KEY
|
|
6382
|
+
: entry.agentConnection?.entitlement?.route === 'subscription'
|
|
6383
|
+
? BILLING_CLASSES.SUBSCRIPTION
|
|
6384
|
+
: undefined
|
|
6385
|
+
if (!billingClass && entry.agentConnection?.provenance?.source === 'legacy') {
|
|
6386
|
+
try {
|
|
6387
|
+
billingClass = getProviderAuthInfo(usageProvider, entry.session.constructor)?.billingClass
|
|
6388
|
+
} catch {
|
|
6389
|
+
billingClass = undefined
|
|
6390
|
+
}
|
|
6391
|
+
if (!billingClass) billingClass = billingClassForProvider(usageProvider, Date.now())
|
|
3439
6392
|
}
|
|
3440
|
-
if (!billingClass) billingClass = billingClassForProvider(usageProvider, Date.now())
|
|
3441
6393
|
// Shallow-copy on emit so a subscriber that mutates the payload
|
|
3442
6394
|
// can't corrupt the canonical accumulator (#4072 review-prep).
|
|
3443
6395
|
this.emit('session_event', {
|
|
3444
6396
|
sessionId,
|
|
3445
6397
|
event: 'session_usage',
|
|
3446
|
-
data: { cumulativeUsage: { ...acc }, billingClass },
|
|
6398
|
+
data: { cumulativeUsage: { ...acc }, billingClass, agentConnection: entry.agentConnection },
|
|
3447
6399
|
})
|
|
3448
6400
|
// #5665: feed this turn's cost into the machine-wide monthly
|
|
3449
6401
|
// programmatic-credit meter, but ONLY for programmatic-credit sessions
|
|
@@ -3617,6 +6569,233 @@ export class SessionManager extends EventEmitter {
|
|
|
3617
6569
|
this._timeoutManager.stop()
|
|
3618
6570
|
}
|
|
3619
6571
|
|
|
6572
|
+
/**
|
|
6573
|
+
* #7601 — start / stop the proactive container-liveness poll. No-op when the
|
|
6574
|
+
* monitor was not constructed (no `containerInspect` seam wired).
|
|
6575
|
+
*/
|
|
6576
|
+
startContainerLiveness() {
|
|
6577
|
+
this._containerLivenessMonitor?.start()
|
|
6578
|
+
}
|
|
6579
|
+
|
|
6580
|
+
stopContainerLiveness() {
|
|
6581
|
+
this._containerLivenessMonitor?.stop()
|
|
6582
|
+
}
|
|
6583
|
+
|
|
6584
|
+
/**
|
|
6585
|
+
* #7601 — the live containerized sessions the liveness poll should inspect.
|
|
6586
|
+
*
|
|
6587
|
+
* A target is included only when its provider exposes the #7599 vanish-surface
|
|
6588
|
+
* contract (`notifyContainerVanished`) AND currently holds a container id.
|
|
6589
|
+
* The feature-detect is the gate, not a hard-coded provider list: `docker-byok`
|
|
6590
|
+
* advertised `containerized` without the surface until #7600 wired it, and was
|
|
6591
|
+
* excluded here by exactly that check — no enumeration change was needed. A session tearing down is skipped (its
|
|
6592
|
+
* container is being removed deliberately). An environment with no sessions
|
|
6593
|
+
* contributes no target, so nothing is inspected for it — the #7601 negative
|
|
6594
|
+
* control falls out of this enumeration rather than a separate check.
|
|
6595
|
+
*
|
|
6596
|
+
* @returns {Array<{sessionId: string, containerId: string, session: object}>}
|
|
6597
|
+
*/
|
|
6598
|
+
_listContainerLivenessTargets() {
|
|
6599
|
+
const targets = []
|
|
6600
|
+
for (const [sessionId, entry] of this._sessions) {
|
|
6601
|
+
if (!entry || entry._destroying) continue
|
|
6602
|
+
const session = entry.session
|
|
6603
|
+
if (!session || typeof session.notifyContainerVanished !== 'function') continue
|
|
6604
|
+
// The LIVE container id lives on the provider (mutated at runtime when it
|
|
6605
|
+
// owns the container); the persisted `entry.containerId` is null for a
|
|
6606
|
+
// per-session `--rm` container, so read the provider's.
|
|
6607
|
+
const containerId = session._containerId
|
|
6608
|
+
if (!containerId) continue
|
|
6609
|
+
targets.push({ sessionId, containerId, session })
|
|
6610
|
+
}
|
|
6611
|
+
return targets
|
|
6612
|
+
}
|
|
6613
|
+
|
|
6614
|
+
/**
|
|
6615
|
+
* #7602 — fan a recovery edge across every live session bound to `envId`, for a
|
|
6616
|
+
* container chroxy itself just brought back (`EnvironmentManager.restart()`,
|
|
6617
|
+
* which has already awaited `docker restart` and set `status: 'running'`).
|
|
6618
|
+
*
|
|
6619
|
+
* The #7601 fast-path was asymmetric without this: a Control Room restart
|
|
6620
|
+
* surfaced CONTAINER_VANISHED on every bound session IMMEDIATELY, but the
|
|
6621
|
+
* matching re-attach waited up to a full poll interval. That is not only slow
|
|
6622
|
+
* on the one trigger whose container is most certainly back — it leaves the
|
|
6623
|
+
* vanish latch SET for up to 30s, so a genuine second vanish inside that window
|
|
6624
|
+
* would find the latch armed and surface NOTHING. Clearing the latch promptly
|
|
6625
|
+
* is what makes the next real vanish visible again.
|
|
6626
|
+
*
|
|
6627
|
+
* MUST run AFTER the vanish fan-out for the same event: the edge is defined as
|
|
6628
|
+
* `clearContainerVanished()` actually flipping the latch, so a session whose
|
|
6629
|
+
* vanish has not been surfaced yet correctly contributes no edge, and a session
|
|
6630
|
+
* that never vanished is skipped rather than gratuitously re-resolved.
|
|
6631
|
+
*
|
|
6632
|
+
* Reads `_sessions` filtered by `environmentId` rather than the environment's
|
|
6633
|
+
* own `env.sessions` roster — deliberately the SAME source
|
|
6634
|
+
* `_listContainerLivenessTargets` reads, so the two paths that can produce a
|
|
6635
|
+
* recovery edge cannot disagree about who is in the environment.
|
|
6636
|
+
*
|
|
6637
|
+
* #7621 — that agreement is with the POLL. It is a DISAGREEMENT with the fan-out
|
|
6638
|
+
* this method is ordered directly behind: `WsServer._surfaceContainerVanishedForEnvironment`
|
|
6639
|
+
* arms the latch from `env.sessions`, and this clears it from `_sessions`. An
|
|
6640
|
+
* edge therefore exists only for a session in BOTH rosters, and the two
|
|
6641
|
+
* divergences are not equally harmless:
|
|
6642
|
+
*
|
|
6643
|
+
* - in `_sessions` but NOT in `env.sessions` → armed by nothing, so there is
|
|
6644
|
+
* no latch to clear and no edge. Costs latency only: the 30s poll reads
|
|
6645
|
+
* this same roster and still reaches it.
|
|
6646
|
+
* - in `env.sessions` but the entry is tagged with a different env (or null)
|
|
6647
|
+
* → armed here and NOT cleared by this fast path, so the latch stays SET
|
|
6648
|
+
* until the next poll tick. The latch is idempotent, so a genuine second
|
|
6649
|
+
* vanish inside that window surfaces NOTHING. Worse than the first mode,
|
|
6650
|
+
* but bounded the same way and not permanent: `_listContainerLivenessTargets`
|
|
6651
|
+
* carries no `environmentId` filter, so the poll reaches a mis-tagged
|
|
6652
|
+
* session this method cannot, and one tick clears it.
|
|
6653
|
+
*
|
|
6654
|
+
* #7552's `addSession`/`removeSession` tagging is what keeps the two rosters in
|
|
6655
|
+
* sync, which is why the second mode is a dependency rather than a live bug.
|
|
6656
|
+
* Both modes are pinned by tests — which set the two rosters directly and so
|
|
6657
|
+
* document the coupling; they do NOT exercise that tagging and would not catch
|
|
6658
|
+
* a regression in it.
|
|
6659
|
+
*
|
|
6660
|
+
* @param {string} envId
|
|
6661
|
+
* @param {string} [reason] the emitting event, for the log line
|
|
6662
|
+
* @returns {number} how many sessions were re-attached
|
|
6663
|
+
*/
|
|
6664
|
+
reattachEnvironmentSessions(envId, reason = 'environment_restarted') {
|
|
6665
|
+
// No `!envId` guard: `entry.environmentId` is normalised to a non-empty
|
|
6666
|
+
// string or null at create time, so a blank/undefined `envId` matches no
|
|
6667
|
+
// entry and the filter below already makes this a no-op. A separate
|
|
6668
|
+
// emptiness check could not be made to fail — docs/false-safety-guards.md.
|
|
6669
|
+
let reattached = 0
|
|
6670
|
+
for (const [sessionId, entry] of [...this._sessions]) {
|
|
6671
|
+
// No `_destroying` filter here on purpose: `_reattachEnvironmentBoundSession`
|
|
6672
|
+
// already owns that gate, and a second copy of it could not be made to fail
|
|
6673
|
+
// independently — see docs/false-safety-guards.md.
|
|
6674
|
+
if (!entry || entry.environmentId !== envId) continue
|
|
6675
|
+
const session = entry.session
|
|
6676
|
+
try {
|
|
6677
|
+
// The edge, synthesised exactly as the poll observes it.
|
|
6678
|
+
if (session?.clearContainerVanished?.() !== true) continue
|
|
6679
|
+
const outcome = this._reattachEnvironmentBoundSession(sessionId)
|
|
6680
|
+
if (outcome.reattached) reattached++
|
|
6681
|
+
log.info(`[${reason}] re-attach for session ${sessionId} in env ${envId}: ${outcome.reason}`)
|
|
6682
|
+
} catch (err) {
|
|
6683
|
+
// Contained per session: one throwing provider must not strand the rest.
|
|
6684
|
+
log.warn(`[${reason}] re-attach failed for session ${sessionId}: ${err?.message || err}`)
|
|
6685
|
+
}
|
|
6686
|
+
}
|
|
6687
|
+
return reattached
|
|
6688
|
+
}
|
|
6689
|
+
|
|
6690
|
+
/**
|
|
6691
|
+
* #7602 — the LIVE analogue of `_resolveRestoredContainerBinding`: re-affirm a
|
|
6692
|
+
* running env-bound session's container binding when the liveness poll reports
|
|
6693
|
+
* that container running again, so the next turn resumes inside it.
|
|
6694
|
+
*
|
|
6695
|
+
* Reconnect is BEST-EFFORT and sits strictly ON TOP of #7599's non-negotiable
|
|
6696
|
+
* fail-visible surface. The vanish has already been surfaced by the time this
|
|
6697
|
+
* runs; nothing here can make a session quietly resume something it should not,
|
|
6698
|
+
* because the only mutation it can produce is a re-affirmation of the binding
|
|
6699
|
+
* the session already has. Every refusal below leaves `_containerId` exactly as
|
|
6700
|
+
* it was — never nulled (the #7561 trap: a null id reads as `_containerOwned`
|
|
6701
|
+
* and spawns a fresh default `node:22-slim`), never repointed.
|
|
6702
|
+
*
|
|
6703
|
+
* The gate order, and why each case lands where it does:
|
|
6704
|
+
*
|
|
6705
|
+
* 1. No `reattachContainer` on the provider → SILENT no-op. Feature-detect,
|
|
6706
|
+
* not a provider allow-list, exactly as #7601 gates the poll on
|
|
6707
|
+
* `notifyContainerVanished`. `DockerSession` (always self-owned `--rm`)
|
|
6708
|
+
* and `DockerByokSession` (whose whole re-attach is the readiness restore
|
|
6709
|
+
* inside its own `clearContainerVanished`, #7600) are excluded by this
|
|
6710
|
+
* and need no entry in any list here.
|
|
6711
|
+
* 2. No `entry.environmentId` → SILENT no-op: TERMINAL by classification.
|
|
6712
|
+
* A session-owned `--rm` container and a bare-`containerId` session have
|
|
6713
|
+
* no environment to re-resolve against and no registry that could vouch
|
|
6714
|
+
* for the container; #7599's error is the whole story for them, and a
|
|
6715
|
+
* second error would be noise on a case that is working as designed.
|
|
6716
|
+
* 3. Anything past that which cannot be confirmed — environments disabled,
|
|
6717
|
+
* `getContainerInfo` refusing (`status !== 'running'`, `destroying`), no
|
|
6718
|
+
* container on the environment, or an id that DIFFERS from the session's
|
|
6719
|
+
* — is a REFUSAL: one visible `ENVIRONMENT_UNAVAILABLE` session error and
|
|
6720
|
+
* no rebind. The differing-id case is the important one: it means the
|
|
6721
|
+
* environment's container was REBUILT, so it carries none of this
|
|
6722
|
+
* session's in-container state, and re-pointing at it would resume the
|
|
6723
|
+
* conversation as a silently blank one.
|
|
6724
|
+
*
|
|
6725
|
+
* The refusal emits at most once per vanish because it can only be reached
|
|
6726
|
+
* from the poll's recovery EDGE (see ContainerLivenessMonitor._tick) — the
|
|
6727
|
+
* latch transitions once, so a permanently-refusing environment produces one
|
|
6728
|
+
* error, not one every 30s.
|
|
6729
|
+
*
|
|
6730
|
+
* `env.sessions` is deliberately untouched: the session never left the
|
|
6731
|
+
* environment, so `addSession`/`removeSession` symmetry — and with it the
|
|
6732
|
+
* #7562 destroy guard's truthfulness — is preserved by not participating.
|
|
6733
|
+
*
|
|
6734
|
+
* @param {string} sessionId
|
|
6735
|
+
* @returns {{reattached: boolean, reason: string}}
|
|
6736
|
+
* @private
|
|
6737
|
+
*/
|
|
6738
|
+
_reattachEnvironmentBoundSession(sessionId) {
|
|
6739
|
+
const entry = this._sessions.get(sessionId)
|
|
6740
|
+
if (!entry || entry._destroying) return { reattached: false, reason: 'session_gone' }
|
|
6741
|
+
const session = entry.session
|
|
6742
|
+
if (!session || session._destroying) return { reattached: false, reason: 'session_gone' }
|
|
6743
|
+
if (typeof session.reattachContainer !== 'function') {
|
|
6744
|
+
return { reattached: false, reason: 'provider_unsupported' }
|
|
6745
|
+
}
|
|
6746
|
+
|
|
6747
|
+
const environmentId = typeof entry.environmentId === 'string' && entry.environmentId.length > 0
|
|
6748
|
+
? entry.environmentId
|
|
6749
|
+
: null
|
|
6750
|
+
if (!environmentId) return { reattached: false, reason: 'not_environment_bound' }
|
|
6751
|
+
|
|
6752
|
+
const refuse = (reason, detail) => {
|
|
6753
|
+
log.warn(`Session ${sessionId}: refusing to re-attach to environment "${environmentId}" — ${detail}`)
|
|
6754
|
+
session.emit('error', {
|
|
6755
|
+
code: 'ENVIRONMENT_UNAVAILABLE',
|
|
6756
|
+
message: `This session's container environment cannot be re-entered: ${detail}. ` +
|
|
6757
|
+
`The session stays bound to its original container and will not be resumed elsewhere.`,
|
|
6758
|
+
})
|
|
6759
|
+
return { reattached: false, reason }
|
|
6760
|
+
}
|
|
6761
|
+
|
|
6762
|
+
if (!this._environmentManager || typeof this._environmentManager.getContainerInfo !== 'function') {
|
|
6763
|
+
return refuse('environments_disabled', 'container environments are not enabled on this server')
|
|
6764
|
+
}
|
|
6765
|
+
|
|
6766
|
+
let info
|
|
6767
|
+
try {
|
|
6768
|
+
info = this._environmentManager.getContainerInfo(environmentId)
|
|
6769
|
+
} catch (err) {
|
|
6770
|
+
// Covers "no such environment" and "not running (status: stopped | error |
|
|
6771
|
+
// destroying)" alike — getContainerInfo throws for each.
|
|
6772
|
+
return refuse('environment_unavailable', err?.message || String(err))
|
|
6773
|
+
}
|
|
6774
|
+
// LOAD-BEARING, and the reason teardown is checked ONCE at the top: the call
|
|
6775
|
+
// above is SYNCHRONOUS, so this whole method runs as one uninterrupted block
|
|
6776
|
+
// from those checks through `reattachContainer` below. If `getContainerInfo`
|
|
6777
|
+
// ever becomes async (a remote backend, say), `entry._destroying` /
|
|
6778
|
+
// `session._destroying` must be re-taken AFTER the await — a destroy landing
|
|
6779
|
+
// in that gap would emit 'error' on a session whose listeners are already
|
|
6780
|
+
// gone, and Node throws on an unhandled 'error'.
|
|
6781
|
+
if (!info || typeof info.containerId !== 'string' || info.containerId.length === 0) {
|
|
6782
|
+
return refuse('no_container', 'the environment reports no container')
|
|
6783
|
+
}
|
|
6784
|
+
if (info.containerId !== session._containerId) {
|
|
6785
|
+
return refuse(
|
|
6786
|
+
'container_replaced',
|
|
6787
|
+
`the environment now runs a different container (${info.containerId.slice(0, 12)}), ` +
|
|
6788
|
+
`not the one this session was created in (${String(session._containerId).slice(0, 12)})`,
|
|
6789
|
+
)
|
|
6790
|
+
}
|
|
6791
|
+
|
|
6792
|
+
if (!session.reattachContainer(info)) {
|
|
6793
|
+
return refuse('provider_refused', 'the session provider refused the binding')
|
|
6794
|
+
}
|
|
6795
|
+
log.info(`Session ${sessionId} re-attached to environment "${environmentId}" container ${info.containerId.slice(0, 12)}`)
|
|
6796
|
+
return { reattached: true, reason: 'ok' }
|
|
6797
|
+
}
|
|
6798
|
+
|
|
3620
6799
|
getSessionCost(sessionId) {
|
|
3621
6800
|
return this._costBudget.getSessionCost(sessionId)
|
|
3622
6801
|
}
|