@chroxy/server 0.10.0
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 +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- package/src/ws-server.js +2866 -0
|
@@ -0,0 +1,1820 @@
|
|
|
1
|
+
import { spawn } from 'child_process'
|
|
2
|
+
import { createInterface } from 'readline'
|
|
3
|
+
import { randomBytes } from 'crypto'
|
|
4
|
+
import { homedir } from 'os'
|
|
5
|
+
import { join } from 'path'
|
|
6
|
+
import { createPermissionHookManager } from './permission-hook.js'
|
|
7
|
+
import { guardChildStreams } from './child-stream-guard.js'
|
|
8
|
+
import { BaseSession, buildBaseSessionOpts } from './base-session.js'
|
|
9
|
+
import { buildContentBlocks } from './content-blocks.js'
|
|
10
|
+
import { ALLOWED_MODEL_IDS } from './models.js'
|
|
11
|
+
import { CLAUDE_FALLBACK_MODELS, claudeModelMetadata } from './claude-model-catalog.js'
|
|
12
|
+
import { forceKill } from './platform.js'
|
|
13
|
+
import { MessageTransformPipeline } from './message-transform.js'
|
|
14
|
+
import { emitToolResults } from './tool-result.js'
|
|
15
|
+
import { buildToolStartData, extractToolInputSemantics } from './claude-stream-parser.js'
|
|
16
|
+
import { resolveBinary } from './utils/resolve-binary.js'
|
|
17
|
+
import { prepareSpawn } from './utils/win-spawn.js'
|
|
18
|
+
import { buildSpawnEnv } from './utils/spawn-env.js'
|
|
19
|
+
import { RespawnRateLimiter } from './utils/respawn-rate-limiter.js'
|
|
20
|
+
import { createLogger, loggerForSession } from './logger.js'
|
|
21
|
+
import { formatIdleDuration } from './session-timeout-manager.js'
|
|
22
|
+
import { BILLING_CLASSES, isProgrammaticCreditEra } from './billing-class.js'
|
|
23
|
+
|
|
24
|
+
const log = createLogger('cli-session')
|
|
25
|
+
|
|
26
|
+
// Resolve the claude binary once at module load. Under a GUI launch
|
|
27
|
+
// (e.g. Tauri on macOS) PATH is minimal and may exclude the user's
|
|
28
|
+
// install dir — fall through to known locations so `spawn()` succeeds.
|
|
29
|
+
const CLAUDE = resolveBinary('claude', [
|
|
30
|
+
join(homedir(), '.local/bin/claude'),
|
|
31
|
+
'/opt/homebrew/bin/claude',
|
|
32
|
+
'/usr/local/bin/claude',
|
|
33
|
+
join(homedir(), '.claude/local/node_modules/.bin/claude'),
|
|
34
|
+
join(homedir(), '.npm-global/bin/claude'),
|
|
35
|
+
])
|
|
36
|
+
|
|
37
|
+
// Default max accumulated size for tool_use input_json_delta chunks (~256KB)
|
|
38
|
+
const DEFAULT_MAX_TOOL_INPUT_LENGTH = 262144
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Patterns the claude CLI emits on stderr when `--resume <id>` fails because
|
|
42
|
+
* the conversation id is unknown locally (e.g. the operator wiped
|
|
43
|
+
* `~/.claude/projects/` between chroxy boots, or restored a state file from a
|
|
44
|
+
* different machine). Matched case-insensitively against each buffered stderr
|
|
45
|
+
* line; one match is enough to classify the failure as `resume_unknown` and
|
|
46
|
+
* trigger the one-shot fresh-conversation fallback in #4929.
|
|
47
|
+
*
|
|
48
|
+
* Kept as an exported constant so the regression test can pin both the
|
|
49
|
+
* detection contract AND the exact strings without re-implementing the matcher.
|
|
50
|
+
* If claude CLI ever changes its wording, the test will fail loudly here
|
|
51
|
+
* rather than silently regressing back into the "exited unexpectedly" respawn
|
|
52
|
+
* loop reported in #4929.
|
|
53
|
+
*
|
|
54
|
+
* #4950 — the original seventh pattern `/resume.*failed/i` was too loose:
|
|
55
|
+
* unrelated stderr like "tool resume failed" or "user wanted to resume after
|
|
56
|
+
* the failed sync" would falsely classify as resume_unknown and wipe
|
|
57
|
+
* `_sessionId` mid-conversation. The three replacement patterns require both
|
|
58
|
+
* the resume verb AND a session/conversation/id keyword nearby, so a tool-side
|
|
59
|
+
* failure that happens to log "resume failed" in isolation no longer triggers
|
|
60
|
+
* a phantom `_sessionId` wipe.
|
|
61
|
+
*/
|
|
62
|
+
export const RESUME_UNKNOWN_STDERR_PATTERNS = [
|
|
63
|
+
/no conversation found/i,
|
|
64
|
+
/conversation.*not.*found/i,
|
|
65
|
+
/session.*not.*found/i,
|
|
66
|
+
/no such conversation/i,
|
|
67
|
+
/unknown session/i,
|
|
68
|
+
/could not find session/i,
|
|
69
|
+
// #4950 — tightened replacements for the dropped `/resume.*failed/i`. Each
|
|
70
|
+
// requires the resume verb to co-occur with session/conversation/id so the
|
|
71
|
+
// matcher stays scoped to the --resume-id failure mode it was designed for.
|
|
72
|
+
//
|
|
73
|
+
// #4968 — `id` is anchored with \b so it doesn't bleed into substrings of
|
|
74
|
+
// unrelated words (invalid, considered, avoided, widget, mid, kid, …). The
|
|
75
|
+
// long tokens `session` and `conversation` don't need anchoring.
|
|
76
|
+
//
|
|
77
|
+
// #4969 — `resum(e|ing)` covers the gerund form claude CLI may emit
|
|
78
|
+
// ("Error resuming session abc-123"). Original `resume.*` patterns missed
|
|
79
|
+
// the gerund and silently fell through to the generic "exited unexpectedly"
|
|
80
|
+
// respawn loop reported in #4929.
|
|
81
|
+
/resum(e|ing).*(fail|error).*(session|conversation|\bid\b)/i,
|
|
82
|
+
/resum(e|ing).*(session|conversation|\bid\b).*(fail|error)/i,
|
|
83
|
+
/(fail|error|could not|unable to|cannot).*resum(e|ing).*(session|conversation|\bid\b)/i,
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Inspect a buffered stderr line set and return true if any line matches a
|
|
88
|
+
* known "unknown resume id" pattern. Pure helper — exported so the test suite
|
|
89
|
+
* can pin the matcher behavior without spawning a child process.
|
|
90
|
+
*
|
|
91
|
+
* @param {string[]} stderrLines
|
|
92
|
+
* @returns {boolean}
|
|
93
|
+
*/
|
|
94
|
+
export function stderrIndicatesUnknownResume(stderrLines) {
|
|
95
|
+
if (!Array.isArray(stderrLines) || stderrLines.length === 0) return false
|
|
96
|
+
for (const line of stderrLines) {
|
|
97
|
+
if (typeof line !== 'string' || !line) continue
|
|
98
|
+
for (const pattern of RESUME_UNKNOWN_STDERR_PATTERNS) {
|
|
99
|
+
if (pattern.test(line)) return true
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return false
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Build the argv passed to `claude -p --input-format stream-json …`.
|
|
107
|
+
*
|
|
108
|
+
* Extracted so #4887 has a single, pure place to assert the resume contract.
|
|
109
|
+
* Mirrors the historical inline build in `start()` exactly — same arg order,
|
|
110
|
+
* same flag spellings — plus an optional `--resume <id>` segment when a prior
|
|
111
|
+
* `_sessionId` is known.
|
|
112
|
+
*
|
|
113
|
+
* Resume invariants (#4887):
|
|
114
|
+
* - A fresh session (no `_sessionId` yet) omits `--resume`. claude CLI
|
|
115
|
+
* allocates a brand-new conversation on first init.
|
|
116
|
+
* - A respawn (model switch, perm-mode flip, crash) or a server-restart
|
|
117
|
+
* restore call MUST include `--resume <id>`. Without it, the new
|
|
118
|
+
* subprocess inherits the chroxy-side history ring buffer (replayed to
|
|
119
|
+
* the dashboard) but the model itself starts cold mid-conversation —
|
|
120
|
+
* the failure mode reported in #4887.
|
|
121
|
+
*
|
|
122
|
+
* @param {object} opts
|
|
123
|
+
* @param {string|null} opts.model
|
|
124
|
+
* @param {string} opts.permissionMode
|
|
125
|
+
* @param {string[]} opts.allowedTools
|
|
126
|
+
* @param {string} opts.skillsText
|
|
127
|
+
* @param {string|null} opts.resumeSessionId
|
|
128
|
+
* @returns {string[]}
|
|
129
|
+
*/
|
|
130
|
+
export function buildClaudeCliArgs({ model, permissionMode, allowedTools, skillsText, resumeSessionId } = {}) {
|
|
131
|
+
const args = [
|
|
132
|
+
'-p',
|
|
133
|
+
'--input-format', 'stream-json',
|
|
134
|
+
'--output-format', 'stream-json',
|
|
135
|
+
'--verbose',
|
|
136
|
+
'--include-partial-messages',
|
|
137
|
+
]
|
|
138
|
+
|
|
139
|
+
if (model) {
|
|
140
|
+
args.push('--model', model)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (permissionMode === 'auto') {
|
|
144
|
+
args.push('--permission-mode', 'bypassPermissions')
|
|
145
|
+
} else if (permissionMode === 'plan') {
|
|
146
|
+
args.push('--permission-mode', 'plan')
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (Array.isArray(allowedTools) && allowedTools.length > 0) {
|
|
150
|
+
args.push('--allowedTools', allowedTools.join(','))
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (skillsText) {
|
|
154
|
+
args.push('--append-system-prompt', skillsText)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// #4887 — wire the prior claude session_id back onto the new subprocess so
|
|
158
|
+
// the model retains the full prior transcript. Only emitted when a non-empty
|
|
159
|
+
// string is known; a brand-new session (first start()) leaves this off so
|
|
160
|
+
// claude CLI mints a fresh conversation id on its `system.init` line.
|
|
161
|
+
if (typeof resumeSessionId === 'string' && resumeSessionId.length > 0) {
|
|
162
|
+
args.push('--resume', resumeSessionId)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return args
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Manages a persistent Claude Code CLI session using headless mode.
|
|
170
|
+
*
|
|
171
|
+
* A single `claude -p --input-format stream-json --output-format stream-json`
|
|
172
|
+
* process stays alive for the lifetime of the session. Messages are sent as
|
|
173
|
+
* NDJSON on stdin; "message complete" is signaled by a `result` event on
|
|
174
|
+
* stdout (not process exit).
|
|
175
|
+
*
|
|
176
|
+
* Events emitted:
|
|
177
|
+
* ready { sessionId, model, tools }
|
|
178
|
+
* stream_start { messageId }
|
|
179
|
+
* stream_delta { messageId, delta }
|
|
180
|
+
* stream_end { messageId }
|
|
181
|
+
* message { type, content, tool, timestamp }
|
|
182
|
+
* tool_start { messageId, tool, input }
|
|
183
|
+
* result { cost, duration, usage, sessionId }
|
|
184
|
+
* error { message }
|
|
185
|
+
* user_question { toolUseId, questions }
|
|
186
|
+
* agent_spawned { toolUseId, description, startedAt }
|
|
187
|
+
* agent_completed { toolUseId }
|
|
188
|
+
* plan_started {}
|
|
189
|
+
* plan_ready { allowedPrompts }
|
|
190
|
+
* tool_result { toolUseId, result, truncated }
|
|
191
|
+
*/
|
|
192
|
+
|
|
193
|
+
export class CliSession extends BaseSession {
|
|
194
|
+
// #5858: Claude-family flag — single source of truth for isClaudeProvider().
|
|
195
|
+
// DockerSession (docker-cli / docker) extends this and inherits it.
|
|
196
|
+
static claudeFamily = true
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Human-readable label shown in the startup banner and anywhere else the
|
|
200
|
+
* server needs to name this provider (#2953). Each provider owns its own
|
|
201
|
+
* display name so `server-cli.js` no longer has to maintain a hardcoded
|
|
202
|
+
* `PROVIDER_LABELS` map that drifts every time a new provider lands.
|
|
203
|
+
*/
|
|
204
|
+
static get displayLabel() {
|
|
205
|
+
return 'Claude Code (CLI)'
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* #5698: `respawn_exhausted` is the terminal "session is dead (flapping)"
|
|
210
|
+
* signal — emitted by `_scheduleRespawn` once the bounded auto-respawn budget
|
|
211
|
+
* (the rolling rate cap or the consecutive max of 5) is spent. SessionManager
|
|
212
|
+
* listens for it and drops the session from its list (no input-rejecting
|
|
213
|
+
* zombie tab), mirroring ClaudeTuiSession's contract. Listing it here makes
|
|
214
|
+
* `_wireSessionEvents` bridge it onto the transient `session_event` channel
|
|
215
|
+
* as well. DockerSession is the only subclass of CliSession, so it inherits
|
|
216
|
+
* this getter and the terminal signal; the other subprocess providers
|
|
217
|
+
* (BYOK/DeepSeek extend BaseSession, Gemini/Codex extend
|
|
218
|
+
* JsonlSubprocessSession) have no auto-respawn loop, so there is nothing to
|
|
219
|
+
* exhaust there.
|
|
220
|
+
*/
|
|
221
|
+
static get customEvents() {
|
|
222
|
+
return ['respawn_exhausted']
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Root data directory for this provider (#2965).
|
|
227
|
+
* Consumers (conversation-scanner, ws-file-ops) use this to locate
|
|
228
|
+
* provider-specific subdirs (projects/, agents/, commands/) without
|
|
229
|
+
* hardcoding the path.
|
|
230
|
+
*/
|
|
231
|
+
static get dataDir() {
|
|
232
|
+
return join(homedir(), '.claude')
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
static get capabilities() {
|
|
236
|
+
return {
|
|
237
|
+
permissions: true,
|
|
238
|
+
inProcessPermissions: false,
|
|
239
|
+
modelSwitch: true,
|
|
240
|
+
permissionModeSwitch: true,
|
|
241
|
+
// #5609: switching to 'auto' mid-turn is the #3729 panic-button —
|
|
242
|
+
// BaseSession lets 'auto' bypass the _isBusy guard and CliSession's
|
|
243
|
+
// _onPermissionModeChanged respawns the `claude -p` subprocess, which
|
|
244
|
+
// DROPS the in-flight turn. Surfaced as a capability so the dashboard /
|
|
245
|
+
// app can word their confirm dialog accurately (CLI = interrupts;
|
|
246
|
+
// SDK/TUI = safe) instead of silently differing per provider.
|
|
247
|
+
interruptsTurnOnAutoSwitch: true,
|
|
248
|
+
planMode: true,
|
|
249
|
+
// #4887 — claude CLI supports `--resume <id>`; CliSession now wires
|
|
250
|
+
// `_sessionId` into the spawn argv on respawn / restore so the model
|
|
251
|
+
// retains the prior transcript instead of starting cold mid-conversation.
|
|
252
|
+
// Persistence + UI gating both branch on this flag.
|
|
253
|
+
resume: true,
|
|
254
|
+
terminal: false,
|
|
255
|
+
thinkingLevel: false,
|
|
256
|
+
// #3932: declared explicitly so the capability matrix matches across
|
|
257
|
+
// providers — claude-tui is the only one that sets this to false.
|
|
258
|
+
streaming: true,
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Preflight dependency spec used by `chroxy doctor`.
|
|
264
|
+
* Declares the binary and credential requirements for this provider so
|
|
265
|
+
* doctor.js can check only the binaries the configured provider actually
|
|
266
|
+
* needs (see issue #2951).
|
|
267
|
+
*/
|
|
268
|
+
static get preflight() {
|
|
269
|
+
return {
|
|
270
|
+
label: 'Claude CLI',
|
|
271
|
+
binary: {
|
|
272
|
+
name: 'claude',
|
|
273
|
+
args: ['--version'],
|
|
274
|
+
candidates: [
|
|
275
|
+
join(homedir(), '.local/bin/claude'),
|
|
276
|
+
'/opt/homebrew/bin/claude',
|
|
277
|
+
'/usr/local/bin/claude',
|
|
278
|
+
join(homedir(), '.claude/local/node_modules/.bin/claude'),
|
|
279
|
+
join(homedir(), '.npm-global/bin/claude'),
|
|
280
|
+
],
|
|
281
|
+
installHint: 'install Claude Code CLI',
|
|
282
|
+
},
|
|
283
|
+
credentials: {
|
|
284
|
+
envVars: ['ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN'],
|
|
285
|
+
hint: 'run `claude login` or set ANTHROPIC_API_KEY',
|
|
286
|
+
optional: true,
|
|
287
|
+
},
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Resolve runtime auth state for the dashboard (#4769).
|
|
293
|
+
*
|
|
294
|
+
* Host `claude-cli` always bills the Claude subscription: spawn-env.js's
|
|
295
|
+
* `claude` denylist strips ANTHROPIC_API_KEY before the subprocess starts,
|
|
296
|
+
* so the env var is irrelevant — the CLI auths via the host's ~/.claude
|
|
297
|
+
* OAuth state. Mark ready up front; the on-disk OAuth probe doesn't see
|
|
298
|
+
* Keychain credentials and would otherwise misreport unconfigured.
|
|
299
|
+
*
|
|
300
|
+
* @returns {{ready:boolean, source:string, envVar:string|null, envVars:string[], hint:string, detail:string, billingClass:string}}
|
|
301
|
+
*/
|
|
302
|
+
static resolveAuth() {
|
|
303
|
+
const envVars = this.preflight.credentials.envVars
|
|
304
|
+
// claude-cli always auths via the host OAuth/subscription pool (the env
|
|
305
|
+
// key is stripped before spawn), so it's never the `api-key` class. Before
|
|
306
|
+
// 2026-06-15 this is flat subscription; on/after it draws from the metered
|
|
307
|
+
// programmatic-credit pool (#5629). The era is read at call time so a
|
|
308
|
+
// long-running daemon flips copy at the boundary without a restart.
|
|
309
|
+
const era = isProgrammaticCreditEra()
|
|
310
|
+
return {
|
|
311
|
+
ready: true,
|
|
312
|
+
source: 'oauth',
|
|
313
|
+
envVar: null,
|
|
314
|
+
envVars,
|
|
315
|
+
hint: 'run `claude login` if not yet authed',
|
|
316
|
+
detail: era
|
|
317
|
+
? 'Programmatic credit pool — monthly metered credits (CLI strips ANTHROPIC_API_KEY before spawn)'
|
|
318
|
+
: 'Claude subscription (CLI strips ANTHROPIC_API_KEY before spawn)',
|
|
319
|
+
billingClass: era ? BILLING_CLASSES.PROGRAMMATIC_CREDIT : BILLING_CLASSES.SUBSCRIPTION,
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Per-provider fallback model list (#2956). Shared with every Claude
|
|
325
|
+
* provider via `CLAUDE_FALLBACK_MODELS` in claude-model-catalog.js
|
|
326
|
+
* (#6201 OCP). The default Claude registry is
|
|
327
|
+
* what this provider uses at runtime — this static exists so
|
|
328
|
+
* `getRegistryForProvider('claude-cli')` and the per-provider tests
|
|
329
|
+
* can discover the Claude defaults through the same hook shape used
|
|
330
|
+
* by Codex/Gemini.
|
|
331
|
+
*
|
|
332
|
+
* @returns {ReadonlyArray<{id:string,label:string,fullId:string,contextWindow:number}>}
|
|
333
|
+
*/
|
|
334
|
+
static getFallbackModels() {
|
|
335
|
+
return CLAUDE_FALLBACK_MODELS
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
static getAllowedModels() {
|
|
339
|
+
return [...ALLOWED_MODEL_IDS]
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Claude-style metadata via the shared claudeModelMetadata() helper
|
|
344
|
+
* (#6201 OCP). Mirrors SdkSession (#2956).
|
|
345
|
+
*
|
|
346
|
+
* @param {string} modelId
|
|
347
|
+
* @returns {{id:string,label:string,fullId:string,contextWindow:number,description?:string}|null}
|
|
348
|
+
*/
|
|
349
|
+
static getModelMetadata(modelId) {
|
|
350
|
+
return claudeModelMetadata(modelId)
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
constructor(opts = {}) {
|
|
354
|
+
super(buildBaseSessionOpts(opts, { provider: opts.provider || 'claude-cli' }))
|
|
355
|
+
// CliSession-local opts (not BaseSession opts — see buildBaseSessionOpts).
|
|
356
|
+
const { allowedTools, port, apiToken, settingsPath, maxToolInput, transforms, resumeSessionId } = opts
|
|
357
|
+
this.allowedTools = allowedTools || []
|
|
358
|
+
this._port = port || null
|
|
359
|
+
this._apiToken = apiToken || null
|
|
360
|
+
// Per-session secret for the permission hook endpoint — never the primary API token
|
|
361
|
+
this._hookSecret = randomBytes(32).toString('hex')
|
|
362
|
+
this._maxToolInput = maxToolInput || DEFAULT_MAX_TOOL_INPUT_LENGTH
|
|
363
|
+
this._transformPipeline = new MessageTransformPipeline(transforms || [])
|
|
364
|
+
// #4887 — seed `_sessionId` from the persisted resume id so the very-first
|
|
365
|
+
// start() (post-restore) passes `--resume <id>` and the new claude
|
|
366
|
+
// subprocess re-hydrates the prior conversation. Falsy / non-string values
|
|
367
|
+
// (older state files, missing opt) leave `_sessionId` null exactly as
|
|
368
|
+
// before, so brand-new sessions still mint a fresh claude conversation.
|
|
369
|
+
this._sessionId = (typeof resumeSessionId === 'string' && resumeSessionId.length > 0)
|
|
370
|
+
? resumeSessionId
|
|
371
|
+
: null
|
|
372
|
+
// #4828: session-scoped logger, lazily bound when the CLI emits its
|
|
373
|
+
// `init` message (where session_id becomes known). Pre-init log lines
|
|
374
|
+
// stay on the module-level `log` — same fallback pattern as SdkSession
|
|
375
|
+
// / ClaudeTuiSession.
|
|
376
|
+
this._log = null
|
|
377
|
+
this._child = null
|
|
378
|
+
this._rl = null
|
|
379
|
+
this._stderrRL = null
|
|
380
|
+
|
|
381
|
+
// Persistent-process state
|
|
382
|
+
this._inPlanMode = false
|
|
383
|
+
this._planAllowedPrompts = null
|
|
384
|
+
this._waitingForAnswer = false
|
|
385
|
+
this._currentCtx = null
|
|
386
|
+
this._pendingQueue = []
|
|
387
|
+
this._respawnCount = 0
|
|
388
|
+
this._respawnTimer = null
|
|
389
|
+
this._respawnScheduled = false
|
|
390
|
+
this._respawning = false
|
|
391
|
+
// #5349: rolling-window respawn cap independent of `_respawnCount`, which
|
|
392
|
+
// resets on every `system.init` (warmup success). Without it a session that
|
|
393
|
+
// dies shortly after each successful init flaps forever. Mirrors the same
|
|
394
|
+
// guard in ClaudeTuiSession.
|
|
395
|
+
this._respawnRateLimiter = new RespawnRateLimiter()
|
|
396
|
+
this._interruptTimer = null
|
|
397
|
+
// #4929: track in-flight `--resume <id>` attempts so we can detect when
|
|
398
|
+
// claude CLI rejects an unknown id and avoid the spin-retry loop reported
|
|
399
|
+
// in the issue. Set in `_spawnPersistentProcess` whenever we passed
|
|
400
|
+
// `--resume`, cleared by `system.init` (resume confirmed) and inspected
|
|
401
|
+
// by `_handleChildClose` if the child exits before init fires.
|
|
402
|
+
this._attemptedResumeId = null
|
|
403
|
+
this._recentStderrLines = []
|
|
404
|
+
// One-shot fallback latch: if we detect `resume_unknown`, drop `_sessionId`
|
|
405
|
+
// and respawn a fresh conversation exactly once. If THAT also fails the
|
|
406
|
+
// child exits for a different reason and the normal respawn path runs.
|
|
407
|
+
// Prevents an infinite "clear → respawn → resume → clear" oscillation if
|
|
408
|
+
// some future bug ever re-introduces a phantom resume id.
|
|
409
|
+
this._didFallbackFromUnknownResume = false
|
|
410
|
+
// #4602: distinguishes "user clicked Stop" (interrupt → child exits)
|
|
411
|
+
// from "child crashed" so _handleChildClose skips the misleading
|
|
412
|
+
// "exited unexpectedly" toast + auto-respawn on the stop path.
|
|
413
|
+
// Single-use: set by interrupt(), cleared by _handleChildClose / destroy.
|
|
414
|
+
// The flag itself is declared+initialized on BaseSession (#5375).
|
|
415
|
+
|
|
416
|
+
// Hook manager (shared module)
|
|
417
|
+
this._hookManager = (this._port) ? createPermissionHookManager(this, { settingsPath }) : null
|
|
418
|
+
|
|
419
|
+
// Pending-permission bookkeeping for the inactivity timer (#2831).
|
|
420
|
+
// WsServer calls notifyPermissionPending/Resolved when a hook
|
|
421
|
+
// permission belonging to this session is broadcast/resolved.
|
|
422
|
+
this._pendingPermissionIds = new Set()
|
|
423
|
+
this._resultTimeoutPaused = false
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
get sessionId() {
|
|
427
|
+
return this._sessionId
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* Public accessor for the claude CLI session id used to resume conversations
|
|
432
|
+
* via `claude -p --resume <id>` (#4887). SessionManager.serializeState reads
|
|
433
|
+
* this to persist `sdkSessionId` (the cross-provider name for the resume
|
|
434
|
+
* token); restoreState forwards it back into the constructor as
|
|
435
|
+
* `resumeSessionId` so the new chroxy boot re-attaches to the prior
|
|
436
|
+
* conversation instead of starting cold.
|
|
437
|
+
*
|
|
438
|
+
* Returns `null` until the CLI emits its first `system.init` event (or until
|
|
439
|
+
* the constructor seeds the value from a persisted state file).
|
|
440
|
+
*
|
|
441
|
+
* @returns {string|null}
|
|
442
|
+
*/
|
|
443
|
+
get resumeSessionId() {
|
|
444
|
+
return this._sessionId || null
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Start the persistent Claude process. Call once after construction.
|
|
449
|
+
*/
|
|
450
|
+
start() {
|
|
451
|
+
// Register permission hook before starting the process (only once, not on respawn)
|
|
452
|
+
if (this._hookManager && this._respawnCount === 0) {
|
|
453
|
+
this._hookManager.register()
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// Skills MVP (#2957) — append shared skills to the Claude CLI system prompt.
|
|
457
|
+
const skillsText = this._buildSystemPrompt()
|
|
458
|
+
|
|
459
|
+
// #4887 — pass `_sessionId` as `--resume` whenever it's known. This is the
|
|
460
|
+
// load-bearing flag for the bug: on respawn (crash / model switch / perm-
|
|
461
|
+
// mode flip) and on server-restart restore, the new claude subprocess
|
|
462
|
+
// would otherwise lose every prior turn in the model's context window and
|
|
463
|
+
// the user would see the dashboard transcript replay correctly while the
|
|
464
|
+
// model itself starts cold mid-conversation.
|
|
465
|
+
const args = buildClaudeCliArgs({
|
|
466
|
+
model: this.model,
|
|
467
|
+
permissionMode: this.permissionMode,
|
|
468
|
+
allowedTools: this.allowedTools,
|
|
469
|
+
skillsText,
|
|
470
|
+
resumeSessionId: this._sessionId,
|
|
471
|
+
})
|
|
472
|
+
|
|
473
|
+
const resumeNote = this._sessionId ? ` (resume ${this._sessionId})` : ''
|
|
474
|
+
log.info(`Starting persistent process (model: ${this.model || 'default'}, permission: ${this.permissionMode})${resumeNote}`)
|
|
475
|
+
this._spawnPersistentProcess(args)
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Spawn the persistent claude process and wire up event handlers.
|
|
480
|
+
*
|
|
481
|
+
* Uses buildSpawnEnv('claude') which strips ANTHROPIC_API_KEY from the
|
|
482
|
+
* parent env (so the CLI uses OAuth/subscription auth instead of burning
|
|
483
|
+
* API credits) while still forwarding the rest of the user's environment
|
|
484
|
+
* — Claude Code tools expect the full shell env to be available.
|
|
485
|
+
*/
|
|
486
|
+
_buildChildEnv() {
|
|
487
|
+
const extras = {
|
|
488
|
+
CI: '1',
|
|
489
|
+
CLAUDE_HEADLESS: '1',
|
|
490
|
+
CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING: '1',
|
|
491
|
+
CHROXY_PERMISSION_MODE: this.permissionMode,
|
|
492
|
+
...(this._port ? { CHROXY_PORT: String(this._port) } : {}),
|
|
493
|
+
// Pass a short-lived per-session secret instead of the primary API token.
|
|
494
|
+
// This limits the blast radius if a tool reads process.env — the hook secret
|
|
495
|
+
// only authorises POST /permission, not the WebSocket API.
|
|
496
|
+
...(this._port ? { CHROXY_HOOK_SECRET: this._hookSecret } : {}),
|
|
497
|
+
}
|
|
498
|
+
return buildSpawnEnv('claude', extras)
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
_spawnPersistentProcess(args) {
|
|
502
|
+
this._cleanupReadlines()
|
|
503
|
+
this._processReady = false
|
|
504
|
+
|
|
505
|
+
// #4929: capture which `--resume <id>` (if any) this spawn attempted.
|
|
506
|
+
// Read off the argv we're about to pass instead of `_sessionId` so the
|
|
507
|
+
// detection is robust to future refactors that build args differently —
|
|
508
|
+
// we're asking "what did we actually tell claude to resume?" not "what's
|
|
509
|
+
// our in-memory id?". `_handleChildClose` inspects this on exit to decide
|
|
510
|
+
// whether to classify a quick failure as `resume_unknown` (#4929).
|
|
511
|
+
const resumeIdx = args.indexOf('--resume')
|
|
512
|
+
this._attemptedResumeId = (resumeIdx >= 0 && typeof args[resumeIdx + 1] === 'string')
|
|
513
|
+
? args[resumeIdx + 1]
|
|
514
|
+
: null
|
|
515
|
+
this._recentStderrLines = []
|
|
516
|
+
|
|
517
|
+
// On Windows the resolver can land on a `claude.cmd` shim (npm-global install
|
|
518
|
+
// with no native `claude.exe`); spawning a `.cmd` via child_process throws
|
|
519
|
+
// EINVAL on Node 24, so route it through cmd.exe with proper escaping. No-op
|
|
520
|
+
// for a directly-runnable `.exe` and on POSIX. See utils/win-spawn.js.
|
|
521
|
+
const spawnSpec = prepareSpawn(CLAUDE, args)
|
|
522
|
+
const child = spawn(spawnSpec.command, spawnSpec.args, {
|
|
523
|
+
cwd: this.cwd,
|
|
524
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
525
|
+
env: this._buildChildEnv(),
|
|
526
|
+
...spawnSpec.options,
|
|
527
|
+
})
|
|
528
|
+
|
|
529
|
+
this._child = child
|
|
530
|
+
|
|
531
|
+
// Do NOT close stdin — we write messages to it
|
|
532
|
+
|
|
533
|
+
// Read stdout line by line — each line is a JSON object
|
|
534
|
+
const rl = createInterface({ input: child.stdout })
|
|
535
|
+
this._rl = rl
|
|
536
|
+
|
|
537
|
+
rl.on('line', (line) => this._handleStdoutLine(line))
|
|
538
|
+
|
|
539
|
+
// Log stderr for debugging
|
|
540
|
+
const stderrRL = createInterface({ input: child.stderr })
|
|
541
|
+
this._stderrRL = stderrRL
|
|
542
|
+
stderrRL.on('line', (line) => {
|
|
543
|
+
if (line.trim()) {
|
|
544
|
+
// #4828: session-scoped when init has fired (stderr arrives both
|
|
545
|
+
// pre- and post-init; the fallback covers the pre-init case).
|
|
546
|
+
;(this._log || log).info(`stderr: ${line}`)
|
|
547
|
+
// #4929: buffer the most recent stderr lines while a `--resume` is
|
|
548
|
+
// outstanding so `_handleChildClose` can classify the failure. Bounded
|
|
549
|
+
// to 50 lines so a chatty subprocess can't grow this unbounded — the
|
|
550
|
+
// unknown-resume error fits in the first handful of lines so 50 is
|
|
551
|
+
// generous. Only buffer until `system.init` clears `_attemptedResumeId`
|
|
552
|
+
// (a successful resume confirms via init); after that we drop lines on
|
|
553
|
+
// the floor and let the normal stderr->log path do its job.
|
|
554
|
+
if (this._attemptedResumeId) {
|
|
555
|
+
this._recentStderrLines.push(line)
|
|
556
|
+
if (this._recentStderrLines.length > 50) {
|
|
557
|
+
this._recentStderrLines.shift()
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
})
|
|
562
|
+
|
|
563
|
+
// #5361 (follow-up to #5324) — guard the child's stdout/stderr streams
|
|
564
|
+
// against an unhandled 'error' event that would crash the daemon. Shared
|
|
565
|
+
// helper (P2-9); `_destroying` flips after attach so it is read lazily.
|
|
566
|
+
guardChildStreams(child, { destroying: () => this._destroying, log: this._log || log })
|
|
567
|
+
|
|
568
|
+
// Absorb EPIPE and other low-level stdin errors so they don't become
|
|
569
|
+
// unhandled exceptions. Writes are already wrapped in try/catch below.
|
|
570
|
+
child.stdin.on('error', (err) => {
|
|
571
|
+
// #4828: session-scoped when init has fired.
|
|
572
|
+
;(this._log || log).warn(`stdin error (ignored): ${err.message}`)
|
|
573
|
+
})
|
|
574
|
+
|
|
575
|
+
child.on('error', (err) => {
|
|
576
|
+
this._cleanupReadlines()
|
|
577
|
+
this._processReady = false
|
|
578
|
+
this._child = null
|
|
579
|
+
this.emit('error', { message: `Failed to spawn claude: ${err.message}` })
|
|
580
|
+
this._scheduleRespawn()
|
|
581
|
+
})
|
|
582
|
+
|
|
583
|
+
child.on('close', (code) => this._handleChildClose(code))
|
|
584
|
+
|
|
585
|
+
// stdin is writable immediately — process is ready for NDJSON messages.
|
|
586
|
+
// system.init arrives with the first response, not at startup.
|
|
587
|
+
this._processReady = true
|
|
588
|
+
log.info('Process started, ready for messages')
|
|
589
|
+
this.emit('ready', { sessionId: null, model: this.model, tools: [] })
|
|
590
|
+
|
|
591
|
+
// Dequeue the next pending message if not already busy.
|
|
592
|
+
// sendMessage() sets _isBusy, so the loop sends at most one message.
|
|
593
|
+
// Remaining items stay in the queue and are drained one-by-one via
|
|
594
|
+
// _clearMessageState() after each result.
|
|
595
|
+
while (this._pendingQueue.length > 0 && !this._isBusy) {
|
|
596
|
+
const pending = this._pendingQueue.shift()
|
|
597
|
+
// #4828: session-scoped when init has fired (dequeue can race with
|
|
598
|
+
// the very-first init so the fallback is intentional).
|
|
599
|
+
;(this._log || log).info(`Dequeuing pending message (${this._pendingQueue.length} remaining)`)
|
|
600
|
+
this.sendMessage(pending.prompt, pending.attachments, pending.options || {})
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* Schedule a respawn with exponential backoff.
|
|
606
|
+
* Backoff: 1s, 2s, 4s, 8s, 15s (max). Cap at 5 retries then stop.
|
|
607
|
+
*/
|
|
608
|
+
_scheduleRespawn() {
|
|
609
|
+
if (this._destroying) return
|
|
610
|
+
if (this._respawning) return
|
|
611
|
+
if (this._respawnScheduled) return
|
|
612
|
+
|
|
613
|
+
// #5349: rolling-window cap, checked BEFORE _respawnCount so a session that
|
|
614
|
+
// keeps surviving warmup (resetting _respawnCount on system.init) still
|
|
615
|
+
// gives up once it flaps past the window cap.
|
|
616
|
+
if (!this._respawnRateLimiter.record()) {
|
|
617
|
+
const { maxPerWindow, windowMs } = this._respawnRateLimiter
|
|
618
|
+
log.error(`Respawn rate cap reached (>${maxPerWindow} in ${Math.round(windowMs / 60000)}min), giving up — session is flapping`)
|
|
619
|
+
// #5698: a CODED terminal error (so the client can render a distinct
|
|
620
|
+
// "session ended (flapping)" final state instead of a transient toast)
|
|
621
|
+
// PLUS `respawn_exhausted` so SessionManager drops the dead session.
|
|
622
|
+
this.emit('error', { code: 'cli_respawn_exhausted', message: `Claude process is flapping — exceeded ${maxPerWindow} respawns in ${Math.round(windowMs / 60000)} minutes` })
|
|
623
|
+
this.emit('respawn_exhausted', { reason: 'cli_respawn_rate_capped' })
|
|
624
|
+
return
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
this._respawnCount++
|
|
628
|
+
if (this._respawnCount > 5) {
|
|
629
|
+
log.error('Max respawn attempts reached (5), giving up')
|
|
630
|
+
// #5698: see the rate-cap branch above — coded terminal error + the
|
|
631
|
+
// session-dropping `respawn_exhausted` signal.
|
|
632
|
+
this.emit('error', { code: 'cli_respawn_exhausted', message: 'Claude process failed to stay alive after 5 attempts' })
|
|
633
|
+
this.emit('respawn_exhausted', { reason: 'cli_respawn_exhausted', attempts: this._respawnCount - 1 })
|
|
634
|
+
return
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
const delays = [1000, 2000, 4000, 8000, 15000]
|
|
638
|
+
const delay = delays[Math.min(this._respawnCount - 1, delays.length - 1)]
|
|
639
|
+
log.info(`Respawning in ${delay}ms (attempt ${this._respawnCount}/5)`)
|
|
640
|
+
|
|
641
|
+
this._respawnScheduled = true
|
|
642
|
+
this._respawnTimer = setTimeout(() => {
|
|
643
|
+
this._respawnTimer = null
|
|
644
|
+
this._respawnScheduled = false
|
|
645
|
+
if (!this._destroying) {
|
|
646
|
+
this.start()
|
|
647
|
+
}
|
|
648
|
+
}, delay)
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* Send a message to Claude via stdin NDJSON.
|
|
653
|
+
*/
|
|
654
|
+
async sendMessage(prompt, attachments, options = {}) {
|
|
655
|
+
if (this._isBusy) {
|
|
656
|
+
// #5936 (epic #5935): a send-while-busy follow-up now QUEUES into the
|
|
657
|
+
// shared outgoing queue (BaseSession) instead of rejecting with "Already
|
|
658
|
+
// processing a message" — flushed FIFO on the turn-complete `result` (via
|
|
659
|
+
// _clearMessageState's drain below). Matches the SDK's behaviour. The
|
|
660
|
+
// overflow cap + the message_queued mirror live in enqueueOutgoingMessage.
|
|
661
|
+
this.enqueueOutgoingMessage({ prompt, attachments, sendOptions: options })
|
|
662
|
+
return
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
if (!this._processReady) {
|
|
666
|
+
if (this._pendingQueue.length >= 3) {
|
|
667
|
+
this.emit('error', { message: 'Pending message queue full (max 3) — message discarded' })
|
|
668
|
+
return
|
|
669
|
+
}
|
|
670
|
+
// #4828: session-scoped when init has fired (queuing typically happens
|
|
671
|
+
// pre-init or during respawn — both can race with the binding).
|
|
672
|
+
;(this._log || log).info(`Process not ready, queuing message (queue depth: ${this._pendingQueue.length + 1})`)
|
|
673
|
+
this._pendingQueue.push({ prompt, attachments, options })
|
|
674
|
+
return
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
// Apply message transforms if configured
|
|
678
|
+
let transformedPrompt = prompt
|
|
679
|
+
if (this._transformPipeline.hasTransforms && typeof prompt === 'string') {
|
|
680
|
+
transformedPrompt = this._transformPipeline.apply(prompt, {
|
|
681
|
+
cwd: this.cwd,
|
|
682
|
+
model: this.model,
|
|
683
|
+
isVoiceInput: !!options.isVoice,
|
|
684
|
+
platform: process.platform,
|
|
685
|
+
})
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
// Per-skill injection mode (#3200): skills with `injection: prepend`
|
|
689
|
+
// need to ride on the first user message. The append/system bucket is
|
|
690
|
+
// already wired through `--append-system-prompt` at process start
|
|
691
|
+
// (see _buildArgs); only the prepend bucket is handled here, once
|
|
692
|
+
// per session.
|
|
693
|
+
//
|
|
694
|
+
// `_skillsPrepended` is NOT flipped here — we wait for the stdin write
|
|
695
|
+
// to succeed (#3225). If the write throws (EPIPE on a dead child), a
|
|
696
|
+
// retry needs to re-include the prepend bucket, otherwise the skill
|
|
697
|
+
// text is silently lost. The flag is set just after the successful
|
|
698
|
+
// `_child.stdin.write(...)` below.
|
|
699
|
+
let willPrependSkills = false
|
|
700
|
+
if (!this._skillsPrepended && typeof transformedPrompt === 'string') {
|
|
701
|
+
const prependText = typeof this._buildPrependPrompt === 'function'
|
|
702
|
+
? this._buildPrependPrompt()
|
|
703
|
+
: ''
|
|
704
|
+
if (prependText) {
|
|
705
|
+
transformedPrompt = `${prependText}\n\n---\n\n${transformedPrompt}`
|
|
706
|
+
willPrependSkills = true
|
|
707
|
+
} else {
|
|
708
|
+
// Nothing to prepend — flag flip is a no-op cost-saver only;
|
|
709
|
+
// mark prepended so we skip the cost on every subsequent turn.
|
|
710
|
+
willPrependSkills = true
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
this._isBusy = true
|
|
715
|
+
this._messageCounter++
|
|
716
|
+
// `msg-{bootPrefix}-{counter}` — see BaseSession constructor for why
|
|
717
|
+
// the boot-unique prefix is needed (#3700). Format change does not
|
|
718
|
+
// affect the wire schema; clients treat messageId as opaque string.
|
|
719
|
+
this._currentMessageId = `msg-${this._messageIdPrefix}-${this._messageCounter}`
|
|
720
|
+
this._currentCtx = { hasStreamStarted: false, didStreamText: false, assistantTextSeen: 0, currentContentBlockType: null, currentToolName: null, currentToolUseId: null, toolInputChunks: '', toolInputBytes: 0, toolInputOverflow: false }
|
|
721
|
+
|
|
722
|
+
const content = buildContentBlocks(transformedPrompt, attachments)
|
|
723
|
+
|
|
724
|
+
const ndjson = JSON.stringify({
|
|
725
|
+
type: 'user',
|
|
726
|
+
message: {
|
|
727
|
+
role: 'user',
|
|
728
|
+
content,
|
|
729
|
+
},
|
|
730
|
+
})
|
|
731
|
+
|
|
732
|
+
// #4828: session-scoped when init has fired. The very first message
|
|
733
|
+
// sends pre-init (CLI's `init` arrives in the first response), so the
|
|
734
|
+
// first turn falls back to module-level `log`; all subsequent sends
|
|
735
|
+
// route through `this._log`.
|
|
736
|
+
;(this._log || log).info(`Sending message ${this._currentMessageId}: "${(prompt || '').slice(0, 60)}"${attachments?.length ? ` (+${attachments.length} attachment(s))` : ''}`)
|
|
737
|
+
try {
|
|
738
|
+
this._child.stdin.write(ndjson + '\n')
|
|
739
|
+
} catch (err) {
|
|
740
|
+
// #4828: session-scoped when init has fired.
|
|
741
|
+
;(this._log || log).error(`stdin.write failed (sendMessage): ${err.message}`)
|
|
742
|
+
this._clearMessageState()
|
|
743
|
+
this.emit('error', { message: `Failed to send message: ${err.message}` })
|
|
744
|
+
return
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
// Skills text is committed to the wire — safe to flip the flag now (#3225).
|
|
748
|
+
// If the write threw above we returned early, leaving the flag false so
|
|
749
|
+
// the next attempt re-injects the prepend bucket.
|
|
750
|
+
if (willPrependSkills) {
|
|
751
|
+
this._skillsPrepended = true
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
// Safety timeouts: soft warning + hard cap. Both armed on every
|
|
755
|
+
// activity; soft fires `inactivity_warning` (session stays alive),
|
|
756
|
+
// hard fires the existing kill path. Both paused while a permission
|
|
757
|
+
// prompt is outstanding (#2831) — waiting on user input is not
|
|
758
|
+
// inactivity. Defaults + overrides documented in BaseSession.
|
|
759
|
+
this._armResultTimeout()
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/**
|
|
763
|
+
* Arm the SOFT-warning + HARD-cap + STREAM-STALL timers in parallel.
|
|
764
|
+
* No-op when paused because of a pending permission prompt (#2831).
|
|
765
|
+
* Windows are configurable per server via config.resultTimeoutMs /
|
|
766
|
+
* hardTimeoutMs / streamStallTimeoutMs (#3749 / #3899 / #4467).
|
|
767
|
+
*
|
|
768
|
+
* Stall timer is only armed when `_streamStallTimeoutMs > 0` —
|
|
769
|
+
* operators can disable the active-recovery path via config 0.
|
|
770
|
+
*
|
|
771
|
+
* All timers are cleared at the top of every call, so any activity-
|
|
772
|
+
* triggered reset (`_handleStdoutLine`) restarts the silence windows
|
|
773
|
+
* from zero. That's by design: every cap bounds *silent* stretches,
|
|
774
|
+
* not the wall-clock session duration.
|
|
775
|
+
*/
|
|
776
|
+
_armResultTimeout() {
|
|
777
|
+
if (this._resultTimeout) clearTimeout(this._resultTimeout)
|
|
778
|
+
if (this._hardTimeout) clearTimeout(this._hardTimeout)
|
|
779
|
+
if (this._streamStallTimeout) clearTimeout(this._streamStallTimeout)
|
|
780
|
+
this._resultTimeout = null
|
|
781
|
+
this._hardTimeout = null
|
|
782
|
+
this._streamStallTimeout = null
|
|
783
|
+
if (this._resultTimeoutPaused) return
|
|
784
|
+
this._resultTimeout = setTimeout(() => {
|
|
785
|
+
this._resultTimeout = null
|
|
786
|
+
this._handleInactivityWarning()
|
|
787
|
+
}, this._resultTimeoutMs)
|
|
788
|
+
this._hardTimeout = setTimeout(() => {
|
|
789
|
+
this._hardTimeout = null
|
|
790
|
+
this._handleHardTimeout()
|
|
791
|
+
}, this._hardTimeoutMs)
|
|
792
|
+
// #4467: only arm if configured > 0 (operators can disable).
|
|
793
|
+
if (this._streamStallTimeoutMs > 0) {
|
|
794
|
+
this._streamStallTimeout = setTimeout(() => {
|
|
795
|
+
this._streamStallTimeout = null
|
|
796
|
+
this._handleStreamStall()
|
|
797
|
+
}, this._streamStallTimeoutMs)
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/**
|
|
802
|
+
* Handle the SOFT inactivity warning (#3899). Fired after
|
|
803
|
+
* `_resultTimeoutMs` of silence with no activity to reset it.
|
|
804
|
+
*
|
|
805
|
+
* Unlike `_handleHardTimeout`, this does NOT clear busy state,
|
|
806
|
+
* does NOT auto-deny pending permissions, and does NOT emit `error`.
|
|
807
|
+
* It just emits a transient `inactivity_warning` event so the client
|
|
808
|
+
* can render a check-in affordance ("Status update?") and (if the
|
|
809
|
+
* server has push wired) deliver an Expo notification.
|
|
810
|
+
*
|
|
811
|
+
* The hard-cap timer keeps running — if the user never engages, the
|
|
812
|
+
* kill path eventually fires anyway. The soft timer is NOT re-armed
|
|
813
|
+
* here: each silent stretch produces exactly one warning (subsequent
|
|
814
|
+
* activity resets BOTH timers, so the next stretch fires a fresh
|
|
815
|
+
* warning).
|
|
816
|
+
*/
|
|
817
|
+
_handleInactivityWarning() {
|
|
818
|
+
if (!this._isBusy) return
|
|
819
|
+
const idleMs = this._resultTimeoutMs
|
|
820
|
+
const friendly = formatIdleDuration(idleMs)
|
|
821
|
+
// #4828: session-scoped (inactivity warning fires from active turn).
|
|
822
|
+
;(this._log || log).info(`Inactivity warning (${friendly}) — session alive, prompting check-in`)
|
|
823
|
+
this.emit('inactivity_warning', {
|
|
824
|
+
messageId: this._currentMessageId,
|
|
825
|
+
idleMs,
|
|
826
|
+
prefab: 'Status update?',
|
|
827
|
+
})
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* Handle the HARD-cap timeout (#3899; pre-#3899 this was the only
|
|
832
|
+
* handler — kept as the absolute backstop for genuinely stuck
|
|
833
|
+
* sessions). Before clearing state, emit `permission_expired` for
|
|
834
|
+
* any registered pending permissions so the client UI clears stale
|
|
835
|
+
* prompts (#2831). Without this, late user approvals would resolve
|
|
836
|
+
* into a dead message context and no response ever streams.
|
|
837
|
+
*/
|
|
838
|
+
_handleHardTimeout() {
|
|
839
|
+
if (!this._isBusy) return
|
|
840
|
+
const friendly = formatIdleDuration(this._hardTimeoutMs)
|
|
841
|
+
// #4828: session-scoped (hard-cap fires from active turn).
|
|
842
|
+
;(this._log || log).warn(`Hard-cap timeout (${friendly}) — force-clearing busy state`)
|
|
843
|
+
// Fire permission_expired for every pending permission we know about
|
|
844
|
+
// so the client clears the stale prompt.
|
|
845
|
+
for (const requestId of this._pendingPermissionIds) {
|
|
846
|
+
this.emit('permission_expired', {
|
|
847
|
+
requestId,
|
|
848
|
+
message: 'Permission request expired (session timeout)',
|
|
849
|
+
})
|
|
850
|
+
}
|
|
851
|
+
this._pendingPermissionIds.clear()
|
|
852
|
+
this._emitInterruptedTurnResult(this._hardTimeoutMs)
|
|
853
|
+
this.emit('error', { message: `Response timed out after ${friendly}` })
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
// #4467: stream-stall recovery. Fires when the child has been silent
|
|
857
|
+
// for `_streamStallTimeoutMs` despite the session being busy — typically
|
|
858
|
+
// a half-open TCP to the Anthropic API that the OS hasn't surfaced yet.
|
|
859
|
+
// Logs with context, emits `error` with `code: 'stream_stall'` so the
|
|
860
|
+
// dashboard can show a distinct "Stream stalled — retry?" affordance,
|
|
861
|
+
// then clears busy state so the user CAN actually retry.
|
|
862
|
+
_handleStreamStall() {
|
|
863
|
+
if (!this._isBusy) return
|
|
864
|
+
const friendly = formatIdleDuration(this._streamStallTimeoutMs)
|
|
865
|
+
// #4828: session-scoped (stall fires from active turn).
|
|
866
|
+
;(this._log || log).warn(
|
|
867
|
+
`Stream stalled (${friendly}, messageId=${this._currentMessageId}) — clearing busy state for retry`,
|
|
868
|
+
)
|
|
869
|
+
this._emitInterruptedTurnResult(this._streamStallTimeoutMs)
|
|
870
|
+
this.emit('error', {
|
|
871
|
+
code: 'stream_stall',
|
|
872
|
+
message: `Stream stalled — no response for ${friendly}. Try sending again.`,
|
|
873
|
+
})
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
/**
|
|
877
|
+
* Notify the session that a permission request belonging to it is
|
|
878
|
+
* outstanding — pauses the inactivity timer so the session doesn't
|
|
879
|
+
* time out while waiting on user input. #2831.
|
|
880
|
+
*
|
|
881
|
+
* @param {string} requestId
|
|
882
|
+
*/
|
|
883
|
+
notifyPermissionPending(requestId) {
|
|
884
|
+
if (!requestId || this._pendingPermissionIds.has(requestId)) return
|
|
885
|
+
this._pendingPermissionIds.add(requestId)
|
|
886
|
+
if (this._pendingPermissionIds.size === 1) {
|
|
887
|
+
this._resultTimeoutPaused = true
|
|
888
|
+
// #3899: clear BOTH the soft warning and hard cap. Awaiting user
|
|
889
|
+
// input is not inactivity; the timer trio re-arms together when
|
|
890
|
+
// the last pending permission resolves.
|
|
891
|
+
if (this._resultTimeout) {
|
|
892
|
+
clearTimeout(this._resultTimeout)
|
|
893
|
+
this._resultTimeout = null
|
|
894
|
+
}
|
|
895
|
+
if (this._hardTimeout) {
|
|
896
|
+
clearTimeout(this._hardTimeout)
|
|
897
|
+
this._hardTimeout = null
|
|
898
|
+
}
|
|
899
|
+
// #4467: clear the stall timer too — waiting on the user is not a stall.
|
|
900
|
+
if (this._streamStallTimeout) {
|
|
901
|
+
clearTimeout(this._streamStallTimeout)
|
|
902
|
+
this._streamStallTimeout = null
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
/**
|
|
908
|
+
* Notify the session that a permission request has been resolved
|
|
909
|
+
* (allow/deny/expired). When the last outstanding permission clears,
|
|
910
|
+
* the inactivity timer re-arms for a fresh window. #2831.
|
|
911
|
+
*
|
|
912
|
+
* @param {string} requestId
|
|
913
|
+
*/
|
|
914
|
+
notifyPermissionResolved(requestId) {
|
|
915
|
+
if (!requestId || !this._pendingPermissionIds.has(requestId)) return
|
|
916
|
+
this._pendingPermissionIds.delete(requestId)
|
|
917
|
+
if (this._pendingPermissionIds.size === 0) {
|
|
918
|
+
this._resultTimeoutPaused = false
|
|
919
|
+
if (this._isBusy) {
|
|
920
|
+
this._armResultTimeout()
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
/**
|
|
926
|
+
* Process one raw line from the CLI subprocess's stdout. Skips blanks
|
|
927
|
+
* and JSON-parse failures, then resets the inactivity timer (#3884 —
|
|
928
|
+
* every parsed event proves the subprocess is alive, so the timer was
|
|
929
|
+
* never meant to be wall-clock from send) before handing the parsed
|
|
930
|
+
* event off to `_handleEvent`. Extracted from the inline `rl.on('line')`
|
|
931
|
+
* handler so tests can drive the production path without standing up
|
|
932
|
+
* a real readline interface.
|
|
933
|
+
*
|
|
934
|
+
* @param {string} line
|
|
935
|
+
*/
|
|
936
|
+
_handleStdoutLine(line) {
|
|
937
|
+
if (!line.trim()) return
|
|
938
|
+
|
|
939
|
+
let data
|
|
940
|
+
try {
|
|
941
|
+
data = JSON.parse(line)
|
|
942
|
+
} catch {
|
|
943
|
+
return
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
// _armResultTimeout is a no-op while paused for a pending permission,
|
|
947
|
+
// so this is safe to call unconditionally on every event.
|
|
948
|
+
this._armResultTimeout()
|
|
949
|
+
|
|
950
|
+
this._handleEvent(data)
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
/**
|
|
954
|
+
* Handle a single parsed JSON event from Claude CLI stdout.
|
|
955
|
+
* Uses instance state (_currentMessageId, _currentCtx) instead of params.
|
|
956
|
+
*/
|
|
957
|
+
_handleEvent(data) {
|
|
958
|
+
switch (data.type) {
|
|
959
|
+
case 'system': {
|
|
960
|
+
if (data.subtype === 'init') {
|
|
961
|
+
this._sessionId = data.session_id
|
|
962
|
+
this._respawnCount = 0
|
|
963
|
+
// #4929: resume confirmed — claude CLI fired its first system.init,
|
|
964
|
+
// so the `--resume` (if any) succeeded. Clear the attempt tracker so
|
|
965
|
+
// a later unrelated exit doesn't get misclassified as resume failure,
|
|
966
|
+
// drop the stderr buffer (was only useful for failure diagnostics),
|
|
967
|
+
// and release the one-shot fallback latch so a FUTURE unknown-resume
|
|
968
|
+
// (e.g. user wipes ~/.claude/projects/ while chroxy keeps running and
|
|
969
|
+
// then crashes) can fall back again.
|
|
970
|
+
this._attemptedResumeId = null
|
|
971
|
+
this._recentStderrLines = []
|
|
972
|
+
this._didFallbackFromUnknownResume = false
|
|
973
|
+
// #4828: bind the session-scoped logger now that session_id is
|
|
974
|
+
// known. Subsequent log lines route through the WsServer log
|
|
975
|
+
// fan-out (#4787) to dashboards bound to this session.
|
|
976
|
+
this._log = loggerForSession('cli-session', data.session_id)
|
|
977
|
+
// #3687: persist the actual model the CLI booted with so
|
|
978
|
+
// sendSessionInfo (replay on reconnect / tab switch) reports the
|
|
979
|
+
// truth instead of `null` when the user didn't specify a model.
|
|
980
|
+
if (typeof data.model === 'string' && data.model) {
|
|
981
|
+
this.bootedModel = data.model
|
|
982
|
+
}
|
|
983
|
+
;(this._log || log).info(`Session initialized: ${data.session_id}`)
|
|
984
|
+
this.emit('ready', {
|
|
985
|
+
sessionId: data.session_id,
|
|
986
|
+
model: data.model,
|
|
987
|
+
tools: data.tools,
|
|
988
|
+
})
|
|
989
|
+
// Emit MCP server status if present (including empty list to clear stale state)
|
|
990
|
+
if (Array.isArray(data.mcp_servers)) {
|
|
991
|
+
if (data.mcp_servers.length > 0) {
|
|
992
|
+
// #4828: session-scoped (post-init).
|
|
993
|
+
;(this._log || log).info(`MCP servers: ${data.mcp_servers.map(s => `${s.name}(${s.status})`).join(', ')}`)
|
|
994
|
+
}
|
|
995
|
+
this.emit('mcp_servers', { servers: data.mcp_servers })
|
|
996
|
+
}
|
|
997
|
+
} else {
|
|
998
|
+
// Forward non-init system events (e.g. usage limits, sub-agent
|
|
999
|
+
// notifications) as system messages to the client
|
|
1000
|
+
const text = data.message || data.text || data.subtype || 'System event'
|
|
1001
|
+
// #4828: session-scoped (non-init system event arrives after init).
|
|
1002
|
+
;(this._log || log).info(`System event (${data.subtype || 'unknown'}): ${text}`)
|
|
1003
|
+
this.emit('message', {
|
|
1004
|
+
type: 'system',
|
|
1005
|
+
content: text,
|
|
1006
|
+
timestamp: Date.now(),
|
|
1007
|
+
})
|
|
1008
|
+
}
|
|
1009
|
+
break
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
case 'stream_event': {
|
|
1013
|
+
const event = data.event
|
|
1014
|
+
if (!event) break
|
|
1015
|
+
|
|
1016
|
+
const messageId = this._currentMessageId
|
|
1017
|
+
const ctx = this._currentCtx
|
|
1018
|
+
if (!messageId || !ctx) break
|
|
1019
|
+
|
|
1020
|
+
switch (event.type) {
|
|
1021
|
+
case 'content_block_start': {
|
|
1022
|
+
const blockType = event.content_block?.type
|
|
1023
|
+
ctx.currentContentBlockType = blockType
|
|
1024
|
+
|
|
1025
|
+
if (blockType === 'text') {
|
|
1026
|
+
if (!ctx.hasStreamStarted) {
|
|
1027
|
+
ctx.hasStreamStarted = true
|
|
1028
|
+
this.emit('stream_start', { messageId })
|
|
1029
|
+
}
|
|
1030
|
+
} else if (blockType === 'tool_use') {
|
|
1031
|
+
ctx.currentToolName = event.content_block.name
|
|
1032
|
+
ctx.toolInputChunks = ''
|
|
1033
|
+
ctx.toolInputBytes = 0
|
|
1034
|
+
ctx.toolInputOverflow = false
|
|
1035
|
+
// Delegate to the shared parser so CliSession + SdkSession
|
|
1036
|
+
// emit identical tool_start payloads (see
|
|
1037
|
+
// claude-stream-parser.js for the toolId-derivation rules).
|
|
1038
|
+
const toolStartData = buildToolStartData(messageId, event.content_block)
|
|
1039
|
+
// #4778: align ctx with the wire-emitted toolUseId so the
|
|
1040
|
+
// synthesized fallback (`${messageId}-tool` when
|
|
1041
|
+
// content_block.id is missing) propagates to
|
|
1042
|
+
// _applyToolInputSemantics → user_question / agent_spawned
|
|
1043
|
+
// and _activeAgents.set(). Without this, ctx.currentToolUseId
|
|
1044
|
+
// stayed undefined on the fallback path and downstream
|
|
1045
|
+
// payloads carried toolUseId=undefined.
|
|
1046
|
+
ctx.currentToolUseId = toolStartData.toolUseId
|
|
1047
|
+
this.emit('tool_start', toolStartData)
|
|
1048
|
+
// #4628: track so _clearMessageState (or _emitResult) can
|
|
1049
|
+
// sweep on turn-end if the API ever drops a tool_result.
|
|
1050
|
+
this._trackToolStart(toolStartData.toolUseId, event.content_block.name)
|
|
1051
|
+
}
|
|
1052
|
+
break
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
case 'content_block_delta': {
|
|
1056
|
+
const delta = event.delta
|
|
1057
|
+
if (!delta) break
|
|
1058
|
+
|
|
1059
|
+
if (delta.type === 'text_delta' && ctx.currentContentBlockType === 'text') {
|
|
1060
|
+
if (!ctx.hasStreamStarted) {
|
|
1061
|
+
ctx.hasStreamStarted = true
|
|
1062
|
+
this.emit('stream_start', { messageId })
|
|
1063
|
+
}
|
|
1064
|
+
ctx.didStreamText = true
|
|
1065
|
+
this.emit('stream_delta', { messageId, delta: delta.text })
|
|
1066
|
+
} else if (delta.type === 'input_json_delta' && ctx.currentContentBlockType === 'tool_use') {
|
|
1067
|
+
if (typeof delta.partial_json === 'string' && !ctx.toolInputOverflow) {
|
|
1068
|
+
const chunkBytes = Buffer.byteLength(delta.partial_json, 'utf8')
|
|
1069
|
+
if (ctx.toolInputBytes + chunkBytes > this._maxToolInput) {
|
|
1070
|
+
ctx.toolInputChunks = ''
|
|
1071
|
+
ctx.toolInputOverflow = true
|
|
1072
|
+
// #4828: session-scoped (stream_event fires post-init).
|
|
1073
|
+
;(this._log || log).warn(`toolInputChunks exceeded ${this._maxToolInput} bytes, discarding buffer`)
|
|
1074
|
+
this.emit('error', {
|
|
1075
|
+
message: `Tool input too large (>${Math.round(this._maxToolInput / 1024)}KB) for ${ctx.currentToolName || 'unknown tool'} — input was truncated`,
|
|
1076
|
+
})
|
|
1077
|
+
} else {
|
|
1078
|
+
ctx.toolInputChunks += delta.partial_json
|
|
1079
|
+
ctx.toolInputBytes += chunkBytes
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
break
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
case 'content_block_stop': {
|
|
1087
|
+
if (ctx && ctx.currentToolName) {
|
|
1088
|
+
this._applyToolInputSemantics(ctx)
|
|
1089
|
+
}
|
|
1090
|
+
if (ctx) {
|
|
1091
|
+
ctx.currentContentBlockType = null
|
|
1092
|
+
ctx.currentToolName = null
|
|
1093
|
+
ctx.currentToolUseId = null
|
|
1094
|
+
ctx.toolInputChunks = ''
|
|
1095
|
+
}
|
|
1096
|
+
break
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
break
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
case 'assistant': {
|
|
1103
|
+
// The assistant event fires repeatedly with --include-partial-messages,
|
|
1104
|
+
// delivering incrementally growing text content. When stream_event events
|
|
1105
|
+
// provide real-time deltas, we skip assistant text (didStreamText guard).
|
|
1106
|
+
// Otherwise, derive streaming from the incremental assistant text growth
|
|
1107
|
+
// so the dashboard shows real-time token-by-token rendering.
|
|
1108
|
+
const ctx = this._currentCtx
|
|
1109
|
+
const messageId = this._currentMessageId
|
|
1110
|
+
const content = data.message?.content
|
|
1111
|
+
if (Array.isArray(content) && ctx && messageId) {
|
|
1112
|
+
// If stream_event deltas already drove streaming, skip assistant text
|
|
1113
|
+
if (ctx.didStreamText) {
|
|
1114
|
+
break
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
// Concatenate all text blocks to handle multi-block content safely
|
|
1118
|
+
let fullText = ''
|
|
1119
|
+
for (const block of content) {
|
|
1120
|
+
if (block.type === 'text' && block.text) fullText += block.text
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
const prevLen = ctx.assistantTextSeen
|
|
1124
|
+
if (fullText.length > prevLen) {
|
|
1125
|
+
if (!ctx.hasStreamStarted) {
|
|
1126
|
+
ctx.hasStreamStarted = true
|
|
1127
|
+
this.emit('stream_start', { messageId })
|
|
1128
|
+
}
|
|
1129
|
+
this.emit('stream_delta', { messageId, delta: fullText.slice(prevLen) })
|
|
1130
|
+
ctx.assistantTextSeen = fullText.length
|
|
1131
|
+
}
|
|
1132
|
+
// tool_use blocks are handled by content_block_start → tool_start event;
|
|
1133
|
+
// emitting them here too would create duplicate tool messages in the app
|
|
1134
|
+
}
|
|
1135
|
+
break
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
case 'user': {
|
|
1139
|
+
// Tool result content blocks appear in user-role messages during the tool loop
|
|
1140
|
+
emitToolResults(data.message?.content, this)
|
|
1141
|
+
break
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
case 'result': {
|
|
1145
|
+
if (data.session_id) {
|
|
1146
|
+
this._sessionId = data.session_id
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
const messageId = this._currentMessageId
|
|
1150
|
+
const ctx = this._currentCtx
|
|
1151
|
+
|
|
1152
|
+
// #5064 — Fallback for turns that complete without ever emitting
|
|
1153
|
+
// streamed assistant text. The canonical case is `/compact`: the
|
|
1154
|
+
// CLI returns the compaction summary in `data.result` but emits
|
|
1155
|
+
// either no `assistant` event at all, or one with empty/no-growth
|
|
1156
|
+
// text content, so the dashboard sees nothing. Mirror the SDK
|
|
1157
|
+
// fallback (sdk-session.js:801) and surface `data.result` as a
|
|
1158
|
+
// `message` of type `response` before the `result` event fires.
|
|
1159
|
+
// Guard on !hasStreamStarted so normal streamed turns aren't
|
|
1160
|
+
// double-emitted.
|
|
1161
|
+
//
|
|
1162
|
+
// #5088 — Same silent-disappear pattern for error-subtype text.
|
|
1163
|
+
// Some result events carry human-readable text in `data.error.subtype`
|
|
1164
|
+
// (e.g. permission_denied, usage_limit_exceeded) without any
|
|
1165
|
+
// streamed assistant content. Surface that text by emitting a
|
|
1166
|
+
// `type: 'error'` message (→ `messageType: 'error'` on the wire) so
|
|
1167
|
+
// downstream consumers render it as a distinct error bubble rather
|
|
1168
|
+
// than a normal reply. The `data.result` path above takes priority —
|
|
1169
|
+
// only fall back to error-subtype text when `data.result` was
|
|
1170
|
+
// missing/empty so we never double-emit for the same turn.
|
|
1171
|
+
if (!ctx?.hasStreamStarted && typeof data.result === 'string' && data.result.length > 0) {
|
|
1172
|
+
this.emit('message', {
|
|
1173
|
+
type: 'response',
|
|
1174
|
+
content: data.result,
|
|
1175
|
+
timestamp: Date.now(),
|
|
1176
|
+
})
|
|
1177
|
+
} else if (
|
|
1178
|
+
!ctx?.hasStreamStarted &&
|
|
1179
|
+
typeof data.error?.subtype === 'string' &&
|
|
1180
|
+
data.error.subtype.length > 0
|
|
1181
|
+
) {
|
|
1182
|
+
this.emit('message', {
|
|
1183
|
+
type: 'error',
|
|
1184
|
+
content: data.error.subtype,
|
|
1185
|
+
timestamp: Date.now(),
|
|
1186
|
+
})
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
// Close any open stream before emitting result
|
|
1190
|
+
if (ctx?.hasStreamStarted) {
|
|
1191
|
+
this.emit('stream_end', { messageId })
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
// Emit plan_ready before clearing state — the turn that calls
|
|
1195
|
+
// ExitPlanMode ends with a normal result event
|
|
1196
|
+
if (this._inPlanMode && this._planAllowedPrompts !== null) {
|
|
1197
|
+
this.emit('plan_ready', { allowedPrompts: this._planAllowedPrompts })
|
|
1198
|
+
this._inPlanMode = false
|
|
1199
|
+
this._planAllowedPrompts = null
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
this.emit('result', {
|
|
1203
|
+
sessionId: data.session_id,
|
|
1204
|
+
// #5629: `total_cost_usd` is forwarded verbatim from claude's
|
|
1205
|
+
// stream-json result. Historically this was `null` for subscription
|
|
1206
|
+
// runs (no dollar charge). On/after 2026-06-15 claude-cli draws on
|
|
1207
|
+
// the metered programmatic-credit pool, so this becomes REAL credit
|
|
1208
|
+
// spend — the session-manager finite-cost gate accumulates it the
|
|
1209
|
+
// same way it does api-key spend (see _trackUsage / the billing-class
|
|
1210
|
+
// cost contract there). No code change needed here; the field just
|
|
1211
|
+
// starts carrying a finite number for those runs.
|
|
1212
|
+
cost: data.total_cost_usd,
|
|
1213
|
+
duration: data.duration_ms,
|
|
1214
|
+
usage: data.usage,
|
|
1215
|
+
})
|
|
1216
|
+
|
|
1217
|
+
// Message complete — ready for next message
|
|
1218
|
+
this._clearMessageState()
|
|
1219
|
+
break
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
/**
|
|
1225
|
+
* Apply session-state side effects for tools whose accumulated
|
|
1226
|
+
* `toolInputChunks` JSON drives plan-mode flags, agent tracking, or
|
|
1227
|
+
* user-question prompts. Called at `content_block_stop` once the full
|
|
1228
|
+
* tool input has been buffered. Delegates the wire-format parsing to
|
|
1229
|
+
* the shared {@link extractToolInputSemantics} so SdkSession (which
|
|
1230
|
+
* receives the full input directly in `_handleToolUseBlock`) cannot
|
|
1231
|
+
* drift in how it interprets the same tool names.
|
|
1232
|
+
*
|
|
1233
|
+
* `ctx.toolInputChunks` is the empty string after overflow discard, so
|
|
1234
|
+
* AskUserQuestion / Task / ExitPlanMode paths that need a real payload
|
|
1235
|
+
* are naturally skipped on overflow; EnterPlanMode takes the no-input
|
|
1236
|
+
* path and still fires.
|
|
1237
|
+
*
|
|
1238
|
+
* @param {{ currentToolName: string|null, currentToolUseId: string|null, toolInputChunks: string }} ctx
|
|
1239
|
+
* @private
|
|
1240
|
+
*/
|
|
1241
|
+
_applyToolInputSemantics(ctx) {
|
|
1242
|
+
const toolName = ctx.currentToolName
|
|
1243
|
+
const toolUseId = ctx.currentToolUseId
|
|
1244
|
+
// `parseSucceeded` tracks whether the buffered JSON parsed without
|
|
1245
|
+
// throwing — distinct from `parsed != null`, because JSON.parse can
|
|
1246
|
+
// legally return falsy values (0, false, '', null) and the
|
|
1247
|
+
// pre-extraction code emitted on any successful parse regardless of
|
|
1248
|
+
// the parsed value. Gating on truthiness would silently drop those
|
|
1249
|
+
// payloads. (#4774 Copilot review)
|
|
1250
|
+
let parsed = null
|
|
1251
|
+
let parseSucceeded = false
|
|
1252
|
+
if (ctx.toolInputChunks) {
|
|
1253
|
+
try {
|
|
1254
|
+
parsed = JSON.parse(ctx.toolInputChunks)
|
|
1255
|
+
parseSucceeded = true
|
|
1256
|
+
} catch (err) {
|
|
1257
|
+
// Parse-failure logging matches the per-tool pre-extraction
|
|
1258
|
+
// messages so existing log scraping continues to work.
|
|
1259
|
+
if (toolName === 'AskUserQuestion') {
|
|
1260
|
+
// #4828: session-scoped (tool parsing runs strictly post-init).
|
|
1261
|
+
;(this._log || log).error(`Failed to parse AskUserQuestion input: ${err.message}`)
|
|
1262
|
+
return
|
|
1263
|
+
}
|
|
1264
|
+
if (toolName === 'Task') {
|
|
1265
|
+
;(this._log || log).warn(`Failed to parse Task tool input: ${err.message}`)
|
|
1266
|
+
return
|
|
1267
|
+
}
|
|
1268
|
+
if (toolName === 'ExitPlanMode') {
|
|
1269
|
+
;(this._log || log).warn(`Failed to parse ExitPlanMode input: ${err.message}`)
|
|
1270
|
+
// ExitPlanMode falls through with parseSucceeded=false so the
|
|
1271
|
+
// empty allowedPrompts default still applies.
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
const semantics = extractToolInputSemantics(toolName, parsed)
|
|
1277
|
+
if (!semantics) return
|
|
1278
|
+
|
|
1279
|
+
switch (semantics.kind) {
|
|
1280
|
+
case 'ask_user_question': {
|
|
1281
|
+
// The pre-extraction code required a non-empty buffer AND a
|
|
1282
|
+
// successful parse before emitting; preserve that gate via
|
|
1283
|
+
// `parseSucceeded` (truthiness of `parsed` would drop legal
|
|
1284
|
+
// falsy JSON values).
|
|
1285
|
+
if (!parseSucceeded) return
|
|
1286
|
+
// #4828: session-scoped.
|
|
1287
|
+
;(this._log || log).info(`AskUserQuestion detected (${toolUseId})`)
|
|
1288
|
+
this._waitingForAnswer = true
|
|
1289
|
+
this.emit('user_question', {
|
|
1290
|
+
toolUseId,
|
|
1291
|
+
questions: semantics.payload.questions,
|
|
1292
|
+
})
|
|
1293
|
+
return
|
|
1294
|
+
}
|
|
1295
|
+
case 'task': {
|
|
1296
|
+
if (!parseSucceeded) return
|
|
1297
|
+
const agentInfo = {
|
|
1298
|
+
toolUseId,
|
|
1299
|
+
description: semantics.payload.description,
|
|
1300
|
+
startedAt: Date.now(),
|
|
1301
|
+
}
|
|
1302
|
+
this._activeAgents.set(toolUseId, agentInfo)
|
|
1303
|
+
this.emit('agent_spawned', agentInfo)
|
|
1304
|
+
return
|
|
1305
|
+
}
|
|
1306
|
+
case 'enter_plan': {
|
|
1307
|
+
this._inPlanMode = true
|
|
1308
|
+
this.emit('plan_started')
|
|
1309
|
+
return
|
|
1310
|
+
}
|
|
1311
|
+
case 'exit_plan': {
|
|
1312
|
+
this._planAllowedPrompts = semantics.payload.allowedPrompts
|
|
1313
|
+
return
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
/**
|
|
1319
|
+
* Clear per-message state, marking us as ready for the next message.
|
|
1320
|
+
* After clearing, drains the next item from _pendingQueue (if any) so
|
|
1321
|
+
* that all queued messages are eventually delivered in FIFO order.
|
|
1322
|
+
*/
|
|
1323
|
+
_clearMessageState() {
|
|
1324
|
+
super._clearMessageState()
|
|
1325
|
+
this._waitingForAnswer = false
|
|
1326
|
+
this._currentCtx = null
|
|
1327
|
+
// Reset permission pause bookkeeping — the next message starts fresh.
|
|
1328
|
+
this._pendingPermissionIds.clear()
|
|
1329
|
+
this._resultTimeoutPaused = false
|
|
1330
|
+
// If plan mode is active but ExitPlanMode never arrived (interrupt/crash),
|
|
1331
|
+
// the flag is stale — reset it. In normal flow, _planAllowedPrompts is
|
|
1332
|
+
// non-null (set by ExitPlanMode) and plan_ready has already been emitted
|
|
1333
|
+
// + both flags reset before we reach here.
|
|
1334
|
+
if (this._inPlanMode && this._planAllowedPrompts === null) {
|
|
1335
|
+
this._inPlanMode = false
|
|
1336
|
+
}
|
|
1337
|
+
this._planAllowedPrompts = null
|
|
1338
|
+
if (this._interruptTimer) {
|
|
1339
|
+
clearTimeout(this._interruptTimer)
|
|
1340
|
+
this._interruptTimer = null
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
// Drain the next queued message on the next tick so that any synchronous
|
|
1344
|
+
// 'result' event listeners finish before sendMessage() is called.
|
|
1345
|
+
// This prevents re-entrancy where both a result listener and the drain
|
|
1346
|
+
// both call sendMessage() in the same tick, sending two messages when
|
|
1347
|
+
// only one is expected.
|
|
1348
|
+
//
|
|
1349
|
+
// #5936: two distinct queues drain here, in priority order:
|
|
1350
|
+
// 1. `_outgoingQueue` (shared, BaseSession) — mid-turn send-while-busy
|
|
1351
|
+
// follow-ups. Flushed via dequeueNextOutgoing() (which emits
|
|
1352
|
+
// message_dequeued + re-dispatches on nextTick). This is the common
|
|
1353
|
+
// case after a normal turn.
|
|
1354
|
+
// 2. `_pendingQueue` (CLI-only) — messages that arrived while the child
|
|
1355
|
+
// process was NOT ready (pre-init / respawn). Pre-#5936 behaviour,
|
|
1356
|
+
// unchanged. Only drained when the outgoing queue is empty so a single
|
|
1357
|
+
// turn flushes exactly one message and the next `result` flushes the
|
|
1358
|
+
// next (each re-dispatch re-sets _isBusy).
|
|
1359
|
+
if (this._processReady) {
|
|
1360
|
+
if (this._outgoingQueue.length > 0) {
|
|
1361
|
+
this.dequeueNextOutgoing()
|
|
1362
|
+
} else if (this._pendingQueue.length > 0) {
|
|
1363
|
+
process.nextTick(() => {
|
|
1364
|
+
if (this._destroying) return
|
|
1365
|
+
if (!this._processReady || this._pendingQueue.length === 0) return
|
|
1366
|
+
const pending = this._pendingQueue.shift()
|
|
1367
|
+
// #4828: session-scoped (post-result, post-init).
|
|
1368
|
+
;(this._log || log).info(`Dequeuing next pending message after result (${this._pendingQueue.length} remaining)`)
|
|
1369
|
+
this.sendMessage(pending.prompt, pending.attachments, pending.options || {})
|
|
1370
|
+
})
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
/**
|
|
1376
|
+
* Kill the current child process (if any) and respawn.
|
|
1377
|
+
* Suppresses auto-respawn during the kill, clears timers, and starts fresh.
|
|
1378
|
+
*/
|
|
1379
|
+
_killAndRespawn() {
|
|
1380
|
+
// #4471: emit synthetic terminating events BEFORE setting _respawning,
|
|
1381
|
+
// otherwise the _handleChildClose guard short-circuits and the dashboard
|
|
1382
|
+
// never receives `agent_idle` — Stop stays stuck on panic-button +
|
|
1383
|
+
// mid-turn setModel paths.
|
|
1384
|
+
this._emitInterruptedTurnResult()
|
|
1385
|
+
|
|
1386
|
+
this._respawning = true
|
|
1387
|
+
this._processReady = false
|
|
1388
|
+
// #4887 — DO NOT null `_sessionId` here. `start()` reads it as the
|
|
1389
|
+
// `--resume` argument; clearing it would force the respawned subprocess
|
|
1390
|
+
// to mint a brand-new conversation and the model would see the new user
|
|
1391
|
+
// message with no prior turns — exactly the cold-start failure in #4887.
|
|
1392
|
+
// The session id is re-confirmed by the next `system.init` (claude CLI
|
|
1393
|
+
// echoes the resumed id back), so the in-process value stays accurate
|
|
1394
|
+
// even on the rare fork case.
|
|
1395
|
+
// #4828: drop the session-scoped logger so the next init re-binds it
|
|
1396
|
+
// (the underlying session_id is unchanged on a normal resume, but the
|
|
1397
|
+
// logger context is re-created on every init for symmetry with first-
|
|
1398
|
+
// boot — cheap and avoids any stale closure).
|
|
1399
|
+
this._log = null
|
|
1400
|
+
|
|
1401
|
+
// #4887 — the respawned child re-attaches to the prior conversation via
|
|
1402
|
+
// `--resume <_sessionId>`. The append/system bucket still rides on
|
|
1403
|
+
// `--append-system-prompt` at spawn (already in the new argv). The
|
|
1404
|
+
// prepend bucket is concatenated onto the FIRST user message; a respawn
|
|
1405
|
+
// means the next sendMessage() is once again that first message. Reset
|
|
1406
|
+
// the flag so the prepend bucket flows through on the next turn (#3225).
|
|
1407
|
+
this._skillsPrepended = false
|
|
1408
|
+
|
|
1409
|
+
if (this._interruptTimer) {
|
|
1410
|
+
clearTimeout(this._interruptTimer)
|
|
1411
|
+
this._interruptTimer = null
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
if (this._respawnTimer) {
|
|
1415
|
+
clearTimeout(this._respawnTimer)
|
|
1416
|
+
this._respawnTimer = null
|
|
1417
|
+
}
|
|
1418
|
+
this._respawnScheduled = false
|
|
1419
|
+
|
|
1420
|
+
// #3966: release the soft + hard inactivity timers armed for the dropped
|
|
1421
|
+
// turn. The panic-button path (`setPermissionMode('auto')` while busy)
|
|
1422
|
+
// and `setModel` mid-turn both detach the in-flight message context, so
|
|
1423
|
+
// these timers would otherwise either fire `_handleHardTimeout` against
|
|
1424
|
+
// a stale messageId or linger past test boundaries as phantom timers.
|
|
1425
|
+
if (this._resultTimeout) {
|
|
1426
|
+
clearTimeout(this._resultTimeout)
|
|
1427
|
+
this._resultTimeout = null
|
|
1428
|
+
}
|
|
1429
|
+
if (this._hardTimeout) {
|
|
1430
|
+
clearTimeout(this._hardTimeout)
|
|
1431
|
+
this._hardTimeout = null
|
|
1432
|
+
}
|
|
1433
|
+
// #4467: release the stream-stall timer too for the same reason.
|
|
1434
|
+
if (this._streamStallTimeout) {
|
|
1435
|
+
clearTimeout(this._streamStallTimeout)
|
|
1436
|
+
this._streamStallTimeout = null
|
|
1437
|
+
}
|
|
1438
|
+
this._resultTimeoutPaused = false
|
|
1439
|
+
|
|
1440
|
+
this._cleanupReadlines()
|
|
1441
|
+
|
|
1442
|
+
if (this._child) {
|
|
1443
|
+
const oldChild = this._child
|
|
1444
|
+
this._child = null
|
|
1445
|
+
|
|
1446
|
+
let didClose = false
|
|
1447
|
+
const respawn = () => {
|
|
1448
|
+
if (didClose) return
|
|
1449
|
+
didClose = true
|
|
1450
|
+
this._respawning = false
|
|
1451
|
+
this._respawnCount = 0
|
|
1452
|
+
if (this._destroying) return
|
|
1453
|
+
this.start()
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
oldChild.on('close', () => {
|
|
1457
|
+
clearTimeout(forceKillTimer)
|
|
1458
|
+
respawn()
|
|
1459
|
+
})
|
|
1460
|
+
|
|
1461
|
+
// Force-kill after 10s if process doesn't exit cleanly
|
|
1462
|
+
const forceKillTimer = setTimeout(() => {
|
|
1463
|
+
if (!didClose) {
|
|
1464
|
+
// #4828: session-scoped if init has fired before kill.
|
|
1465
|
+
;(this._log || log).warn('Process did not exit after 10s, force-killing')
|
|
1466
|
+
try {
|
|
1467
|
+
forceKill(oldChild)
|
|
1468
|
+
} catch (_err) {
|
|
1469
|
+
// Process may already be gone, that's fine
|
|
1470
|
+
}
|
|
1471
|
+
respawn()
|
|
1472
|
+
}
|
|
1473
|
+
}, 10000)
|
|
1474
|
+
// #6043: fire-and-forget respawn safety net — never gate process exit on
|
|
1475
|
+
// it. Respawn runs either off the child's 'close' or this fallback; if the
|
|
1476
|
+
// loop is otherwise dead the process is exiting and there is nothing to
|
|
1477
|
+
// respawn into, so holding the loop open for 10s only leaks (notably in
|
|
1478
|
+
// tests with a mock child that never emits 'close').
|
|
1479
|
+
if (typeof forceKillTimer.unref === 'function') forceKillTimer.unref()
|
|
1480
|
+
|
|
1481
|
+
oldChild.kill('SIGTERM')
|
|
1482
|
+
} else {
|
|
1483
|
+
this._respawning = false
|
|
1484
|
+
this._respawnCount = 0
|
|
1485
|
+
if (!this._destroying) {
|
|
1486
|
+
this.start()
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
/** Clean up readline interfaces */
|
|
1492
|
+
_cleanupReadlines() {
|
|
1493
|
+
if (this._rl) {
|
|
1494
|
+
this._rl.close()
|
|
1495
|
+
this._rl = null
|
|
1496
|
+
}
|
|
1497
|
+
if (this._stderrRL) {
|
|
1498
|
+
this._stderrRL.close()
|
|
1499
|
+
this._stderrRL = null
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
/**
|
|
1504
|
+
* Change the model used for subsequent messages.
|
|
1505
|
+
* Kills the current process and respawns with the new model (new session).
|
|
1506
|
+
* #5374: BaseSession.setModel owns the guard + resolve and fires this hook.
|
|
1507
|
+
*/
|
|
1508
|
+
_onModelChanged() {
|
|
1509
|
+
// #4828: session-scoped if init has fired before the model change.
|
|
1510
|
+
;(this._log || log).info(`Model changed to ${this.model || 'default'}, restarting process`)
|
|
1511
|
+
this._killAndRespawn()
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
_onPermissionModeChanged(mode) {
|
|
1515
|
+
// #3729 panic-button semantics: BaseSession.setPermissionMode lets `'auto'`
|
|
1516
|
+
// bypass the `_isBusy` guard, so flipping to auto mid-turn IS destructive —
|
|
1517
|
+
// the in-flight `claude -p` process is killed and respawned, dropping the
|
|
1518
|
+
// current turn. This is by design (parity with SDK auto-resolve of pending
|
|
1519
|
+
// prompts); see #3735 for the regression test pinning this behavior.
|
|
1520
|
+
// #4828: session-scoped if init has fired.
|
|
1521
|
+
;(this._log || log).info(`Permission mode changed to ${mode}, restarting process`)
|
|
1522
|
+
this._killAndRespawn()
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
/**
|
|
1526
|
+
* Send a response to an AskUserQuestion prompt.
|
|
1527
|
+
* Claude is waiting for user input on stdin mid-turn, so we bypass
|
|
1528
|
+
* the _isBusy check and write directly.
|
|
1529
|
+
*/
|
|
1530
|
+
respondToQuestion(text) {
|
|
1531
|
+
if (!this._child || !this._waitingForAnswer) return
|
|
1532
|
+
this._waitingForAnswer = false
|
|
1533
|
+
const ndjson = JSON.stringify({
|
|
1534
|
+
type: 'user',
|
|
1535
|
+
message: {
|
|
1536
|
+
role: 'user',
|
|
1537
|
+
content: [{ type: 'text', text }],
|
|
1538
|
+
},
|
|
1539
|
+
})
|
|
1540
|
+
try {
|
|
1541
|
+
this._child.stdin.write(ndjson + '\n')
|
|
1542
|
+
} catch (err) {
|
|
1543
|
+
// #4828: session-scoped (respondToQuestion fires strictly post-init).
|
|
1544
|
+
;(this._log || log).error(`stdin.write failed (respondToQuestion): ${err.message}`)
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
// Synthetic terminating events for an interrupted turn. The `result` emit
|
|
1549
|
+
// is load-bearing: event-normalizer fans it to `agent_idle`, which clears
|
|
1550
|
+
// the dashboard's streamingMessageId/isIdle. Without it, an interrupted
|
|
1551
|
+
// turn leaves Stop stuck visible and "Thinking…" permanent.
|
|
1552
|
+
// Mirrors TUI #4010. cost:null skips session-manager billing.
|
|
1553
|
+
_emitInterruptedTurnResult(duration = 0) {
|
|
1554
|
+
if (!this._isBusy || !this._currentMessageId) return
|
|
1555
|
+
const messageId = this._currentMessageId
|
|
1556
|
+
const sessionId = this._sessionId
|
|
1557
|
+
if (this._currentCtx?.hasStreamStarted) {
|
|
1558
|
+
this.emit('stream_end', { messageId })
|
|
1559
|
+
}
|
|
1560
|
+
this._clearMessageState()
|
|
1561
|
+
this.emit('result', { cost: null, duration, usage: null, sessionId })
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
_handleChildClose(code) {
|
|
1565
|
+
this._cleanupReadlines()
|
|
1566
|
+
this._processReady = false
|
|
1567
|
+
this._child = null
|
|
1568
|
+
|
|
1569
|
+
// #4602: capture-and-clear up front so the flag never leaks past a
|
|
1570
|
+
// close, even when the _destroying / _respawning guards short-circuit
|
|
1571
|
+
// (e.g. user clicks Stop → flag set → model switch fires
|
|
1572
|
+
// _killAndRespawn → _respawning short-circuit hits, but the flag must
|
|
1573
|
+
// not persist to silently swallow a real crash on a future close).
|
|
1574
|
+
const wasIntentionalStop = this._consumeIntentionalStop()
|
|
1575
|
+
|
|
1576
|
+
// #4929: capture the resume-attempt state for this child BEFORE the
|
|
1577
|
+
// destroy/respawn short-circuits return. A `--resume <id>` that the CLI
|
|
1578
|
+
// rejected ("No conversation found …") exits the child quickly without
|
|
1579
|
+
// ever emitting system.init, so `_attemptedResumeId` is still set when we
|
|
1580
|
+
// get here. We mirror the wasIntentionalStop capture-and-clear pattern so
|
|
1581
|
+
// the flag never leaks past a close.
|
|
1582
|
+
const attemptedResumeId = this._attemptedResumeId
|
|
1583
|
+
const stderrLines = this._recentStderrLines
|
|
1584
|
+
this._attemptedResumeId = null
|
|
1585
|
+
this._recentStderrLines = []
|
|
1586
|
+
|
|
1587
|
+
if (this._destroying) return
|
|
1588
|
+
if (this._respawning) return
|
|
1589
|
+
|
|
1590
|
+
this._emitInterruptedTurnResult()
|
|
1591
|
+
|
|
1592
|
+
// #4602: user-initiated Stop sent SIGINT via interrupt(). The child
|
|
1593
|
+
// exited cleanly as a result — do NOT show "exited unexpectedly" and
|
|
1594
|
+
// do NOT auto-respawn the child the user explicitly stopped.
|
|
1595
|
+
if (wasIntentionalStop) {
|
|
1596
|
+
// #4828: session-scoped if init had fired before the stop.
|
|
1597
|
+
;(this._log || log).info(`Process exited (code ${code}) after user stop`)
|
|
1598
|
+
this.emit('stopped', { code })
|
|
1599
|
+
return
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
// #4929: classify as resume-unknown when a `--resume <id>` spawn exited
|
|
1603
|
+
// before claude CLI fired its first system.init AND the buffered stderr
|
|
1604
|
+
// matches a known "no conversation found" pattern. Without this branch the
|
|
1605
|
+
// generic "exited unexpectedly" toast + auto-respawn loop would re-pass
|
|
1606
|
+
// the same broken resume id forever (the bug reported in #4929).
|
|
1607
|
+
//
|
|
1608
|
+
// Detection requires BOTH conditions:
|
|
1609
|
+
// - attemptedResumeId is set (the spawn passed `--resume`)
|
|
1610
|
+
// - stderrIndicatesUnknownResume(stderrLines) matched a known pattern
|
|
1611
|
+
//
|
|
1612
|
+
// We deliberately require the pattern match instead of treating "any exit
|
|
1613
|
+
// before init while resuming" as resume-unknown — a genuine CLI crash
|
|
1614
|
+
// mid-resume (network blip, OAuth refresh, OS OOM kill) would otherwise
|
|
1615
|
+
// get misclassified and we'd silently wipe the user's `_sessionId`. The
|
|
1616
|
+
// pattern matcher is the load-bearing safety net.
|
|
1617
|
+
if (attemptedResumeId && stderrIndicatesUnknownResume(stderrLines)) {
|
|
1618
|
+
// One-shot fallback latch (#4929 — see constructor). If we already
|
|
1619
|
+
// fell back from an unknown resume earlier this lifecycle and the
|
|
1620
|
+
// fresh spawn ALSO died with the same pattern, escalate to a terminal
|
|
1621
|
+
// "auto-recovery exhausted" path: surface a distinct error code and
|
|
1622
|
+
// STOP the auto-respawn so the session sits down until the user takes
|
|
1623
|
+
// a deliberate next step.
|
|
1624
|
+
//
|
|
1625
|
+
// #4948: previously this branch still called `_scheduleRespawn()` —
|
|
1626
|
+
// but the next spawn would re-confirm via `system.init` (clearing the
|
|
1627
|
+
// latch AND re-setting `_sessionId` from the init payload) which made
|
|
1628
|
+
// the "give up" toast immediately precede what looked like a normal
|
|
1629
|
+
// recovery. Two problems with that:
|
|
1630
|
+
// 1. The user sees a confusing "auto-recovery gave up" message and
|
|
1631
|
+
// then the session appears to be working again, with no signal
|
|
1632
|
+
// whether the underlying issue is actually resolved.
|
|
1633
|
+
// 2. If the fresh-start spawn ALSO fails the same way, we'd just
|
|
1634
|
+
// respawn again, ad infinitum until `_respawnCount` hits the cap
|
|
1635
|
+
// buried inside `_scheduleRespawn`.
|
|
1636
|
+
// Stopping here gives a clean terminal state: `_sessionId` is null,
|
|
1637
|
+
// the latch resets so a future explicit start can re-arm the one-shot
|
|
1638
|
+
// fallback, and the operator/UI gets an unambiguous "the auto-recovery
|
|
1639
|
+
// gave up, you need to act" signal.
|
|
1640
|
+
if (this._didFallbackFromUnknownResume) {
|
|
1641
|
+
;(this._log || log).error(
|
|
1642
|
+
`Resume fallback also failed (code ${code}, attemptedResumeId=${attemptedResumeId}) — ` +
|
|
1643
|
+
'auto-recovery exhausted; will NOT respawn. User must start a fresh session manually.',
|
|
1644
|
+
)
|
|
1645
|
+
// Reset the latch so a future explicit user-driven start can re-arm
|
|
1646
|
+
// the one-shot fallback. Without this reset the latch would persist
|
|
1647
|
+
// past the terminal error and prevent recovery on the very next
|
|
1648
|
+
// manual start (which would silently skip the auto-fallback and
|
|
1649
|
+
// fall straight through to the generic-crash respawn loop).
|
|
1650
|
+
this._didFallbackFromUnknownResume = false
|
|
1651
|
+
// Keep `_sessionId = null` (was already cleared by the first
|
|
1652
|
+
// fallback branch below) so a manual restart omits `--resume` and
|
|
1653
|
+
// mints a brand-new conversation rather than re-attempting the
|
|
1654
|
+
// broken id a third time.
|
|
1655
|
+
this._sessionId = null
|
|
1656
|
+
this.emit('error', {
|
|
1657
|
+
code: 'resume_unknown_exhausted',
|
|
1658
|
+
message:
|
|
1659
|
+
'Auto-recovery exhausted: Claude CLI rejected the resumed conversation id and a fresh-start ' +
|
|
1660
|
+
'retry also failed. Start a new session manually to continue. ' +
|
|
1661
|
+
'Check the chroxy logs for the stderr from the claude subprocess.',
|
|
1662
|
+
attemptedResumeId,
|
|
1663
|
+
})
|
|
1664
|
+
return
|
|
1665
|
+
}
|
|
1666
|
+
|
|
1667
|
+
;(this._log || log).warn(
|
|
1668
|
+
`Resume rejected by claude CLI (code ${code}, attemptedResumeId=${attemptedResumeId}) — ` +
|
|
1669
|
+
'falling back to a fresh conversation. Prior transcript is preserved in the chroxy ring buffer ' +
|
|
1670
|
+
'but the model will not see the earlier turns (claude CLI does not know that conversation id).',
|
|
1671
|
+
)
|
|
1672
|
+
// Clear the broken id so the next spawn omits `--resume` and mints a
|
|
1673
|
+
// brand-new claude conversation. SessionManager will pick up the new
|
|
1674
|
+
// session_id from the next system.init via the existing
|
|
1675
|
+
// `resumeSessionId` getter → persistence chain (#4887).
|
|
1676
|
+
this._sessionId = null
|
|
1677
|
+
this._didFallbackFromUnknownResume = true
|
|
1678
|
+
// Reset _skillsPrepended so the prepend bucket flows onto the FIRST
|
|
1679
|
+
// user message of the fresh conversation (#3225) — mirrors the
|
|
1680
|
+
// _killAndRespawn handling, just for the resume-fallback path.
|
|
1681
|
+
this._skillsPrepended = false
|
|
1682
|
+
// Emit a distinct error event so the dashboard can render a one-shot
|
|
1683
|
+
// "Conversation no longer exists on this machine — starting fresh"
|
|
1684
|
+
// affordance instead of the generic "exited unexpectedly" toast.
|
|
1685
|
+
this.emit('error', {
|
|
1686
|
+
code: 'resume_unknown',
|
|
1687
|
+
message:
|
|
1688
|
+
'Previous Claude conversation could not be resumed (the id is unknown to the local claude CLI — ' +
|
|
1689
|
+
'it may have been wiped from ~/.claude/projects/). Starting a fresh conversation; the model will ' +
|
|
1690
|
+
'not see the earlier transcript.',
|
|
1691
|
+
attemptedResumeId,
|
|
1692
|
+
})
|
|
1693
|
+
this._scheduleRespawn()
|
|
1694
|
+
return
|
|
1695
|
+
}
|
|
1696
|
+
|
|
1697
|
+
// #4828: session-scoped if init had fired.
|
|
1698
|
+
;(this._log || log).info(`Process exited (code ${code}), scheduling respawn`)
|
|
1699
|
+
this.emit('error', { message: 'Claude process exited unexpectedly, restarting...' })
|
|
1700
|
+
this._scheduleRespawn()
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
/** Interrupt the current message (send SIGINT to child process) */
|
|
1704
|
+
interrupt() {
|
|
1705
|
+
// #5936: a deliberate Stop cancels the owner's queued follow-ups (cancel,
|
|
1706
|
+
// not flush). Clear BEFORE the SIGINT so the synthetic interrupted-turn
|
|
1707
|
+
// `result` → _clearMessageState drain sees an empty queue and nothing
|
|
1708
|
+
// auto-fires after the halt. Runs even with no child so a queued send is
|
|
1709
|
+
// never stranded.
|
|
1710
|
+
this.clearOutgoingQueue()
|
|
1711
|
+
|
|
1712
|
+
if (!this._child) return
|
|
1713
|
+
|
|
1714
|
+
// #4602: mark the imminent child exit as user-initiated so
|
|
1715
|
+
// _handleChildClose suppresses the "exited unexpectedly" error and the
|
|
1716
|
+
// auto-respawn. If the child survives SIGINT (claude only aborts the
|
|
1717
|
+
// current turn), the next natural exit will be a real crash — the flag
|
|
1718
|
+
// is cleared in _handleChildClose on whichever exit fires first.
|
|
1719
|
+
this.markIntentionalStop()
|
|
1720
|
+
|
|
1721
|
+
// #4828: session-scoped if init has fired.
|
|
1722
|
+
;(this._log || log).info('Sending SIGINT to claude process')
|
|
1723
|
+
this._child.kill('SIGINT')
|
|
1724
|
+
|
|
1725
|
+
// Safety: if still busy after 5s, force-clear state.
|
|
1726
|
+
// Claude should either emit a result (process survives) or die (close handler respawns).
|
|
1727
|
+
// Clear any existing timer first to avoid orphaned timers on rapid interrupts.
|
|
1728
|
+
if (this._interruptTimer) {
|
|
1729
|
+
clearTimeout(this._interruptTimer)
|
|
1730
|
+
this._interruptTimer = null
|
|
1731
|
+
}
|
|
1732
|
+
this._interruptTimer = setTimeout(() => {
|
|
1733
|
+
this._interruptTimer = null
|
|
1734
|
+
// #4602: if the child survived SIGINT (claude only aborted the turn),
|
|
1735
|
+
// clear the flag so a later natural crash still triggers respawn —
|
|
1736
|
+
// otherwise the flag stays armed indefinitely and swallows real crashes.
|
|
1737
|
+
this._clearIntentionalStop()
|
|
1738
|
+
if (this._isBusy) {
|
|
1739
|
+
// #4828: session-scoped.
|
|
1740
|
+
;(this._log || log).warn('Interrupt safety timeout — force-clearing busy state')
|
|
1741
|
+
this._emitInterruptedTurnResult()
|
|
1742
|
+
}
|
|
1743
|
+
}, 5000)
|
|
1744
|
+
// #6043: fire-and-forget busy-state safety net — never gate process exit on
|
|
1745
|
+
// it. It only force-clears local state if the child ignored SIGINT; if the
|
|
1746
|
+
// loop is otherwise idle the process is exiting and the state is moot.
|
|
1747
|
+
if (typeof this._interruptTimer.unref === 'function') this._interruptTimer.unref()
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1750
|
+
/** Clean up resources */
|
|
1751
|
+
destroy() {
|
|
1752
|
+
this._destroying = true
|
|
1753
|
+
this._respawning = false
|
|
1754
|
+
// #5936: tear down the shared outgoing queue silently (no message_dequeued
|
|
1755
|
+
// for a session that's going away).
|
|
1756
|
+
this.clearOutgoingQueue({ emit: false })
|
|
1757
|
+
this._clearIntentionalStop()
|
|
1758
|
+
|
|
1759
|
+
// Clean up permission hook — destroy() now chains unregister() after any
|
|
1760
|
+
// in-flight register() promise, preventing a register-after-unregister race
|
|
1761
|
+
// that would leave a dead hook in settings.json.
|
|
1762
|
+
if (this._hookManager) {
|
|
1763
|
+
this._hookManager.destroy()
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
if (this._respawnTimer) {
|
|
1767
|
+
clearTimeout(this._respawnTimer)
|
|
1768
|
+
this._respawnTimer = null
|
|
1769
|
+
}
|
|
1770
|
+
this._respawnScheduled = false
|
|
1771
|
+
|
|
1772
|
+
if (this._resultTimeout) {
|
|
1773
|
+
clearTimeout(this._resultTimeout)
|
|
1774
|
+
this._resultTimeout = null
|
|
1775
|
+
}
|
|
1776
|
+
if (this._hardTimeout) {
|
|
1777
|
+
clearTimeout(this._hardTimeout)
|
|
1778
|
+
this._hardTimeout = null
|
|
1779
|
+
}
|
|
1780
|
+
if (this._streamStallTimeout) {
|
|
1781
|
+
clearTimeout(this._streamStallTimeout)
|
|
1782
|
+
this._streamStallTimeout = null
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
if (this._interruptTimer) {
|
|
1786
|
+
clearTimeout(this._interruptTimer)
|
|
1787
|
+
this._interruptTimer = null
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
this._cleanupReadlines()
|
|
1791
|
+
|
|
1792
|
+
if (this._child) {
|
|
1793
|
+
// Close stdin for clean exit
|
|
1794
|
+
try { this._child.stdin.end() } catch {}
|
|
1795
|
+
|
|
1796
|
+
// Force-kill after 3s if still alive
|
|
1797
|
+
const child = this._child
|
|
1798
|
+
const forceKillTimer = setTimeout(() => {
|
|
1799
|
+
try { forceKill(child) } catch {}
|
|
1800
|
+
}, 3000)
|
|
1801
|
+
// #6043: fire-and-forget safety net — never gate process exit on it. If
|
|
1802
|
+
// the loop is otherwise idle the process is shutting down anyway and the
|
|
1803
|
+
// child is reaped on exit; the timer only matters while the loop is alive
|
|
1804
|
+
// for other reasons. Without unref it pins the loop for the full 3s in
|
|
1805
|
+
// tests whose mock child never emits 'close'.
|
|
1806
|
+
if (typeof forceKillTimer.unref === 'function') forceKillTimer.unref()
|
|
1807
|
+
|
|
1808
|
+
child.on('close', () => clearTimeout(forceKillTimer))
|
|
1809
|
+
this._child = null
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
// Emit completions for any tracked agents and clear busy state.
|
|
1813
|
+
// Must happen before removeAllListeners() so events are delivered.
|
|
1814
|
+
this._clearMessageState()
|
|
1815
|
+
this._inPlanMode = false
|
|
1816
|
+
|
|
1817
|
+
this._processReady = false
|
|
1818
|
+
this.removeAllListeners()
|
|
1819
|
+
}
|
|
1820
|
+
}
|