@chroxy/server 0.11.0 → 0.11.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +206 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +958 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +304 -0
- package/src/agent-control/client.js +1645 -0
- package/src/agent-control/events.js +551 -0
- package/src/agent-control/local-connection.js +293 -0
- package/src/agent-control/mcp-server.js +547 -0
- package/src/anthropic-compatible-config.js +30 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1520 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +291 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +92 -7
- package/src/byok-mcp-config.js +633 -122
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +37 -23
- package/src/byok-session.js +707 -179
- package/src/byok-tool-executor.js +2742 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-setting-sources.js +74 -0
- package/src/claude-stream-parser.js +53 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +215 -88
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3563 -284
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-cmd.js +236 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/connection-state.js +54 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/pages-cmd.js +6 -4
- package/src/cli/pair-code-cmd.js +7 -6
- package/src/cli/pair-discord-cmd.js +7 -6
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +91 -40
- package/src/cli/server-cmd.js +54 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1250 -126
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1517 -81
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-error-text.js +114 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +450 -27
- package/src/config-dir-migration.js +449 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +306 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +78 -23
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +227 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +42 -39
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +28 -39
- package/src/credential-store.js +23 -19
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +170 -182
- package/src/device-preferences.js +2 -2
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +172 -3
- package/src/docker-session.js +294 -11
- package/src/doctor.js +781 -64
- package/src/durable-write.js +35 -0
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +101 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +186 -235
- package/src/folder-trust-wire.js +137 -0
- package/src/folder-trust-worker.js +17 -0
- package/src/folder-trust.js +1572 -0
- package/src/freshness/activity-meter.js +101 -0
- package/src/freshness/adapter.js +199 -0
- package/src/freshness/checks.js +239 -0
- package/src/freshness/config.js +98 -0
- package/src/freshness/core.js +185 -0
- package/src/freshness/derive.js +680 -0
- package/src/freshness/exchange.js +305 -0
- package/src/freshness/file-ledger.js +400 -0
- package/src/freshness/grade.js +81 -0
- package/src/freshness/hash.js +45 -0
- package/src/freshness/inbox.js +163 -0
- package/src/freshness/index.js +20 -0
- package/src/freshness/investigation.js +474 -0
- package/src/freshness/keys.js +177 -0
- package/src/freshness/ledger.js +122 -0
- package/src/freshness/outbox.js +131 -0
- package/src/freshness/policy.js +599 -0
- package/src/freshness/queue.js +843 -0
- package/src/freshness/read-errors.js +23 -0
- package/src/freshness/render.js +153 -0
- package/src/freshness/runtime.js +113 -0
- package/src/freshness/session-registry-adapter.js +161 -0
- package/src/freshness/state-file-adapter.js +167 -0
- package/src/freshness-runner/build-info.js +139 -0
- package/src/freshness-runner/cli.js +105 -0
- package/src/freshness-runner/run-tick.js +109 -0
- package/src/freshness-runner/stamp.js +57 -0
- package/src/freshness-sources/claude-transcript-adapter.js +211 -0
- package/src/freshness-sources/codex-transcript-adapter.js +33 -0
- package/src/freshness-sources/index.js +8 -0
- package/src/gemini-byok-session.js +292 -0
- package/src/gemini-credentials.js +67 -0
- package/src/gemini-key-safety.js +246 -0
- package/src/gemini-models.js +386 -0
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +540 -80
- package/src/handlers/checkpoint-handlers.js +47 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +57 -13
- package/src/handlers/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +714 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +92 -18
- package/src/handlers/session-handlers.js +551 -20
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +372 -50
- package/src/handlers/skills-handlers.js +20 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +112 -0
- package/src/http-routes.js +127 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +378 -91
- package/src/jsonl-subprocess-session.js +96 -9
- package/src/keychain.js +1 -1
- package/src/logger.js +166 -30
- package/src/mailbox-route.js +113 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +27 -4
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +64 -23
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +112 -36
- package/src/orchestration/permission-gate.js +17 -2
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +185 -43
- package/src/orphan-reaper.js +470 -0
- package/src/outgoing-policy.js +189 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1410 -43
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +737 -89
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +126 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +315 -47
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/principal-audit.js +189 -0
- package/src/principal-binding.js +25 -0
- package/src/principal-brakes.js +21 -0
- package/src/principal-effect.js +101 -0
- package/src/principal-journal.js +905 -0
- package/src/principal-kill-switch.js +183 -0
- package/src/principal-label.js +5 -0
- package/src/principal-pending-permissions.js +177 -0
- package/src/principal-policy.js +1094 -0
- package/src/principal-sessions-snapshot.js +208 -0
- package/src/principal-store.js +488 -0
- package/src/principal-subscriptions.js +283 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +209 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +531 -20
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +330 -26
- package/src/scheduler.js +368 -11
- package/src/sdk-session.js +2114 -188
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +17 -3
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +553 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +1099 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +4062 -312
- package/src/session-message-history.js +841 -16
- package/src/session-name-allocator.js +685 -0
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-token-store.js +17 -8
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +100 -29
- package/src/summarize-session.js +53 -4
- package/src/supervisor.js +22 -11
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +140 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +770 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +639 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +29 -0
- package/src/utils/bounded-regex.js +162 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +133 -37
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/pid-liveness.js +47 -0
- package/src/utils/preflight.js +360 -16
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +297 -16
- package/src/worktree-gc.js +202 -6
- package/src/ws-auth.js +163 -31
- package/src/ws-broadcaster.js +49 -5
- package/src/ws-client-manager.js +24 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +363 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +349 -39
- package/src/ws-handler-context.js +88 -2
- package/src/ws-history.js +1010 -175
- package/src/ws-message-handlers.js +25 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +885 -98
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
package/src/cli-session.js
CHANGED
|
@@ -1,48 +1,41 @@
|
|
|
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'
|
|
5
|
+
import { randomBytes, randomUUID } from 'crypto'
|
|
6
|
+
import { mkdirSync, rmSync, writeFileSync } from 'fs'
|
|
4
7
|
import { normalizeSdkModelUsage } from './usage-normalize.js'
|
|
5
|
-
import {
|
|
8
|
+
import { tmpdir } from 'os'
|
|
9
|
+
import { claudeConfigDir } from './utils/claude-config-dir.js'
|
|
10
|
+
import { claudeSettingSourcesValueFor, projectSettingsAllowedAsync, projectSettingsDecidedWithoutScan } from './claude-setting-sources.js'
|
|
6
11
|
import { join } from 'path'
|
|
7
12
|
import { createPermissionHookManager } from './permission-hook.js'
|
|
8
13
|
import { guardChildStreams } from './child-stream-guard.js'
|
|
9
|
-
import { BaseSession, buildBaseSessionOpts } from './base-session.js'
|
|
14
|
+
import { BaseSession, buildBaseSessionOpts, reportInputAdmission, spawnRefusalAdmission } from './base-session.js'
|
|
10
15
|
import { buildContentBlocks } from './content-blocks.js'
|
|
11
16
|
import { ALLOWED_MODEL_IDS } from './models.js'
|
|
12
17
|
import { CLAUDE_FALLBACK_MODELS, claudeModelMetadata } from './claude-model-catalog.js'
|
|
13
|
-
import { forceKill, killProcessTree } from './platform.js'
|
|
18
|
+
import { forceKill, killProcessTree, killRecordedTree, recordProcessTree } from './platform.js'
|
|
14
19
|
import { MessageTransformPipeline } from './message-transform.js'
|
|
15
20
|
import { emitToolResults } from './tool-result.js'
|
|
16
|
-
import { buildToolStartData, extractToolInputSemantics, parseCompactBoundaryMeta, formatCompactBoundaryContent } from './claude-stream-parser.js'
|
|
17
|
-
import {
|
|
21
|
+
import { buildToolStartData, extractToolInputSemantics, parseCompactBoundaryMeta, formatCompactBoundaryContent, formatStatusContent } from './claude-stream-parser.js'
|
|
22
|
+
import { ThinkingStreams } from './thinking-stream.js'
|
|
23
|
+
import { CLAUDE_BINARY_CANDIDATES, resolveClaudeBinary } from './utils/claude-binary.js'
|
|
18
24
|
import { labelBinarySpawnFailure } from './utils/verify-binary.js'
|
|
19
25
|
import { prepareSpawn } from './utils/win-spawn.js'
|
|
26
|
+
import { CLAUDE_CLI_CUSTOMIZATION } from './provider-customization.js'
|
|
20
27
|
import { buildSpawnEnv } from './utils/spawn-env.js'
|
|
21
28
|
import { RespawnRateLimiter } from './utils/respawn-rate-limiter.js'
|
|
29
|
+
import { assertSafeArgvValue } from './utils/argv-safety.js'
|
|
30
|
+
import { writePermissionModeSidecarAtomic } from './utils/permission-mode-sidecar.js'
|
|
31
|
+
import { sweepStaleOwnedDirs, ensureOwnedBaseDir, OWNER_PID_FILE } from './utils/stale-session-dirs.js'
|
|
22
32
|
import { createLogger, loggerForSession } from './logger.js'
|
|
23
33
|
import { formatIdleDuration } from './session-timeout-manager.js'
|
|
24
34
|
import { BILLING_CLASSES, isProgrammaticCreditEra } from './billing-class.js'
|
|
35
|
+
import { turnOutcomeField, outcomeFromSdkResult } from './turn-outcome.js'
|
|
25
36
|
|
|
26
37
|
const log = createLogger('cli-session')
|
|
27
38
|
|
|
28
|
-
// Well-known fallback locations. Under a GUI launch (e.g. Tauri on macOS) PATH
|
|
29
|
-
// is minimal and may exclude the user's install dir — fall through to these so
|
|
30
|
-
// `spawn()` succeeds.
|
|
31
|
-
const CLAUDE_BINARY_CANDIDATES = [
|
|
32
|
-
join(homedir(), '.local/bin/claude'),
|
|
33
|
-
'/opt/homebrew/bin/claude',
|
|
34
|
-
'/usr/local/bin/claude',
|
|
35
|
-
join(homedir(), '.claude/local/node_modules/.bin/claude'),
|
|
36
|
-
join(homedir(), '.npm-global/bin/claude'),
|
|
37
|
-
]
|
|
38
|
-
|
|
39
|
-
// Re-resolve fresh on every spawn (NOT a frozen module-load const) so a binary
|
|
40
|
-
// quarantined / moved / reinstalled after daemon start is spawned from its
|
|
41
|
-
// CURRENT path — and matches what preflight verified (#6708 defect #3).
|
|
42
|
-
function resolveClaudeBinary() {
|
|
43
|
-
return resolveBinary('claude', CLAUDE_BINARY_CANDIDATES)
|
|
44
|
-
}
|
|
45
|
-
|
|
46
39
|
// Default max accumulated size for tool_use input_json_delta chunks (~256KB)
|
|
47
40
|
const DEFAULT_MAX_TOOL_INPUT_LENGTH = 262144
|
|
48
41
|
|
|
@@ -111,6 +104,38 @@ export function stderrIndicatesUnknownResume(stderrLines) {
|
|
|
111
104
|
return false
|
|
112
105
|
}
|
|
113
106
|
|
|
107
|
+
// #7847: the canonical rejection with every space removed, followed by the session UUID.
|
|
108
|
+
export const COMPACTED_UNKNOWN_RESUME_PATTERN =
|
|
109
|
+
/noconversationfoundwithsessionid:?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Cursor-positioned TUI rendering of claude's unknown-resume rejection can reach
|
|
113
|
+
* the PTY tail as several fragments with the inter-word spaces removed
|
|
114
|
+
* (`Noconvers` / `ation` / `foundwith` / `session` / `ID:<uuid>`, #7847), so
|
|
115
|
+
* neither a single line nor a space-joined adjacent pair matches the
|
|
116
|
+
* per-line patterns above. This tests a whitespace-compacted join of up to
|
|
117
|
+
* `windowLines` consecutive lines against the canonical rejection ONLY: the full
|
|
118
|
+
* phrase "No conversation found with session ID:" followed by a UUID. The UUID
|
|
119
|
+
* anchor keeps it narrow — transcript text that merely discusses resume or
|
|
120
|
+
* session errors has no such phrase+id shape and never matches.
|
|
121
|
+
*
|
|
122
|
+
* The window is 10 lines: the five phrase fragments plus a UUID that may itself
|
|
123
|
+
* wrap across several rows at the narrowest widths.
|
|
124
|
+
*
|
|
125
|
+
* @param {string[]} lines
|
|
126
|
+
* @param {number} [windowLines=10]
|
|
127
|
+
* @returns {boolean}
|
|
128
|
+
*/
|
|
129
|
+
export function stderrIndicatesUnknownResumeCompacted(lines, windowLines = 10) {
|
|
130
|
+
if (!Array.isArray(lines) || lines.length === 0) return false
|
|
131
|
+
const compact = lines.map((l) => (typeof l === 'string' ? l.replace(/\s+/g, '') : ''))
|
|
132
|
+
for (let i = 0; i < compact.length; i++) {
|
|
133
|
+
const joined = compact.slice(i, i + windowLines).join('')
|
|
134
|
+
if (COMPACTED_UNKNOWN_RESUME_PATTERN.test(joined)) return true
|
|
135
|
+
}
|
|
136
|
+
return false
|
|
137
|
+
}
|
|
138
|
+
|
|
114
139
|
/**
|
|
115
140
|
* Build the argv passed to `claude -p --input-format stream-json …`.
|
|
116
141
|
*
|
|
@@ -134,9 +159,10 @@ export function stderrIndicatesUnknownResume(stderrLines) {
|
|
|
134
159
|
* @param {string[]} opts.allowedTools
|
|
135
160
|
* @param {string} opts.skillsText
|
|
136
161
|
* @param {string|null} opts.resumeSessionId
|
|
162
|
+
* @param {boolean} [opts.projectAllowed] - the launch decision for the session folder (claude-setting-sources.js); absent means not allowed
|
|
137
163
|
* @returns {string[]}
|
|
138
164
|
*/
|
|
139
|
-
export function buildClaudeCliArgs({ model, permissionMode, allowedTools, skillsText, resumeSessionId } = {}) {
|
|
165
|
+
export function buildClaudeCliArgs({ model, permissionMode, allowedTools, skillsText, resumeSessionId, projectAllowed } = {}) {
|
|
140
166
|
const args = [
|
|
141
167
|
'-p',
|
|
142
168
|
'--input-format', 'stream-json',
|
|
@@ -144,6 +170,8 @@ export function buildClaudeCliArgs({ model, permissionMode, allowedTools, skills
|
|
|
144
170
|
'--verbose',
|
|
145
171
|
'--include-partial-messages',
|
|
146
172
|
]
|
|
173
|
+
const allowed = projectAllowed === true
|
|
174
|
+
args.push('--setting-sources', claudeSettingSourcesValueFor(allowed))
|
|
147
175
|
|
|
148
176
|
if (model) {
|
|
149
177
|
args.push('--model', model)
|
|
@@ -167,7 +195,26 @@ export function buildClaudeCliArgs({ model, permissionMode, allowedTools, skills
|
|
|
167
195
|
// the model retains the full prior transcript. Only emitted when a non-empty
|
|
168
196
|
// string is known; a brand-new session (first start()) leaves this off so
|
|
169
197
|
// claude CLI mints a fresh conversation id on its `system.init` line.
|
|
198
|
+
//
|
|
199
|
+
// #7868 — REJECTED, not merely passed through, because `-r, --resume` is
|
|
200
|
+
// declared with an OPTIONAL argument (`[value]`), not a required one.
|
|
201
|
+
// Measured against the installed claude CLI (2.1.282):
|
|
202
|
+
//
|
|
203
|
+
// claude -p --resume --this-is-not-a-real-flag-xyz --output-format ...
|
|
204
|
+
// → error: unknown option '--this-is-not-a-real-flag-xyz' (exit 1)
|
|
205
|
+
//
|
|
206
|
+
// — i.e. the two-token form INJECTS for an optional-arg flag (the opposite
|
|
207
|
+
// of `--model <model>` / `--append-system-prompt <prompt>` above, both
|
|
208
|
+
// declared REQUIRED and measured swallowed-as-value). `resumeSessionId` can
|
|
209
|
+
// never legitimately start with `-`: it is either this file's own
|
|
210
|
+
// CLI-emitted `system.init` session_id, or a client-supplied resume target
|
|
211
|
+
// already required to be a canonical UUID by
|
|
212
|
+
// handlers/conversation-handlers.js's CONVERSATION_ID_RE before it reaches
|
|
213
|
+
// here — but relying on every current and future caller to keep that
|
|
214
|
+
// constraint is the exact "someone remembers to sweep" gap #7868 exists to
|
|
215
|
+
// close, so it is asserted here too (case 1: reject).
|
|
170
216
|
if (typeof resumeSessionId === 'string' && resumeSessionId.length > 0) {
|
|
217
|
+
assertSafeArgvValue(resumeSessionId, 'resumeSessionId')
|
|
171
218
|
args.push('--resume', resumeSessionId)
|
|
172
219
|
}
|
|
173
220
|
|
|
@@ -189,6 +236,7 @@ export function buildClaudeCliArgs({ model, permissionMode, allowedTools, skills
|
|
|
189
236
|
* stream_end { messageId }
|
|
190
237
|
* message { type, content, tool, timestamp }
|
|
191
238
|
* tool_start { messageId, tool, input }
|
|
239
|
+
* tool_input_delta { messageId, toolUseId, partialJson }
|
|
192
240
|
* result { cost, duration, usage, sessionId }
|
|
193
241
|
* error { message }
|
|
194
242
|
* user_question { toolUseId, questions }
|
|
@@ -196,14 +244,20 @@ export function buildClaudeCliArgs({ model, permissionMode, allowedTools, skills
|
|
|
196
244
|
* agent_completed { toolUseId }
|
|
197
245
|
* plan_started {}
|
|
198
246
|
* plan_ready { allowedPrompts }
|
|
199
|
-
* tool_result { toolUseId, result, truncated }
|
|
247
|
+
* tool_result { toolUseId, result, truncated, input? }
|
|
200
248
|
*/
|
|
201
249
|
|
|
202
250
|
export class CliSession extends BaseSession {
|
|
251
|
+
static canonicalAssistantResponses = true
|
|
252
|
+
|
|
203
253
|
// #5858: Claude-family flag — single source of truth for isClaudeProvider().
|
|
204
254
|
// DockerSession (docker-cli / docker) extends this and inherits it.
|
|
205
255
|
static claudeFamily = true
|
|
206
256
|
|
|
257
|
+
static get customizationDescriptor() {
|
|
258
|
+
return CLAUDE_CLI_CUSTOMIZATION
|
|
259
|
+
}
|
|
260
|
+
|
|
207
261
|
/**
|
|
208
262
|
* Human-readable label shown in the startup banner and anywhere else the
|
|
209
263
|
* server needs to name this provider (#2953). Each provider owns its own
|
|
@@ -228,7 +282,21 @@ export class CliSession extends BaseSession {
|
|
|
228
282
|
* exhaust there.
|
|
229
283
|
*/
|
|
230
284
|
static get customEvents() {
|
|
231
|
-
|
|
285
|
+
// #7346: `tool_input_delta` delivers the SANITIZED full tool input
|
|
286
|
+
// as a single chunk once its content_block finalizes (see
|
|
287
|
+
// `_captureFinalizedToolInput`, called from `content_block_stop`) —
|
|
288
|
+
// matches byok-session.js's wire shape/client handler exactly so
|
|
289
|
+
// store-core's `handleToolInputDelta` needs no provider branch.
|
|
290
|
+
// Per #8135/#8137, NEITHER cli-session.js NOR byok-session.js
|
|
291
|
+
// streams raw per-chunk `input_json_delta` partials any more — a
|
|
292
|
+
// secret can straddle chunk boundaries and can't be sanitized
|
|
293
|
+
// mid-stream, so both providers only ever emit once, already-safe.
|
|
294
|
+
// Without listing it here, `session-manager.js`'s
|
|
295
|
+
// `_wireSessionEvents` never bridges the local EventEmitter emit
|
|
296
|
+
// onto the `session_event` channel and it never reaches the client
|
|
297
|
+
// (same wiring requirement documented on byok-session.js's
|
|
298
|
+
// `customEvents`).
|
|
299
|
+
return ['respawn_exhausted', 'tool_input_delta']
|
|
232
300
|
}
|
|
233
301
|
|
|
234
302
|
/**
|
|
@@ -238,13 +306,15 @@ export class CliSession extends BaseSession {
|
|
|
238
306
|
* hardcoding the path.
|
|
239
307
|
*/
|
|
240
308
|
static get dataDir() {
|
|
241
|
-
return
|
|
309
|
+
return claudeConfigDir()
|
|
242
310
|
}
|
|
243
311
|
|
|
244
312
|
static get capabilities() {
|
|
245
313
|
return {
|
|
246
314
|
permissions: true,
|
|
247
315
|
inProcessPermissions: false,
|
|
316
|
+
permissionFloor: true,
|
|
317
|
+
autoPermissionMode: true,
|
|
248
318
|
modelSwitch: true,
|
|
249
319
|
permissionModeSwitch: true,
|
|
250
320
|
// #5609: switching to 'auto' mid-turn is the #3729 panic-button —
|
|
@@ -262,9 +332,22 @@ export class CliSession extends BaseSession {
|
|
|
262
332
|
resume: true,
|
|
263
333
|
terminal: false,
|
|
264
334
|
thinkingLevel: false,
|
|
335
|
+
// #7725: the legacy `claude -p` subprocess never runs
|
|
336
|
+
// detect-thinking-keyword.js, so typing `ultrathink` escalates nothing
|
|
337
|
+
// here. Declared explicitly (like `streaming`) so the matrix stays
|
|
338
|
+
// uniform rather than leaving the flag's absence to be guessed.
|
|
339
|
+
thinkingKeywords: false,
|
|
340
|
+
thinkingLevelEffective: false, // #8700: no report of the applied level
|
|
265
341
|
// #3932: declared explicitly so the capability matrix matches across
|
|
266
342
|
// providers — claude-tui is the only one that sets this to false.
|
|
267
343
|
streaming: true,
|
|
344
|
+
// #8301: the provider-neutral turn-input seam. `sendMessage` dispatches when
|
|
345
|
+
// idle, queues via `enqueueOutgoingMessage` when busy (flushed at turn end,
|
|
346
|
+
// cleared by `interrupt()`), and reports admission through
|
|
347
|
+
// `onInputAdmission` — so a daemon-authored line (the CI-completion wake)
|
|
348
|
+
// can travel it as an ordinary user turn. session-wake.js gates on this with
|
|
349
|
+
// strict `=== true`; absent means NOT supported. Never duck-typed.
|
|
350
|
+
daemonTurnInput: true,
|
|
268
351
|
}
|
|
269
352
|
}
|
|
270
353
|
|
|
@@ -288,13 +371,7 @@ export class CliSession extends BaseSession {
|
|
|
288
371
|
binary: {
|
|
289
372
|
name: 'claude',
|
|
290
373
|
args: ['--version'],
|
|
291
|
-
candidates:
|
|
292
|
-
join(homedir(), '.local/bin/claude'),
|
|
293
|
-
'/opt/homebrew/bin/claude',
|
|
294
|
-
'/usr/local/bin/claude',
|
|
295
|
-
join(homedir(), '.claude/local/node_modules/.bin/claude'),
|
|
296
|
-
join(homedir(), '.npm-global/bin/claude'),
|
|
297
|
-
],
|
|
374
|
+
candidates: CLAUDE_BINARY_CANDIDATES,
|
|
298
375
|
installHint: 'install Claude Code CLI',
|
|
299
376
|
},
|
|
300
377
|
credentials: {
|
|
@@ -399,6 +476,14 @@ export class CliSession extends BaseSession {
|
|
|
399
476
|
this._inPlanMode = false
|
|
400
477
|
this._planAllowedPrompts = null
|
|
401
478
|
this._waitingForAnswer = false
|
|
479
|
+
// #7457 -- the AskUserQuestion payload behind `_waitingForAnswer`, so a
|
|
480
|
+
// reconnecting client can be handed the question the child is parked on
|
|
481
|
+
// (`getPendingQuestions`). Kept strictly CO-LOCATED with the flag: every
|
|
482
|
+
// line that writes `_waitingForAnswer` writes this in the same statement
|
|
483
|
+
// block, so the two cannot disagree and there is no second lifecycle to
|
|
484
|
+
// leak. `_waitingForAnswer` stays the read gate `respondToQuestion` uses --
|
|
485
|
+
// this is a payload, not a new source of truth.
|
|
486
|
+
this._pendingQuestion = null
|
|
402
487
|
this._currentCtx = null
|
|
403
488
|
this._pendingQueue = []
|
|
404
489
|
this._respawnCount = 0
|
|
@@ -430,13 +515,38 @@ export class CliSession extends BaseSession {
|
|
|
430
515
|
// Single-use: set by interrupt(), cleared by _handleChildClose / destroy.
|
|
431
516
|
// The flag itself is declared+initialized on BaseSession (#5375).
|
|
432
517
|
|
|
518
|
+
// #7438: latched by the intentional-stop branch of _handleChildClose when
|
|
519
|
+
// that stop leaves us with no child, and consumed by the next sendMessage
|
|
520
|
+
// (_restartAfterStop). It is what makes a stopped session restartable —
|
|
521
|
+
// see _restartAfterStop for why the restart is gated on this rather than
|
|
522
|
+
// on "the child is gone".
|
|
523
|
+
this._stoppedByUser = false
|
|
524
|
+
|
|
525
|
+
// #9267: children the 5 s Stop timer retired, each with the descendants
|
|
526
|
+
// recorded (pid + start time) before it was signalled, so the escalation and
|
|
527
|
+
// destroy() can still reap a tree whose parent already exited. `_treeDeps`
|
|
528
|
+
// is the test seam for the ps / process.kill the tree operations use.
|
|
529
|
+
this._retiredChildren = new Set()
|
|
530
|
+
this._drainOutgoingFirst = false
|
|
531
|
+
this._treeDeps = {}
|
|
532
|
+
|
|
433
533
|
// Hook manager (shared module)
|
|
434
534
|
this._hookManager = (this._port) ? createPermissionHookManager(this, { settingsPath }) : null
|
|
435
535
|
|
|
536
|
+
// #7337: the re-readable permission-mode sidecar. `permission-hook.sh`
|
|
537
|
+
// prefers this file over CHROXY_PERMISSION_MODE, which is frozen at spawn.
|
|
538
|
+
// Created on the first start() when permissions are enabled, reused across
|
|
539
|
+
// respawns, removed on destroy(). Null means "env-var-only" — either
|
|
540
|
+
// permissions are off (no port) or the initial write failed.
|
|
541
|
+
this._permissionModeFile = null
|
|
542
|
+
this._permissionModeDir = null
|
|
543
|
+
|
|
436
544
|
// Pending-permission bookkeeping for the inactivity timer (#2831).
|
|
437
545
|
// WsServer calls notifyPermissionPending/Resolved when a hook
|
|
438
546
|
// permission belonging to this session is broadcast/resolved.
|
|
439
|
-
|
|
547
|
+
// #7382: `_pendingPermissionIds` now lives on BaseSession so every
|
|
548
|
+
// hook-routed provider has it. The inactivity PAUSE stays CLI-local — it is
|
|
549
|
+
// wired to this provider's timer trio via the _on*Permission* hooks below.
|
|
440
550
|
this._resultTimeoutPaused = false
|
|
441
551
|
}
|
|
442
552
|
|
|
@@ -465,11 +575,51 @@ export class CliSession extends BaseSession {
|
|
|
465
575
|
* Start the persistent Claude process. Call once after construction.
|
|
466
576
|
*/
|
|
467
577
|
start() {
|
|
578
|
+
// #7438: the session is running again by any route (first start, backoff
|
|
579
|
+
// respawn, model-switch respawn, restart-on-input), so the stop latch is
|
|
580
|
+
// spent. Cleared FIRST so a throw below cannot leave it armed.
|
|
581
|
+
this._stoppedByUser = false
|
|
582
|
+
// Every start takes a new generation; a verification still pending for an older
|
|
583
|
+
// one never launches (see below).
|
|
584
|
+
const startGen = (this._startGen = (this._startGen || 0) + 1)
|
|
585
|
+
this._pendingStartGen = null
|
|
586
|
+
|
|
468
587
|
// Register permission hook before starting the process (only once, not on respawn)
|
|
469
588
|
if (this._hookManager && this._respawnCount === 0) {
|
|
470
589
|
this._hookManager.register()
|
|
471
590
|
}
|
|
472
591
|
|
|
592
|
+
// #7337: must run BEFORE _spawnPersistentProcess, which is where
|
|
593
|
+
// _buildChildEnv() reads `_permissionModeFile` to point the child at it.
|
|
594
|
+
this._ensurePermissionModeSidecar()
|
|
595
|
+
|
|
596
|
+
// One project-settings decision per launch: it picks the argv and is what is
|
|
597
|
+
// reported as loaded in this running process. A folder with no trust record is
|
|
598
|
+
// decided at once; a trusted one is verified by a fresh scan off the main
|
|
599
|
+
// thread, and the process is launched when that answers (unless the session
|
|
600
|
+
// was stopped or destroyed meanwhile).
|
|
601
|
+
const decided = projectSettingsDecidedWithoutScan(this.cwd)
|
|
602
|
+
if (decided !== null) {
|
|
603
|
+
this._launchPersistent(decided)
|
|
604
|
+
return
|
|
605
|
+
}
|
|
606
|
+
this._pendingStartGen = startGen
|
|
607
|
+
projectSettingsAllowedAsync(this.cwd).catch(() => false).then((allowed) => {
|
|
608
|
+
if (this._pendingStartGen === startGen) this._pendingStartGen = null
|
|
609
|
+
// Launch only if nothing started, stopped or destroyed the session since, and no
|
|
610
|
+
// child exists (a newer start that took the fast path has already spawned one).
|
|
611
|
+
if (this._startGen !== startGen || this._destroying || this._stoppedByUser || this._child) return
|
|
612
|
+
try {
|
|
613
|
+
this._launchPersistent(allowed)
|
|
614
|
+
} catch (err) {
|
|
615
|
+
;(this._log || log).error(`Start failed: ${err.message}`)
|
|
616
|
+
this.emit('error', { message: `Failed to start the Claude process: ${err.message}` })
|
|
617
|
+
}
|
|
618
|
+
})
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** Build the argv for the decided project-settings scope and spawn the persistent process. */
|
|
622
|
+
_launchPersistent(projectAllowed) {
|
|
473
623
|
// Skills MVP (#2957) — append shared skills to the Claude CLI system prompt.
|
|
474
624
|
const skillsText = this._buildSystemPrompt()
|
|
475
625
|
|
|
@@ -479,12 +629,14 @@ export class CliSession extends BaseSession {
|
|
|
479
629
|
// would otherwise lose every prior turn in the model's context window and
|
|
480
630
|
// the user would see the dashboard transcript replay correctly while the
|
|
481
631
|
// model itself starts cold mid-conversation.
|
|
632
|
+
this._launchedWithProject = projectAllowed
|
|
482
633
|
const args = buildClaudeCliArgs({
|
|
483
634
|
model: this.model,
|
|
484
635
|
permissionMode: this.permissionMode,
|
|
485
636
|
allowedTools: this.allowedTools,
|
|
486
637
|
skillsText,
|
|
487
638
|
resumeSessionId: this._sessionId,
|
|
639
|
+
projectAllowed,
|
|
488
640
|
})
|
|
489
641
|
|
|
490
642
|
const resumeNote = this._sessionId ? ` (resume ${this._sessionId})` : ''
|
|
@@ -506,6 +658,19 @@ export class CliSession extends BaseSession {
|
|
|
506
658
|
CLAUDE_HEADLESS: '1',
|
|
507
659
|
CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING: '1',
|
|
508
660
|
CHROXY_PERMISSION_MODE: this.permissionMode,
|
|
661
|
+
// #7337: the hook prefers this file and re-reads it on EVERY tool call,
|
|
662
|
+
// so a mid-session mode change reaches even the child already running.
|
|
663
|
+
// CHROXY_PERMISSION_MODE above stays as the fallback for a hook that
|
|
664
|
+
// cannot read the file (deleted /tmp entry, container without the mount).
|
|
665
|
+
//
|
|
666
|
+
// ALWAYS set, never omitted. buildSpawnEnv('claude') is DENYLIST mode, so
|
|
667
|
+
// the whole parent env passes through — and this daemon may itself have
|
|
668
|
+
// been launched from inside another chroxy session, whose sidecar path is
|
|
669
|
+
// then sitting in our env. Omitting the key would let that FOREIGN file
|
|
670
|
+
// decide this session's permissions, since the hook prefers it over our
|
|
671
|
+
// own CHROXY_PERMISSION_MODE. Empty string fails the hook's `[ -n ]` guard
|
|
672
|
+
// and falls through to the env var, which is the documented intent.
|
|
673
|
+
CHROXY_PERMISSION_MODE_FILE: this._permissionModeFile || '',
|
|
509
674
|
...(this._port ? { CHROXY_PORT: String(this._port) } : {}),
|
|
510
675
|
// Pass a short-lived per-session secret instead of the primary API token.
|
|
511
676
|
// This limits the blast radius if a tool reads process.env — the hook secret
|
|
@@ -518,6 +683,12 @@ export class CliSession extends BaseSession {
|
|
|
518
683
|
_spawnPersistentProcess(args) {
|
|
519
684
|
this._cleanupReadlines()
|
|
520
685
|
this._processReady = false
|
|
686
|
+
// #8038: clear any refusal latched by a PRIOR spawn attempt at the very
|
|
687
|
+
// top of every attempt (mirrors ClaudeTuiSession._spawnPty). A fresh
|
|
688
|
+
// attempt gets a fresh gate verdict — a stale latch from a prior crash
|
|
689
|
+
// respawn must never suppress a NEW attempt's own error or silently
|
|
690
|
+
// survive a revival that is about to succeed.
|
|
691
|
+
this._spawnRefusal = null
|
|
521
692
|
|
|
522
693
|
// #4929: capture which `--resume <id>` (if any) this spawn attempted.
|
|
523
694
|
// Read off the argv we're about to pass instead of `_sessionId` so the
|
|
@@ -537,7 +708,38 @@ export class CliSession extends BaseSession {
|
|
|
537
708
|
// for a directly-runnable `.exe` and on POSIX. See utils/win-spawn.js.
|
|
538
709
|
// Captured so the spawn-time backstop (#6708) verifies the EXACT binary this
|
|
539
710
|
// attempt used, not a fresh re-resolve that could land on a different path.
|
|
540
|
-
|
|
711
|
+
//
|
|
712
|
+
// #8038: routed through the shared binary gate instead of a bare
|
|
713
|
+
// `resolveClaudeBinary()` — this ONE method is what every (re)spawn funnels
|
|
714
|
+
// through (first start, `_killAndRespawn` for a model switch or permission-
|
|
715
|
+
// mode change, `_restartAfterStop`'s post-Stop revival, and `_scheduleRespawn`'s
|
|
716
|
+
// crash backoff), so gating it here covers every entry point in the #8038
|
|
717
|
+
// issue with no per-caller duplication. A refusal here means the gate
|
|
718
|
+
// rejected this attempt (provenance mismatch, quarantine, a vanished pinned
|
|
719
|
+
// path, …): nothing is spawned, the backoff chain resets (the NEXT spawn is
|
|
720
|
+
// user-initiated, mirroring `_killAndRespawn` zeroing `_respawnCount`), and
|
|
721
|
+
// `_scheduleRespawn` is deliberately NOT called — this is not "the child
|
|
722
|
+
// died", it is "we refused to start a child at all", and a timer retrying
|
|
723
|
+
// the same refused gate would just burn the bounded respawn budget into a
|
|
724
|
+
// misleading `respawn_exhausted` ("failed to stay alive"). Revival happens
|
|
725
|
+
// lazily on the next `sendMessage` instead (see there, and `_refuseSpawn`).
|
|
726
|
+
let attemptedBinary
|
|
727
|
+
try {
|
|
728
|
+
attemptedBinary = this._gatedSpawnBinary('claude')
|
|
729
|
+
} catch (err) {
|
|
730
|
+
// The chain that got us here (crash backoff, model switch, …) is over —
|
|
731
|
+
// the next spawn attempt is a fresh, user-initiated one, exactly as
|
|
732
|
+
// `_killAndRespawn` already resets this counter on its own respawn path.
|
|
733
|
+
//
|
|
734
|
+
// On the FIRST start this is only a race (create-time preflight passed
|
|
735
|
+
// moments earlier), and it latches rather than throwing like every other
|
|
736
|
+
// attempt. SessionManager has not broadcast `session_created` yet, so a
|
|
737
|
+
// client can miss this error: the session is listed but never ready,
|
|
738
|
+
// and its first input re-runs the gate and is rejected with the code.
|
|
739
|
+
this._respawnCount = 0
|
|
740
|
+
this._refuseSpawn(err, this._log || log)
|
|
741
|
+
return
|
|
742
|
+
}
|
|
541
743
|
const spawnSpec = prepareSpawn(attemptedBinary, args)
|
|
542
744
|
const child = spawn(spawnSpec.command, spawnSpec.args, {
|
|
543
745
|
cwd: this.cwd,
|
|
@@ -548,13 +750,27 @@ export class CliSession extends BaseSession {
|
|
|
548
750
|
|
|
549
751
|
this._child = child
|
|
550
752
|
|
|
753
|
+
// A returned ChildProcess is not ready proof: missing or non-executable
|
|
754
|
+
// binaries report ENOENT/EACCES asynchronously. Only expose readiness and
|
|
755
|
+
// drain startup input after Node confirms the child `spawn` event. Ignore
|
|
756
|
+
// a late event from a child that was replaced during a restart.
|
|
757
|
+
child.once('spawn', () => {
|
|
758
|
+
if (this._destroying || this._child !== child) return
|
|
759
|
+
this._processReady = true
|
|
760
|
+
log.info('Process started, ready for messages')
|
|
761
|
+
this.emit('ready', { sessionId: null, model: this.model, tools: [] })
|
|
762
|
+
this._drainPendingQueue()
|
|
763
|
+
})
|
|
764
|
+
|
|
551
765
|
// Do NOT close stdin — we write messages to it
|
|
552
766
|
|
|
553
767
|
// Read stdout line by line — each line is a JSON object
|
|
554
768
|
const rl = createInterface({ input: child.stdout })
|
|
555
769
|
this._rl = rl
|
|
556
770
|
|
|
557
|
-
|
|
771
|
+
// #9267: tag every line with the child that wrote it, so a child the Stop
|
|
772
|
+
// safety timer retired cannot feed its late reply into the session.
|
|
773
|
+
rl.on('line', (line) => this._handleStdoutLine(line, child))
|
|
558
774
|
|
|
559
775
|
// Log stderr for debugging
|
|
560
776
|
const stderrRL = createInterface({ input: child.stderr })
|
|
@@ -593,6 +809,7 @@ export class CliSession extends BaseSession {
|
|
|
593
809
|
})
|
|
594
810
|
|
|
595
811
|
child.on('error', (err) => {
|
|
812
|
+
if (this._child !== child) return
|
|
596
813
|
this._cleanupReadlines()
|
|
597
814
|
this._processReady = false
|
|
598
815
|
this._child = null
|
|
@@ -605,20 +822,65 @@ export class CliSession extends BaseSession {
|
|
|
605
822
|
this._scheduleRespawn()
|
|
606
823
|
})
|
|
607
824
|
|
|
608
|
-
child.on('close', (code) =>
|
|
825
|
+
child.on('close', (code) => {
|
|
826
|
+
if (this._child !== child) return
|
|
827
|
+
this._handleChildClose(code)
|
|
828
|
+
})
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
/**
|
|
832
|
+
* Warmup drain: dequeue the next pending message if not already busy.
|
|
833
|
+
* sendMessage() sets _isBusy, so the loop sends at most one message.
|
|
834
|
+
* Remaining items stay in the queue and are drained one-by-one via
|
|
835
|
+
* _clearMessageState() after each result.
|
|
836
|
+
*
|
|
837
|
+
* Called at the end of every _spawnPersistentProcess — i.e. this is what
|
|
838
|
+
* delivers a message queued while the process was down, whether it went down
|
|
839
|
+
* for a crash, a model switch, or a user Stop (#7438).
|
|
840
|
+
*/
|
|
841
|
+
/**
|
|
842
|
+
* A startup-queued message is dispatched only while the connection that sent it
|
|
843
|
+
* is still authorized; otherwise it is dropped and reported as not dispatched.
|
|
844
|
+
*/
|
|
845
|
+
_admitPendingItem(pending) {
|
|
846
|
+
if (stillAuthorized(pending?.options?.isAuthorized)) return true
|
|
847
|
+
reportInputAdmission(pending?.options, {
|
|
848
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: false,
|
|
849
|
+
reason: 'connection_not_authorized',
|
|
850
|
+
message: 'The sending connection is no longer authorized; the input was not dispatched.',
|
|
851
|
+
})
|
|
852
|
+
return false
|
|
853
|
+
}
|
|
609
854
|
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
855
|
+
/**
|
|
856
|
+
* #8281: the startup queue (`_pendingQueue`) counts as queued prompts. Both
|
|
857
|
+
* drains shift an item and call `sendMessage` (which sets busy) in the same
|
|
858
|
+
* synchronous step, so the item is in this queue until the instant the session
|
|
859
|
+
* is busy: the post-result drain's nextTick window and the respawn-to-ready
|
|
860
|
+
* window are both covered by the length alone, with no in-flight marker.
|
|
861
|
+
* @returns {number}
|
|
862
|
+
*/
|
|
863
|
+
_extraQueuedPromptCount() {
|
|
864
|
+
return this._pendingQueue.length
|
|
865
|
+
}
|
|
615
866
|
|
|
616
|
-
|
|
617
|
-
//
|
|
618
|
-
//
|
|
619
|
-
//
|
|
867
|
+
_drainPendingQueue() {
|
|
868
|
+
// #9267: the warmup of the child the Stop timer's retirement started drains the
|
|
869
|
+
// OUTGOING queue first (a follow-up accepted during the 5 s window is older than
|
|
870
|
+
// anything parked behind the fresh child), one turn at a time: the rest, startup
|
|
871
|
+
// queue included, follows from each `result` in the order the result path keeps.
|
|
872
|
+
// Only that restart sets the flag; crash and model/permission-mode respawns drain
|
|
873
|
+
// exactly what they always did.
|
|
874
|
+
if (this._drainOutgoingFirst) {
|
|
875
|
+
this._drainOutgoingFirst = false
|
|
876
|
+
if (!this._isBusy && this._outgoingQueue.length > 0) {
|
|
877
|
+
this.dequeueNextOutgoing()
|
|
878
|
+
return
|
|
879
|
+
}
|
|
880
|
+
}
|
|
620
881
|
while (this._pendingQueue.length > 0 && !this._isBusy) {
|
|
621
882
|
const pending = this._pendingQueue.shift()
|
|
883
|
+
if (!this._admitPendingItem(pending)) continue
|
|
622
884
|
// #4828: session-scoped when init has fired (dequeue can race with
|
|
623
885
|
// the very-first init so the fallback is intentional).
|
|
624
886
|
;(this._log || log).info(`Dequeuing pending message (${this._pendingQueue.length} remaining)`)
|
|
@@ -673,6 +935,69 @@ export class CliSession extends BaseSession {
|
|
|
673
935
|
}, delay)
|
|
674
936
|
}
|
|
675
937
|
|
|
938
|
+
/**
|
|
939
|
+
* #8301: a daemon wake is handed to a session that is READY, or not at all.
|
|
940
|
+
*
|
|
941
|
+
* `sendMessage` on a process that is not ready either respawns it
|
|
942
|
+
* (`_restartAfterStop()`, right for typed input, wrong for a wake) or parks the
|
|
943
|
+
* message in `_pendingQueue`. That queue is drained by `sendMessage` directly
|
|
944
|
+
* from three places (the warmup drain, the post-result drain, and
|
|
945
|
+
* DockerSession's start), none of which consults `admitAtFlush`, so a wake
|
|
946
|
+
* parked there would reach the child after a budget pause or a user Stop had
|
|
947
|
+
* been decided. The only way to keep the flush-time check meaningful is to
|
|
948
|
+
* never let a wake in: any not-ready state refuses. A wake that finds the
|
|
949
|
+
* session still starting is simply dropped; CI completion is not replayed, and
|
|
950
|
+
* the user was notified.
|
|
951
|
+
*
|
|
952
|
+
* `'stopped'` is kept for the two latches because it is the more useful
|
|
953
|
+
* answer (the user, or the binary gate, did this); everything else is
|
|
954
|
+
* `'not-ready'` (pre-init, mid-respawn, crashed).
|
|
955
|
+
*
|
|
956
|
+
* @returns {string|null}
|
|
957
|
+
*/
|
|
958
|
+
daemonTurnRefusal() {
|
|
959
|
+
if (this._processReady) return null
|
|
960
|
+
return (this._stoppedByUser || this._spawnRefusal) ? 'stopped' : 'not-ready'
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
/**
|
|
964
|
+
* #8301: a queued daemon item was refused at flush. The base hook just keeps
|
|
965
|
+
* draining `_outgoingQueue`; CliSession has a SECOND queue behind it, and the
|
|
966
|
+
* refused item's slot must not strand it. `_clearMessageState` hands the turn
|
|
967
|
+
* to `_outgoingQueue` first and to `_pendingQueue` only when the former is
|
|
968
|
+
* empty, so a refusal that empties the former has to fall through to the
|
|
969
|
+
* latter exactly as `_clearMessageState` would have.
|
|
970
|
+
*/
|
|
971
|
+
_continueDrainAfterRefusal() {
|
|
972
|
+
if (this._destroying) return
|
|
973
|
+
if (this._outgoingQueue.length > 0) {
|
|
974
|
+
this.dequeueNextOutgoing()
|
|
975
|
+
} else {
|
|
976
|
+
this._drainNextPendingAfterResult()
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
/**
|
|
981
|
+
* Dispatch the next message parked while the child was not ready, on the next
|
|
982
|
+
* tick (so synchronous `result` listeners finish first). Shared by the
|
|
983
|
+
* post-result drain in `_clearMessageState` and `_continueDrainAfterRefusal`.
|
|
984
|
+
*/
|
|
985
|
+
_drainNextPendingAfterResult() {
|
|
986
|
+
if (!this._processReady || this._pendingQueue.length === 0) return
|
|
987
|
+
process.nextTick(() => {
|
|
988
|
+
if (this._destroying) return
|
|
989
|
+
if (!this._processReady || this._pendingQueue.length === 0) return
|
|
990
|
+
const pending = this._pendingQueue.shift()
|
|
991
|
+
if (!this._admitPendingItem(pending)) {
|
|
992
|
+
this._drainNextPendingAfterResult()
|
|
993
|
+
return
|
|
994
|
+
}
|
|
995
|
+
// #4828: session-scoped (post-result, post-init).
|
|
996
|
+
;(this._log || log).info(`Dequeuing next pending message after result (${this._pendingQueue.length} remaining)`)
|
|
997
|
+
this.sendMessage(pending.prompt, pending.attachments, pending.options || {})
|
|
998
|
+
})
|
|
999
|
+
}
|
|
1000
|
+
|
|
676
1001
|
/**
|
|
677
1002
|
* Send a message to Claude via stdin NDJSON.
|
|
678
1003
|
*/
|
|
@@ -683,19 +1008,57 @@ export class CliSession extends BaseSession {
|
|
|
683
1008
|
// processing a message" — flushed FIFO on the turn-complete `result` (via
|
|
684
1009
|
// _clearMessageState's drain below). Matches the SDK's behaviour. The
|
|
685
1010
|
// overflow cap + the message_queued mirror live in enqueueOutgoingMessage.
|
|
686
|
-
this.enqueueOutgoingMessage({ prompt, attachments, sendOptions: options })
|
|
1011
|
+
const queued = this.enqueueOutgoingMessage({ prompt, attachments, sendOptions: options })
|
|
1012
|
+
reportInputAdmission(options, queued
|
|
1013
|
+
? { status: 'queued', delivery: 'queued' }
|
|
1014
|
+
: {
|
|
1015
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
1016
|
+
reason: 'queue_full', message: 'The provider input queue is full; retry after queued work advances.',
|
|
1017
|
+
})
|
|
687
1018
|
return
|
|
688
1019
|
}
|
|
689
1020
|
|
|
690
1021
|
if (!this._processReady) {
|
|
1022
|
+
// #8038: revive FIRST, before deciding whether THIS input can be
|
|
1023
|
+
// admitted. `_restartAfterStop` now also fires on a latched spawn
|
|
1024
|
+
// refusal (see its doc) so a session left idle by a gate refusal gets
|
|
1025
|
+
// the same lazy on-next-input revival a user Stop already got via
|
|
1026
|
+
// #7438 — moved ahead of the queue-full check / push below. It used to
|
|
1027
|
+
// run AFTER queuing, which is fine when the restart spawns a child (the
|
|
1028
|
+
// warmup drain delivers the push), but with a gate that can refuse it
|
|
1029
|
+
// would admit this input as `queued` behind a child that never starts.
|
|
1030
|
+
this._restartAfterStop()
|
|
1031
|
+
|
|
1032
|
+
// #8038: the revival attempt above may have hit the SAME gate refusal
|
|
1033
|
+
// again (or a fresh one) — reject THIS input immediately with the coded
|
|
1034
|
+
// admission instead of queuing it behind a child that is not coming
|
|
1035
|
+
// back on its own. Messages already sitting in `_pendingQueue` from
|
|
1036
|
+
// BEFORE this refusal are untouched (their admission was already
|
|
1037
|
+
// reported as `queued`, and `onInputAdmission` is final after its first
|
|
1038
|
+
// call) — they stay queued and are delivered FIFO by the warmup drain
|
|
1039
|
+
// once a future revival actually spawns.
|
|
1040
|
+
if (this._spawnRefusal) {
|
|
1041
|
+
reportInputAdmission(options, spawnRefusalAdmission(this._spawnRefusal))
|
|
1042
|
+
return
|
|
1043
|
+
}
|
|
1044
|
+
|
|
691
1045
|
if (this._pendingQueue.length >= 3) {
|
|
692
1046
|
this.emit('error', { message: 'Pending message queue full (max 3) — message discarded' })
|
|
1047
|
+
reportInputAdmission(options, {
|
|
1048
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
1049
|
+
reason: 'queue_full', message: 'The provider startup queue is full; retry after the session becomes ready.',
|
|
1050
|
+
})
|
|
693
1051
|
return
|
|
694
1052
|
}
|
|
695
1053
|
// #4828: session-scoped when init has fired (queuing typically happens
|
|
696
1054
|
// pre-init or during respawn — both can race with the binding).
|
|
697
1055
|
;(this._log || log).info(`Process not ready, queuing message (queue depth: ${this._pendingQueue.length + 1})`)
|
|
698
1056
|
this._pendingQueue.push({ prompt, attachments, options })
|
|
1057
|
+
reportInputAdmission(options, { status: 'queued', delivery: 'queued' })
|
|
1058
|
+
// #9267: the restart above can finish its warmup synchronously (an existing
|
|
1059
|
+
// container, a folder needing no trust scan), i.e. BEFORE this push, leaving
|
|
1060
|
+
// nothing to drain the prompt just parked. Ready and idle now means drain now.
|
|
1061
|
+
if (this._processReady && !this._isBusy) this._drainPendingQueue()
|
|
699
1062
|
return
|
|
700
1063
|
}
|
|
701
1064
|
|
|
@@ -737,6 +1100,8 @@ export class CliSession extends BaseSession {
|
|
|
737
1100
|
}
|
|
738
1101
|
|
|
739
1102
|
this._isBusy = true
|
|
1103
|
+
// #7376: a turn starts with no Stop requested, whatever the last one did.
|
|
1104
|
+
this._stopRequestedThisTurn = false
|
|
740
1105
|
this._messageCounter++
|
|
741
1106
|
// `msg-{bootPrefix}-{counter}` — see BaseSession constructor for why
|
|
742
1107
|
// the boot-unique prefix is needed (#3700). Format change does not
|
|
@@ -766,9 +1131,15 @@ export class CliSession extends BaseSession {
|
|
|
766
1131
|
;(this._log || log).error(`stdin.write failed (sendMessage): ${err.message}`)
|
|
767
1132
|
this._clearMessageState()
|
|
768
1133
|
this.emit('error', { message: `Failed to send message: ${err.message}` })
|
|
1134
|
+
reportInputAdmission(options, {
|
|
1135
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
1136
|
+
reason: 'write_failed', message: 'The provider input channel rejected the write.',
|
|
1137
|
+
})
|
|
769
1138
|
return
|
|
770
1139
|
}
|
|
771
1140
|
|
|
1141
|
+
reportInputAdmission(options, { status: 'accepted', delivery: 'dispatch_started' })
|
|
1142
|
+
|
|
772
1143
|
// Skills text is committed to the wire — safe to flip the flag now (#3225).
|
|
773
1144
|
// If the write threw above we returned early, leaving the flag false so
|
|
774
1145
|
// the next attempt re-injects the prepend bucket.
|
|
@@ -865,19 +1236,63 @@ export class CliSession extends BaseSession {
|
|
|
865
1236
|
const friendly = formatIdleDuration(this._hardTimeoutMs)
|
|
866
1237
|
// #4828: session-scoped (hard-cap fires from active turn).
|
|
867
1238
|
;(this._log || log).warn(`Hard-cap timeout (${friendly}) — force-clearing busy state`)
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
for (const requestId of this._pendingPermissionIds) {
|
|
871
|
-
this.emit('permission_expired', {
|
|
872
|
-
requestId,
|
|
873
|
-
message: 'Permission request expired (session timeout)',
|
|
874
|
-
})
|
|
875
|
-
}
|
|
876
|
-
this._pendingPermissionIds.clear()
|
|
877
|
-
this._emitInterruptedTurnResult(this._hardTimeoutMs)
|
|
1239
|
+
this._expirePendingPermissions('Permission request expired (session timeout)')
|
|
1240
|
+
this._emitInterruptedTurnResult(this._hardTimeoutMs, 'hard_timeout')
|
|
878
1241
|
this.emit('error', { message: `Response timed out after ${friendly}` })
|
|
879
1242
|
}
|
|
880
1243
|
|
|
1244
|
+
/**
|
|
1245
|
+
* Emit `permission_expired` for every prompt this session is still blocked
|
|
1246
|
+
* on, then drop the bookkeeping (#2831, extended by #7335).
|
|
1247
|
+
*
|
|
1248
|
+
* A prompt outlives its turn on BOTH sides and neither side says so:
|
|
1249
|
+
* client-side the card stays live until its own 5-minute `expiresAt`, and
|
|
1250
|
+
* server-side the daemon's HTTP handler tears the pending entry down on the
|
|
1251
|
+
* hook's `req 'aborted'` / `res 'close'` without broadcasting anything. So a
|
|
1252
|
+
* user who clicks Allow afterwards gets the "stale/unknown toolUseId …
|
|
1253
|
+
* already resolved" path with nothing explaining which decision died.
|
|
1254
|
+
*
|
|
1255
|
+
* The dashboard's `permission_expired` handler appends the expiry note AND
|
|
1256
|
+
* clears the prompt's `options`, which is what actually retires the dead
|
|
1257
|
+
* Allow button — so emitting here is the whole client-side fix.
|
|
1258
|
+
*
|
|
1259
|
+
* Wired at three sites, and the third is the one that matters:
|
|
1260
|
+
*
|
|
1261
|
+
* - `_clearMessageState` — the FUNNEL. Every turn end reaches it: the
|
|
1262
|
+
* normal `result`, the hard cap, the interrupt safety timeout,
|
|
1263
|
+
* `destroy()`. It is also where the ids used to be dropped silently.
|
|
1264
|
+
* - `_killAndRespawn` — the #3729 panic-button, the auto-mode switch,
|
|
1265
|
+
* mid-turn setModel. Needs its OWN call because it reaches the funnel via
|
|
1266
|
+
* `_emitInterruptedTurnResult`, which early-returns when the session is
|
|
1267
|
+
* not busy.
|
|
1268
|
+
* - `_handleChildClose` — a crash, or user Stop where the child dies. Same
|
|
1269
|
+
* early-return caveat.
|
|
1270
|
+
*
|
|
1271
|
+
* An earlier draft wired only the two death sites and justified skipping the
|
|
1272
|
+
* rest in a table. Review found the table wrong twice over: the interrupt
|
|
1273
|
+
* safety timeout was excused as "the child ignored SIGINT so the prompt is
|
|
1274
|
+
* still answerable", which this file contradicts eleven hundred lines below
|
|
1275
|
+
* (`claude only aborts the current turn` — the hook dies with the turn), and
|
|
1276
|
+
* that path then wiped the ids anyway via `_clearMessageState`, so no later
|
|
1277
|
+
* close could expire them. The plain `result` path was not in the table at
|
|
1278
|
+
* all. Enumerating callers by hand is what produced both errors; wiring the
|
|
1279
|
+
* funnel is what fixes them.
|
|
1280
|
+
*
|
|
1281
|
+
* `_handleStreamStall` is genuinely unreachable with a permission pending —
|
|
1282
|
+
* `notifyPermissionPending` clears the stall timer and `_armResultTimeout`
|
|
1283
|
+
* bails on `_resultTimeoutPaused` — and it routes through the funnel anyway.
|
|
1284
|
+
*
|
|
1285
|
+
* NOT a full solution on its own: this retires the prompt in the CLIENTS. The
|
|
1286
|
+
* daemon's own `pendingPermissions` entry (ws-permissions.js) is still
|
|
1287
|
+
* released explicitly rather than by relying on the hook dying: since #7606
|
|
1288
|
+
* POSIX `killProcessTree` does signal the hook's `bash` → `curl` grandchildren
|
|
1289
|
+
* on a respawn/destroy, but a crash runs no kill at all, and an explicit
|
|
1290
|
+
* release is the only path that covers both. See #7379.
|
|
1291
|
+
*
|
|
1292
|
+
* @param {string} message Reason forwarded on the wire (clients log it; the
|
|
1293
|
+
* user-visible copy is fixed client-side).
|
|
1294
|
+
*/
|
|
1295
|
+
|
|
881
1296
|
// #4467: stream-stall recovery. Fires when the child has been silent
|
|
882
1297
|
// for `_streamStallTimeoutMs` despite the session being busy — typically
|
|
883
1298
|
// a half-open TCP to the Anthropic API that the OS hasn't surfaced yet.
|
|
@@ -891,7 +1306,7 @@ export class CliSession extends BaseSession {
|
|
|
891
1306
|
;(this._log || log).warn(
|
|
892
1307
|
`Stream stalled (${friendly}, messageId=${this._currentMessageId}) — clearing busy state for retry`,
|
|
893
1308
|
)
|
|
894
|
-
this._emitInterruptedTurnResult(this._streamStallTimeoutMs)
|
|
1309
|
+
this._emitInterruptedTurnResult(this._streamStallTimeoutMs, 'stream_stall')
|
|
895
1310
|
this.emit('error', {
|
|
896
1311
|
code: 'stream_stall',
|
|
897
1312
|
message: `Stream stalled — no response for ${friendly}. Try sending again.`,
|
|
@@ -905,46 +1320,52 @@ export class CliSession extends BaseSession {
|
|
|
905
1320
|
*
|
|
906
1321
|
* @param {string} requestId
|
|
907
1322
|
*/
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
1323
|
+
/**
|
|
1324
|
+
* #7382: the generic add/remove bookkeeping is BaseSession's. These hooks are
|
|
1325
|
+
* the CLI-specific half — pausing the inactivity trio while the user is being
|
|
1326
|
+
* asked (#2831/#3899/#4467), which is not behaviour every provider shares.
|
|
1327
|
+
*/
|
|
1328
|
+
_onFirstPermissionPending() {
|
|
1329
|
+
this._resultTimeoutPaused = true
|
|
1330
|
+
// #3899: clear BOTH the soft warning and the hard cap. Awaiting user input
|
|
1331
|
+
// is not inactivity; the trio re-arms together when the last pending
|
|
1332
|
+
// permission resolves. #4467: the stall timer too — waiting on the user is
|
|
1333
|
+
// not a stall.
|
|
1334
|
+
if (this._resultTimeout) {
|
|
1335
|
+
clearTimeout(this._resultTimeout)
|
|
1336
|
+
this._resultTimeout = null
|
|
1337
|
+
}
|
|
1338
|
+
if (this._hardTimeout) {
|
|
1339
|
+
clearTimeout(this._hardTimeout)
|
|
1340
|
+
this._hardTimeout = null
|
|
1341
|
+
}
|
|
1342
|
+
if (this._streamStallTimeout) {
|
|
1343
|
+
clearTimeout(this._streamStallTimeout)
|
|
1344
|
+
this._streamStallTimeout = null
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
/** Last prompt ANSWERED — the turn continues, so re-arm the trio. */
|
|
1349
|
+
_onLastPermissionResolved() {
|
|
1350
|
+
this._resultTimeoutPaused = false
|
|
1351
|
+
if (this._isBusy) {
|
|
1352
|
+
this._armResultTimeout()
|
|
929
1353
|
}
|
|
930
1354
|
}
|
|
931
1355
|
|
|
932
1356
|
/**
|
|
933
|
-
*
|
|
934
|
-
*
|
|
935
|
-
* the inactivity timer re-arms for a fresh window. #2831.
|
|
1357
|
+
* Last prompt ABANDONED — the turn that raised it is over, so release the
|
|
1358
|
+
* pause but do NOT re-arm.
|
|
936
1359
|
*
|
|
937
|
-
*
|
|
1360
|
+
* #7375: releasing the flag is the load-bearing half. It and the id set are
|
|
1361
|
+
* one piece of bookkeeping, and `notifyPermissionResolved` only unsets the
|
|
1362
|
+
* flag for an id still IN the set — so taking the ids without releasing it
|
|
1363
|
+
* wedged the flag true on any path that does not reach `_clearMessageState`,
|
|
1364
|
+
* leaving the inactivity warning, the hard cap and the stall recovery dead
|
|
1365
|
+
* for the rest of the session.
|
|
938
1366
|
*/
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
this._pendingPermissionIds.delete(requestId)
|
|
942
|
-
if (this._pendingPermissionIds.size === 0) {
|
|
943
|
-
this._resultTimeoutPaused = false
|
|
944
|
-
if (this._isBusy) {
|
|
945
|
-
this._armResultTimeout()
|
|
946
|
-
}
|
|
947
|
-
}
|
|
1367
|
+
_onPendingPermissionsAbandoned() {
|
|
1368
|
+
this._resultTimeoutPaused = false
|
|
948
1369
|
}
|
|
949
1370
|
|
|
950
1371
|
/**
|
|
@@ -957,8 +1378,13 @@ export class CliSession extends BaseSession {
|
|
|
957
1378
|
* a real readline interface.
|
|
958
1379
|
*
|
|
959
1380
|
* @param {string} line
|
|
1381
|
+
* @param {object} [child] #9267: the child that wrote the line. When given and
|
|
1382
|
+
* it is no longer the session's current child (the Stop safety timer retired
|
|
1383
|
+
* it, or a respawn replaced it) the line is dropped before it can touch the
|
|
1384
|
+
* turn state of whatever the session is doing now.
|
|
960
1385
|
*/
|
|
961
|
-
_handleStdoutLine(line) {
|
|
1386
|
+
_handleStdoutLine(line, child) {
|
|
1387
|
+
if (child && this._child !== child) return
|
|
962
1388
|
if (!line.trim()) return
|
|
963
1389
|
|
|
964
1390
|
let data
|
|
@@ -1038,6 +1464,62 @@ export class CliSession extends BaseSession {
|
|
|
1038
1464
|
compactMetadata: meta,
|
|
1039
1465
|
timestamp: Date.now(),
|
|
1040
1466
|
})
|
|
1467
|
+
} else if (data.subtype === 'task_started' || data.subtype === 'task_notification') {
|
|
1468
|
+
// #7340: the CLI's subagent lifecycle events. Until now these fell
|
|
1469
|
+
// into the generic branch below, which forwarded the literal string
|
|
1470
|
+
// "task_started" / "task_notification" to the client as a chat
|
|
1471
|
+
// bubble — noise in place of state.
|
|
1472
|
+
//
|
|
1473
|
+
// `task_started` is authoritative in two ways the tool_use block is
|
|
1474
|
+
// not: it carries `is_backgrounded` (the model's `run_in_background`
|
|
1475
|
+
// is a request; this is what the CLI actually did), and it identifies
|
|
1476
|
+
// subagents by `task_type` rather than by tool NAME, so tracking
|
|
1477
|
+
// survives a rename the way `Task` -> `Agent` was not survived.
|
|
1478
|
+
// `task_type: 'local_bash'` is a backgrounded shell — #4307's
|
|
1479
|
+
// surface, tracked separately, and never an agent.
|
|
1480
|
+
//
|
|
1481
|
+
// `task_notification` is the terminal signal. It is the ONLY thing
|
|
1482
|
+
// that clears a backgrounded agent now that the turn-end sweep no
|
|
1483
|
+
// longer does, so it is wired here rather than left to the sweep.
|
|
1484
|
+
// It fires for FAILED and STOPPED subagents too, not just completed
|
|
1485
|
+
// ones — every terminal status must clear the badge, or a subagent
|
|
1486
|
+
// that errored pins the session as working forever.
|
|
1487
|
+
if (data.subtype === 'task_started') {
|
|
1488
|
+
if (data.task_type === 'local_agent') {
|
|
1489
|
+
this._trackAgent({
|
|
1490
|
+
toolUseId: data.tool_use_id,
|
|
1491
|
+
description: typeof data.description === 'string' && data.description
|
|
1492
|
+
? data.description
|
|
1493
|
+
: 'Background task',
|
|
1494
|
+
background: data.is_backgrounded === true,
|
|
1495
|
+
// #7340: authoritative -- the CLI's own account, so it
|
|
1496
|
+
// overwrites the model's request in BOTH directions. It is
|
|
1497
|
+
// also the evidence that this build emits task lifecycle
|
|
1498
|
+
// messages at all, which is what makes the turn-end exemption
|
|
1499
|
+
// safe: `task_notification` can arrive.
|
|
1500
|
+
authoritative: true,
|
|
1501
|
+
})
|
|
1502
|
+
}
|
|
1503
|
+
} else {
|
|
1504
|
+
this._completeAgent(data.tool_use_id)
|
|
1505
|
+
}
|
|
1506
|
+
} else if (data.subtype === 'status') {
|
|
1507
|
+
// #8153 (review nit): mirrors SdkSession's 'status' branch —
|
|
1508
|
+
// `SDKStatusMessage` carries no `message`/`text` field, just
|
|
1509
|
+
// `status: 'compacting' | 'requesting' | null`, so the generic
|
|
1510
|
+
// fallback below would otherwise forward the bare literal string
|
|
1511
|
+
// "status" as a chat bubble. `status: null` means the previous
|
|
1512
|
+
// status cleared — nothing new to show, so it's suppressed
|
|
1513
|
+
// entirely rather than emitted as an empty/placeholder bubble.
|
|
1514
|
+
const statusText = formatStatusContent(data.status)
|
|
1515
|
+
if (statusText) {
|
|
1516
|
+
this.emit('message', {
|
|
1517
|
+
type: 'system',
|
|
1518
|
+
subtype: 'status',
|
|
1519
|
+
content: statusText,
|
|
1520
|
+
timestamp: Date.now(),
|
|
1521
|
+
})
|
|
1522
|
+
}
|
|
1041
1523
|
} else {
|
|
1042
1524
|
// Forward non-init system events (e.g. usage limits, sub-agent
|
|
1043
1525
|
// notifications) as system messages to the client
|
|
@@ -1062,6 +1544,14 @@ export class CliSession extends BaseSession {
|
|
|
1062
1544
|
if (!messageId || !ctx) break
|
|
1063
1545
|
|
|
1064
1546
|
switch (event.type) {
|
|
1547
|
+
case 'message_start': {
|
|
1548
|
+
// #7393: a new API message (the next round of a tool loop) restarts
|
|
1549
|
+
// block indexes at 0. A reasoning block the last message never closed
|
|
1550
|
+
// must not absorb this one's block 0.
|
|
1551
|
+
this._closeThinking(ctx)
|
|
1552
|
+
break
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1065
1555
|
case 'content_block_start': {
|
|
1066
1556
|
const blockType = event.content_block?.type
|
|
1067
1557
|
ctx.currentContentBlockType = blockType
|
|
@@ -1071,6 +1561,12 @@ export class CliSession extends BaseSession {
|
|
|
1071
1561
|
ctx.hasStreamStarted = true
|
|
1072
1562
|
this.emit('stream_start', { messageId })
|
|
1073
1563
|
}
|
|
1564
|
+
} else if (blockType === 'thinking' || blockType === 'redacted_thinking') {
|
|
1565
|
+
// #7393: the model's reasoning. Open its stream now (the "it is
|
|
1566
|
+
// thinking" signal); the text is held until the block closes.
|
|
1567
|
+
const key = event.index ?? 0
|
|
1568
|
+
this._thinkingStreams(ctx, messageId).open(key)
|
|
1569
|
+
if (blockType === 'redacted_thinking') (ctx.redactedThinking ??= new Set()).add(key)
|
|
1074
1570
|
} else if (blockType === 'tool_use') {
|
|
1075
1571
|
ctx.currentToolName = event.content_block.name
|
|
1076
1572
|
ctx.toolInputChunks = ''
|
|
@@ -1107,6 +1603,14 @@ export class CliSession extends BaseSession {
|
|
|
1107
1603
|
}
|
|
1108
1604
|
ctx.didStreamText = true
|
|
1109
1605
|
this.emit('stream_delta', { messageId, delta: delta.text })
|
|
1606
|
+
} else if (delta.type === 'thinking_delta' && typeof delta.thinking === 'string') {
|
|
1607
|
+
// #7393: opening is idempotent, so a delta that beats its
|
|
1608
|
+
// content_block_start still lands in ONE stream. `signature_delta`
|
|
1609
|
+
// is not reasoning and falls through to nothing.
|
|
1610
|
+
const key = event.index ?? 0
|
|
1611
|
+
const streams = this._thinkingStreams(ctx, messageId)
|
|
1612
|
+
streams.open(key)
|
|
1613
|
+
streams.append(key, delta.thinking)
|
|
1110
1614
|
} else if (delta.type === 'input_json_delta' && ctx.currentContentBlockType === 'tool_use') {
|
|
1111
1615
|
if (typeof delta.partial_json === 'string' && !ctx.toolInputOverflow) {
|
|
1112
1616
|
const chunkBytes = Buffer.byteLength(delta.partial_json, 'utf8')
|
|
@@ -1121,6 +1625,18 @@ export class CliSession extends BaseSession {
|
|
|
1121
1625
|
} else {
|
|
1122
1626
|
ctx.toolInputChunks += delta.partial_json
|
|
1123
1627
|
ctx.toolInputBytes += chunkBytes
|
|
1628
|
+
// #8135 (review on #7346): do NOT forward this raw
|
|
1629
|
+
// chunk as a live `tool_input_delta` — a secret can
|
|
1630
|
+
// straddle chunk boundaries (e.g. "export TOKEN=sk-"
|
|
1631
|
+
// in one delta, "ant-api03-…" in the next), so a
|
|
1632
|
+
// per-chunk value can't be redacted safely, and
|
|
1633
|
+
// mid-stream partial JSON can't be parsed to run the
|
|
1634
|
+
// structured sanitizer over it either. The sanitized
|
|
1635
|
+
// FULL input is instead delivered as a single
|
|
1636
|
+
// `tool_input_delta` once the block finalizes — see
|
|
1637
|
+
// `_captureFinalizedToolInput` at `content_block_stop`,
|
|
1638
|
+
// a few ms later (execution, not this streaming
|
|
1639
|
+
// window, is the long part of a Bash call).
|
|
1124
1640
|
}
|
|
1125
1641
|
}
|
|
1126
1642
|
}
|
|
@@ -1128,7 +1644,23 @@ export class CliSession extends BaseSession {
|
|
|
1128
1644
|
}
|
|
1129
1645
|
|
|
1130
1646
|
case 'content_block_stop': {
|
|
1647
|
+
if (ctx?.thinking) {
|
|
1648
|
+
// #7393: close the reasoning block this stop belongs to (a no-op
|
|
1649
|
+
// for any other block type).
|
|
1650
|
+
const key = event.index ?? 0
|
|
1651
|
+
ctx.thinking.close(key, { redacted: ctx.redactedThinking?.delete(key) === true })
|
|
1652
|
+
}
|
|
1131
1653
|
if (ctx && ctx.currentToolName) {
|
|
1654
|
+
// #7346: backfill EVERY tool's finalized input (not just the
|
|
1655
|
+
// four special-cased by _applyToolInputSemantics below) so a
|
|
1656
|
+
// generic Bash/Read/etc. call's input rides out on its
|
|
1657
|
+
// tool_result instead of staying null forever — the actual
|
|
1658
|
+
// root cause of the "(no input)" bug, in flight AND after
|
|
1659
|
+
// completion/session-switch replay. Must run before
|
|
1660
|
+
// _applyToolInputSemantics only by convention (the two are
|
|
1661
|
+
// independent; ordering doesn't matter since neither mutates
|
|
1662
|
+
// ctx.toolInputChunks).
|
|
1663
|
+
this._captureFinalizedToolInput(ctx)
|
|
1132
1664
|
this._applyToolInputSemantics(ctx)
|
|
1133
1665
|
}
|
|
1134
1666
|
if (ctx) {
|
|
@@ -1152,6 +1684,8 @@ export class CliSession extends BaseSession {
|
|
|
1152
1684
|
const ctx = this._currentCtx
|
|
1153
1685
|
const messageId = this._currentMessageId
|
|
1154
1686
|
const content = data.message?.content
|
|
1687
|
+
this.emit('assistant_response', { responseId: data.message?.id ?? data.uuid, text: assistantResponseText(content) })
|
|
1688
|
+
if (ctx) ctx.assistantResponseSeen = true
|
|
1155
1689
|
if (Array.isArray(content) && ctx && messageId) {
|
|
1156
1690
|
// If stream_event deltas already drove streaming, skip assistant text
|
|
1157
1691
|
if (ctx.didStreamText) {
|
|
@@ -1193,6 +1727,14 @@ export class CliSession extends BaseSession {
|
|
|
1193
1727
|
const messageId = this._currentMessageId
|
|
1194
1728
|
const ctx = this._currentCtx
|
|
1195
1729
|
|
|
1730
|
+
if (!ctx?.assistantResponseSeen && typeof data.result === 'string') {
|
|
1731
|
+
this.emit('assistant_response', { text: assistantResponseText(data.result) })
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
// #7393: a turn can end under an open reasoning block; finalise it so the
|
|
1735
|
+
// client's "Thinking…" settles, before anything else this result emits.
|
|
1736
|
+
this._closeThinking(ctx)
|
|
1737
|
+
|
|
1196
1738
|
// #5064 — Fallback for turns that complete without ever emitting
|
|
1197
1739
|
// streamed assistant text. The canonical case is `/compact`: the
|
|
1198
1740
|
// CLI returns the compaction summary in `data.result` but emits
|
|
@@ -1263,15 +1805,88 @@ export class CliSession extends BaseSession {
|
|
|
1263
1805
|
numTurns: Number.isFinite(data.num_turns) ? data.num_turns : null,
|
|
1264
1806
|
apiDurationMs: Number.isFinite(data.duration_api_ms) ? data.duration_api_ms : null,
|
|
1265
1807
|
modelUsage: normalizeSdkModelUsage(data.modelUsage),
|
|
1808
|
+
// #7326: the CLI's result is the same message the SDK's is, so it
|
|
1809
|
+
// carries the same stop_reason / subtype / terminal_reason.
|
|
1810
|
+
declarationEligible: sdkDeclarationEligible(data),
|
|
1811
|
+
...turnOutcomeField(outcomeFromSdkResult(data)),
|
|
1812
|
+
// #9241: `aborted_*` is the child saying the abort ended the turn.
|
|
1813
|
+
...(outcomeFromSdkResult(data) === 'stopped' ? { stopRequested: true } : {}),
|
|
1266
1814
|
})
|
|
1267
1815
|
|
|
1268
|
-
// Message complete — ready for next message
|
|
1269
|
-
|
|
1816
|
+
// Message complete — ready for next message.
|
|
1817
|
+
// #7340: the CLI's own `result` message -- the child is alive and
|
|
1818
|
+
// reported the turn over itself, so a confirmed-backgrounded subagent
|
|
1819
|
+
// survives the sweep and clears later on `task_notification`. This and
|
|
1820
|
+
// SdkSession's `result` are the ONLY two sites that may pass this flag;
|
|
1821
|
+
// see the contract on `BaseSession._clearMessageState`.
|
|
1822
|
+
// #7376: `completion: 'normal'` -- the child's own `result` ended the
|
|
1823
|
+
// turn, so a Stop requested during it may have cut its tools off.
|
|
1824
|
+
this._clearMessageState({ turnEndedCleanly: true, completion: 'normal' })
|
|
1270
1825
|
break
|
|
1271
1826
|
}
|
|
1272
1827
|
}
|
|
1273
1828
|
}
|
|
1274
1829
|
|
|
1830
|
+
/**
|
|
1831
|
+
* #7346: backfill the finalized tool input onto `_inFlightToolStarts`
|
|
1832
|
+
* (base-session.js `_recordToolInput`, which sanitizes + size-caps it
|
|
1833
|
+
* — see #8135/#8136) so `tool-result.js`'s `emitToolResults` can
|
|
1834
|
+
* attach it to the matching `tool_result` via `_getTrackedToolInput`.
|
|
1835
|
+
* Runs for every tool (unlike `_applyToolInputSemantics`, which only
|
|
1836
|
+
* parses to drive four special-cased tools' session state) — the
|
|
1837
|
+
* #7346 root cause was that nothing captured the finalized input for
|
|
1838
|
+
* a generic Bash/Read/etc. call, so it stayed `null` forever: not
|
|
1839
|
+
* just in flight, but in the persisted `tool_start` history entry a
|
|
1840
|
+
* session-switch replay rebuilds from.
|
|
1841
|
+
*
|
|
1842
|
+
* #8135 (review): also delivers the SANITIZED full input as a
|
|
1843
|
+
* single-shot `tool_input_delta` right here, so the in-flight panel
|
|
1844
|
+
* lights up within milliseconds of the block finalizing — long
|
|
1845
|
+
* before the tool actually finishes executing (the #4341 client
|
|
1846
|
+
* fallback already renders whatever lands in `toolInputPartial`; one
|
|
1847
|
+
* complete-JSON chunk parses via `tryParseCompleteJson` exactly like
|
|
1848
|
+
* many partial ones would have). This REPLACES the raw per-chunk
|
|
1849
|
+
* `tool_input_delta` streaming `content_block_delta` used to do
|
|
1850
|
+
* (removed — see the comment there): a secret can straddle chunk
|
|
1851
|
+
* boundaries and mid-stream partial JSON can't be sanitized, so the
|
|
1852
|
+
* safe delivery point is "sanitize the complete parsed value, then
|
|
1853
|
+
* send it once."
|
|
1854
|
+
*
|
|
1855
|
+
* Best-effort and silent on failure: a JSON parse error (malformed
|
|
1856
|
+
* chunk) or an empty buffer (the overflow path already reset
|
|
1857
|
+
* `ctx.toolInputChunks` to `''` and told the user via the `error`
|
|
1858
|
+
* event emitted at accumulation time) simply skips both the backfill
|
|
1859
|
+
* and the delta — the tool_start entry's `input` stays `null` and the
|
|
1860
|
+
* client shows the "(input not received yet)" placeholder (#7346
|
|
1861
|
+
* direction 3) rather than a stale or fabricated value.
|
|
1862
|
+
*
|
|
1863
|
+
* @param {{ currentToolUseId: string|null, toolInputChunks: string }} ctx
|
|
1864
|
+
* @private
|
|
1865
|
+
*/
|
|
1866
|
+
_captureFinalizedToolInput(ctx) {
|
|
1867
|
+
const toolUseId = ctx.currentToolUseId
|
|
1868
|
+
if (!toolUseId || !ctx.toolInputChunks) return
|
|
1869
|
+
let parsed
|
|
1870
|
+
try {
|
|
1871
|
+
parsed = JSON.parse(ctx.toolInputChunks)
|
|
1872
|
+
} catch {
|
|
1873
|
+
// Malformed/truncated JSON — nothing to backfill or deliver.
|
|
1874
|
+
return
|
|
1875
|
+
}
|
|
1876
|
+
const sanitized = this._recordToolInput(toolUseId, parsed)
|
|
1877
|
+
// `null`/`undefined` means "known to have no input" (or the parse
|
|
1878
|
+
// above legitimately produced one of those) — the placeholder logic
|
|
1879
|
+
// covers that case on its own; don't ship a literal "null" chunk.
|
|
1880
|
+
if (sanitized === null || sanitized === undefined) return
|
|
1881
|
+
const messageId = this._currentMessageId
|
|
1882
|
+
if (!messageId) return
|
|
1883
|
+
this.emit('tool_input_delta', {
|
|
1884
|
+
messageId,
|
|
1885
|
+
toolUseId,
|
|
1886
|
+
partialJson: JSON.stringify(sanitized),
|
|
1887
|
+
})
|
|
1888
|
+
}
|
|
1889
|
+
|
|
1275
1890
|
/**
|
|
1276
1891
|
* Apply session-state side effects for tools whose accumulated
|
|
1277
1892
|
* `toolInputChunks` JSON drives plan-mode flags, agent tracking, or
|
|
@@ -1312,8 +1927,13 @@ export class CliSession extends BaseSession {
|
|
|
1312
1927
|
;(this._log || log).error(`Failed to parse AskUserQuestion input: ${err.message}`)
|
|
1313
1928
|
return
|
|
1314
1929
|
}
|
|
1315
|
-
|
|
1316
|
-
|
|
1930
|
+
// #7340: `Agent` alongside `Task` here too. Control flow is identical
|
|
1931
|
+
// either way (both `return`), so only the diagnostic differed -- which
|
|
1932
|
+
// is exactly how a roster gets fixed in three places and missed in the
|
|
1933
|
+
// fourth. A subagent spawn whose input failed to parse would have been
|
|
1934
|
+
// logged as a generic tool under the current tool name.
|
|
1935
|
+
if (toolName === 'Task' || toolName === 'Agent') {
|
|
1936
|
+
;(this._log || log).warn(`Failed to parse ${toolName} tool input: ${err.message}`)
|
|
1317
1937
|
return
|
|
1318
1938
|
}
|
|
1319
1939
|
if (toolName === 'ExitPlanMode') {
|
|
@@ -1337,6 +1957,8 @@ export class CliSession extends BaseSession {
|
|
|
1337
1957
|
// #4828: session-scoped.
|
|
1338
1958
|
;(this._log || log).info(`AskUserQuestion detected (${toolUseId})`)
|
|
1339
1959
|
this._waitingForAnswer = true
|
|
1960
|
+
// #7457 -- co-located with the flag (see the constructor).
|
|
1961
|
+
this._pendingQuestion = { toolUseId, questions: semantics.payload.questions ?? [] }
|
|
1340
1962
|
this.emit('user_question', {
|
|
1341
1963
|
toolUseId,
|
|
1342
1964
|
questions: semantics.payload.questions,
|
|
@@ -1345,13 +1967,19 @@ export class CliSession extends BaseSession {
|
|
|
1345
1967
|
}
|
|
1346
1968
|
case 'task': {
|
|
1347
1969
|
if (!parseSucceeded) return
|
|
1348
|
-
|
|
1970
|
+
// #7340: this records the MODEL'S REQUEST (`run_in_background`) into
|
|
1971
|
+
// `background`. It does NOT exempt the agent from the turn-end sweep —
|
|
1972
|
+
// `backgroundConfirmed` does, and only the CLI's own `task_started` can
|
|
1973
|
+
// set that. Exempting on an unconfirmed request would strand an agent
|
|
1974
|
+
// on a build that emits no task lifecycle events, because the same
|
|
1975
|
+
// event is what proves a terminal `task_notification` can arrive.
|
|
1976
|
+
// `task_started` may correct this value in EITHER direction;
|
|
1977
|
+
// `_trackAgent` upgrades rather than re-emits, so either order is fine.
|
|
1978
|
+
this._trackAgent({
|
|
1349
1979
|
toolUseId,
|
|
1350
1980
|
description: semantics.payload.description,
|
|
1351
|
-
|
|
1352
|
-
}
|
|
1353
|
-
this._activeAgents.set(toolUseId, agentInfo)
|
|
1354
|
-
this.emit('agent_spawned', agentInfo)
|
|
1981
|
+
background: semantics.payload.background,
|
|
1982
|
+
})
|
|
1355
1983
|
return
|
|
1356
1984
|
}
|
|
1357
1985
|
case 'enter_plan': {
|
|
@@ -1366,15 +1994,55 @@ export class CliSession extends BaseSession {
|
|
|
1366
1994
|
}
|
|
1367
1995
|
}
|
|
1368
1996
|
|
|
1997
|
+
/**
|
|
1998
|
+
* #7393 — the turn's reasoning streams, created on first use. Lives on the
|
|
1999
|
+
* per-turn `ctx` so it dies with the turn, and is built lazily so a ctx built
|
|
2000
|
+
* without it (tests, an older shape) still works.
|
|
2001
|
+
*/
|
|
2002
|
+
_thinkingStreams(ctx, messageId) {
|
|
2003
|
+
return (ctx.thinking ??= new ThinkingStreams((event, data) => this.emit(event, data), messageId))
|
|
2004
|
+
}
|
|
2005
|
+
|
|
2006
|
+
/**
|
|
2007
|
+
* #7393 — finish every open reasoning block of `ctx` and forget which of them
|
|
2008
|
+
* were `redacted_thinking`. The two must go together: a redacted block that
|
|
2009
|
+
* never got its stop would otherwise leave its index in the set, and a later
|
|
2010
|
+
* plain block at that index would be shown as the redacted marker.
|
|
2011
|
+
*/
|
|
2012
|
+
_closeThinking(ctx) {
|
|
2013
|
+
if (!ctx) return
|
|
2014
|
+
// A redacted block closes as the marker even when its stop never came.
|
|
2015
|
+
for (const key of ctx.redactedThinking ?? []) ctx.thinking?.close(key, { redacted: true })
|
|
2016
|
+
ctx.thinking?.closeAll()
|
|
2017
|
+
ctx.redactedThinking?.clear()
|
|
2018
|
+
}
|
|
2019
|
+
|
|
1369
2020
|
/**
|
|
1370
2021
|
* Clear per-message state, marking us as ready for the next message.
|
|
1371
2022
|
* After clearing, drains the next item from _pendingQueue (if any) so
|
|
1372
2023
|
* that all queued messages are eventually delivered in FIFO order.
|
|
1373
2024
|
*/
|
|
1374
|
-
|
|
1375
|
-
|
|
2025
|
+
// #7340: forward the opts to super. `turnEndedCleanly` decides whether a
|
|
2026
|
+
// confirmed-backgrounded subagent survives BaseSession's turn-end sweep;
|
|
2027
|
+
// an override that drops it silently disables the exemption.
|
|
2028
|
+
_clearMessageState(opts) {
|
|
2029
|
+
super._clearMessageState(opts)
|
|
1376
2030
|
this._waitingForAnswer = false
|
|
2031
|
+
this._pendingQuestion = null // #7457 -- co-located with the flag.
|
|
1377
2032
|
this._currentCtx = null
|
|
2033
|
+
// #7335: this is the ONE funnel every turn end passes through — the normal
|
|
2034
|
+
// `result`, the hard cap, the interrupt safety timeout, destroy() — and it
|
|
2035
|
+
// used to drop `_pendingPermissionIds` on the floor without telling anyone.
|
|
2036
|
+
// Expiring here rather than only at the individual death sites is the
|
|
2037
|
+
// difference between a guard wired to the callers someone remembered and
|
|
2038
|
+
// one wired to all of them (docs/false-safety-guards.md). Idempotent: a
|
|
2039
|
+
// no-op when the set is already empty, which it is on the paths that
|
|
2040
|
+
// expired explicitly moments earlier.
|
|
2041
|
+
// #7382: the expire itself moved to BaseSession._clearMessageState (called
|
|
2042
|
+
// by super above), so every provider inherits it rather than each wiring
|
|
2043
|
+
// its own. The explicit calls in _killAndRespawn / _handleChildClose stay:
|
|
2044
|
+
// both reach this funnel via _emitInterruptedTurnResult, which early-returns
|
|
2045
|
+
// when the session is not busy.
|
|
1378
2046
|
// Reset permission pause bookkeeping — the next message starts fresh.
|
|
1379
2047
|
this._pendingPermissionIds.clear()
|
|
1380
2048
|
this._resultTimeoutPaused = false
|
|
@@ -1411,14 +2079,7 @@ export class CliSession extends BaseSession {
|
|
|
1411
2079
|
if (this._outgoingQueue.length > 0) {
|
|
1412
2080
|
this.dequeueNextOutgoing()
|
|
1413
2081
|
} else if (this._pendingQueue.length > 0) {
|
|
1414
|
-
|
|
1415
|
-
if (this._destroying) return
|
|
1416
|
-
if (!this._processReady || this._pendingQueue.length === 0) return
|
|
1417
|
-
const pending = this._pendingQueue.shift()
|
|
1418
|
-
// #4828: session-scoped (post-result, post-init).
|
|
1419
|
-
;(this._log || log).info(`Dequeuing next pending message after result (${this._pendingQueue.length} remaining)`)
|
|
1420
|
-
this.sendMessage(pending.prompt, pending.attachments, pending.options || {})
|
|
1421
|
-
})
|
|
2082
|
+
this._drainNextPendingAfterResult()
|
|
1422
2083
|
}
|
|
1423
2084
|
}
|
|
1424
2085
|
}
|
|
@@ -1426,13 +2087,52 @@ export class CliSession extends BaseSession {
|
|
|
1426
2087
|
/**
|
|
1427
2088
|
* Kill the current child process (if any) and respawn.
|
|
1428
2089
|
* Suppresses auto-respawn during the kill, clears timers, and starts fresh.
|
|
2090
|
+
*
|
|
2091
|
+
* @param {string} [terminatedReason] #7376: why the turn is being ended
|
|
2092
|
+
* (`permission_mode_switch` / `model_switch`). Passed in by each caller
|
|
2093
|
+
* rather than inferred -- this is shared by the panic-button and a mid-turn
|
|
2094
|
+
* model change -- and stamped onto the synthetic `tool_result` of every tool
|
|
2095
|
+
* the dying turn left in flight.
|
|
1429
2096
|
*/
|
|
1430
|
-
_killAndRespawn() {
|
|
2097
|
+
_killAndRespawn(terminatedReason) {
|
|
2098
|
+
// #7335: retire the prompts the dying turn was blocked on BEFORE
|
|
2099
|
+
// _emitInterruptedTurnResult, which reaches _clearMessageState and wipes
|
|
2100
|
+
// `_pendingPermissionIds` silently. Ordering is the whole fix: after that
|
|
2101
|
+
// call there is nothing left to tell the client about, which is exactly
|
|
2102
|
+
// how the card ended up stranded live on screen with a dead Allow button.
|
|
2103
|
+
this._expirePendingPermissions('Permission request expired (the turn it belonged to was interrupted and the session restarted)')
|
|
2104
|
+
|
|
2105
|
+
// #7340: the child is about to be gone (or already is), and with it every
|
|
2106
|
+
// subagent it was running. `task_notification` -- the ONLY signal that
|
|
2107
|
+
// clears a confirmed-backgrounded agent now that the turn-end sweep spares
|
|
2108
|
+
// it -- can never arrive, so drain them here or the session claims to be
|
|
2109
|
+
// working for the rest of the daemon's life.
|
|
2110
|
+
//
|
|
2111
|
+
// Needs its OWN call for the same reason `_expirePendingPermissions` above
|
|
2112
|
+
// does (#7335): both reach the `_clearMessageState` funnel via
|
|
2113
|
+
// `_emitInterruptedTurnResult`, which early-returns when the session is not
|
|
2114
|
+
// busy -- and "not busy with a backgrounded agent still running" is the
|
|
2115
|
+
// exact state the exemption creates. Idempotent, and the funnel's own
|
|
2116
|
+
// unconditional sweep covers the busy case.
|
|
2117
|
+
this._completeAgents()
|
|
2118
|
+
|
|
2119
|
+
// #7611: the same child-is-going-away reasoning for background SHELLS.
|
|
2120
|
+
// `killProcessTree` below (since #7608) signals the child's whole descendant
|
|
2121
|
+
// tree, which includes the shells the agent started with
|
|
2122
|
+
// `run_in_background`, and nothing can poll or hear back from them after
|
|
2123
|
+
// this. Forget them here — before `_emitInterruptedTurnResult`, so a
|
|
2124
|
+
// listener of its `result` already sees the truthful `isRunning` — or the
|
|
2125
|
+
// tracker keeps the session 'running' (immune to the idle timeout) until the
|
|
2126
|
+
// 4 h hard-quiesce reap. NOT `_destroyPendingBackgroundShells`: that is the
|
|
2127
|
+
// end-of-session teardown and also drops the activity tree. A no-op for a
|
|
2128
|
+
// provider that tracks no shells.
|
|
2129
|
+
this._clearPendingBackgroundShells()
|
|
2130
|
+
|
|
1431
2131
|
// #4471: emit synthetic terminating events BEFORE setting _respawning,
|
|
1432
2132
|
// otherwise the _handleChildClose guard short-circuits and the dashboard
|
|
1433
2133
|
// never receives `agent_idle` — Stop stays stuck on panic-button +
|
|
1434
2134
|
// mid-turn setModel paths.
|
|
1435
|
-
this._emitInterruptedTurnResult()
|
|
2135
|
+
this._emitInterruptedTurnResult(0, terminatedReason)
|
|
1436
2136
|
|
|
1437
2137
|
this._respawning = true
|
|
1438
2138
|
this._processReady = false
|
|
@@ -1533,7 +2233,8 @@ export class CliSession extends BaseSession {
|
|
|
1533
2233
|
// shim wrapping a `.cmd` provider (claude/codex/…); the real node
|
|
1534
2234
|
// grandchild is orphaned and the wrapper's `close` above then cancels the
|
|
1535
2235
|
// forceKill escalation before it can fire. killProcessTree reaps the whole
|
|
1536
|
-
// tree
|
|
2236
|
+
// tree — since #7606 on POSIX too (graceful SIGTERM to every descendant,
|
|
2237
|
+
// enumerated before the child is signalled).
|
|
1537
2238
|
killProcessTree(oldChild)
|
|
1538
2239
|
} else {
|
|
1539
2240
|
this._respawning = false
|
|
@@ -1564,18 +2265,181 @@ export class CliSession extends BaseSession {
|
|
|
1564
2265
|
_onModelChanged() {
|
|
1565
2266
|
// #4828: session-scoped if init has fired before the model change.
|
|
1566
2267
|
;(this._log || log).info(`Model changed to ${this.model || 'default'}, restarting process`)
|
|
1567
|
-
this._killAndRespawn()
|
|
2268
|
+
this._killAndRespawn('model_switch')
|
|
2269
|
+
}
|
|
2270
|
+
|
|
2271
|
+
/**
|
|
2272
|
+
* Base dir for the per-session permission-mode sidecar dirs (#7337).
|
|
2273
|
+
* Exposed so the boot sweep and its tests name it once.
|
|
2274
|
+
*/
|
|
2275
|
+
static get PERMISSION_MODE_SIDECAR_BASE() { return join(tmpdir(), 'chroxy-claude-cli') }
|
|
2276
|
+
|
|
2277
|
+
/**
|
|
2278
|
+
* #7337: boot-time sweep of sidecar dirs orphaned by a crash. destroy()
|
|
2279
|
+
* removes a session's own dir, but a SIGKILL leaks it, so a long-lived host
|
|
2280
|
+
* accumulates one per crashed session. Same ownership rule as the claude-tui
|
|
2281
|
+
* sink sweep and the same implementation — only dirs whose `owner.pid` is
|
|
2282
|
+
* DEAD are removed, so a live daemon's dirs (including this one's) are kept
|
|
2283
|
+
* and the sweep is safe to run unconditionally at boot.
|
|
2284
|
+
*
|
|
2285
|
+
* @param {object} [logger] - logger with info/warn (defaults to module log)
|
|
2286
|
+
* @returns {{swept:number, kept:number}}
|
|
2287
|
+
*/
|
|
2288
|
+
static sweepStaleSidecarDirs(logger = log) {
|
|
2289
|
+
return sweepStaleOwnedDirs(CliSession.PERMISSION_MODE_SIDECAR_BASE, {
|
|
2290
|
+
logger,
|
|
2291
|
+
label: 'claude-cli permission-mode sidecar',
|
|
2292
|
+
})
|
|
2293
|
+
}
|
|
2294
|
+
|
|
2295
|
+
/**
|
|
2296
|
+
* #7337: create the re-readable permission-mode sidecar and seed it with the
|
|
2297
|
+
* session's current mode. Idempotent — a respawn calls start() again and must
|
|
2298
|
+
* keep the SAME path, because the sidecar the still-draining old child holds
|
|
2299
|
+
* in its env has to stay valid until that child is gone.
|
|
2300
|
+
*
|
|
2301
|
+
* Only meaningful when permissions are enabled: with no port there is no hook
|
|
2302
|
+
* endpoint, so `permission-hook.sh` never runs and the mode is moot. A failed
|
|
2303
|
+
* initial write leaves `_permissionModeFile` null and the session falls back
|
|
2304
|
+
* to env-var-only mode — losing the ability to hot-swap the mode is bad, but
|
|
2305
|
+
* failing session start over a /tmp write is worse (same trade ClaudeTuiSession
|
|
2306
|
+
* makes at #4013).
|
|
2307
|
+
*/
|
|
2308
|
+
_ensurePermissionModeSidecar() {
|
|
2309
|
+
if (!this._port) return
|
|
2310
|
+
const mode = this.permissionMode || 'approve'
|
|
2311
|
+
|
|
2312
|
+
// Re-seed on EVERY start(), not only the first. The path is kept stable
|
|
2313
|
+
// across a respawn (a still-draining old child holds it in its env), but
|
|
2314
|
+
// the CONTENTS must be re-asserted, because the file outranks the env var
|
|
2315
|
+
// in the hook's resolution order. Without this, a mid-session write that
|
|
2316
|
+
// failed (ENOSPC / EROFS / EIO) left the sidecar holding the OLD mode while
|
|
2317
|
+
// the respawned child carried the NEW one in CHROXY_PERMISSION_MODE — and
|
|
2318
|
+
// the hook read the file. A tighten to `approve` would then keep
|
|
2319
|
+
// auto-allowing for the rest of the session while the daemon, the state
|
|
2320
|
+
// file and the UI all said `approve`. The respawn was documented as the
|
|
2321
|
+
// repair and was not one.
|
|
2322
|
+
if (this._permissionModeFile) {
|
|
2323
|
+
try {
|
|
2324
|
+
writePermissionModeSidecarAtomic(this._permissionModeFile, mode)
|
|
2325
|
+
return
|
|
2326
|
+
} catch (err) {
|
|
2327
|
+
// The existing file is now untrustworthy — and a stale file is WORSE
|
|
2328
|
+
// than none, because it outranks the correct env var. Drop it so the
|
|
2329
|
+
// hook falls back to CHROXY_PERMISSION_MODE, then try a fresh dir below.
|
|
2330
|
+
;(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`)
|
|
2331
|
+
this._cleanupPermissionModeSidecar()
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
|
|
2335
|
+
let dir = null
|
|
2336
|
+
try {
|
|
2337
|
+
const base = ensureOwnedBaseDir(CliSession.PERMISSION_MODE_SIDECAR_BASE)
|
|
2338
|
+
dir = join(base, `s-${randomUUID()}`)
|
|
2339
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
2340
|
+
// Stamp the owning pid so the boot-time sweep can tell a live daemon's
|
|
2341
|
+
// dir from one orphaned by a crash. Best-effort: a missing pidfile just
|
|
2342
|
+
// makes the dir sweep-eligible after a grace window, which is the safe
|
|
2343
|
+
// default for an orphan.
|
|
2344
|
+
try { writeFileSync(join(dir, OWNER_PID_FILE), String(process.pid)) } catch { /* best effort */ }
|
|
2345
|
+
const path = join(dir, 'permission-mode')
|
|
2346
|
+
writePermissionModeSidecarAtomic(path, mode)
|
|
2347
|
+
this._permissionModeDir = dir
|
|
2348
|
+
this._permissionModeFile = path
|
|
2349
|
+
} catch (err) {
|
|
2350
|
+
// Remove the dir we just created, if we got that far — otherwise a
|
|
2351
|
+
// persistent write failure leaks one dir per respawn, and because
|
|
2352
|
+
// owner.pid names this LIVE daemon the boot sweep keeps every one of
|
|
2353
|
+
// them for the daemon's whole lifetime.
|
|
2354
|
+
if (dir) { try { rmSync(dir, { recursive: true, force: true }) } catch { /* best effort */ } }
|
|
2355
|
+
;(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`)
|
|
2356
|
+
this._permissionModeFile = null
|
|
2357
|
+
this._permissionModeDir = null
|
|
2358
|
+
}
|
|
2359
|
+
}
|
|
2360
|
+
|
|
2361
|
+
/** Remove the sidecar dir created by _ensurePermissionModeSidecar. */
|
|
2362
|
+
_cleanupPermissionModeSidecar() {
|
|
2363
|
+
if (this._permissionModeDir) {
|
|
2364
|
+
try { rmSync(this._permissionModeDir, { recursive: true, force: true }) }
|
|
2365
|
+
catch (err) { (this._log || log).warn(`permission-mode sidecar cleanup failed: ${err.message}`) }
|
|
2366
|
+
}
|
|
2367
|
+
this._permissionModeDir = null
|
|
2368
|
+
this._permissionModeFile = null
|
|
1568
2369
|
}
|
|
1569
2370
|
|
|
1570
2371
|
_onPermissionModeChanged(mode) {
|
|
2372
|
+
// #7337: publish to the sidecar FIRST. `permission-hook.sh` prefers the
|
|
2373
|
+
// file over CHROXY_PERMISSION_MODE and re-reads it on every tool call, so
|
|
2374
|
+
// this takes effect immediately — including for the child that is still
|
|
2375
|
+
// alive right now. Without it the only channel was the respawn below, which
|
|
2376
|
+
// does not land until the old child's `close` fires (up to the 10s
|
|
2377
|
+
// force-kill grace in _killAndRespawn), and every PreToolUse hook that old
|
|
2378
|
+
// child raises in the meantime resolves the STALE mode. That is #7337: a
|
|
2379
|
+
// Bash approval card on a session whose state file already read `"auto"`.
|
|
2380
|
+
if (this._permissionModeFile) {
|
|
2381
|
+
try {
|
|
2382
|
+
writePermissionModeSidecarAtomic(this._permissionModeFile, mode)
|
|
2383
|
+
} catch (err) {
|
|
2384
|
+
// Hook precedence is file -> env var, so a sidecar left holding the
|
|
2385
|
+
// PREVIOUS mode outranks the correct value in CHROXY_PERMISSION_MODE —
|
|
2386
|
+
// and on a TIGHTEN that is fail-open. Remove it rather than leave it:
|
|
2387
|
+
// the hook then falls back to the env var, and start()'s re-seed
|
|
2388
|
+
// rebuilds a fresh sidecar on the respawn below. Leaving it in place
|
|
2389
|
+
// pinned the old mode for the whole session.
|
|
2390
|
+
;(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`)
|
|
2391
|
+
this._cleanupPermissionModeSidecar()
|
|
2392
|
+
}
|
|
2393
|
+
}
|
|
2394
|
+
|
|
1571
2395
|
// #3729 panic-button semantics: BaseSession.setPermissionMode lets `'auto'`
|
|
1572
2396
|
// bypass the `_isBusy` guard, so flipping to auto mid-turn IS destructive —
|
|
1573
2397
|
// the in-flight `claude -p` process is killed and respawned, dropping the
|
|
1574
2398
|
// current turn. This is by design (parity with SDK auto-resolve of pending
|
|
1575
|
-
// prompts); see #3735 for the regression test pinning this behavior.
|
|
2399
|
+
// prompts); see #3735 for the regression test pinning this behavior. The
|
|
2400
|
+
// respawn is still required for the OTHER mode channel: `--permission-mode
|
|
2401
|
+
// bypassPermissions` / `plan` is argv, not env, so only a new process picks
|
|
2402
|
+
// it up (buildClaudeCliArgs). The sidecar covers the hook; the respawn
|
|
2403
|
+
// covers claude's own flag.
|
|
1576
2404
|
// #4828: session-scoped if init has fired.
|
|
1577
2405
|
;(this._log || log).info(`Permission mode changed to ${mode}, restarting process`)
|
|
1578
|
-
this._killAndRespawn()
|
|
2406
|
+
this._killAndRespawn('permission_mode_switch')
|
|
2407
|
+
}
|
|
2408
|
+
|
|
2409
|
+
getRestartBlockers() {
|
|
2410
|
+
const reasons = super.getRestartBlockers()
|
|
2411
|
+
// Messages acknowledged as `queued` while the CLI child warms up or
|
|
2412
|
+
// respawns live here, NOT in `_outgoingQueue` (see sendMessage's
|
|
2413
|
+
// `!_processReady` branch) — a restart would drop them (#8324).
|
|
2414
|
+
const pending = this._pendingQueue.length
|
|
2415
|
+
if (pending > 0) reasons.push(`${pending} message(s) queued while the CLI is not ready`)
|
|
2416
|
+
return reasons
|
|
2417
|
+
}
|
|
2418
|
+
|
|
2419
|
+
/**
|
|
2420
|
+
* #7457 -- the AskUserQuestion this child is parked on stdin for, if any.
|
|
2421
|
+
*
|
|
2422
|
+
* A read-through of `_pendingQuestion`, which is written and cleared in the
|
|
2423
|
+
* same statement block as `_waitingForAnswer` at every one of that flag's
|
|
2424
|
+
* four sites -- construction, the emit, the `_clearMessageState` turn-end
|
|
2425
|
+
* funnel ("the ONE funnel every turn end passes through": normal `result`,
|
|
2426
|
+
* hard cap, interrupt safety timeout, destroy) and `respondToQuestion`. So it
|
|
2427
|
+
* cannot report a question the child has stopped waiting on.
|
|
2428
|
+
*
|
|
2429
|
+
* It reads `_pendingQuestion` ALONE and does not re-check `_waitingForAnswer`.
|
|
2430
|
+
* The two are set and cleared together, so the extra clause could never
|
|
2431
|
+
* change an answer -- and it would make every one of those null-outs
|
|
2432
|
+
* unfalsifiable, since the flag would mask a leaked payload
|
|
2433
|
+
* (docs/false-safety-guards.md: a guard whose only two states are green).
|
|
2434
|
+
* `tests/pending-question-resend.test.js` asserts the co-location mechanically
|
|
2435
|
+
* rather than trusting this paragraph.
|
|
2436
|
+
*
|
|
2437
|
+
* @returns {{ toolUseId: string, questions: object[] }[]}
|
|
2438
|
+
*/
|
|
2439
|
+
getPendingQuestions() {
|
|
2440
|
+
const pending = this._pendingQuestion
|
|
2441
|
+
if (!pending) return []
|
|
2442
|
+
return [{ toolUseId: pending.toolUseId, questions: pending.questions }]
|
|
1579
2443
|
}
|
|
1580
2444
|
|
|
1581
2445
|
/**
|
|
@@ -1586,6 +2450,7 @@ export class CliSession extends BaseSession {
|
|
|
1586
2450
|
respondToQuestion(text) {
|
|
1587
2451
|
if (!this._child || !this._waitingForAnswer) return
|
|
1588
2452
|
this._waitingForAnswer = false
|
|
2453
|
+
this._pendingQuestion = null // #7457 -- co-located with the flag.
|
|
1589
2454
|
const ndjson = JSON.stringify({
|
|
1590
2455
|
type: 'user',
|
|
1591
2456
|
message: {
|
|
@@ -1606,15 +2471,25 @@ export class CliSession extends BaseSession {
|
|
|
1606
2471
|
// the dashboard's streamingMessageId/isIdle. Without it, an interrupted
|
|
1607
2472
|
// turn leaves Stop stuck visible and "Thinking…" permanent.
|
|
1608
2473
|
// Mirrors TUI #4010. cost:null skips session-manager billing.
|
|
1609
|
-
|
|
2474
|
+
//
|
|
2475
|
+
// #7376: `terminatedReason` says WHY, so the tools this turn left in flight
|
|
2476
|
+
// are reported as "the turn was terminated under it" rather than as failed
|
|
2477
|
+
// commands. Supplied by each caller -- this is shared by the panic-button,
|
|
2478
|
+
// mid-turn setModel, Stop, a crash and both watchdogs -- and never inferred.
|
|
2479
|
+
// #9241: `stopSignal` is the caller's word that the Stop is why the turn ended: a real
|
|
2480
|
+
// child close after it. The 5 s safety timer does NOT give it (the child may still be
|
|
2481
|
+
// running and answer), and the stall / hard-timeout watchdogs never did.
|
|
2482
|
+
_emitInterruptedTurnResult(duration = 0, terminatedReason, { stopSignal = false } = {}) {
|
|
1610
2483
|
if (!this._isBusy || !this._currentMessageId) return
|
|
1611
2484
|
const messageId = this._currentMessageId
|
|
1612
2485
|
const sessionId = this._sessionId
|
|
2486
|
+
this._closeThinking(this._currentCtx) // #7393
|
|
1613
2487
|
if (this._currentCtx?.hasStreamStarted) {
|
|
1614
2488
|
this.emit('stream_end', { messageId })
|
|
1615
2489
|
}
|
|
1616
|
-
this._clearMessageState()
|
|
1617
|
-
|
|
2490
|
+
this._clearMessageState({ terminatedReason })
|
|
2491
|
+
// #7072: terminal but not a completed turn (internal; not on the wire).
|
|
2492
|
+
this.emit('result', { cost: null, duration, usage: null, sessionId, interrupted: true, ...(stopSignal ? { stopRequested: true } : {}) })
|
|
1618
2493
|
}
|
|
1619
2494
|
|
|
1620
2495
|
_handleChildClose(code) {
|
|
@@ -1643,7 +2518,34 @@ export class CliSession extends BaseSession {
|
|
|
1643
2518
|
if (this._destroying) return
|
|
1644
2519
|
if (this._respawning) return
|
|
1645
2520
|
|
|
1646
|
-
|
|
2521
|
+
// #7335: the child is gone, so every PreToolUse hook it had blocked on
|
|
2522
|
+
// died with it and its prompt can never be answered — same stranded card
|
|
2523
|
+
// as the respawn path, reached a different way. This covers a crash AND a
|
|
2524
|
+
// user Stop (interrupt() → SIGINT → the child exits here, NOT through
|
|
2525
|
+
// _killAndRespawn). Before _emitInterruptedTurnResult for the same reason:
|
|
2526
|
+
// that call reaches _clearMessageState, which drops the ids silently.
|
|
2527
|
+
//
|
|
2528
|
+
// The respawn path already expired them and set `_respawning`, so the
|
|
2529
|
+
// close it causes returns above — no double emit; pinned by a test.
|
|
2530
|
+
this._expirePendingPermissions('Permission request expired (the session process exited before it could be answered)')
|
|
2531
|
+
|
|
2532
|
+
// #7340: the child is about to be gone (or already is), and with it every
|
|
2533
|
+
// subagent it was running. `task_notification` -- the ONLY signal that
|
|
2534
|
+
// clears a confirmed-backgrounded agent now that the turn-end sweep spares
|
|
2535
|
+
// it -- can never arrive, so drain them here or the session claims to be
|
|
2536
|
+
// working for the rest of the daemon's life.
|
|
2537
|
+
//
|
|
2538
|
+
// Needs its OWN call for the same reason `_expirePendingPermissions` above
|
|
2539
|
+
// does (#7335): both reach the `_clearMessageState` funnel via
|
|
2540
|
+
// `_emitInterruptedTurnResult`, which early-returns when the session is not
|
|
2541
|
+
// busy -- and "not busy with a backgrounded agent still running" is the
|
|
2542
|
+
// exact state the exemption creates. Idempotent, and the funnel's own
|
|
2543
|
+
// unconditional sweep covers the busy case.
|
|
2544
|
+
this._completeAgents()
|
|
2545
|
+
|
|
2546
|
+
// #7376: Stop (SIGINT -> the child exits here) and a crash both reach this
|
|
2547
|
+
// point; the tools they leave in flight are worded differently.
|
|
2548
|
+
this._emitInterruptedTurnResult(0, wasIntentionalStop ? 'user_stop' : 'process_exit', { stopSignal: wasIntentionalStop })
|
|
1647
2549
|
|
|
1648
2550
|
// #4602: user-initiated Stop sent SIGINT via interrupt(). The child
|
|
1649
2551
|
// exited cleanly as a result — do NOT show "exited unexpectedly" and
|
|
@@ -1651,7 +2553,13 @@ export class CliSession extends BaseSession {
|
|
|
1651
2553
|
if (wasIntentionalStop) {
|
|
1652
2554
|
// #4828: session-scoped if init had fired before the stop.
|
|
1653
2555
|
;(this._log || log).info(`Process exited (code ${code}) after user stop`)
|
|
1654
|
-
this
|
|
2556
|
+
// #7438: NOT a respawn — the user asked for this child to stop and it
|
|
2557
|
+
// stays stopped. This only records that the session is stoppable-but-
|
|
2558
|
+
// revivable, so the next sendMessage can bring it back (see
|
|
2559
|
+
// _restartAfterStop). Stop halts the turn; it must not end the session's
|
|
2560
|
+
// ability to answer the follow-up.
|
|
2561
|
+
this._stoppedByUser = true
|
|
2562
|
+
this.emit('stopped', { code, stopRequested: true }) // #9241
|
|
1655
2563
|
return
|
|
1656
2564
|
}
|
|
1657
2565
|
|
|
@@ -1750,12 +2658,181 @@ export class CliSession extends BaseSession {
|
|
|
1750
2658
|
return
|
|
1751
2659
|
}
|
|
1752
2660
|
|
|
2661
|
+
// #7599: give a containerized subclass a chance to classify this exit as a
|
|
2662
|
+
// vanished container (a distinct, non-respawnable-but-recoverable state)
|
|
2663
|
+
// BEFORE the generic crash→respawn path. Reached only for a genuine
|
|
2664
|
+
// unexpected exit — the intentional-stop and resume-unknown branches above
|
|
2665
|
+
// have already returned. Base returns false synchronously (no behavior
|
|
2666
|
+
// change for host sessions); DockerSession returns a Promise that PROBES the
|
|
2667
|
+
// container, so the generic respawn is DEFERRED until the probe resolves and
|
|
2668
|
+
// skipped entirely on a confirmed vanish.
|
|
2669
|
+
const maybeVanish = this._handleContainerGoneOnClose(code)
|
|
2670
|
+
if (maybeVanish && typeof maybeVanish.then === 'function') {
|
|
2671
|
+
maybeVanish.then((handled) => {
|
|
2672
|
+
if (!handled && !this._destroying) this._respawnAfterUnexpectedClose(code)
|
|
2673
|
+
})
|
|
2674
|
+
return
|
|
2675
|
+
}
|
|
2676
|
+
if (maybeVanish) return
|
|
2677
|
+
this._respawnAfterUnexpectedClose(code)
|
|
2678
|
+
}
|
|
2679
|
+
|
|
2680
|
+
/**
|
|
2681
|
+
* #7599 — hook for a containerized subclass to intercept a child-close it can
|
|
2682
|
+
* attribute to its container vanishing, before the generic respawn. The base
|
|
2683
|
+
* host-CLI session has no container, so it never intercepts (returns false
|
|
2684
|
+
* synchronously — the generic respawn then runs inline as before).
|
|
2685
|
+
*
|
|
2686
|
+
* @param {number} _code exit code of the closed child
|
|
2687
|
+
* @returns {boolean|Promise<boolean>} true to suppress the generic crash→respawn
|
|
2688
|
+
*/
|
|
2689
|
+
_handleContainerGoneOnClose(_code) {
|
|
2690
|
+
return false
|
|
2691
|
+
}
|
|
2692
|
+
|
|
2693
|
+
/** #7599 — the generic "exited unexpectedly → restart" tail, extracted so the
|
|
2694
|
+
* container-vanish hook can defer or skip it. */
|
|
2695
|
+
_respawnAfterUnexpectedClose(code) {
|
|
1753
2696
|
// #4828: session-scoped if init had fired.
|
|
1754
2697
|
;(this._log || log).info(`Process exited (code ${code}), scheduling respawn`)
|
|
1755
2698
|
this.emit('error', { message: 'Claude process exited unexpectedly, restarting...' })
|
|
1756
2699
|
this._scheduleRespawn()
|
|
1757
2700
|
}
|
|
1758
2701
|
|
|
2702
|
+
/**
|
|
2703
|
+
* #7438 — restart-on-next-input for a session the user Stopped.
|
|
2704
|
+
*
|
|
2705
|
+
* Stop (interrupt → SIGINT → child exits) deliberately does NOT respawn
|
|
2706
|
+
* (#4602): respawning at stop time fights the thing the user just asked for.
|
|
2707
|
+
* But nothing else restarted the child either, so the next sendMessage hit
|
|
2708
|
+
* the `!_processReady` branch, pushed into `_pendingQueue` — and stranded
|
|
2709
|
+
* there forever, because the queue only drains on a start() warmup or after a
|
|
2710
|
+
* `result`, and with no child neither can ever fire. The follow-up was
|
|
2711
|
+
* silently eaten and the 4th one discarded outright ("queue full"). Stop
|
|
2712
|
+
* ended the conversation instead of interrupting a turn.
|
|
2713
|
+
*
|
|
2714
|
+
* So the respawn is lazy: it happens here, when the user actually asks for
|
|
2715
|
+
* more work. start() passes `--resume this._sessionId`, so the new child
|
|
2716
|
+
* re-attaches to the SAME claude conversation rather than starting cold, and
|
|
2717
|
+
* its warmup drain delivers the queued message.
|
|
2718
|
+
*
|
|
2719
|
+
* Gated on `_stoppedByUser` rather than on the broader "there is no child",
|
|
2720
|
+
* deliberately: every OTHER way to lose a child either already owns its own
|
|
2721
|
+
* restart (a crash schedules a backoff respawn; a model switch runs
|
|
2722
|
+
* _killAndRespawn) or is a considered terminal give-up — the respawn cap, the
|
|
2723
|
+
* rate cap, `resume_unknown_exhausted`. Typing into one of those must not
|
|
2724
|
+
* re-arm a flapping session behind the cap that just stopped it.
|
|
2725
|
+
*
|
|
2726
|
+
* #8038: ALSO fires on `_spawnRefusal` — a binary-gate refusal (model
|
|
2727
|
+
* switch / permission-mode change / crash respawn the gate rejected) is
|
|
2728
|
+
* revivable in exactly the same "nothing else will bring this child back"
|
|
2729
|
+
* sense a user Stop is, unlike the terminal give-ups listed above: the gate
|
|
2730
|
+
* refused a SPECIFIC verdict (this binary, right now), and a later input
|
|
2731
|
+
* is a legitimate reason to ask it again (the operator may have restored
|
|
2732
|
+
* the ledger, re-approved the hash, fixed the quarantine, …). Both flags
|
|
2733
|
+
* share this one restart path rather than two near-identical copies.
|
|
2734
|
+
*/
|
|
2735
|
+
_restartAfterStop() {
|
|
2736
|
+
if (!this._stoppedByUser && !this._spawnRefusal) return
|
|
2737
|
+
// #9267: no restart of OURS is coming in these three, so a pending drain-first flag
|
|
2738
|
+
// must not be left for another respawn's warmup to consume.
|
|
2739
|
+
if (this._destroying || this._respawning || this._respawnScheduled) {
|
|
2740
|
+
this._drainOutgoingFirst = false
|
|
2741
|
+
return
|
|
2742
|
+
}
|
|
2743
|
+
// A child already exists — whoever spawned it owns the warmup drain.
|
|
2744
|
+
if (this._child) return
|
|
2745
|
+
|
|
2746
|
+
;(this._log || log).info(this._spawnRefusal
|
|
2747
|
+
? 'Re-running the binary gate to restart claude for a new message (its last spawn was refused)'
|
|
2748
|
+
: 'Restarting the stopped claude process to deliver a new message')
|
|
2749
|
+
// Consume the latches BEFORE starting, not inside start(): DockerSession
|
|
2750
|
+
// overrides start() and defers super.start() behind an async container
|
|
2751
|
+
// launch, so a second message arriving in that window would otherwise see
|
|
2752
|
+
// `_stoppedByUser` still armed and no child yet, and start a SECOND
|
|
2753
|
+
// container. Single-shot here makes the restart at-most-once regardless of
|
|
2754
|
+
// what a subclass's start() does or how long it takes.
|
|
2755
|
+
this._stoppedByUser = false
|
|
2756
|
+
// #8038: the refusal latch is consumed too. The gate re-runs inside start()
|
|
2757
|
+
// and re-latches only if it refuses AGAIN; left armed, a synchronous throw
|
|
2758
|
+
// from elsewhere in start() would get this input rejected under the
|
|
2759
|
+
// previous refusal's code instead of its own error.
|
|
2760
|
+
this._spawnRefusal = null
|
|
2761
|
+
try {
|
|
2762
|
+
this.start()
|
|
2763
|
+
if (this._spawnRefusal) this._drainOutgoingFirst = false // the gate refused: no child is coming
|
|
2764
|
+
} catch (err) {
|
|
2765
|
+
this._drainOutgoingFirst = false
|
|
2766
|
+
// Re-arm the latch: start() threw synchronously (spawn/arg failure) BEFORE
|
|
2767
|
+
// any child or container launch, so nothing was started. Without this the
|
|
2768
|
+
// latch stays consumed and the next sendMessage would only enqueue — never
|
|
2769
|
+
// retry the restart — re-stranding the follow-up behind a start-time error
|
|
2770
|
+
// (the exact #7438 failure mode). Re-arming lets the next user input retry;
|
|
2771
|
+
// it is not a loop — a retry only happens on a fresh send. It is re-armed
|
|
2772
|
+
// for a refusal-triggered restart as well (#8038): a gate refusal never
|
|
2773
|
+
// throws (_spawnPersistentProcess latches it and returns), so reaching
|
|
2774
|
+
// here means a DIFFERENT failure, and `_stoppedByUser` is the latch that
|
|
2775
|
+
// keeps a childless session revivable whatever took its child away.
|
|
2776
|
+
this._stoppedByUser = true
|
|
2777
|
+
;(this._log || log).error(`Restart on new input failed: ${err.message}`)
|
|
2778
|
+
this.emit('error', { message: `Failed to restart the Claude process: ${err.message}` })
|
|
2779
|
+
}
|
|
2780
|
+
}
|
|
2781
|
+
|
|
2782
|
+
/**
|
|
2783
|
+
* #9267: the Stop safety timer fired and the child had not answered SIGINT.
|
|
2784
|
+
* The turn is being reported as stopped, so the child is abandoned like a
|
|
2785
|
+
* respawn abandons one, minus the immediate respawn: its readlines are closed,
|
|
2786
|
+
* it stops being `_child` (so its stdout lines and its eventual `close` are
|
|
2787
|
+
* ignored -- no second result, no stop marker, no "exited unexpectedly"), its
|
|
2788
|
+
* tree is SIGTERMed, and the session is left as a Stop leaves it, revivable by
|
|
2789
|
+
* the next send (`_stoppedByUser`).
|
|
2790
|
+
*
|
|
2791
|
+
* The tree is recorded BEFORE the signal (pid + start time) and kept in
|
|
2792
|
+
* `_retiredChildren` until the escalation, so it still gets SIGKILLed when
|
|
2793
|
+
* the parent exits on SIGTERM but a descendant does not, and so `destroy()`
|
|
2794
|
+
* can reach it although `_child` no longer points at it. Recorded descendants
|
|
2795
|
+
* are signalled only while their start time still matches (never a recycled
|
|
2796
|
+
* pid), and the escalation is NOT cancelled by the parent's close.
|
|
2797
|
+
*/
|
|
2798
|
+
_retireUnresponsiveChild(child) {
|
|
2799
|
+
this._cleanupReadlines()
|
|
2800
|
+
this._processReady = false
|
|
2801
|
+
this._child = null
|
|
2802
|
+
this._stoppedByUser = true
|
|
2803
|
+
;(this._log || log).warn('Retiring the claude process that ignored the Stop signal; the next message starts a fresh one')
|
|
2804
|
+
this._expirePendingPermissions('Permission request expired (the session process was stopped before it could be answered)')
|
|
2805
|
+
this._completeAgents()
|
|
2806
|
+
this._clearPendingBackgroundShells() // the shells died with the child, as on a respawn
|
|
2807
|
+
const entry = { child, recorded: this._recordChildTree(child), timer: null }
|
|
2808
|
+
this._retiredChildren.add(entry)
|
|
2809
|
+
entry.timer = setTimeout(() => {
|
|
2810
|
+
this._retiredChildren.delete(entry)
|
|
2811
|
+
try { this._killChildTree(child, { force: true, recorded: entry.recorded, handleOnly: true }) } catch {}
|
|
2812
|
+
}, 3000)
|
|
2813
|
+
if (typeof entry.timer.unref === 'function') entry.timer.unref()
|
|
2814
|
+
this._killChildTree(child, { recorded: entry.recorded })
|
|
2815
|
+
}
|
|
2816
|
+
|
|
2817
|
+
/** #9267: snapshot the tree to reap (a seam: `_treeDeps` carries the ps stubs). */
|
|
2818
|
+
_recordChildTree(child) {
|
|
2819
|
+
try {
|
|
2820
|
+
return recordProcessTree(child, this._treeDeps)
|
|
2821
|
+
} catch (err) {
|
|
2822
|
+
;(this._log || log).warn(`Could not record the retired child's process tree: ${err.message}`)
|
|
2823
|
+
return [] // fail safe: the handle-only kill still runs
|
|
2824
|
+
}
|
|
2825
|
+
}
|
|
2826
|
+
|
|
2827
|
+
/**
|
|
2828
|
+
* #9267: the one seam for signalling a retired child's process tree. Defaults
|
|
2829
|
+
* to the platform helper; tests whose mock child carries a numeric pid inject
|
|
2830
|
+
* `_treeDeps` (or override this) so no real process is enumerated or signalled.
|
|
2831
|
+
*/
|
|
2832
|
+
_killChildTree(child, { force = false, recorded = [], handleOnly = false } = {}) {
|
|
2833
|
+
killRecordedTree(child, recorded, { force, handleOnly, ...this._treeDeps })
|
|
2834
|
+
}
|
|
2835
|
+
|
|
1759
2836
|
/** Interrupt the current message (send SIGINT to child process) */
|
|
1760
2837
|
interrupt() {
|
|
1761
2838
|
// #5936: a deliberate Stop cancels the owner's queued follow-ups (cancel,
|
|
@@ -1765,6 +2842,15 @@ export class CliSession extends BaseSession {
|
|
|
1765
2842
|
// never stranded.
|
|
1766
2843
|
this.clearOutgoingQueue()
|
|
1767
2844
|
|
|
2845
|
+
// A Stop while a start is still verifying the folder: that start never launches, and
|
|
2846
|
+
// the session is left as a Stop leaves it, revivable by the next send.
|
|
2847
|
+
if (this._pendingStartGen !== null && this._pendingStartGen !== undefined) {
|
|
2848
|
+
this._pendingStartGen = null
|
|
2849
|
+
this._startGen = (this._startGen || 0) + 1
|
|
2850
|
+
this._stoppedByUser = true
|
|
2851
|
+
return
|
|
2852
|
+
}
|
|
2853
|
+
|
|
1768
2854
|
if (!this._child) return
|
|
1769
2855
|
|
|
1770
2856
|
// #4602: mark the imminent child exit as user-initiated so
|
|
@@ -1773,6 +2859,7 @@ export class CliSession extends BaseSession {
|
|
|
1773
2859
|
// current turn), the next natural exit will be a real crash — the flag
|
|
1774
2860
|
// is cleared in _handleChildClose on whichever exit fires first.
|
|
1775
2861
|
this.markIntentionalStop()
|
|
2862
|
+
this._noteTurnStopRequested() // #7376
|
|
1776
2863
|
|
|
1777
2864
|
// #4828: session-scoped if init has fired.
|
|
1778
2865
|
;(this._log || log).info('Sending SIGINT to claude process')
|
|
@@ -1785,6 +2872,7 @@ export class CliSession extends BaseSession {
|
|
|
1785
2872
|
clearTimeout(this._interruptTimer)
|
|
1786
2873
|
this._interruptTimer = null
|
|
1787
2874
|
}
|
|
2875
|
+
const interruptedChild = this._child
|
|
1788
2876
|
this._interruptTimer = setTimeout(() => {
|
|
1789
2877
|
this._interruptTimer = null
|
|
1790
2878
|
// #4602: if the child survived SIGINT (claude only aborted the turn),
|
|
@@ -1794,7 +2882,23 @@ export class CliSession extends BaseSession {
|
|
|
1794
2882
|
if (this._isBusy) {
|
|
1795
2883
|
// #4828: session-scoped.
|
|
1796
2884
|
;(this._log || log).warn('Interrupt safety timeout — force-clearing busy state')
|
|
1797
|
-
|
|
2885
|
+
// #9267: the child ignored SIGINT and the turn is being reported as
|
|
2886
|
+
// stopped. Retire THAT child first, so nothing it says later can grow a
|
|
2887
|
+
// reply onto the ended turn, and so a send from the result listener
|
|
2888
|
+
// starts a fresh child instead of writing to this one.
|
|
2889
|
+
const retired = this._child === interruptedChild
|
|
2890
|
+
if (retired) this._retireUnresponsiveChild(interruptedChild)
|
|
2891
|
+
// The follow-ups accepted in the window must go first whichever restart happens, the
|
|
2892
|
+
// timer's or a synchronous `result` listener's send, so decide BEFORE the emit.
|
|
2893
|
+
if (retired && this._outgoingQueue.length > 0) this._drainOutgoingFirst = true
|
|
2894
|
+
this._emitInterruptedTurnResult(0, 'user_stop')
|
|
2895
|
+
// #9267: a follow-up accepted during the window is parked behind a child that
|
|
2896
|
+
// is gone; start the fresh one now (the path a new send takes) rather than
|
|
2897
|
+
// leaving it to wait for yet another message.
|
|
2898
|
+
if (this._stoppedByUser) {
|
|
2899
|
+
if (this._outgoingQueue.length > 0) this._restartAfterStop()
|
|
2900
|
+
else this._drainOutgoingFirst = false // nothing left to put first, and no restart is coming
|
|
2901
|
+
}
|
|
1798
2902
|
}
|
|
1799
2903
|
}, 5000)
|
|
1800
2904
|
// #6043: fire-and-forget busy-state safety net — never gate process exit on
|
|
@@ -1807,6 +2911,14 @@ export class CliSession extends BaseSession {
|
|
|
1807
2911
|
destroy() {
|
|
1808
2912
|
this._destroying = true
|
|
1809
2913
|
this._respawning = false
|
|
2914
|
+
this._drainOutgoingFirst = false
|
|
2915
|
+
// #9267: a child the Stop timer retired is no longer `_child`, so reach its
|
|
2916
|
+
// tree here; the escalation timer is moot once the session is going away.
|
|
2917
|
+
for (const entry of this._retiredChildren) {
|
|
2918
|
+
clearTimeout(entry.timer)
|
|
2919
|
+
try { this._killChildTree(entry.child, { force: true, recorded: entry.recorded, handleOnly: true }) } catch {}
|
|
2920
|
+
}
|
|
2921
|
+
this._retiredChildren.clear()
|
|
1810
2922
|
// #5936: tear down the shared outgoing queue silently (no message_dequeued
|
|
1811
2923
|
// for a session that's going away).
|
|
1812
2924
|
this.clearOutgoingQueue({ emit: false })
|
|
@@ -1865,6 +2977,18 @@ export class CliSession extends BaseSession {
|
|
|
1865
2977
|
this._child = null
|
|
1866
2978
|
}
|
|
1867
2979
|
|
|
2980
|
+
// #7337: remove the sidecar dir so long-lived daemons don't leak one
|
|
2981
|
+
// directory per session under /tmp. Nulls `_permissionModeFile` too, so a
|
|
2982
|
+
// setPermissionMode() after destroy() no-ops cleanly.
|
|
2983
|
+
//
|
|
2984
|
+
// Deliberately AFTER the kill above, not before it. The child stays alive
|
|
2985
|
+
// for up to the 3s force-kill grace and can fire a PreToolUse hook in that
|
|
2986
|
+
// window; removing the sidecar first makes that hook fall back to the
|
|
2987
|
+
// spawn-frozen CHROXY_PERMISSION_MODE, which is fail-open on a session that
|
|
2988
|
+
// was tightened since spawn (spawned `auto`, switched to `approve`, then
|
|
2989
|
+
// destroyed).
|
|
2990
|
+
this._cleanupPermissionModeSidecar()
|
|
2991
|
+
|
|
1868
2992
|
// Emit completions for any tracked agents and clear busy state.
|
|
1869
2993
|
// Must happen before removeAllListeners() so events are delivered.
|
|
1870
2994
|
this._clearMessageState()
|