@chroxy/server 0.10.0 → 0.11.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +602 -19
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +416 -11
- package/package.json +20 -23
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1353 -41
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +24 -1
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +101 -0
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +74 -9
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +1153 -20
- package/src/byok-mcp-config.js +1712 -8
- package/src/byok-mcp-fleet.js +416 -29
- package/src/byok-mcp-oauth-store.js +329 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +257 -40
- package/src/byok-session.js +1400 -149
- package/src/byok-tool-executor.js +2681 -38
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +96 -51
- package/src/chroxy-host-metadata.js +122 -0
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +109 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +223 -60
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3611 -286
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +6 -6
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +46 -11
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +16 -17
- package/src/cli/providers-cmd.js +6 -6
- package/src/cli/schedule-cmd.js +804 -0
- package/src/cli/server-cmd.js +64 -2
- package/src/cli/service-cmd.js +70 -27
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +168 -14
- package/src/cli/tokens-cmd.js +212 -0
- package/src/cli/tunnel-cmd.js +256 -25
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1117 -116
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +2108 -101
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +571 -45
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +738 -52
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +23 -30
- package/src/control-room/skills-inventory.js +8 -3
- package/src/control-room/survey.js +32 -0
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +279 -29
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diagnostics.js +3 -0
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +188 -4
- package/src/docker-session.js +293 -10
- package/src/doctor.js +783 -66
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +39 -10
- package/src/environments/backends/k8s.js +58 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +137 -14
- package/src/event-normalizer.js +363 -110
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +100 -7
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +563 -62
- package/src/handlers/checkpoint-handlers.js +162 -20
- package/src/handlers/control-room-handlers.js +99 -29
- package/src/handlers/conversation-handlers.js +563 -25
- package/src/handlers/credential-handlers.js +43 -2
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +101 -13
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +689 -48
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +584 -0
- package/src/handlers/session-handlers.js +546 -16
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +822 -35
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/handlers/token-handlers.js +11 -2
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +286 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +309 -48
- package/src/jsonl-subprocess-session.js +122 -9
- package/src/keychain.js +160 -13
- package/src/logger.js +240 -31
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +100 -10
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +82 -12
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +63 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +381 -0
- package/src/orchestration/orchestration-manager.js +1342 -0
- package/src/orchestration/permission-gate.js +121 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +206 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +422 -0
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +236 -12
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-audit.js +79 -3
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1770 -0
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +1175 -94
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +174 -12
- package/src/permission-rule-store.js +411 -0
- package/src/permission-scope.js +43 -0
- package/src/platform.js +483 -23
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +228 -6
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +945 -0
- package/src/scheduler.js +1099 -0
- package/src/sdk-session.js +2374 -168
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +50 -4
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +760 -62
- package/src/server-identity.js +42 -14
- package/src/service.js +682 -53
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3879 -308
- package/src/session-message-history.js +749 -37
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-title.js +168 -0
- package/src/session-token-store.js +70 -36
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +22 -5
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +596 -0
- package/src/subagent-counter.js +9 -1
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +99 -38
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/token-manager.js +39 -9
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +413 -31
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +145 -35
- package/src/tunnel/index.js +13 -1
- package/src/tunnel/preview.js +64 -0
- package/src/tunnel-check.js +1 -1
- package/src/turn-outcome.js +137 -0
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +122 -0
- package/src/user-shell-session.js +157 -37
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +301 -0
- package/src/utils/composite-key.js +45 -0
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/iso-datetime.js +51 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +485 -29
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +196 -5
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +634 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +11 -3
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +370 -66
- package/src/ws-file-ops/common.js +384 -11
- package/src/ws-file-ops/git.js +615 -44
- package/src/ws-file-ops/index.js +7 -0
- package/src/ws-file-ops/memory.js +460 -0
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +676 -94
- package/src/ws-forwarding.js +373 -55
- package/src/ws-handler-context.js +89 -2
- package/src/ws-history.js +1018 -177
- package/src/ws-message-handlers.js +23 -1
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +589 -38
- package/src/ws-schemas.js +6 -0
- package/src/ws-server.js +936 -105
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
package/src/cli-session.js
CHANGED
|
@@ -1,39 +1,40 @@
|
|
|
1
|
+
import { assistantResponseText, sdkDeclarationEligible } from './assistant-response.js'
|
|
1
2
|
import { spawn } from 'child_process'
|
|
3
|
+
import { stillAuthorized } from './connection-authority.js'
|
|
2
4
|
import { createInterface } from 'readline'
|
|
3
|
-
import { randomBytes } from 'crypto'
|
|
4
|
-
import {
|
|
5
|
+
import { randomBytes, randomUUID } from 'crypto'
|
|
6
|
+
import { mkdirSync, rmSync, writeFileSync } from 'fs'
|
|
7
|
+
import { normalizeSdkModelUsage } from './usage-normalize.js'
|
|
8
|
+
import { tmpdir } from 'os'
|
|
9
|
+
import { claudeConfigDir } from './utils/claude-config-dir.js'
|
|
5
10
|
import { join } from 'path'
|
|
6
11
|
import { createPermissionHookManager } from './permission-hook.js'
|
|
7
12
|
import { guardChildStreams } from './child-stream-guard.js'
|
|
8
|
-
import { BaseSession, buildBaseSessionOpts } from './base-session.js'
|
|
13
|
+
import { BaseSession, buildBaseSessionOpts, reportInputAdmission, spawnRefusalAdmission } from './base-session.js'
|
|
9
14
|
import { buildContentBlocks } from './content-blocks.js'
|
|
10
15
|
import { ALLOWED_MODEL_IDS } from './models.js'
|
|
11
16
|
import { CLAUDE_FALLBACK_MODELS, claudeModelMetadata } from './claude-model-catalog.js'
|
|
12
|
-
import { forceKill } from './platform.js'
|
|
17
|
+
import { forceKill, killProcessTree } from './platform.js'
|
|
13
18
|
import { MessageTransformPipeline } from './message-transform.js'
|
|
14
19
|
import { emitToolResults } from './tool-result.js'
|
|
15
|
-
import { buildToolStartData, extractToolInputSemantics } from './claude-stream-parser.js'
|
|
16
|
-
import {
|
|
20
|
+
import { buildToolStartData, extractToolInputSemantics, parseCompactBoundaryMeta, formatCompactBoundaryContent, formatStatusContent } from './claude-stream-parser.js'
|
|
21
|
+
import { ThinkingStreams } from './thinking-stream.js'
|
|
22
|
+
import { CLAUDE_BINARY_CANDIDATES, resolveClaudeBinary } from './utils/claude-binary.js'
|
|
23
|
+
import { labelBinarySpawnFailure } from './utils/verify-binary.js'
|
|
17
24
|
import { prepareSpawn } from './utils/win-spawn.js'
|
|
25
|
+
import { CLAUDE_CLI_CUSTOMIZATION } from './provider-customization.js'
|
|
18
26
|
import { buildSpawnEnv } from './utils/spawn-env.js'
|
|
19
27
|
import { RespawnRateLimiter } from './utils/respawn-rate-limiter.js'
|
|
28
|
+
import { assertSafeArgvValue } from './utils/argv-safety.js'
|
|
29
|
+
import { writePermissionModeSidecarAtomic } from './utils/permission-mode-sidecar.js'
|
|
30
|
+
import { sweepStaleOwnedDirs, ensureOwnedBaseDir, OWNER_PID_FILE } from './utils/stale-session-dirs.js'
|
|
20
31
|
import { createLogger, loggerForSession } from './logger.js'
|
|
21
32
|
import { formatIdleDuration } from './session-timeout-manager.js'
|
|
22
33
|
import { BILLING_CLASSES, isProgrammaticCreditEra } from './billing-class.js'
|
|
34
|
+
import { turnOutcomeField, outcomeFromSdkResult } from './turn-outcome.js'
|
|
23
35
|
|
|
24
36
|
const log = createLogger('cli-session')
|
|
25
37
|
|
|
26
|
-
// Resolve the claude binary once at module load. Under a GUI launch
|
|
27
|
-
// (e.g. Tauri on macOS) PATH is minimal and may exclude the user's
|
|
28
|
-
// install dir — fall through to known locations so `spawn()` succeeds.
|
|
29
|
-
const CLAUDE = resolveBinary('claude', [
|
|
30
|
-
join(homedir(), '.local/bin/claude'),
|
|
31
|
-
'/opt/homebrew/bin/claude',
|
|
32
|
-
'/usr/local/bin/claude',
|
|
33
|
-
join(homedir(), '.claude/local/node_modules/.bin/claude'),
|
|
34
|
-
join(homedir(), '.npm-global/bin/claude'),
|
|
35
|
-
])
|
|
36
|
-
|
|
37
38
|
// Default max accumulated size for tool_use input_json_delta chunks (~256KB)
|
|
38
39
|
const DEFAULT_MAX_TOOL_INPUT_LENGTH = 262144
|
|
39
40
|
|
|
@@ -102,6 +103,38 @@ export function stderrIndicatesUnknownResume(stderrLines) {
|
|
|
102
103
|
return false
|
|
103
104
|
}
|
|
104
105
|
|
|
106
|
+
// #7847: the canonical rejection with every space removed, followed by the session UUID.
|
|
107
|
+
export const COMPACTED_UNKNOWN_RESUME_PATTERN =
|
|
108
|
+
/noconversationfoundwithsessionid:?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Cursor-positioned TUI rendering of claude's unknown-resume rejection can reach
|
|
112
|
+
* the PTY tail as several fragments with the inter-word spaces removed
|
|
113
|
+
* (`Noconvers` / `ation` / `foundwith` / `session` / `ID:<uuid>`, #7847), so
|
|
114
|
+
* neither a single line nor a space-joined adjacent pair matches the
|
|
115
|
+
* per-line patterns above. This tests a whitespace-compacted join of up to
|
|
116
|
+
* `windowLines` consecutive lines against the canonical rejection ONLY: the full
|
|
117
|
+
* phrase "No conversation found with session ID:" followed by a UUID. The UUID
|
|
118
|
+
* anchor keeps it narrow — transcript text that merely discusses resume or
|
|
119
|
+
* session errors has no such phrase+id shape and never matches.
|
|
120
|
+
*
|
|
121
|
+
* The window is 10 lines: the five phrase fragments plus a UUID that may itself
|
|
122
|
+
* wrap across several rows at the narrowest widths.
|
|
123
|
+
*
|
|
124
|
+
* @param {string[]} lines
|
|
125
|
+
* @param {number} [windowLines=10]
|
|
126
|
+
* @returns {boolean}
|
|
127
|
+
*/
|
|
128
|
+
export function stderrIndicatesUnknownResumeCompacted(lines, windowLines = 10) {
|
|
129
|
+
if (!Array.isArray(lines) || lines.length === 0) return false
|
|
130
|
+
const compact = lines.map((l) => (typeof l === 'string' ? l.replace(/\s+/g, '') : ''))
|
|
131
|
+
for (let i = 0; i < compact.length; i++) {
|
|
132
|
+
const joined = compact.slice(i, i + windowLines).join('')
|
|
133
|
+
if (COMPACTED_UNKNOWN_RESUME_PATTERN.test(joined)) return true
|
|
134
|
+
}
|
|
135
|
+
return false
|
|
136
|
+
}
|
|
137
|
+
|
|
105
138
|
/**
|
|
106
139
|
* Build the argv passed to `claude -p --input-format stream-json …`.
|
|
107
140
|
*
|
|
@@ -158,7 +191,26 @@ export function buildClaudeCliArgs({ model, permissionMode, allowedTools, skills
|
|
|
158
191
|
// the model retains the full prior transcript. Only emitted when a non-empty
|
|
159
192
|
// string is known; a brand-new session (first start()) leaves this off so
|
|
160
193
|
// claude CLI mints a fresh conversation id on its `system.init` line.
|
|
194
|
+
//
|
|
195
|
+
// #7868 — REJECTED, not merely passed through, because `-r, --resume` is
|
|
196
|
+
// declared with an OPTIONAL argument (`[value]`), not a required one.
|
|
197
|
+
// Measured against the installed claude CLI (2.1.282):
|
|
198
|
+
//
|
|
199
|
+
// claude -p --resume --this-is-not-a-real-flag-xyz --output-format ...
|
|
200
|
+
// → error: unknown option '--this-is-not-a-real-flag-xyz' (exit 1)
|
|
201
|
+
//
|
|
202
|
+
// — i.e. the two-token form INJECTS for an optional-arg flag (the opposite
|
|
203
|
+
// of `--model <model>` / `--append-system-prompt <prompt>` above, both
|
|
204
|
+
// declared REQUIRED and measured swallowed-as-value). `resumeSessionId` can
|
|
205
|
+
// never legitimately start with `-`: it is either this file's own
|
|
206
|
+
// CLI-emitted `system.init` session_id, or a client-supplied resume target
|
|
207
|
+
// already required to be a canonical UUID by
|
|
208
|
+
// handlers/conversation-handlers.js's CONVERSATION_ID_RE before it reaches
|
|
209
|
+
// here — but relying on every current and future caller to keep that
|
|
210
|
+
// constraint is the exact "someone remembers to sweep" gap #7868 exists to
|
|
211
|
+
// close, so it is asserted here too (case 1: reject).
|
|
161
212
|
if (typeof resumeSessionId === 'string' && resumeSessionId.length > 0) {
|
|
213
|
+
assertSafeArgvValue(resumeSessionId, 'resumeSessionId')
|
|
162
214
|
args.push('--resume', resumeSessionId)
|
|
163
215
|
}
|
|
164
216
|
|
|
@@ -180,6 +232,7 @@ export function buildClaudeCliArgs({ model, permissionMode, allowedTools, skills
|
|
|
180
232
|
* stream_end { messageId }
|
|
181
233
|
* message { type, content, tool, timestamp }
|
|
182
234
|
* tool_start { messageId, tool, input }
|
|
235
|
+
* tool_input_delta { messageId, toolUseId, partialJson }
|
|
183
236
|
* result { cost, duration, usage, sessionId }
|
|
184
237
|
* error { message }
|
|
185
238
|
* user_question { toolUseId, questions }
|
|
@@ -187,14 +240,20 @@ export function buildClaudeCliArgs({ model, permissionMode, allowedTools, skills
|
|
|
187
240
|
* agent_completed { toolUseId }
|
|
188
241
|
* plan_started {}
|
|
189
242
|
* plan_ready { allowedPrompts }
|
|
190
|
-
* tool_result { toolUseId, result, truncated }
|
|
243
|
+
* tool_result { toolUseId, result, truncated, input? }
|
|
191
244
|
*/
|
|
192
245
|
|
|
193
246
|
export class CliSession extends BaseSession {
|
|
247
|
+
static canonicalAssistantResponses = true
|
|
248
|
+
|
|
194
249
|
// #5858: Claude-family flag — single source of truth for isClaudeProvider().
|
|
195
250
|
// DockerSession (docker-cli / docker) extends this and inherits it.
|
|
196
251
|
static claudeFamily = true
|
|
197
252
|
|
|
253
|
+
static get customizationDescriptor() {
|
|
254
|
+
return CLAUDE_CLI_CUSTOMIZATION
|
|
255
|
+
}
|
|
256
|
+
|
|
198
257
|
/**
|
|
199
258
|
* Human-readable label shown in the startup banner and anywhere else the
|
|
200
259
|
* server needs to name this provider (#2953). Each provider owns its own
|
|
@@ -219,7 +278,21 @@ export class CliSession extends BaseSession {
|
|
|
219
278
|
* exhaust there.
|
|
220
279
|
*/
|
|
221
280
|
static get customEvents() {
|
|
222
|
-
|
|
281
|
+
// #7346: `tool_input_delta` delivers the SANITIZED full tool input
|
|
282
|
+
// as a single chunk once its content_block finalizes (see
|
|
283
|
+
// `_captureFinalizedToolInput`, called from `content_block_stop`) —
|
|
284
|
+
// matches byok-session.js's wire shape/client handler exactly so
|
|
285
|
+
// store-core's `handleToolInputDelta` needs no provider branch.
|
|
286
|
+
// Per #8135/#8137, NEITHER cli-session.js NOR byok-session.js
|
|
287
|
+
// streams raw per-chunk `input_json_delta` partials any more — a
|
|
288
|
+
// secret can straddle chunk boundaries and can't be sanitized
|
|
289
|
+
// mid-stream, so both providers only ever emit once, already-safe.
|
|
290
|
+
// Without listing it here, `session-manager.js`'s
|
|
291
|
+
// `_wireSessionEvents` never bridges the local EventEmitter emit
|
|
292
|
+
// onto the `session_event` channel and it never reaches the client
|
|
293
|
+
// (same wiring requirement documented on byok-session.js's
|
|
294
|
+
// `customEvents`).
|
|
295
|
+
return ['respawn_exhausted', 'tool_input_delta']
|
|
223
296
|
}
|
|
224
297
|
|
|
225
298
|
/**
|
|
@@ -229,13 +302,15 @@ export class CliSession extends BaseSession {
|
|
|
229
302
|
* hardcoding the path.
|
|
230
303
|
*/
|
|
231
304
|
static get dataDir() {
|
|
232
|
-
return
|
|
305
|
+
return claudeConfigDir()
|
|
233
306
|
}
|
|
234
307
|
|
|
235
308
|
static get capabilities() {
|
|
236
309
|
return {
|
|
237
310
|
permissions: true,
|
|
238
311
|
inProcessPermissions: false,
|
|
312
|
+
permissionFloor: true,
|
|
313
|
+
autoPermissionMode: true,
|
|
239
314
|
modelSwitch: true,
|
|
240
315
|
permissionModeSwitch: true,
|
|
241
316
|
// #5609: switching to 'auto' mid-turn is the #3729 panic-button —
|
|
@@ -253,12 +328,33 @@ export class CliSession extends BaseSession {
|
|
|
253
328
|
resume: true,
|
|
254
329
|
terminal: false,
|
|
255
330
|
thinkingLevel: false,
|
|
331
|
+
// #7725: the legacy `claude -p` subprocess never runs
|
|
332
|
+
// detect-thinking-keyword.js, so typing `ultrathink` escalates nothing
|
|
333
|
+
// here. Declared explicitly (like `streaming`) so the matrix stays
|
|
334
|
+
// uniform rather than leaving the flag's absence to be guessed.
|
|
335
|
+
thinkingKeywords: false,
|
|
336
|
+
thinkingLevelEffective: false, // #8700: no report of the applied level
|
|
256
337
|
// #3932: declared explicitly so the capability matrix matches across
|
|
257
338
|
// providers — claude-tui is the only one that sets this to false.
|
|
258
339
|
streaming: true,
|
|
340
|
+
// #8301: the provider-neutral turn-input seam. `sendMessage` dispatches when
|
|
341
|
+
// idle, queues via `enqueueOutgoingMessage` when busy (flushed at turn end,
|
|
342
|
+
// cleared by `interrupt()`), and reports admission through
|
|
343
|
+
// `onInputAdmission` — so a daemon-authored line (the CI-completion wake)
|
|
344
|
+
// can travel it as an ordinary user turn. session-wake.js gates on this with
|
|
345
|
+
// strict `=== true`; absent means NOT supported. Never duck-typed.
|
|
346
|
+
daemonTurnInput: true,
|
|
259
347
|
}
|
|
260
348
|
}
|
|
261
349
|
|
|
350
|
+
/**
|
|
351
|
+
* The exact path the CLI subprocess will spawn, re-resolved fresh so
|
|
352
|
+
* preflight verifies the SAME path the spawn uses (no stale const). (#6708)
|
|
353
|
+
*/
|
|
354
|
+
static get resolvedBinary() {
|
|
355
|
+
return resolveClaudeBinary()
|
|
356
|
+
}
|
|
357
|
+
|
|
262
358
|
/**
|
|
263
359
|
* Preflight dependency spec used by `chroxy doctor`.
|
|
264
360
|
* Declares the binary and credential requirements for this provider so
|
|
@@ -271,13 +367,7 @@ export class CliSession extends BaseSession {
|
|
|
271
367
|
binary: {
|
|
272
368
|
name: 'claude',
|
|
273
369
|
args: ['--version'],
|
|
274
|
-
candidates:
|
|
275
|
-
join(homedir(), '.local/bin/claude'),
|
|
276
|
-
'/opt/homebrew/bin/claude',
|
|
277
|
-
'/usr/local/bin/claude',
|
|
278
|
-
join(homedir(), '.claude/local/node_modules/.bin/claude'),
|
|
279
|
-
join(homedir(), '.npm-global/bin/claude'),
|
|
280
|
-
],
|
|
370
|
+
candidates: CLAUDE_BINARY_CANDIDATES,
|
|
281
371
|
installHint: 'install Claude Code CLI',
|
|
282
372
|
},
|
|
283
373
|
credentials: {
|
|
@@ -382,6 +472,14 @@ export class CliSession extends BaseSession {
|
|
|
382
472
|
this._inPlanMode = false
|
|
383
473
|
this._planAllowedPrompts = null
|
|
384
474
|
this._waitingForAnswer = false
|
|
475
|
+
// #7457 -- the AskUserQuestion payload behind `_waitingForAnswer`, so a
|
|
476
|
+
// reconnecting client can be handed the question the child is parked on
|
|
477
|
+
// (`getPendingQuestions`). Kept strictly CO-LOCATED with the flag: every
|
|
478
|
+
// line that writes `_waitingForAnswer` writes this in the same statement
|
|
479
|
+
// block, so the two cannot disagree and there is no second lifecycle to
|
|
480
|
+
// leak. `_waitingForAnswer` stays the read gate `respondToQuestion` uses --
|
|
481
|
+
// this is a payload, not a new source of truth.
|
|
482
|
+
this._pendingQuestion = null
|
|
385
483
|
this._currentCtx = null
|
|
386
484
|
this._pendingQueue = []
|
|
387
485
|
this._respawnCount = 0
|
|
@@ -413,13 +511,30 @@ export class CliSession extends BaseSession {
|
|
|
413
511
|
// Single-use: set by interrupt(), cleared by _handleChildClose / destroy.
|
|
414
512
|
// The flag itself is declared+initialized on BaseSession (#5375).
|
|
415
513
|
|
|
514
|
+
// #7438: latched by the intentional-stop branch of _handleChildClose when
|
|
515
|
+
// that stop leaves us with no child, and consumed by the next sendMessage
|
|
516
|
+
// (_restartAfterStop). It is what makes a stopped session restartable —
|
|
517
|
+
// see _restartAfterStop for why the restart is gated on this rather than
|
|
518
|
+
// on "the child is gone".
|
|
519
|
+
this._stoppedByUser = false
|
|
520
|
+
|
|
416
521
|
// Hook manager (shared module)
|
|
417
522
|
this._hookManager = (this._port) ? createPermissionHookManager(this, { settingsPath }) : null
|
|
418
523
|
|
|
524
|
+
// #7337: the re-readable permission-mode sidecar. `permission-hook.sh`
|
|
525
|
+
// prefers this file over CHROXY_PERMISSION_MODE, which is frozen at spawn.
|
|
526
|
+
// Created on the first start() when permissions are enabled, reused across
|
|
527
|
+
// respawns, removed on destroy(). Null means "env-var-only" — either
|
|
528
|
+
// permissions are off (no port) or the initial write failed.
|
|
529
|
+
this._permissionModeFile = null
|
|
530
|
+
this._permissionModeDir = null
|
|
531
|
+
|
|
419
532
|
// Pending-permission bookkeeping for the inactivity timer (#2831).
|
|
420
533
|
// WsServer calls notifyPermissionPending/Resolved when a hook
|
|
421
534
|
// permission belonging to this session is broadcast/resolved.
|
|
422
|
-
|
|
535
|
+
// #7382: `_pendingPermissionIds` now lives on BaseSession so every
|
|
536
|
+
// hook-routed provider has it. The inactivity PAUSE stays CLI-local — it is
|
|
537
|
+
// wired to this provider's timer trio via the _on*Permission* hooks below.
|
|
423
538
|
this._resultTimeoutPaused = false
|
|
424
539
|
}
|
|
425
540
|
|
|
@@ -448,11 +563,20 @@ export class CliSession extends BaseSession {
|
|
|
448
563
|
* Start the persistent Claude process. Call once after construction.
|
|
449
564
|
*/
|
|
450
565
|
start() {
|
|
566
|
+
// #7438: the session is running again by any route (first start, backoff
|
|
567
|
+
// respawn, model-switch respawn, restart-on-input), so the stop latch is
|
|
568
|
+
// spent. Cleared FIRST so a throw below cannot leave it armed.
|
|
569
|
+
this._stoppedByUser = false
|
|
570
|
+
|
|
451
571
|
// Register permission hook before starting the process (only once, not on respawn)
|
|
452
572
|
if (this._hookManager && this._respawnCount === 0) {
|
|
453
573
|
this._hookManager.register()
|
|
454
574
|
}
|
|
455
575
|
|
|
576
|
+
// #7337: must run BEFORE _spawnPersistentProcess, which is where
|
|
577
|
+
// _buildChildEnv() reads `_permissionModeFile` to point the child at it.
|
|
578
|
+
this._ensurePermissionModeSidecar()
|
|
579
|
+
|
|
456
580
|
// Skills MVP (#2957) — append shared skills to the Claude CLI system prompt.
|
|
457
581
|
const skillsText = this._buildSystemPrompt()
|
|
458
582
|
|
|
@@ -489,6 +613,19 @@ export class CliSession extends BaseSession {
|
|
|
489
613
|
CLAUDE_HEADLESS: '1',
|
|
490
614
|
CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING: '1',
|
|
491
615
|
CHROXY_PERMISSION_MODE: this.permissionMode,
|
|
616
|
+
// #7337: the hook prefers this file and re-reads it on EVERY tool call,
|
|
617
|
+
// so a mid-session mode change reaches even the child already running.
|
|
618
|
+
// CHROXY_PERMISSION_MODE above stays as the fallback for a hook that
|
|
619
|
+
// cannot read the file (deleted /tmp entry, container without the mount).
|
|
620
|
+
//
|
|
621
|
+
// ALWAYS set, never omitted. buildSpawnEnv('claude') is DENYLIST mode, so
|
|
622
|
+
// the whole parent env passes through — and this daemon may itself have
|
|
623
|
+
// been launched from inside another chroxy session, whose sidecar path is
|
|
624
|
+
// then sitting in our env. Omitting the key would let that FOREIGN file
|
|
625
|
+
// decide this session's permissions, since the hook prefers it over our
|
|
626
|
+
// own CHROXY_PERMISSION_MODE. Empty string fails the hook's `[ -n ]` guard
|
|
627
|
+
// and falls through to the env var, which is the documented intent.
|
|
628
|
+
CHROXY_PERMISSION_MODE_FILE: this._permissionModeFile || '',
|
|
492
629
|
...(this._port ? { CHROXY_PORT: String(this._port) } : {}),
|
|
493
630
|
// Pass a short-lived per-session secret instead of the primary API token.
|
|
494
631
|
// This limits the blast radius if a tool reads process.env — the hook secret
|
|
@@ -501,6 +638,12 @@ export class CliSession extends BaseSession {
|
|
|
501
638
|
_spawnPersistentProcess(args) {
|
|
502
639
|
this._cleanupReadlines()
|
|
503
640
|
this._processReady = false
|
|
641
|
+
// #8038: clear any refusal latched by a PRIOR spawn attempt at the very
|
|
642
|
+
// top of every attempt (mirrors ClaudeTuiSession._spawnPty). A fresh
|
|
643
|
+
// attempt gets a fresh gate verdict — a stale latch from a prior crash
|
|
644
|
+
// respawn must never suppress a NEW attempt's own error or silently
|
|
645
|
+
// survive a revival that is about to succeed.
|
|
646
|
+
this._spawnRefusal = null
|
|
504
647
|
|
|
505
648
|
// #4929: capture which `--resume <id>` (if any) this spawn attempted.
|
|
506
649
|
// Read off the argv we're about to pass instead of `_sessionId` so the
|
|
@@ -518,7 +661,41 @@ export class CliSession extends BaseSession {
|
|
|
518
661
|
// with no native `claude.exe`); spawning a `.cmd` via child_process throws
|
|
519
662
|
// EINVAL on Node 24, so route it through cmd.exe with proper escaping. No-op
|
|
520
663
|
// for a directly-runnable `.exe` and on POSIX. See utils/win-spawn.js.
|
|
521
|
-
|
|
664
|
+
// Captured so the spawn-time backstop (#6708) verifies the EXACT binary this
|
|
665
|
+
// attempt used, not a fresh re-resolve that could land on a different path.
|
|
666
|
+
//
|
|
667
|
+
// #8038: routed through the shared binary gate instead of a bare
|
|
668
|
+
// `resolveClaudeBinary()` — this ONE method is what every (re)spawn funnels
|
|
669
|
+
// through (first start, `_killAndRespawn` for a model switch or permission-
|
|
670
|
+
// mode change, `_restartAfterStop`'s post-Stop revival, and `_scheduleRespawn`'s
|
|
671
|
+
// crash backoff), so gating it here covers every entry point in the #8038
|
|
672
|
+
// issue with no per-caller duplication. A refusal here means the gate
|
|
673
|
+
// rejected this attempt (provenance mismatch, quarantine, a vanished pinned
|
|
674
|
+
// path, …): nothing is spawned, the backoff chain resets (the NEXT spawn is
|
|
675
|
+
// user-initiated, mirroring `_killAndRespawn` zeroing `_respawnCount`), and
|
|
676
|
+
// `_scheduleRespawn` is deliberately NOT called — this is not "the child
|
|
677
|
+
// died", it is "we refused to start a child at all", and a timer retrying
|
|
678
|
+
// the same refused gate would just burn the bounded respawn budget into a
|
|
679
|
+
// misleading `respawn_exhausted` ("failed to stay alive"). Revival happens
|
|
680
|
+
// lazily on the next `sendMessage` instead (see there, and `_refuseSpawn`).
|
|
681
|
+
let attemptedBinary
|
|
682
|
+
try {
|
|
683
|
+
attemptedBinary = this._gatedSpawnBinary('claude')
|
|
684
|
+
} catch (err) {
|
|
685
|
+
// The chain that got us here (crash backoff, model switch, …) is over —
|
|
686
|
+
// the next spawn attempt is a fresh, user-initiated one, exactly as
|
|
687
|
+
// `_killAndRespawn` already resets this counter on its own respawn path.
|
|
688
|
+
//
|
|
689
|
+
// On the FIRST start this is only a race (create-time preflight passed
|
|
690
|
+
// moments earlier), and it latches rather than throwing like every other
|
|
691
|
+
// attempt. SessionManager has not broadcast `session_created` yet, so a
|
|
692
|
+
// client can miss this error: the session is listed but never ready,
|
|
693
|
+
// and its first input re-runs the gate and is rejected with the code.
|
|
694
|
+
this._respawnCount = 0
|
|
695
|
+
this._refuseSpawn(err, this._log || log)
|
|
696
|
+
return
|
|
697
|
+
}
|
|
698
|
+
const spawnSpec = prepareSpawn(attemptedBinary, args)
|
|
522
699
|
const child = spawn(spawnSpec.command, spawnSpec.args, {
|
|
523
700
|
cwd: this.cwd,
|
|
524
701
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
@@ -528,6 +705,18 @@ export class CliSession extends BaseSession {
|
|
|
528
705
|
|
|
529
706
|
this._child = child
|
|
530
707
|
|
|
708
|
+
// A returned ChildProcess is not ready proof: missing or non-executable
|
|
709
|
+
// binaries report ENOENT/EACCES asynchronously. Only expose readiness and
|
|
710
|
+
// drain startup input after Node confirms the child `spawn` event. Ignore
|
|
711
|
+
// a late event from a child that was replaced during a restart.
|
|
712
|
+
child.once('spawn', () => {
|
|
713
|
+
if (this._destroying || this._child !== child) return
|
|
714
|
+
this._processReady = true
|
|
715
|
+
log.info('Process started, ready for messages')
|
|
716
|
+
this.emit('ready', { sessionId: null, model: this.model, tools: [] })
|
|
717
|
+
this._drainPendingQueue()
|
|
718
|
+
})
|
|
719
|
+
|
|
531
720
|
// Do NOT close stdin — we write messages to it
|
|
532
721
|
|
|
533
722
|
// Read stdout line by line — each line is a JSON object
|
|
@@ -573,27 +762,53 @@ export class CliSession extends BaseSession {
|
|
|
573
762
|
})
|
|
574
763
|
|
|
575
764
|
child.on('error', (err) => {
|
|
765
|
+
if (this._child !== child) return
|
|
576
766
|
this._cleanupReadlines()
|
|
577
767
|
this._processReady = false
|
|
578
768
|
this._child = null
|
|
579
|
-
|
|
769
|
+
// #6708 — a spawn error (ENOENT/EACCES) can mean the binary was quarantined
|
|
770
|
+
// /moved/removed out from under the running daemon (this is the respawn
|
|
771
|
+
// path too, so it fires mid-session). Verify the ATTEMPTED path and label
|
|
772
|
+
// the cause + fix instead of surfacing a bare ENOENT. Falls back to raw.
|
|
773
|
+
const labeled = labelBinarySpawnFailure({ attemptedPath: err?.path || attemptedBinary, binary: 'claude' })
|
|
774
|
+
this.emit('error', { message: labeled || `Failed to spawn claude: ${err.message}` })
|
|
580
775
|
this._scheduleRespawn()
|
|
581
776
|
})
|
|
582
777
|
|
|
583
|
-
child.on('close', (code) =>
|
|
778
|
+
child.on('close', (code) => {
|
|
779
|
+
if (this._child !== child) return
|
|
780
|
+
this._handleChildClose(code)
|
|
781
|
+
})
|
|
782
|
+
}
|
|
584
783
|
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
784
|
+
/**
|
|
785
|
+
* Warmup drain: dequeue the next pending message if not already busy.
|
|
786
|
+
* sendMessage() sets _isBusy, so the loop sends at most one message.
|
|
787
|
+
* Remaining items stay in the queue and are drained one-by-one via
|
|
788
|
+
* _clearMessageState() after each result.
|
|
789
|
+
*
|
|
790
|
+
* Called at the end of every _spawnPersistentProcess — i.e. this is what
|
|
791
|
+
* delivers a message queued while the process was down, whether it went down
|
|
792
|
+
* for a crash, a model switch, or a user Stop (#7438).
|
|
793
|
+
*/
|
|
794
|
+
/**
|
|
795
|
+
* A startup-queued message is dispatched only while the connection that sent it
|
|
796
|
+
* is still authorized; otherwise it is dropped and reported as not dispatched.
|
|
797
|
+
*/
|
|
798
|
+
_admitPendingItem(pending) {
|
|
799
|
+
if (stillAuthorized(pending?.options?.isAuthorized)) return true
|
|
800
|
+
reportInputAdmission(pending?.options, {
|
|
801
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: false,
|
|
802
|
+
reason: 'connection_not_authorized',
|
|
803
|
+
message: 'The sending connection is no longer authorized; the input was not dispatched.',
|
|
804
|
+
})
|
|
805
|
+
return false
|
|
806
|
+
}
|
|
590
807
|
|
|
591
|
-
|
|
592
|
-
// sendMessage() sets _isBusy, so the loop sends at most one message.
|
|
593
|
-
// Remaining items stay in the queue and are drained one-by-one via
|
|
594
|
-
// _clearMessageState() after each result.
|
|
808
|
+
_drainPendingQueue() {
|
|
595
809
|
while (this._pendingQueue.length > 0 && !this._isBusy) {
|
|
596
810
|
const pending = this._pendingQueue.shift()
|
|
811
|
+
if (!this._admitPendingItem(pending)) continue
|
|
597
812
|
// #4828: session-scoped when init has fired (dequeue can race with
|
|
598
813
|
// the very-first init so the fallback is intentional).
|
|
599
814
|
;(this._log || log).info(`Dequeuing pending message (${this._pendingQueue.length} remaining)`)
|
|
@@ -648,6 +863,69 @@ export class CliSession extends BaseSession {
|
|
|
648
863
|
}, delay)
|
|
649
864
|
}
|
|
650
865
|
|
|
866
|
+
/**
|
|
867
|
+
* #8301: a daemon wake is handed to a session that is READY, or not at all.
|
|
868
|
+
*
|
|
869
|
+
* `sendMessage` on a process that is not ready either respawns it
|
|
870
|
+
* (`_restartAfterStop()`, right for typed input, wrong for a wake) or parks the
|
|
871
|
+
* message in `_pendingQueue`. That queue is drained by `sendMessage` directly
|
|
872
|
+
* from three places (the warmup drain, the post-result drain, and
|
|
873
|
+
* DockerSession's start), none of which consults `admitAtFlush`, so a wake
|
|
874
|
+
* parked there would reach the child after a budget pause or a user Stop had
|
|
875
|
+
* been decided. The only way to keep the flush-time check meaningful is to
|
|
876
|
+
* never let a wake in: any not-ready state refuses. A wake that finds the
|
|
877
|
+
* session still starting is simply dropped; CI completion is not replayed, and
|
|
878
|
+
* the user was notified.
|
|
879
|
+
*
|
|
880
|
+
* `'stopped'` is kept for the two latches because it is the more useful
|
|
881
|
+
* answer (the user, or the binary gate, did this); everything else is
|
|
882
|
+
* `'not-ready'` (pre-init, mid-respawn, crashed).
|
|
883
|
+
*
|
|
884
|
+
* @returns {string|null}
|
|
885
|
+
*/
|
|
886
|
+
daemonTurnRefusal() {
|
|
887
|
+
if (this._processReady) return null
|
|
888
|
+
return (this._stoppedByUser || this._spawnRefusal) ? 'stopped' : 'not-ready'
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
/**
|
|
892
|
+
* #8301: a queued daemon item was refused at flush. The base hook just keeps
|
|
893
|
+
* draining `_outgoingQueue`; CliSession has a SECOND queue behind it, and the
|
|
894
|
+
* refused item's slot must not strand it. `_clearMessageState` hands the turn
|
|
895
|
+
* to `_outgoingQueue` first and to `_pendingQueue` only when the former is
|
|
896
|
+
* empty, so a refusal that empties the former has to fall through to the
|
|
897
|
+
* latter exactly as `_clearMessageState` would have.
|
|
898
|
+
*/
|
|
899
|
+
_continueDrainAfterRefusal() {
|
|
900
|
+
if (this._destroying) return
|
|
901
|
+
if (this._outgoingQueue.length > 0) {
|
|
902
|
+
this.dequeueNextOutgoing()
|
|
903
|
+
} else {
|
|
904
|
+
this._drainNextPendingAfterResult()
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
/**
|
|
909
|
+
* Dispatch the next message parked while the child was not ready, on the next
|
|
910
|
+
* tick (so synchronous `result` listeners finish first). Shared by the
|
|
911
|
+
* post-result drain in `_clearMessageState` and `_continueDrainAfterRefusal`.
|
|
912
|
+
*/
|
|
913
|
+
_drainNextPendingAfterResult() {
|
|
914
|
+
if (!this._processReady || this._pendingQueue.length === 0) return
|
|
915
|
+
process.nextTick(() => {
|
|
916
|
+
if (this._destroying) return
|
|
917
|
+
if (!this._processReady || this._pendingQueue.length === 0) return
|
|
918
|
+
const pending = this._pendingQueue.shift()
|
|
919
|
+
if (!this._admitPendingItem(pending)) {
|
|
920
|
+
this._drainNextPendingAfterResult()
|
|
921
|
+
return
|
|
922
|
+
}
|
|
923
|
+
// #4828: session-scoped (post-result, post-init).
|
|
924
|
+
;(this._log || log).info(`Dequeuing next pending message after result (${this._pendingQueue.length} remaining)`)
|
|
925
|
+
this.sendMessage(pending.prompt, pending.attachments, pending.options || {})
|
|
926
|
+
})
|
|
927
|
+
}
|
|
928
|
+
|
|
651
929
|
/**
|
|
652
930
|
* Send a message to Claude via stdin NDJSON.
|
|
653
931
|
*/
|
|
@@ -658,19 +936,53 @@ export class CliSession extends BaseSession {
|
|
|
658
936
|
// processing a message" — flushed FIFO on the turn-complete `result` (via
|
|
659
937
|
// _clearMessageState's drain below). Matches the SDK's behaviour. The
|
|
660
938
|
// overflow cap + the message_queued mirror live in enqueueOutgoingMessage.
|
|
661
|
-
this.enqueueOutgoingMessage({ prompt, attachments, sendOptions: options })
|
|
939
|
+
const queued = this.enqueueOutgoingMessage({ prompt, attachments, sendOptions: options })
|
|
940
|
+
reportInputAdmission(options, queued
|
|
941
|
+
? { status: 'queued', delivery: 'queued' }
|
|
942
|
+
: {
|
|
943
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
944
|
+
reason: 'queue_full', message: 'The provider input queue is full; retry after queued work advances.',
|
|
945
|
+
})
|
|
662
946
|
return
|
|
663
947
|
}
|
|
664
948
|
|
|
665
949
|
if (!this._processReady) {
|
|
950
|
+
// #8038: revive FIRST, before deciding whether THIS input can be
|
|
951
|
+
// admitted. `_restartAfterStop` now also fires on a latched spawn
|
|
952
|
+
// refusal (see its doc) so a session left idle by a gate refusal gets
|
|
953
|
+
// the same lazy on-next-input revival a user Stop already got via
|
|
954
|
+
// #7438 — moved ahead of the queue-full check / push below. It used to
|
|
955
|
+
// run AFTER queuing, which is fine when the restart spawns a child (the
|
|
956
|
+
// warmup drain delivers the push), but with a gate that can refuse it
|
|
957
|
+
// would admit this input as `queued` behind a child that never starts.
|
|
958
|
+
this._restartAfterStop()
|
|
959
|
+
|
|
960
|
+
// #8038: the revival attempt above may have hit the SAME gate refusal
|
|
961
|
+
// again (or a fresh one) — reject THIS input immediately with the coded
|
|
962
|
+
// admission instead of queuing it behind a child that is not coming
|
|
963
|
+
// back on its own. Messages already sitting in `_pendingQueue` from
|
|
964
|
+
// BEFORE this refusal are untouched (their admission was already
|
|
965
|
+
// reported as `queued`, and `onInputAdmission` is final after its first
|
|
966
|
+
// call) — they stay queued and are delivered FIFO by the warmup drain
|
|
967
|
+
// once a future revival actually spawns.
|
|
968
|
+
if (this._spawnRefusal) {
|
|
969
|
+
reportInputAdmission(options, spawnRefusalAdmission(this._spawnRefusal))
|
|
970
|
+
return
|
|
971
|
+
}
|
|
972
|
+
|
|
666
973
|
if (this._pendingQueue.length >= 3) {
|
|
667
974
|
this.emit('error', { message: 'Pending message queue full (max 3) — message discarded' })
|
|
975
|
+
reportInputAdmission(options, {
|
|
976
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
977
|
+
reason: 'queue_full', message: 'The provider startup queue is full; retry after the session becomes ready.',
|
|
978
|
+
})
|
|
668
979
|
return
|
|
669
980
|
}
|
|
670
981
|
// #4828: session-scoped when init has fired (queuing typically happens
|
|
671
982
|
// pre-init or during respawn — both can race with the binding).
|
|
672
983
|
;(this._log || log).info(`Process not ready, queuing message (queue depth: ${this._pendingQueue.length + 1})`)
|
|
673
984
|
this._pendingQueue.push({ prompt, attachments, options })
|
|
985
|
+
reportInputAdmission(options, { status: 'queued', delivery: 'queued' })
|
|
674
986
|
return
|
|
675
987
|
}
|
|
676
988
|
|
|
@@ -712,6 +1024,8 @@ export class CliSession extends BaseSession {
|
|
|
712
1024
|
}
|
|
713
1025
|
|
|
714
1026
|
this._isBusy = true
|
|
1027
|
+
// #7376: a turn starts with no Stop requested, whatever the last one did.
|
|
1028
|
+
this._stopRequestedThisTurn = false
|
|
715
1029
|
this._messageCounter++
|
|
716
1030
|
// `msg-{bootPrefix}-{counter}` — see BaseSession constructor for why
|
|
717
1031
|
// the boot-unique prefix is needed (#3700). Format change does not
|
|
@@ -741,9 +1055,15 @@ export class CliSession extends BaseSession {
|
|
|
741
1055
|
;(this._log || log).error(`stdin.write failed (sendMessage): ${err.message}`)
|
|
742
1056
|
this._clearMessageState()
|
|
743
1057
|
this.emit('error', { message: `Failed to send message: ${err.message}` })
|
|
1058
|
+
reportInputAdmission(options, {
|
|
1059
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
1060
|
+
reason: 'write_failed', message: 'The provider input channel rejected the write.',
|
|
1061
|
+
})
|
|
744
1062
|
return
|
|
745
1063
|
}
|
|
746
1064
|
|
|
1065
|
+
reportInputAdmission(options, { status: 'accepted', delivery: 'dispatch_started' })
|
|
1066
|
+
|
|
747
1067
|
// Skills text is committed to the wire — safe to flip the flag now (#3225).
|
|
748
1068
|
// If the write threw above we returned early, leaving the flag false so
|
|
749
1069
|
// the next attempt re-injects the prepend bucket.
|
|
@@ -840,19 +1160,63 @@ export class CliSession extends BaseSession {
|
|
|
840
1160
|
const friendly = formatIdleDuration(this._hardTimeoutMs)
|
|
841
1161
|
// #4828: session-scoped (hard-cap fires from active turn).
|
|
842
1162
|
;(this._log || log).warn(`Hard-cap timeout (${friendly}) — force-clearing busy state`)
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
for (const requestId of this._pendingPermissionIds) {
|
|
846
|
-
this.emit('permission_expired', {
|
|
847
|
-
requestId,
|
|
848
|
-
message: 'Permission request expired (session timeout)',
|
|
849
|
-
})
|
|
850
|
-
}
|
|
851
|
-
this._pendingPermissionIds.clear()
|
|
852
|
-
this._emitInterruptedTurnResult(this._hardTimeoutMs)
|
|
1163
|
+
this._expirePendingPermissions('Permission request expired (session timeout)')
|
|
1164
|
+
this._emitInterruptedTurnResult(this._hardTimeoutMs, 'hard_timeout')
|
|
853
1165
|
this.emit('error', { message: `Response timed out after ${friendly}` })
|
|
854
1166
|
}
|
|
855
1167
|
|
|
1168
|
+
/**
|
|
1169
|
+
* Emit `permission_expired` for every prompt this session is still blocked
|
|
1170
|
+
* on, then drop the bookkeeping (#2831, extended by #7335).
|
|
1171
|
+
*
|
|
1172
|
+
* A prompt outlives its turn on BOTH sides and neither side says so:
|
|
1173
|
+
* client-side the card stays live until its own 5-minute `expiresAt`, and
|
|
1174
|
+
* server-side the daemon's HTTP handler tears the pending entry down on the
|
|
1175
|
+
* hook's `req 'aborted'` / `res 'close'` without broadcasting anything. So a
|
|
1176
|
+
* user who clicks Allow afterwards gets the "stale/unknown toolUseId …
|
|
1177
|
+
* already resolved" path with nothing explaining which decision died.
|
|
1178
|
+
*
|
|
1179
|
+
* The dashboard's `permission_expired` handler appends the expiry note AND
|
|
1180
|
+
* clears the prompt's `options`, which is what actually retires the dead
|
|
1181
|
+
* Allow button — so emitting here is the whole client-side fix.
|
|
1182
|
+
*
|
|
1183
|
+
* Wired at three sites, and the third is the one that matters:
|
|
1184
|
+
*
|
|
1185
|
+
* - `_clearMessageState` — the FUNNEL. Every turn end reaches it: the
|
|
1186
|
+
* normal `result`, the hard cap, the interrupt safety timeout,
|
|
1187
|
+
* `destroy()`. It is also where the ids used to be dropped silently.
|
|
1188
|
+
* - `_killAndRespawn` — the #3729 panic-button, the auto-mode switch,
|
|
1189
|
+
* mid-turn setModel. Needs its OWN call because it reaches the funnel via
|
|
1190
|
+
* `_emitInterruptedTurnResult`, which early-returns when the session is
|
|
1191
|
+
* not busy.
|
|
1192
|
+
* - `_handleChildClose` — a crash, or user Stop where the child dies. Same
|
|
1193
|
+
* early-return caveat.
|
|
1194
|
+
*
|
|
1195
|
+
* An earlier draft wired only the two death sites and justified skipping the
|
|
1196
|
+
* rest in a table. Review found the table wrong twice over: the interrupt
|
|
1197
|
+
* safety timeout was excused as "the child ignored SIGINT so the prompt is
|
|
1198
|
+
* still answerable", which this file contradicts eleven hundred lines below
|
|
1199
|
+
* (`claude only aborts the current turn` — the hook dies with the turn), and
|
|
1200
|
+
* that path then wiped the ids anyway via `_clearMessageState`, so no later
|
|
1201
|
+
* close could expire them. The plain `result` path was not in the table at
|
|
1202
|
+
* all. Enumerating callers by hand is what produced both errors; wiring the
|
|
1203
|
+
* funnel is what fixes them.
|
|
1204
|
+
*
|
|
1205
|
+
* `_handleStreamStall` is genuinely unreachable with a permission pending —
|
|
1206
|
+
* `notifyPermissionPending` clears the stall timer and `_armResultTimeout`
|
|
1207
|
+
* bails on `_resultTimeoutPaused` — and it routes through the funnel anyway.
|
|
1208
|
+
*
|
|
1209
|
+
* NOT a full solution on its own: this retires the prompt in the CLIENTS. The
|
|
1210
|
+
* daemon's own `pendingPermissions` entry (ws-permissions.js) is still
|
|
1211
|
+
* released explicitly rather than by relying on the hook dying: since #7606
|
|
1212
|
+
* POSIX `killProcessTree` does signal the hook's `bash` → `curl` grandchildren
|
|
1213
|
+
* on a respawn/destroy, but a crash runs no kill at all, and an explicit
|
|
1214
|
+
* release is the only path that covers both. See #7379.
|
|
1215
|
+
*
|
|
1216
|
+
* @param {string} message Reason forwarded on the wire (clients log it; the
|
|
1217
|
+
* user-visible copy is fixed client-side).
|
|
1218
|
+
*/
|
|
1219
|
+
|
|
856
1220
|
// #4467: stream-stall recovery. Fires when the child has been silent
|
|
857
1221
|
// for `_streamStallTimeoutMs` despite the session being busy — typically
|
|
858
1222
|
// a half-open TCP to the Anthropic API that the OS hasn't surfaced yet.
|
|
@@ -866,7 +1230,7 @@ export class CliSession extends BaseSession {
|
|
|
866
1230
|
;(this._log || log).warn(
|
|
867
1231
|
`Stream stalled (${friendly}, messageId=${this._currentMessageId}) — clearing busy state for retry`,
|
|
868
1232
|
)
|
|
869
|
-
this._emitInterruptedTurnResult(this._streamStallTimeoutMs)
|
|
1233
|
+
this._emitInterruptedTurnResult(this._streamStallTimeoutMs, 'stream_stall')
|
|
870
1234
|
this.emit('error', {
|
|
871
1235
|
code: 'stream_stall',
|
|
872
1236
|
message: `Stream stalled — no response for ${friendly}. Try sending again.`,
|
|
@@ -880,46 +1244,52 @@ export class CliSession extends BaseSession {
|
|
|
880
1244
|
*
|
|
881
1245
|
* @param {string} requestId
|
|
882
1246
|
*/
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
1247
|
+
/**
|
|
1248
|
+
* #7382: the generic add/remove bookkeeping is BaseSession's. These hooks are
|
|
1249
|
+
* the CLI-specific half — pausing the inactivity trio while the user is being
|
|
1250
|
+
* asked (#2831/#3899/#4467), which is not behaviour every provider shares.
|
|
1251
|
+
*/
|
|
1252
|
+
_onFirstPermissionPending() {
|
|
1253
|
+
this._resultTimeoutPaused = true
|
|
1254
|
+
// #3899: clear BOTH the soft warning and the hard cap. Awaiting user input
|
|
1255
|
+
// is not inactivity; the trio re-arms together when the last pending
|
|
1256
|
+
// permission resolves. #4467: the stall timer too — waiting on the user is
|
|
1257
|
+
// not a stall.
|
|
1258
|
+
if (this._resultTimeout) {
|
|
1259
|
+
clearTimeout(this._resultTimeout)
|
|
1260
|
+
this._resultTimeout = null
|
|
1261
|
+
}
|
|
1262
|
+
if (this._hardTimeout) {
|
|
1263
|
+
clearTimeout(this._hardTimeout)
|
|
1264
|
+
this._hardTimeout = null
|
|
1265
|
+
}
|
|
1266
|
+
if (this._streamStallTimeout) {
|
|
1267
|
+
clearTimeout(this._streamStallTimeout)
|
|
1268
|
+
this._streamStallTimeout = null
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
/** Last prompt ANSWERED — the turn continues, so re-arm the trio. */
|
|
1273
|
+
_onLastPermissionResolved() {
|
|
1274
|
+
this._resultTimeoutPaused = false
|
|
1275
|
+
if (this._isBusy) {
|
|
1276
|
+
this._armResultTimeout()
|
|
904
1277
|
}
|
|
905
1278
|
}
|
|
906
1279
|
|
|
907
1280
|
/**
|
|
908
|
-
*
|
|
909
|
-
*
|
|
910
|
-
* the inactivity timer re-arms for a fresh window. #2831.
|
|
1281
|
+
* Last prompt ABANDONED — the turn that raised it is over, so release the
|
|
1282
|
+
* pause but do NOT re-arm.
|
|
911
1283
|
*
|
|
912
|
-
*
|
|
1284
|
+
* #7375: releasing the flag is the load-bearing half. It and the id set are
|
|
1285
|
+
* one piece of bookkeeping, and `notifyPermissionResolved` only unsets the
|
|
1286
|
+
* flag for an id still IN the set — so taking the ids without releasing it
|
|
1287
|
+
* wedged the flag true on any path that does not reach `_clearMessageState`,
|
|
1288
|
+
* leaving the inactivity warning, the hard cap and the stall recovery dead
|
|
1289
|
+
* for the rest of the session.
|
|
913
1290
|
*/
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
this._pendingPermissionIds.delete(requestId)
|
|
917
|
-
if (this._pendingPermissionIds.size === 0) {
|
|
918
|
-
this._resultTimeoutPaused = false
|
|
919
|
-
if (this._isBusy) {
|
|
920
|
-
this._armResultTimeout()
|
|
921
|
-
}
|
|
922
|
-
}
|
|
1291
|
+
_onPendingPermissionsAbandoned() {
|
|
1292
|
+
this._resultTimeoutPaused = false
|
|
923
1293
|
}
|
|
924
1294
|
|
|
925
1295
|
/**
|
|
@@ -994,6 +1364,81 @@ export class CliSession extends BaseSession {
|
|
|
994
1364
|
}
|
|
995
1365
|
this.emit('mcp_servers', { servers: data.mcp_servers })
|
|
996
1366
|
}
|
|
1367
|
+
} else if (data.subtype === 'compact_boundary') {
|
|
1368
|
+
// #6768: `claude -p --output-format stream-json` mirrors the SDK's
|
|
1369
|
+
// `SDKCompactBoundaryMessage` shape, so this is the CLI equivalent
|
|
1370
|
+
// of SdkSession's compact_boundary branch — parse the structured
|
|
1371
|
+
// `compact_metadata` into a distinct marker instead of the generic
|
|
1372
|
+
// fallback below, which would forward the literal string
|
|
1373
|
+
// `compact_boundary` with no human-readable text.
|
|
1374
|
+
const meta = parseCompactBoundaryMeta(data.compact_metadata)
|
|
1375
|
+
;(this._log || log).info(
|
|
1376
|
+
`Context compacted (${meta.trigger}): ${meta.preTokens ?? '?'} -> ${meta.postTokens ?? '?'} tokens` +
|
|
1377
|
+
(meta.durationMs != null ? ` in ${meta.durationMs}ms` : '')
|
|
1378
|
+
)
|
|
1379
|
+
this.emit('message', {
|
|
1380
|
+
type: 'system',
|
|
1381
|
+
subtype: 'compact_boundary',
|
|
1382
|
+
content: formatCompactBoundaryContent(meta),
|
|
1383
|
+
compactMetadata: meta,
|
|
1384
|
+
timestamp: Date.now(),
|
|
1385
|
+
})
|
|
1386
|
+
} else if (data.subtype === 'task_started' || data.subtype === 'task_notification') {
|
|
1387
|
+
// #7340: the CLI's subagent lifecycle events. Until now these fell
|
|
1388
|
+
// into the generic branch below, which forwarded the literal string
|
|
1389
|
+
// "task_started" / "task_notification" to the client as a chat
|
|
1390
|
+
// bubble — noise in place of state.
|
|
1391
|
+
//
|
|
1392
|
+
// `task_started` is authoritative in two ways the tool_use block is
|
|
1393
|
+
// not: it carries `is_backgrounded` (the model's `run_in_background`
|
|
1394
|
+
// is a request; this is what the CLI actually did), and it identifies
|
|
1395
|
+
// subagents by `task_type` rather than by tool NAME, so tracking
|
|
1396
|
+
// survives a rename the way `Task` -> `Agent` was not survived.
|
|
1397
|
+
// `task_type: 'local_bash'` is a backgrounded shell — #4307's
|
|
1398
|
+
// surface, tracked separately, and never an agent.
|
|
1399
|
+
//
|
|
1400
|
+
// `task_notification` is the terminal signal. It is the ONLY thing
|
|
1401
|
+
// that clears a backgrounded agent now that the turn-end sweep no
|
|
1402
|
+
// longer does, so it is wired here rather than left to the sweep.
|
|
1403
|
+
// It fires for FAILED and STOPPED subagents too, not just completed
|
|
1404
|
+
// ones — every terminal status must clear the badge, or a subagent
|
|
1405
|
+
// that errored pins the session as working forever.
|
|
1406
|
+
if (data.subtype === 'task_started') {
|
|
1407
|
+
if (data.task_type === 'local_agent') {
|
|
1408
|
+
this._trackAgent({
|
|
1409
|
+
toolUseId: data.tool_use_id,
|
|
1410
|
+
description: typeof data.description === 'string' && data.description
|
|
1411
|
+
? data.description
|
|
1412
|
+
: 'Background task',
|
|
1413
|
+
background: data.is_backgrounded === true,
|
|
1414
|
+
// #7340: authoritative -- the CLI's own account, so it
|
|
1415
|
+
// overwrites the model's request in BOTH directions. It is
|
|
1416
|
+
// also the evidence that this build emits task lifecycle
|
|
1417
|
+
// messages at all, which is what makes the turn-end exemption
|
|
1418
|
+
// safe: `task_notification` can arrive.
|
|
1419
|
+
authoritative: true,
|
|
1420
|
+
})
|
|
1421
|
+
}
|
|
1422
|
+
} else {
|
|
1423
|
+
this._completeAgent(data.tool_use_id)
|
|
1424
|
+
}
|
|
1425
|
+
} else if (data.subtype === 'status') {
|
|
1426
|
+
// #8153 (review nit): mirrors SdkSession's 'status' branch —
|
|
1427
|
+
// `SDKStatusMessage` carries no `message`/`text` field, just
|
|
1428
|
+
// `status: 'compacting' | 'requesting' | null`, so the generic
|
|
1429
|
+
// fallback below would otherwise forward the bare literal string
|
|
1430
|
+
// "status" as a chat bubble. `status: null` means the previous
|
|
1431
|
+
// status cleared — nothing new to show, so it's suppressed
|
|
1432
|
+
// entirely rather than emitted as an empty/placeholder bubble.
|
|
1433
|
+
const statusText = formatStatusContent(data.status)
|
|
1434
|
+
if (statusText) {
|
|
1435
|
+
this.emit('message', {
|
|
1436
|
+
type: 'system',
|
|
1437
|
+
subtype: 'status',
|
|
1438
|
+
content: statusText,
|
|
1439
|
+
timestamp: Date.now(),
|
|
1440
|
+
})
|
|
1441
|
+
}
|
|
997
1442
|
} else {
|
|
998
1443
|
// Forward non-init system events (e.g. usage limits, sub-agent
|
|
999
1444
|
// notifications) as system messages to the client
|
|
@@ -1018,6 +1463,14 @@ export class CliSession extends BaseSession {
|
|
|
1018
1463
|
if (!messageId || !ctx) break
|
|
1019
1464
|
|
|
1020
1465
|
switch (event.type) {
|
|
1466
|
+
case 'message_start': {
|
|
1467
|
+
// #7393: a new API message (the next round of a tool loop) restarts
|
|
1468
|
+
// block indexes at 0. A reasoning block the last message never closed
|
|
1469
|
+
// must not absorb this one's block 0.
|
|
1470
|
+
this._closeThinking(ctx)
|
|
1471
|
+
break
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1021
1474
|
case 'content_block_start': {
|
|
1022
1475
|
const blockType = event.content_block?.type
|
|
1023
1476
|
ctx.currentContentBlockType = blockType
|
|
@@ -1027,6 +1480,12 @@ export class CliSession extends BaseSession {
|
|
|
1027
1480
|
ctx.hasStreamStarted = true
|
|
1028
1481
|
this.emit('stream_start', { messageId })
|
|
1029
1482
|
}
|
|
1483
|
+
} else if (blockType === 'thinking' || blockType === 'redacted_thinking') {
|
|
1484
|
+
// #7393: the model's reasoning. Open its stream now (the "it is
|
|
1485
|
+
// thinking" signal); the text is held until the block closes.
|
|
1486
|
+
const key = event.index ?? 0
|
|
1487
|
+
this._thinkingStreams(ctx, messageId).open(key)
|
|
1488
|
+
if (blockType === 'redacted_thinking') (ctx.redactedThinking ??= new Set()).add(key)
|
|
1030
1489
|
} else if (blockType === 'tool_use') {
|
|
1031
1490
|
ctx.currentToolName = event.content_block.name
|
|
1032
1491
|
ctx.toolInputChunks = ''
|
|
@@ -1063,6 +1522,14 @@ export class CliSession extends BaseSession {
|
|
|
1063
1522
|
}
|
|
1064
1523
|
ctx.didStreamText = true
|
|
1065
1524
|
this.emit('stream_delta', { messageId, delta: delta.text })
|
|
1525
|
+
} else if (delta.type === 'thinking_delta' && typeof delta.thinking === 'string') {
|
|
1526
|
+
// #7393: opening is idempotent, so a delta that beats its
|
|
1527
|
+
// content_block_start still lands in ONE stream. `signature_delta`
|
|
1528
|
+
// is not reasoning and falls through to nothing.
|
|
1529
|
+
const key = event.index ?? 0
|
|
1530
|
+
const streams = this._thinkingStreams(ctx, messageId)
|
|
1531
|
+
streams.open(key)
|
|
1532
|
+
streams.append(key, delta.thinking)
|
|
1066
1533
|
} else if (delta.type === 'input_json_delta' && ctx.currentContentBlockType === 'tool_use') {
|
|
1067
1534
|
if (typeof delta.partial_json === 'string' && !ctx.toolInputOverflow) {
|
|
1068
1535
|
const chunkBytes = Buffer.byteLength(delta.partial_json, 'utf8')
|
|
@@ -1077,6 +1544,18 @@ export class CliSession extends BaseSession {
|
|
|
1077
1544
|
} else {
|
|
1078
1545
|
ctx.toolInputChunks += delta.partial_json
|
|
1079
1546
|
ctx.toolInputBytes += chunkBytes
|
|
1547
|
+
// #8135 (review on #7346): do NOT forward this raw
|
|
1548
|
+
// chunk as a live `tool_input_delta` — a secret can
|
|
1549
|
+
// straddle chunk boundaries (e.g. "export TOKEN=sk-"
|
|
1550
|
+
// in one delta, "ant-api03-…" in the next), so a
|
|
1551
|
+
// per-chunk value can't be redacted safely, and
|
|
1552
|
+
// mid-stream partial JSON can't be parsed to run the
|
|
1553
|
+
// structured sanitizer over it either. The sanitized
|
|
1554
|
+
// FULL input is instead delivered as a single
|
|
1555
|
+
// `tool_input_delta` once the block finalizes — see
|
|
1556
|
+
// `_captureFinalizedToolInput` at `content_block_stop`,
|
|
1557
|
+
// a few ms later (execution, not this streaming
|
|
1558
|
+
// window, is the long part of a Bash call).
|
|
1080
1559
|
}
|
|
1081
1560
|
}
|
|
1082
1561
|
}
|
|
@@ -1084,7 +1563,23 @@ export class CliSession extends BaseSession {
|
|
|
1084
1563
|
}
|
|
1085
1564
|
|
|
1086
1565
|
case 'content_block_stop': {
|
|
1566
|
+
if (ctx?.thinking) {
|
|
1567
|
+
// #7393: close the reasoning block this stop belongs to (a no-op
|
|
1568
|
+
// for any other block type).
|
|
1569
|
+
const key = event.index ?? 0
|
|
1570
|
+
ctx.thinking.close(key, { redacted: ctx.redactedThinking?.delete(key) === true })
|
|
1571
|
+
}
|
|
1087
1572
|
if (ctx && ctx.currentToolName) {
|
|
1573
|
+
// #7346: backfill EVERY tool's finalized input (not just the
|
|
1574
|
+
// four special-cased by _applyToolInputSemantics below) so a
|
|
1575
|
+
// generic Bash/Read/etc. call's input rides out on its
|
|
1576
|
+
// tool_result instead of staying null forever — the actual
|
|
1577
|
+
// root cause of the "(no input)" bug, in flight AND after
|
|
1578
|
+
// completion/session-switch replay. Must run before
|
|
1579
|
+
// _applyToolInputSemantics only by convention (the two are
|
|
1580
|
+
// independent; ordering doesn't matter since neither mutates
|
|
1581
|
+
// ctx.toolInputChunks).
|
|
1582
|
+
this._captureFinalizedToolInput(ctx)
|
|
1088
1583
|
this._applyToolInputSemantics(ctx)
|
|
1089
1584
|
}
|
|
1090
1585
|
if (ctx) {
|
|
@@ -1108,6 +1603,8 @@ export class CliSession extends BaseSession {
|
|
|
1108
1603
|
const ctx = this._currentCtx
|
|
1109
1604
|
const messageId = this._currentMessageId
|
|
1110
1605
|
const content = data.message?.content
|
|
1606
|
+
this.emit('assistant_response', { responseId: data.message?.id ?? data.uuid, text: assistantResponseText(content) })
|
|
1607
|
+
if (ctx) ctx.assistantResponseSeen = true
|
|
1111
1608
|
if (Array.isArray(content) && ctx && messageId) {
|
|
1112
1609
|
// If stream_event deltas already drove streaming, skip assistant text
|
|
1113
1610
|
if (ctx.didStreamText) {
|
|
@@ -1149,6 +1646,14 @@ export class CliSession extends BaseSession {
|
|
|
1149
1646
|
const messageId = this._currentMessageId
|
|
1150
1647
|
const ctx = this._currentCtx
|
|
1151
1648
|
|
|
1649
|
+
if (!ctx?.assistantResponseSeen && typeof data.result === 'string') {
|
|
1650
|
+
this.emit('assistant_response', { text: assistantResponseText(data.result) })
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
// #7393: a turn can end under an open reasoning block; finalise it so the
|
|
1654
|
+
// client's "Thinking…" settles, before anything else this result emits.
|
|
1655
|
+
this._closeThinking(ctx)
|
|
1656
|
+
|
|
1152
1657
|
// #5064 — Fallback for turns that complete without ever emitting
|
|
1153
1658
|
// streamed assistant text. The canonical case is `/compact`: the
|
|
1154
1659
|
// CLI returns the compaction summary in `data.result` but emits
|
|
@@ -1212,15 +1717,93 @@ export class CliSession extends BaseSession {
|
|
|
1212
1717
|
cost: data.total_cost_usd,
|
|
1213
1718
|
duration: data.duration_ms,
|
|
1214
1719
|
usage: data.usage,
|
|
1720
|
+
// #6692: the CLI's stream-json result is produced by the same
|
|
1721
|
+
// runtime as the SDK's; when it carries modelUsage/num_turns/
|
|
1722
|
+
// duration_api_ms, forward them — all three degrade to null on
|
|
1723
|
+
// older CLI builds that omit them.
|
|
1724
|
+
numTurns: Number.isFinite(data.num_turns) ? data.num_turns : null,
|
|
1725
|
+
apiDurationMs: Number.isFinite(data.duration_api_ms) ? data.duration_api_ms : null,
|
|
1726
|
+
modelUsage: normalizeSdkModelUsage(data.modelUsage),
|
|
1727
|
+
// #7326: the CLI's result is the same message the SDK's is, so it
|
|
1728
|
+
// carries the same stop_reason / subtype / terminal_reason.
|
|
1729
|
+
declarationEligible: sdkDeclarationEligible(data),
|
|
1730
|
+
...turnOutcomeField(outcomeFromSdkResult(data)),
|
|
1215
1731
|
})
|
|
1216
1732
|
|
|
1217
|
-
// Message complete — ready for next message
|
|
1218
|
-
|
|
1733
|
+
// Message complete — ready for next message.
|
|
1734
|
+
// #7340: the CLI's own `result` message -- the child is alive and
|
|
1735
|
+
// reported the turn over itself, so a confirmed-backgrounded subagent
|
|
1736
|
+
// survives the sweep and clears later on `task_notification`. This and
|
|
1737
|
+
// SdkSession's `result` are the ONLY two sites that may pass this flag;
|
|
1738
|
+
// see the contract on `BaseSession._clearMessageState`.
|
|
1739
|
+
// #7376: `completion: 'normal'` -- the child's own `result` ended the
|
|
1740
|
+
// turn, so a Stop requested during it may have cut its tools off.
|
|
1741
|
+
this._clearMessageState({ turnEndedCleanly: true, completion: 'normal' })
|
|
1219
1742
|
break
|
|
1220
1743
|
}
|
|
1221
1744
|
}
|
|
1222
1745
|
}
|
|
1223
1746
|
|
|
1747
|
+
/**
|
|
1748
|
+
* #7346: backfill the finalized tool input onto `_inFlightToolStarts`
|
|
1749
|
+
* (base-session.js `_recordToolInput`, which sanitizes + size-caps it
|
|
1750
|
+
* — see #8135/#8136) so `tool-result.js`'s `emitToolResults` can
|
|
1751
|
+
* attach it to the matching `tool_result` via `_getTrackedToolInput`.
|
|
1752
|
+
* Runs for every tool (unlike `_applyToolInputSemantics`, which only
|
|
1753
|
+
* parses to drive four special-cased tools' session state) — the
|
|
1754
|
+
* #7346 root cause was that nothing captured the finalized input for
|
|
1755
|
+
* a generic Bash/Read/etc. call, so it stayed `null` forever: not
|
|
1756
|
+
* just in flight, but in the persisted `tool_start` history entry a
|
|
1757
|
+
* session-switch replay rebuilds from.
|
|
1758
|
+
*
|
|
1759
|
+
* #8135 (review): also delivers the SANITIZED full input as a
|
|
1760
|
+
* single-shot `tool_input_delta` right here, so the in-flight panel
|
|
1761
|
+
* lights up within milliseconds of the block finalizing — long
|
|
1762
|
+
* before the tool actually finishes executing (the #4341 client
|
|
1763
|
+
* fallback already renders whatever lands in `toolInputPartial`; one
|
|
1764
|
+
* complete-JSON chunk parses via `tryParseCompleteJson` exactly like
|
|
1765
|
+
* many partial ones would have). This REPLACES the raw per-chunk
|
|
1766
|
+
* `tool_input_delta` streaming `content_block_delta` used to do
|
|
1767
|
+
* (removed — see the comment there): a secret can straddle chunk
|
|
1768
|
+
* boundaries and mid-stream partial JSON can't be sanitized, so the
|
|
1769
|
+
* safe delivery point is "sanitize the complete parsed value, then
|
|
1770
|
+
* send it once."
|
|
1771
|
+
*
|
|
1772
|
+
* Best-effort and silent on failure: a JSON parse error (malformed
|
|
1773
|
+
* chunk) or an empty buffer (the overflow path already reset
|
|
1774
|
+
* `ctx.toolInputChunks` to `''` and told the user via the `error`
|
|
1775
|
+
* event emitted at accumulation time) simply skips both the backfill
|
|
1776
|
+
* and the delta — the tool_start entry's `input` stays `null` and the
|
|
1777
|
+
* client shows the "(input not received yet)" placeholder (#7346
|
|
1778
|
+
* direction 3) rather than a stale or fabricated value.
|
|
1779
|
+
*
|
|
1780
|
+
* @param {{ currentToolUseId: string|null, toolInputChunks: string }} ctx
|
|
1781
|
+
* @private
|
|
1782
|
+
*/
|
|
1783
|
+
_captureFinalizedToolInput(ctx) {
|
|
1784
|
+
const toolUseId = ctx.currentToolUseId
|
|
1785
|
+
if (!toolUseId || !ctx.toolInputChunks) return
|
|
1786
|
+
let parsed
|
|
1787
|
+
try {
|
|
1788
|
+
parsed = JSON.parse(ctx.toolInputChunks)
|
|
1789
|
+
} catch {
|
|
1790
|
+
// Malformed/truncated JSON — nothing to backfill or deliver.
|
|
1791
|
+
return
|
|
1792
|
+
}
|
|
1793
|
+
const sanitized = this._recordToolInput(toolUseId, parsed)
|
|
1794
|
+
// `null`/`undefined` means "known to have no input" (or the parse
|
|
1795
|
+
// above legitimately produced one of those) — the placeholder logic
|
|
1796
|
+
// covers that case on its own; don't ship a literal "null" chunk.
|
|
1797
|
+
if (sanitized === null || sanitized === undefined) return
|
|
1798
|
+
const messageId = this._currentMessageId
|
|
1799
|
+
if (!messageId) return
|
|
1800
|
+
this.emit('tool_input_delta', {
|
|
1801
|
+
messageId,
|
|
1802
|
+
toolUseId,
|
|
1803
|
+
partialJson: JSON.stringify(sanitized),
|
|
1804
|
+
})
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1224
1807
|
/**
|
|
1225
1808
|
* Apply session-state side effects for tools whose accumulated
|
|
1226
1809
|
* `toolInputChunks` JSON drives plan-mode flags, agent tracking, or
|
|
@@ -1261,8 +1844,13 @@ export class CliSession extends BaseSession {
|
|
|
1261
1844
|
;(this._log || log).error(`Failed to parse AskUserQuestion input: ${err.message}`)
|
|
1262
1845
|
return
|
|
1263
1846
|
}
|
|
1264
|
-
|
|
1265
|
-
|
|
1847
|
+
// #7340: `Agent` alongside `Task` here too. Control flow is identical
|
|
1848
|
+
// either way (both `return`), so only the diagnostic differed -- which
|
|
1849
|
+
// is exactly how a roster gets fixed in three places and missed in the
|
|
1850
|
+
// fourth. A subagent spawn whose input failed to parse would have been
|
|
1851
|
+
// logged as a generic tool under the current tool name.
|
|
1852
|
+
if (toolName === 'Task' || toolName === 'Agent') {
|
|
1853
|
+
;(this._log || log).warn(`Failed to parse ${toolName} tool input: ${err.message}`)
|
|
1266
1854
|
return
|
|
1267
1855
|
}
|
|
1268
1856
|
if (toolName === 'ExitPlanMode') {
|
|
@@ -1286,6 +1874,8 @@ export class CliSession extends BaseSession {
|
|
|
1286
1874
|
// #4828: session-scoped.
|
|
1287
1875
|
;(this._log || log).info(`AskUserQuestion detected (${toolUseId})`)
|
|
1288
1876
|
this._waitingForAnswer = true
|
|
1877
|
+
// #7457 -- co-located with the flag (see the constructor).
|
|
1878
|
+
this._pendingQuestion = { toolUseId, questions: semantics.payload.questions ?? [] }
|
|
1289
1879
|
this.emit('user_question', {
|
|
1290
1880
|
toolUseId,
|
|
1291
1881
|
questions: semantics.payload.questions,
|
|
@@ -1294,13 +1884,19 @@ export class CliSession extends BaseSession {
|
|
|
1294
1884
|
}
|
|
1295
1885
|
case 'task': {
|
|
1296
1886
|
if (!parseSucceeded) return
|
|
1297
|
-
|
|
1887
|
+
// #7340: this records the MODEL'S REQUEST (`run_in_background`) into
|
|
1888
|
+
// `background`. It does NOT exempt the agent from the turn-end sweep —
|
|
1889
|
+
// `backgroundConfirmed` does, and only the CLI's own `task_started` can
|
|
1890
|
+
// set that. Exempting on an unconfirmed request would strand an agent
|
|
1891
|
+
// on a build that emits no task lifecycle events, because the same
|
|
1892
|
+
// event is what proves a terminal `task_notification` can arrive.
|
|
1893
|
+
// `task_started` may correct this value in EITHER direction;
|
|
1894
|
+
// `_trackAgent` upgrades rather than re-emits, so either order is fine.
|
|
1895
|
+
this._trackAgent({
|
|
1298
1896
|
toolUseId,
|
|
1299
1897
|
description: semantics.payload.description,
|
|
1300
|
-
|
|
1301
|
-
}
|
|
1302
|
-
this._activeAgents.set(toolUseId, agentInfo)
|
|
1303
|
-
this.emit('agent_spawned', agentInfo)
|
|
1898
|
+
background: semantics.payload.background,
|
|
1899
|
+
})
|
|
1304
1900
|
return
|
|
1305
1901
|
}
|
|
1306
1902
|
case 'enter_plan': {
|
|
@@ -1315,15 +1911,55 @@ export class CliSession extends BaseSession {
|
|
|
1315
1911
|
}
|
|
1316
1912
|
}
|
|
1317
1913
|
|
|
1914
|
+
/**
|
|
1915
|
+
* #7393 — the turn's reasoning streams, created on first use. Lives on the
|
|
1916
|
+
* per-turn `ctx` so it dies with the turn, and is built lazily so a ctx built
|
|
1917
|
+
* without it (tests, an older shape) still works.
|
|
1918
|
+
*/
|
|
1919
|
+
_thinkingStreams(ctx, messageId) {
|
|
1920
|
+
return (ctx.thinking ??= new ThinkingStreams((event, data) => this.emit(event, data), messageId))
|
|
1921
|
+
}
|
|
1922
|
+
|
|
1923
|
+
/**
|
|
1924
|
+
* #7393 — finish every open reasoning block of `ctx` and forget which of them
|
|
1925
|
+
* were `redacted_thinking`. The two must go together: a redacted block that
|
|
1926
|
+
* never got its stop would otherwise leave its index in the set, and a later
|
|
1927
|
+
* plain block at that index would be shown as the redacted marker.
|
|
1928
|
+
*/
|
|
1929
|
+
_closeThinking(ctx) {
|
|
1930
|
+
if (!ctx) return
|
|
1931
|
+
// A redacted block closes as the marker even when its stop never came.
|
|
1932
|
+
for (const key of ctx.redactedThinking ?? []) ctx.thinking?.close(key, { redacted: true })
|
|
1933
|
+
ctx.thinking?.closeAll()
|
|
1934
|
+
ctx.redactedThinking?.clear()
|
|
1935
|
+
}
|
|
1936
|
+
|
|
1318
1937
|
/**
|
|
1319
1938
|
* Clear per-message state, marking us as ready for the next message.
|
|
1320
1939
|
* After clearing, drains the next item from _pendingQueue (if any) so
|
|
1321
1940
|
* that all queued messages are eventually delivered in FIFO order.
|
|
1322
1941
|
*/
|
|
1323
|
-
|
|
1324
|
-
|
|
1942
|
+
// #7340: forward the opts to super. `turnEndedCleanly` decides whether a
|
|
1943
|
+
// confirmed-backgrounded subagent survives BaseSession's turn-end sweep;
|
|
1944
|
+
// an override that drops it silently disables the exemption.
|
|
1945
|
+
_clearMessageState(opts) {
|
|
1946
|
+
super._clearMessageState(opts)
|
|
1325
1947
|
this._waitingForAnswer = false
|
|
1948
|
+
this._pendingQuestion = null // #7457 -- co-located with the flag.
|
|
1326
1949
|
this._currentCtx = null
|
|
1950
|
+
// #7335: this is the ONE funnel every turn end passes through — the normal
|
|
1951
|
+
// `result`, the hard cap, the interrupt safety timeout, destroy() — and it
|
|
1952
|
+
// used to drop `_pendingPermissionIds` on the floor without telling anyone.
|
|
1953
|
+
// Expiring here rather than only at the individual death sites is the
|
|
1954
|
+
// difference between a guard wired to the callers someone remembered and
|
|
1955
|
+
// one wired to all of them (docs/false-safety-guards.md). Idempotent: a
|
|
1956
|
+
// no-op when the set is already empty, which it is on the paths that
|
|
1957
|
+
// expired explicitly moments earlier.
|
|
1958
|
+
// #7382: the expire itself moved to BaseSession._clearMessageState (called
|
|
1959
|
+
// by super above), so every provider inherits it rather than each wiring
|
|
1960
|
+
// its own. The explicit calls in _killAndRespawn / _handleChildClose stay:
|
|
1961
|
+
// both reach this funnel via _emitInterruptedTurnResult, which early-returns
|
|
1962
|
+
// when the session is not busy.
|
|
1327
1963
|
// Reset permission pause bookkeeping — the next message starts fresh.
|
|
1328
1964
|
this._pendingPermissionIds.clear()
|
|
1329
1965
|
this._resultTimeoutPaused = false
|
|
@@ -1360,14 +1996,7 @@ export class CliSession extends BaseSession {
|
|
|
1360
1996
|
if (this._outgoingQueue.length > 0) {
|
|
1361
1997
|
this.dequeueNextOutgoing()
|
|
1362
1998
|
} else if (this._pendingQueue.length > 0) {
|
|
1363
|
-
|
|
1364
|
-
if (this._destroying) return
|
|
1365
|
-
if (!this._processReady || this._pendingQueue.length === 0) return
|
|
1366
|
-
const pending = this._pendingQueue.shift()
|
|
1367
|
-
// #4828: session-scoped (post-result, post-init).
|
|
1368
|
-
;(this._log || log).info(`Dequeuing next pending message after result (${this._pendingQueue.length} remaining)`)
|
|
1369
|
-
this.sendMessage(pending.prompt, pending.attachments, pending.options || {})
|
|
1370
|
-
})
|
|
1999
|
+
this._drainNextPendingAfterResult()
|
|
1371
2000
|
}
|
|
1372
2001
|
}
|
|
1373
2002
|
}
|
|
@@ -1375,13 +2004,52 @@ export class CliSession extends BaseSession {
|
|
|
1375
2004
|
/**
|
|
1376
2005
|
* Kill the current child process (if any) and respawn.
|
|
1377
2006
|
* Suppresses auto-respawn during the kill, clears timers, and starts fresh.
|
|
2007
|
+
*
|
|
2008
|
+
* @param {string} [terminatedReason] #7376: why the turn is being ended
|
|
2009
|
+
* (`permission_mode_switch` / `model_switch`). Passed in by each caller
|
|
2010
|
+
* rather than inferred -- this is shared by the panic-button and a mid-turn
|
|
2011
|
+
* model change -- and stamped onto the synthetic `tool_result` of every tool
|
|
2012
|
+
* the dying turn left in flight.
|
|
1378
2013
|
*/
|
|
1379
|
-
_killAndRespawn() {
|
|
2014
|
+
_killAndRespawn(terminatedReason) {
|
|
2015
|
+
// #7335: retire the prompts the dying turn was blocked on BEFORE
|
|
2016
|
+
// _emitInterruptedTurnResult, which reaches _clearMessageState and wipes
|
|
2017
|
+
// `_pendingPermissionIds` silently. Ordering is the whole fix: after that
|
|
2018
|
+
// call there is nothing left to tell the client about, which is exactly
|
|
2019
|
+
// how the card ended up stranded live on screen with a dead Allow button.
|
|
2020
|
+
this._expirePendingPermissions('Permission request expired (the turn it belonged to was interrupted and the session restarted)')
|
|
2021
|
+
|
|
2022
|
+
// #7340: the child is about to be gone (or already is), and with it every
|
|
2023
|
+
// subagent it was running. `task_notification` -- the ONLY signal that
|
|
2024
|
+
// clears a confirmed-backgrounded agent now that the turn-end sweep spares
|
|
2025
|
+
// it -- can never arrive, so drain them here or the session claims to be
|
|
2026
|
+
// working for the rest of the daemon's life.
|
|
2027
|
+
//
|
|
2028
|
+
// Needs its OWN call for the same reason `_expirePendingPermissions` above
|
|
2029
|
+
// does (#7335): both reach the `_clearMessageState` funnel via
|
|
2030
|
+
// `_emitInterruptedTurnResult`, which early-returns when the session is not
|
|
2031
|
+
// busy -- and "not busy with a backgrounded agent still running" is the
|
|
2032
|
+
// exact state the exemption creates. Idempotent, and the funnel's own
|
|
2033
|
+
// unconditional sweep covers the busy case.
|
|
2034
|
+
this._completeAgents()
|
|
2035
|
+
|
|
2036
|
+
// #7611: the same child-is-going-away reasoning for background SHELLS.
|
|
2037
|
+
// `killProcessTree` below (since #7608) signals the child's whole descendant
|
|
2038
|
+
// tree, which includes the shells the agent started with
|
|
2039
|
+
// `run_in_background`, and nothing can poll or hear back from them after
|
|
2040
|
+
// this. Forget them here — before `_emitInterruptedTurnResult`, so a
|
|
2041
|
+
// listener of its `result` already sees the truthful `isRunning` — or the
|
|
2042
|
+
// tracker keeps the session 'running' (immune to the idle timeout) until the
|
|
2043
|
+
// 4 h hard-quiesce reap. NOT `_destroyPendingBackgroundShells`: that is the
|
|
2044
|
+
// end-of-session teardown and also drops the activity tree. A no-op for a
|
|
2045
|
+
// provider that tracks no shells.
|
|
2046
|
+
this._clearPendingBackgroundShells()
|
|
2047
|
+
|
|
1380
2048
|
// #4471: emit synthetic terminating events BEFORE setting _respawning,
|
|
1381
2049
|
// otherwise the _handleChildClose guard short-circuits and the dashboard
|
|
1382
2050
|
// never receives `agent_idle` — Stop stays stuck on panic-button +
|
|
1383
2051
|
// mid-turn setModel paths.
|
|
1384
|
-
this._emitInterruptedTurnResult()
|
|
2052
|
+
this._emitInterruptedTurnResult(0, terminatedReason)
|
|
1385
2053
|
|
|
1386
2054
|
this._respawning = true
|
|
1387
2055
|
this._processReady = false
|
|
@@ -1478,7 +2146,13 @@ export class CliSession extends BaseSession {
|
|
|
1478
2146
|
// tests with a mock child that never emits 'close').
|
|
1479
2147
|
if (typeof forceKillTimer.unref === 'function') forceKillTimer.unref()
|
|
1480
2148
|
|
|
1481
|
-
|
|
2149
|
+
// #6643 — on Windows a plain SIGTERM only TerminateProcess-es the cmd.exe
|
|
2150
|
+
// shim wrapping a `.cmd` provider (claude/codex/…); the real node
|
|
2151
|
+
// grandchild is orphaned and the wrapper's `close` above then cancels the
|
|
2152
|
+
// forceKill escalation before it can fire. killProcessTree reaps the whole
|
|
2153
|
+
// tree — since #7606 on POSIX too (graceful SIGTERM to every descendant,
|
|
2154
|
+
// enumerated before the child is signalled).
|
|
2155
|
+
killProcessTree(oldChild)
|
|
1482
2156
|
} else {
|
|
1483
2157
|
this._respawning = false
|
|
1484
2158
|
this._respawnCount = 0
|
|
@@ -1508,18 +2182,181 @@ export class CliSession extends BaseSession {
|
|
|
1508
2182
|
_onModelChanged() {
|
|
1509
2183
|
// #4828: session-scoped if init has fired before the model change.
|
|
1510
2184
|
;(this._log || log).info(`Model changed to ${this.model || 'default'}, restarting process`)
|
|
1511
|
-
this._killAndRespawn()
|
|
2185
|
+
this._killAndRespawn('model_switch')
|
|
2186
|
+
}
|
|
2187
|
+
|
|
2188
|
+
/**
|
|
2189
|
+
* Base dir for the per-session permission-mode sidecar dirs (#7337).
|
|
2190
|
+
* Exposed so the boot sweep and its tests name it once.
|
|
2191
|
+
*/
|
|
2192
|
+
static get PERMISSION_MODE_SIDECAR_BASE() { return join(tmpdir(), 'chroxy-claude-cli') }
|
|
2193
|
+
|
|
2194
|
+
/**
|
|
2195
|
+
* #7337: boot-time sweep of sidecar dirs orphaned by a crash. destroy()
|
|
2196
|
+
* removes a session's own dir, but a SIGKILL leaks it, so a long-lived host
|
|
2197
|
+
* accumulates one per crashed session. Same ownership rule as the claude-tui
|
|
2198
|
+
* sink sweep and the same implementation — only dirs whose `owner.pid` is
|
|
2199
|
+
* DEAD are removed, so a live daemon's dirs (including this one's) are kept
|
|
2200
|
+
* and the sweep is safe to run unconditionally at boot.
|
|
2201
|
+
*
|
|
2202
|
+
* @param {object} [logger] - logger with info/warn (defaults to module log)
|
|
2203
|
+
* @returns {{swept:number, kept:number}}
|
|
2204
|
+
*/
|
|
2205
|
+
static sweepStaleSidecarDirs(logger = log) {
|
|
2206
|
+
return sweepStaleOwnedDirs(CliSession.PERMISSION_MODE_SIDECAR_BASE, {
|
|
2207
|
+
logger,
|
|
2208
|
+
label: 'claude-cli permission-mode sidecar',
|
|
2209
|
+
})
|
|
2210
|
+
}
|
|
2211
|
+
|
|
2212
|
+
/**
|
|
2213
|
+
* #7337: create the re-readable permission-mode sidecar and seed it with the
|
|
2214
|
+
* session's current mode. Idempotent — a respawn calls start() again and must
|
|
2215
|
+
* keep the SAME path, because the sidecar the still-draining old child holds
|
|
2216
|
+
* in its env has to stay valid until that child is gone.
|
|
2217
|
+
*
|
|
2218
|
+
* Only meaningful when permissions are enabled: with no port there is no hook
|
|
2219
|
+
* endpoint, so `permission-hook.sh` never runs and the mode is moot. A failed
|
|
2220
|
+
* initial write leaves `_permissionModeFile` null and the session falls back
|
|
2221
|
+
* to env-var-only mode — losing the ability to hot-swap the mode is bad, but
|
|
2222
|
+
* failing session start over a /tmp write is worse (same trade ClaudeTuiSession
|
|
2223
|
+
* makes at #4013).
|
|
2224
|
+
*/
|
|
2225
|
+
_ensurePermissionModeSidecar() {
|
|
2226
|
+
if (!this._port) return
|
|
2227
|
+
const mode = this.permissionMode || 'approve'
|
|
2228
|
+
|
|
2229
|
+
// Re-seed on EVERY start(), not only the first. The path is kept stable
|
|
2230
|
+
// across a respawn (a still-draining old child holds it in its env), but
|
|
2231
|
+
// the CONTENTS must be re-asserted, because the file outranks the env var
|
|
2232
|
+
// in the hook's resolution order. Without this, a mid-session write that
|
|
2233
|
+
// failed (ENOSPC / EROFS / EIO) left the sidecar holding the OLD mode while
|
|
2234
|
+
// the respawned child carried the NEW one in CHROXY_PERMISSION_MODE — and
|
|
2235
|
+
// the hook read the file. A tighten to `approve` would then keep
|
|
2236
|
+
// auto-allowing for the rest of the session while the daemon, the state
|
|
2237
|
+
// file and the UI all said `approve`. The respawn was documented as the
|
|
2238
|
+
// repair and was not one.
|
|
2239
|
+
if (this._permissionModeFile) {
|
|
2240
|
+
try {
|
|
2241
|
+
writePermissionModeSidecarAtomic(this._permissionModeFile, mode)
|
|
2242
|
+
return
|
|
2243
|
+
} catch (err) {
|
|
2244
|
+
// The existing file is now untrustworthy — and a stale file is WORSE
|
|
2245
|
+
// than none, because it outranks the correct env var. Drop it so the
|
|
2246
|
+
// hook falls back to CHROXY_PERMISSION_MODE, then try a fresh dir below.
|
|
2247
|
+
;(this._log || log).warn(`permission-mode sidecar re-seed failed (${err.message}) — dropping the stale sidecar so the hook falls back to the env var`)
|
|
2248
|
+
this._cleanupPermissionModeSidecar()
|
|
2249
|
+
}
|
|
2250
|
+
}
|
|
2251
|
+
|
|
2252
|
+
let dir = null
|
|
2253
|
+
try {
|
|
2254
|
+
const base = ensureOwnedBaseDir(CliSession.PERMISSION_MODE_SIDECAR_BASE)
|
|
2255
|
+
dir = join(base, `s-${randomUUID()}`)
|
|
2256
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
2257
|
+
// Stamp the owning pid so the boot-time sweep can tell a live daemon's
|
|
2258
|
+
// dir from one orphaned by a crash. Best-effort: a missing pidfile just
|
|
2259
|
+
// makes the dir sweep-eligible after a grace window, which is the safe
|
|
2260
|
+
// default for an orphan.
|
|
2261
|
+
try { writeFileSync(join(dir, OWNER_PID_FILE), String(process.pid)) } catch { /* best effort */ }
|
|
2262
|
+
const path = join(dir, 'permission-mode')
|
|
2263
|
+
writePermissionModeSidecarAtomic(path, mode)
|
|
2264
|
+
this._permissionModeDir = dir
|
|
2265
|
+
this._permissionModeFile = path
|
|
2266
|
+
} catch (err) {
|
|
2267
|
+
// Remove the dir we just created, if we got that far — otherwise a
|
|
2268
|
+
// persistent write failure leaks one dir per respawn, and because
|
|
2269
|
+
// owner.pid names this LIVE daemon the boot sweep keeps every one of
|
|
2270
|
+
// them for the daemon's whole lifetime.
|
|
2271
|
+
if (dir) { try { rmSync(dir, { recursive: true, force: true }) } catch { /* best effort */ } }
|
|
2272
|
+
;(this._log || log).warn(`permission-mode sidecar unavailable (${err.message}) — falling back to env-var-only mode; a mid-session permission switch will not reach the running process until it respawns`)
|
|
2273
|
+
this._permissionModeFile = null
|
|
2274
|
+
this._permissionModeDir = null
|
|
2275
|
+
}
|
|
2276
|
+
}
|
|
2277
|
+
|
|
2278
|
+
/** Remove the sidecar dir created by _ensurePermissionModeSidecar. */
|
|
2279
|
+
_cleanupPermissionModeSidecar() {
|
|
2280
|
+
if (this._permissionModeDir) {
|
|
2281
|
+
try { rmSync(this._permissionModeDir, { recursive: true, force: true }) }
|
|
2282
|
+
catch (err) { (this._log || log).warn(`permission-mode sidecar cleanup failed: ${err.message}`) }
|
|
2283
|
+
}
|
|
2284
|
+
this._permissionModeDir = null
|
|
2285
|
+
this._permissionModeFile = null
|
|
1512
2286
|
}
|
|
1513
2287
|
|
|
1514
2288
|
_onPermissionModeChanged(mode) {
|
|
2289
|
+
// #7337: publish to the sidecar FIRST. `permission-hook.sh` prefers the
|
|
2290
|
+
// file over CHROXY_PERMISSION_MODE and re-reads it on every tool call, so
|
|
2291
|
+
// this takes effect immediately — including for the child that is still
|
|
2292
|
+
// alive right now. Without it the only channel was the respawn below, which
|
|
2293
|
+
// does not land until the old child's `close` fires (up to the 10s
|
|
2294
|
+
// force-kill grace in _killAndRespawn), and every PreToolUse hook that old
|
|
2295
|
+
// child raises in the meantime resolves the STALE mode. That is #7337: a
|
|
2296
|
+
// Bash approval card on a session whose state file already read `"auto"`.
|
|
2297
|
+
if (this._permissionModeFile) {
|
|
2298
|
+
try {
|
|
2299
|
+
writePermissionModeSidecarAtomic(this._permissionModeFile, mode)
|
|
2300
|
+
} catch (err) {
|
|
2301
|
+
// Hook precedence is file -> env var, so a sidecar left holding the
|
|
2302
|
+
// PREVIOUS mode outranks the correct value in CHROXY_PERMISSION_MODE —
|
|
2303
|
+
// and on a TIGHTEN that is fail-open. Remove it rather than leave it:
|
|
2304
|
+
// the hook then falls back to the env var, and start()'s re-seed
|
|
2305
|
+
// rebuilds a fresh sidecar on the respawn below. Leaving it in place
|
|
2306
|
+
// pinned the old mode for the whole session.
|
|
2307
|
+
;(this._log || log).warn(`failed to write permission-mode sidecar (${err.message}) — removing it so the hook falls back to the spawn env var until the respawn re-seeds`)
|
|
2308
|
+
this._cleanupPermissionModeSidecar()
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
|
|
1515
2312
|
// #3729 panic-button semantics: BaseSession.setPermissionMode lets `'auto'`
|
|
1516
2313
|
// bypass the `_isBusy` guard, so flipping to auto mid-turn IS destructive —
|
|
1517
2314
|
// the in-flight `claude -p` process is killed and respawned, dropping the
|
|
1518
2315
|
// current turn. This is by design (parity with SDK auto-resolve of pending
|
|
1519
|
-
// prompts); see #3735 for the regression test pinning this behavior.
|
|
2316
|
+
// prompts); see #3735 for the regression test pinning this behavior. The
|
|
2317
|
+
// respawn is still required for the OTHER mode channel: `--permission-mode
|
|
2318
|
+
// bypassPermissions` / `plan` is argv, not env, so only a new process picks
|
|
2319
|
+
// it up (buildClaudeCliArgs). The sidecar covers the hook; the respawn
|
|
2320
|
+
// covers claude's own flag.
|
|
1520
2321
|
// #4828: session-scoped if init has fired.
|
|
1521
2322
|
;(this._log || log).info(`Permission mode changed to ${mode}, restarting process`)
|
|
1522
|
-
this._killAndRespawn()
|
|
2323
|
+
this._killAndRespawn('permission_mode_switch')
|
|
2324
|
+
}
|
|
2325
|
+
|
|
2326
|
+
getRestartBlockers() {
|
|
2327
|
+
const reasons = super.getRestartBlockers()
|
|
2328
|
+
// Messages acknowledged as `queued` while the CLI child warms up or
|
|
2329
|
+
// respawns live here, NOT in `_outgoingQueue` (see sendMessage's
|
|
2330
|
+
// `!_processReady` branch) — a restart would drop them (#8324).
|
|
2331
|
+
const pending = this._pendingQueue.length
|
|
2332
|
+
if (pending > 0) reasons.push(`${pending} message(s) queued while the CLI is not ready`)
|
|
2333
|
+
return reasons
|
|
2334
|
+
}
|
|
2335
|
+
|
|
2336
|
+
/**
|
|
2337
|
+
* #7457 -- the AskUserQuestion this child is parked on stdin for, if any.
|
|
2338
|
+
*
|
|
2339
|
+
* A read-through of `_pendingQuestion`, which is written and cleared in the
|
|
2340
|
+
* same statement block as `_waitingForAnswer` at every one of that flag's
|
|
2341
|
+
* four sites -- construction, the emit, the `_clearMessageState` turn-end
|
|
2342
|
+
* funnel ("the ONE funnel every turn end passes through": normal `result`,
|
|
2343
|
+
* hard cap, interrupt safety timeout, destroy) and `respondToQuestion`. So it
|
|
2344
|
+
* cannot report a question the child has stopped waiting on.
|
|
2345
|
+
*
|
|
2346
|
+
* It reads `_pendingQuestion` ALONE and does not re-check `_waitingForAnswer`.
|
|
2347
|
+
* The two are set and cleared together, so the extra clause could never
|
|
2348
|
+
* change an answer -- and it would make every one of those null-outs
|
|
2349
|
+
* unfalsifiable, since the flag would mask a leaked payload
|
|
2350
|
+
* (docs/false-safety-guards.md: a guard whose only two states are green).
|
|
2351
|
+
* `tests/pending-question-resend.test.js` asserts the co-location mechanically
|
|
2352
|
+
* rather than trusting this paragraph.
|
|
2353
|
+
*
|
|
2354
|
+
* @returns {{ toolUseId: string, questions: object[] }[]}
|
|
2355
|
+
*/
|
|
2356
|
+
getPendingQuestions() {
|
|
2357
|
+
const pending = this._pendingQuestion
|
|
2358
|
+
if (!pending) return []
|
|
2359
|
+
return [{ toolUseId: pending.toolUseId, questions: pending.questions }]
|
|
1523
2360
|
}
|
|
1524
2361
|
|
|
1525
2362
|
/**
|
|
@@ -1530,6 +2367,7 @@ export class CliSession extends BaseSession {
|
|
|
1530
2367
|
respondToQuestion(text) {
|
|
1531
2368
|
if (!this._child || !this._waitingForAnswer) return
|
|
1532
2369
|
this._waitingForAnswer = false
|
|
2370
|
+
this._pendingQuestion = null // #7457 -- co-located with the flag.
|
|
1533
2371
|
const ndjson = JSON.stringify({
|
|
1534
2372
|
type: 'user',
|
|
1535
2373
|
message: {
|
|
@@ -1550,15 +2388,22 @@ export class CliSession extends BaseSession {
|
|
|
1550
2388
|
// the dashboard's streamingMessageId/isIdle. Without it, an interrupted
|
|
1551
2389
|
// turn leaves Stop stuck visible and "Thinking…" permanent.
|
|
1552
2390
|
// Mirrors TUI #4010. cost:null skips session-manager billing.
|
|
1553
|
-
|
|
2391
|
+
//
|
|
2392
|
+
// #7376: `terminatedReason` says WHY, so the tools this turn left in flight
|
|
2393
|
+
// are reported as "the turn was terminated under it" rather than as failed
|
|
2394
|
+
// commands. Supplied by each caller -- this is shared by the panic-button,
|
|
2395
|
+
// mid-turn setModel, Stop, a crash and both watchdogs -- and never inferred.
|
|
2396
|
+
_emitInterruptedTurnResult(duration = 0, terminatedReason) {
|
|
1554
2397
|
if (!this._isBusy || !this._currentMessageId) return
|
|
1555
2398
|
const messageId = this._currentMessageId
|
|
1556
2399
|
const sessionId = this._sessionId
|
|
2400
|
+
this._closeThinking(this._currentCtx) // #7393
|
|
1557
2401
|
if (this._currentCtx?.hasStreamStarted) {
|
|
1558
2402
|
this.emit('stream_end', { messageId })
|
|
1559
2403
|
}
|
|
1560
|
-
this._clearMessageState()
|
|
1561
|
-
|
|
2404
|
+
this._clearMessageState({ terminatedReason })
|
|
2405
|
+
// #7072: terminal but not a completed turn (internal; not on the wire).
|
|
2406
|
+
this.emit('result', { cost: null, duration, usage: null, sessionId, interrupted: true })
|
|
1562
2407
|
}
|
|
1563
2408
|
|
|
1564
2409
|
_handleChildClose(code) {
|
|
@@ -1587,7 +2432,34 @@ export class CliSession extends BaseSession {
|
|
|
1587
2432
|
if (this._destroying) return
|
|
1588
2433
|
if (this._respawning) return
|
|
1589
2434
|
|
|
1590
|
-
|
|
2435
|
+
// #7335: the child is gone, so every PreToolUse hook it had blocked on
|
|
2436
|
+
// died with it and its prompt can never be answered — same stranded card
|
|
2437
|
+
// as the respawn path, reached a different way. This covers a crash AND a
|
|
2438
|
+
// user Stop (interrupt() → SIGINT → the child exits here, NOT through
|
|
2439
|
+
// _killAndRespawn). Before _emitInterruptedTurnResult for the same reason:
|
|
2440
|
+
// that call reaches _clearMessageState, which drops the ids silently.
|
|
2441
|
+
//
|
|
2442
|
+
// The respawn path already expired them and set `_respawning`, so the
|
|
2443
|
+
// close it causes returns above — no double emit; pinned by a test.
|
|
2444
|
+
this._expirePendingPermissions('Permission request expired (the session process exited before it could be answered)')
|
|
2445
|
+
|
|
2446
|
+
// #7340: the child is about to be gone (or already is), and with it every
|
|
2447
|
+
// subagent it was running. `task_notification` -- the ONLY signal that
|
|
2448
|
+
// clears a confirmed-backgrounded agent now that the turn-end sweep spares
|
|
2449
|
+
// it -- can never arrive, so drain them here or the session claims to be
|
|
2450
|
+
// working for the rest of the daemon's life.
|
|
2451
|
+
//
|
|
2452
|
+
// Needs its OWN call for the same reason `_expirePendingPermissions` above
|
|
2453
|
+
// does (#7335): both reach the `_clearMessageState` funnel via
|
|
2454
|
+
// `_emitInterruptedTurnResult`, which early-returns when the session is not
|
|
2455
|
+
// busy -- and "not busy with a backgrounded agent still running" is the
|
|
2456
|
+
// exact state the exemption creates. Idempotent, and the funnel's own
|
|
2457
|
+
// unconditional sweep covers the busy case.
|
|
2458
|
+
this._completeAgents()
|
|
2459
|
+
|
|
2460
|
+
// #7376: Stop (SIGINT -> the child exits here) and a crash both reach this
|
|
2461
|
+
// point; the tools they leave in flight are worded differently.
|
|
2462
|
+
this._emitInterruptedTurnResult(0, wasIntentionalStop ? 'user_stop' : 'process_exit')
|
|
1591
2463
|
|
|
1592
2464
|
// #4602: user-initiated Stop sent SIGINT via interrupt(). The child
|
|
1593
2465
|
// exited cleanly as a result — do NOT show "exited unexpectedly" and
|
|
@@ -1595,6 +2467,12 @@ export class CliSession extends BaseSession {
|
|
|
1595
2467
|
if (wasIntentionalStop) {
|
|
1596
2468
|
// #4828: session-scoped if init had fired before the stop.
|
|
1597
2469
|
;(this._log || log).info(`Process exited (code ${code}) after user stop`)
|
|
2470
|
+
// #7438: NOT a respawn — the user asked for this child to stop and it
|
|
2471
|
+
// stays stopped. This only records that the session is stoppable-but-
|
|
2472
|
+
// revivable, so the next sendMessage can bring it back (see
|
|
2473
|
+
// _restartAfterStop). Stop halts the turn; it must not end the session's
|
|
2474
|
+
// ability to answer the follow-up.
|
|
2475
|
+
this._stoppedByUser = true
|
|
1598
2476
|
this.emit('stopped', { code })
|
|
1599
2477
|
return
|
|
1600
2478
|
}
|
|
@@ -1694,12 +2572,122 @@ export class CliSession extends BaseSession {
|
|
|
1694
2572
|
return
|
|
1695
2573
|
}
|
|
1696
2574
|
|
|
2575
|
+
// #7599: give a containerized subclass a chance to classify this exit as a
|
|
2576
|
+
// vanished container (a distinct, non-respawnable-but-recoverable state)
|
|
2577
|
+
// BEFORE the generic crash→respawn path. Reached only for a genuine
|
|
2578
|
+
// unexpected exit — the intentional-stop and resume-unknown branches above
|
|
2579
|
+
// have already returned. Base returns false synchronously (no behavior
|
|
2580
|
+
// change for host sessions); DockerSession returns a Promise that PROBES the
|
|
2581
|
+
// container, so the generic respawn is DEFERRED until the probe resolves and
|
|
2582
|
+
// skipped entirely on a confirmed vanish.
|
|
2583
|
+
const maybeVanish = this._handleContainerGoneOnClose(code)
|
|
2584
|
+
if (maybeVanish && typeof maybeVanish.then === 'function') {
|
|
2585
|
+
maybeVanish.then((handled) => {
|
|
2586
|
+
if (!handled && !this._destroying) this._respawnAfterUnexpectedClose(code)
|
|
2587
|
+
})
|
|
2588
|
+
return
|
|
2589
|
+
}
|
|
2590
|
+
if (maybeVanish) return
|
|
2591
|
+
this._respawnAfterUnexpectedClose(code)
|
|
2592
|
+
}
|
|
2593
|
+
|
|
2594
|
+
/**
|
|
2595
|
+
* #7599 — hook for a containerized subclass to intercept a child-close it can
|
|
2596
|
+
* attribute to its container vanishing, before the generic respawn. The base
|
|
2597
|
+
* host-CLI session has no container, so it never intercepts (returns false
|
|
2598
|
+
* synchronously — the generic respawn then runs inline as before).
|
|
2599
|
+
*
|
|
2600
|
+
* @param {number} _code exit code of the closed child
|
|
2601
|
+
* @returns {boolean|Promise<boolean>} true to suppress the generic crash→respawn
|
|
2602
|
+
*/
|
|
2603
|
+
_handleContainerGoneOnClose(_code) {
|
|
2604
|
+
return false
|
|
2605
|
+
}
|
|
2606
|
+
|
|
2607
|
+
/** #7599 — the generic "exited unexpectedly → restart" tail, extracted so the
|
|
2608
|
+
* container-vanish hook can defer or skip it. */
|
|
2609
|
+
_respawnAfterUnexpectedClose(code) {
|
|
1697
2610
|
// #4828: session-scoped if init had fired.
|
|
1698
2611
|
;(this._log || log).info(`Process exited (code ${code}), scheduling respawn`)
|
|
1699
2612
|
this.emit('error', { message: 'Claude process exited unexpectedly, restarting...' })
|
|
1700
2613
|
this._scheduleRespawn()
|
|
1701
2614
|
}
|
|
1702
2615
|
|
|
2616
|
+
/**
|
|
2617
|
+
* #7438 — restart-on-next-input for a session the user Stopped.
|
|
2618
|
+
*
|
|
2619
|
+
* Stop (interrupt → SIGINT → child exits) deliberately does NOT respawn
|
|
2620
|
+
* (#4602): respawning at stop time fights the thing the user just asked for.
|
|
2621
|
+
* But nothing else restarted the child either, so the next sendMessage hit
|
|
2622
|
+
* the `!_processReady` branch, pushed into `_pendingQueue` — and stranded
|
|
2623
|
+
* there forever, because the queue only drains on a start() warmup or after a
|
|
2624
|
+
* `result`, and with no child neither can ever fire. The follow-up was
|
|
2625
|
+
* silently eaten and the 4th one discarded outright ("queue full"). Stop
|
|
2626
|
+
* ended the conversation instead of interrupting a turn.
|
|
2627
|
+
*
|
|
2628
|
+
* So the respawn is lazy: it happens here, when the user actually asks for
|
|
2629
|
+
* more work. start() passes `--resume this._sessionId`, so the new child
|
|
2630
|
+
* re-attaches to the SAME claude conversation rather than starting cold, and
|
|
2631
|
+
* its warmup drain delivers the queued message.
|
|
2632
|
+
*
|
|
2633
|
+
* Gated on `_stoppedByUser` rather than on the broader "there is no child",
|
|
2634
|
+
* deliberately: every OTHER way to lose a child either already owns its own
|
|
2635
|
+
* restart (a crash schedules a backoff respawn; a model switch runs
|
|
2636
|
+
* _killAndRespawn) or is a considered terminal give-up — the respawn cap, the
|
|
2637
|
+
* rate cap, `resume_unknown_exhausted`. Typing into one of those must not
|
|
2638
|
+
* re-arm a flapping session behind the cap that just stopped it.
|
|
2639
|
+
*
|
|
2640
|
+
* #8038: ALSO fires on `_spawnRefusal` — a binary-gate refusal (model
|
|
2641
|
+
* switch / permission-mode change / crash respawn the gate rejected) is
|
|
2642
|
+
* revivable in exactly the same "nothing else will bring this child back"
|
|
2643
|
+
* sense a user Stop is, unlike the terminal give-ups listed above: the gate
|
|
2644
|
+
* refused a SPECIFIC verdict (this binary, right now), and a later input
|
|
2645
|
+
* is a legitimate reason to ask it again (the operator may have restored
|
|
2646
|
+
* the ledger, re-approved the hash, fixed the quarantine, …). Both flags
|
|
2647
|
+
* share this one restart path rather than two near-identical copies.
|
|
2648
|
+
*/
|
|
2649
|
+
_restartAfterStop() {
|
|
2650
|
+
if (!this._stoppedByUser && !this._spawnRefusal) return
|
|
2651
|
+
if (this._destroying) return
|
|
2652
|
+
if (this._respawning) return
|
|
2653
|
+
if (this._respawnScheduled) return
|
|
2654
|
+
// A child already exists — whoever spawned it owns the warmup drain.
|
|
2655
|
+
if (this._child) return
|
|
2656
|
+
|
|
2657
|
+
;(this._log || log).info(this._spawnRefusal
|
|
2658
|
+
? 'Re-running the binary gate to restart claude for a new message (its last spawn was refused)'
|
|
2659
|
+
: 'Restarting the stopped claude process to deliver a new message')
|
|
2660
|
+
// Consume the latches BEFORE starting, not inside start(): DockerSession
|
|
2661
|
+
// overrides start() and defers super.start() behind an async container
|
|
2662
|
+
// launch, so a second message arriving in that window would otherwise see
|
|
2663
|
+
// `_stoppedByUser` still armed and no child yet, and start a SECOND
|
|
2664
|
+
// container. Single-shot here makes the restart at-most-once regardless of
|
|
2665
|
+
// what a subclass's start() does or how long it takes.
|
|
2666
|
+
this._stoppedByUser = false
|
|
2667
|
+
// #8038: the refusal latch is consumed too. The gate re-runs inside start()
|
|
2668
|
+
// and re-latches only if it refuses AGAIN; left armed, a synchronous throw
|
|
2669
|
+
// from elsewhere in start() would get this input rejected under the
|
|
2670
|
+
// previous refusal's code instead of its own error.
|
|
2671
|
+
this._spawnRefusal = null
|
|
2672
|
+
try {
|
|
2673
|
+
this.start()
|
|
2674
|
+
} catch (err) {
|
|
2675
|
+
// Re-arm the latch: start() threw synchronously (spawn/arg failure) BEFORE
|
|
2676
|
+
// any child or container launch, so nothing was started. Without this the
|
|
2677
|
+
// latch stays consumed and the next sendMessage would only enqueue — never
|
|
2678
|
+
// retry the restart — re-stranding the follow-up behind a start-time error
|
|
2679
|
+
// (the exact #7438 failure mode). Re-arming lets the next user input retry;
|
|
2680
|
+
// it is not a loop — a retry only happens on a fresh send. It is re-armed
|
|
2681
|
+
// for a refusal-triggered restart as well (#8038): a gate refusal never
|
|
2682
|
+
// throws (_spawnPersistentProcess latches it and returns), so reaching
|
|
2683
|
+
// here means a DIFFERENT failure, and `_stoppedByUser` is the latch that
|
|
2684
|
+
// keeps a childless session revivable whatever took its child away.
|
|
2685
|
+
this._stoppedByUser = true
|
|
2686
|
+
;(this._log || log).error(`Restart on new input failed: ${err.message}`)
|
|
2687
|
+
this.emit('error', { message: `Failed to restart the Claude process: ${err.message}` })
|
|
2688
|
+
}
|
|
2689
|
+
}
|
|
2690
|
+
|
|
1703
2691
|
/** Interrupt the current message (send SIGINT to child process) */
|
|
1704
2692
|
interrupt() {
|
|
1705
2693
|
// #5936: a deliberate Stop cancels the owner's queued follow-ups (cancel,
|
|
@@ -1717,6 +2705,7 @@ export class CliSession extends BaseSession {
|
|
|
1717
2705
|
// current turn), the next natural exit will be a real crash — the flag
|
|
1718
2706
|
// is cleared in _handleChildClose on whichever exit fires first.
|
|
1719
2707
|
this.markIntentionalStop()
|
|
2708
|
+
this._noteTurnStopRequested() // #7376
|
|
1720
2709
|
|
|
1721
2710
|
// #4828: session-scoped if init has fired.
|
|
1722
2711
|
;(this._log || log).info('Sending SIGINT to claude process')
|
|
@@ -1738,7 +2727,7 @@ export class CliSession extends BaseSession {
|
|
|
1738
2727
|
if (this._isBusy) {
|
|
1739
2728
|
// #4828: session-scoped.
|
|
1740
2729
|
;(this._log || log).warn('Interrupt safety timeout — force-clearing busy state')
|
|
1741
|
-
this._emitInterruptedTurnResult()
|
|
2730
|
+
this._emitInterruptedTurnResult(0, 'user_stop')
|
|
1742
2731
|
}
|
|
1743
2732
|
}, 5000)
|
|
1744
2733
|
// #6043: fire-and-forget busy-state safety net — never gate process exit on
|
|
@@ -1809,6 +2798,18 @@ export class CliSession extends BaseSession {
|
|
|
1809
2798
|
this._child = null
|
|
1810
2799
|
}
|
|
1811
2800
|
|
|
2801
|
+
// #7337: remove the sidecar dir so long-lived daemons don't leak one
|
|
2802
|
+
// directory per session under /tmp. Nulls `_permissionModeFile` too, so a
|
|
2803
|
+
// setPermissionMode() after destroy() no-ops cleanly.
|
|
2804
|
+
//
|
|
2805
|
+
// Deliberately AFTER the kill above, not before it. The child stays alive
|
|
2806
|
+
// for up to the 3s force-kill grace and can fire a PreToolUse hook in that
|
|
2807
|
+
// window; removing the sidecar first makes that hook fall back to the
|
|
2808
|
+
// spawn-frozen CHROXY_PERMISSION_MODE, which is fail-open on a session that
|
|
2809
|
+
// was tightened since spawn (spawned `auto`, switched to `approve`, then
|
|
2810
|
+
// destroyed).
|
|
2811
|
+
this._cleanupPermissionModeSidecar()
|
|
2812
|
+
|
|
1812
2813
|
// Emit completions for any tracked agents and clear busy state.
|
|
1813
2814
|
// Must happen before removeAllListeners() so events are delivered.
|
|
1814
2815
|
this._clearMessageState()
|