@chroxy/server 0.11.0 → 0.11.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +206 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +958 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +304 -0
- package/src/agent-control/client.js +1645 -0
- package/src/agent-control/events.js +551 -0
- package/src/agent-control/local-connection.js +293 -0
- package/src/agent-control/mcp-server.js +547 -0
- package/src/anthropic-compatible-config.js +30 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1520 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +291 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +92 -7
- package/src/byok-mcp-config.js +633 -122
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +37 -23
- package/src/byok-session.js +707 -179
- package/src/byok-tool-executor.js +2742 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-setting-sources.js +74 -0
- package/src/claude-stream-parser.js +53 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +215 -88
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3563 -284
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-cmd.js +236 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/connection-state.js +54 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/pages-cmd.js +6 -4
- package/src/cli/pair-code-cmd.js +7 -6
- package/src/cli/pair-discord-cmd.js +7 -6
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +91 -40
- package/src/cli/server-cmd.js +54 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1250 -126
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1517 -81
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-error-text.js +114 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +450 -27
- package/src/config-dir-migration.js +449 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +306 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +78 -23
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +227 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +42 -39
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +28 -39
- package/src/credential-store.js +23 -19
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +170 -182
- package/src/device-preferences.js +2 -2
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +172 -3
- package/src/docker-session.js +294 -11
- package/src/doctor.js +781 -64
- package/src/durable-write.js +35 -0
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +101 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +186 -235
- package/src/folder-trust-wire.js +137 -0
- package/src/folder-trust-worker.js +17 -0
- package/src/folder-trust.js +1572 -0
- package/src/freshness/activity-meter.js +101 -0
- package/src/freshness/adapter.js +199 -0
- package/src/freshness/checks.js +239 -0
- package/src/freshness/config.js +98 -0
- package/src/freshness/core.js +185 -0
- package/src/freshness/derive.js +680 -0
- package/src/freshness/exchange.js +305 -0
- package/src/freshness/file-ledger.js +400 -0
- package/src/freshness/grade.js +81 -0
- package/src/freshness/hash.js +45 -0
- package/src/freshness/inbox.js +163 -0
- package/src/freshness/index.js +20 -0
- package/src/freshness/investigation.js +474 -0
- package/src/freshness/keys.js +177 -0
- package/src/freshness/ledger.js +122 -0
- package/src/freshness/outbox.js +131 -0
- package/src/freshness/policy.js +599 -0
- package/src/freshness/queue.js +843 -0
- package/src/freshness/read-errors.js +23 -0
- package/src/freshness/render.js +153 -0
- package/src/freshness/runtime.js +113 -0
- package/src/freshness/session-registry-adapter.js +161 -0
- package/src/freshness/state-file-adapter.js +167 -0
- package/src/freshness-runner/build-info.js +139 -0
- package/src/freshness-runner/cli.js +105 -0
- package/src/freshness-runner/run-tick.js +109 -0
- package/src/freshness-runner/stamp.js +57 -0
- package/src/freshness-sources/claude-transcript-adapter.js +211 -0
- package/src/freshness-sources/codex-transcript-adapter.js +33 -0
- package/src/freshness-sources/index.js +8 -0
- package/src/gemini-byok-session.js +292 -0
- package/src/gemini-credentials.js +67 -0
- package/src/gemini-key-safety.js +246 -0
- package/src/gemini-models.js +386 -0
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +540 -80
- package/src/handlers/checkpoint-handlers.js +47 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +57 -13
- package/src/handlers/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +714 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +92 -18
- package/src/handlers/session-handlers.js +551 -20
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +372 -50
- package/src/handlers/skills-handlers.js +20 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +112 -0
- package/src/http-routes.js +127 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +378 -91
- package/src/jsonl-subprocess-session.js +96 -9
- package/src/keychain.js +1 -1
- package/src/logger.js +166 -30
- package/src/mailbox-route.js +113 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +27 -4
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +64 -23
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +112 -36
- package/src/orchestration/permission-gate.js +17 -2
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +185 -43
- package/src/orphan-reaper.js +470 -0
- package/src/outgoing-policy.js +189 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1410 -43
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +737 -89
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +126 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +315 -47
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/principal-audit.js +189 -0
- package/src/principal-binding.js +25 -0
- package/src/principal-brakes.js +21 -0
- package/src/principal-effect.js +101 -0
- package/src/principal-journal.js +905 -0
- package/src/principal-kill-switch.js +183 -0
- package/src/principal-label.js +5 -0
- package/src/principal-pending-permissions.js +177 -0
- package/src/principal-policy.js +1094 -0
- package/src/principal-sessions-snapshot.js +208 -0
- package/src/principal-store.js +488 -0
- package/src/principal-subscriptions.js +283 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +209 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +531 -20
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +330 -26
- package/src/scheduler.js +368 -11
- package/src/sdk-session.js +2114 -188
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +17 -3
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +553 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +1099 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +4062 -312
- package/src/session-message-history.js +841 -16
- package/src/session-name-allocator.js +685 -0
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-token-store.js +17 -8
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +100 -29
- package/src/summarize-session.js +53 -4
- package/src/supervisor.js +22 -11
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +140 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +770 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +639 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +29 -0
- package/src/utils/bounded-regex.js +162 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +133 -37
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/pid-liveness.js +47 -0
- package/src/utils/preflight.js +360 -16
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +297 -16
- package/src/worktree-gc.js +202 -6
- package/src/ws-auth.js +163 -31
- package/src/ws-broadcaster.js +49 -5
- package/src/ws-client-manager.js +24 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +363 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +349 -39
- package/src/ws-handler-context.js +88 -2
- package/src/ws-history.js +1010 -175
- package/src/ws-message-handlers.js +25 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +885 -98
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
package/src/base-session.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* SdkSession, and GeminiSession don't duplicate them.
|
|
8
8
|
*/
|
|
9
9
|
import { EventEmitter } from 'events'
|
|
10
|
+
import { stillAuthorized } from './connection-authority.js'
|
|
10
11
|
import { randomBytes } from 'crypto'
|
|
11
12
|
import { resolveModelId } from './models.js'
|
|
12
13
|
import {
|
|
@@ -15,13 +16,27 @@ import {
|
|
|
15
16
|
} from './skills-loader.js'
|
|
16
17
|
import { SkillsManager } from './skills-manager.js'
|
|
17
18
|
import { BackgroundShellTracker } from './background-shell-tracker.js'
|
|
19
|
+
import { deriveBusyReason } from './session-busy-state.js'
|
|
18
20
|
import { isOperatorTimeoutInRange } from './duration.js'
|
|
19
21
|
import { createLogger } from './logger.js'
|
|
20
22
|
import { ActivityRegistry } from './activity-registry.js'
|
|
21
23
|
import { ALLOWED_PERMISSION_MODE_IDS } from './handler-utils.js'
|
|
24
|
+
import { assertProviderPermissionModeSupported, getProviderPermissionModeSupport } from './permission-mode-support.js'
|
|
25
|
+
import { AGENT_DESCRIPTION_MAX } from './claude-stream-parser.js'
|
|
26
|
+
import { sanitizeToolInput } from './redaction.js'
|
|
27
|
+
import { isTurnTerminationReason, describeTurnTermination } from '@chroxy/protocol'
|
|
28
|
+
import { isTurnOutcome } from './turn-outcome.js'
|
|
29
|
+
import { PROJECT_INSTRUCTION_BUDGET_BYTES } from './provider-customization.js'
|
|
22
30
|
|
|
23
31
|
const log = createLogger('base-session')
|
|
24
32
|
|
|
33
|
+
// #8252: the text of a synthesized `tool_result` for a tool whose turn ended
|
|
34
|
+
// with no result and no termination reason (see `_sweepUnresolvedToolStarts`).
|
|
35
|
+
// A termination reason gets its own `describeTurnTermination(reason).summary`;
|
|
36
|
+
// this is the protocol's neutral wording for "no reason known", so the two cannot
|
|
37
|
+
// drift and neither claims the tool did not run.
|
|
38
|
+
export const UNFINISHED_TOOL_RESULT_TEXT = describeTurnTermination().summary
|
|
39
|
+
|
|
25
40
|
// #3805: opt-in Chroxy context paragraph. Prepended to `_buildSystemPrompt()`
|
|
26
41
|
// output when `chroxyContextHint` is true so the model knows it's running
|
|
27
42
|
// inside Chroxy's remote-terminal front-end and can adjust its output for
|
|
@@ -40,6 +55,109 @@ export const CHROXY_CONTEXT_HINT_TEXT =
|
|
|
40
55
|
// turn token overhead predictable.
|
|
41
56
|
export const SESSION_PREAMBLE_MAX_LENGTH = 4000
|
|
42
57
|
|
|
58
|
+
// #8743: the events that mean the provider is doing something, stamped by the
|
|
59
|
+
// emit() override below and read as `providerActivityAgeMs` by the idle-only
|
|
60
|
+
// auto-deploy (daemon-idle-state.js). It is the conversation stream a working
|
|
61
|
+
// turn produces, so it is independent of the turn bookkeeping that `isBusy`
|
|
62
|
+
// reads: in trial run B2-cy-codex that bookkeeping said the turn was over while
|
|
63
|
+
// codex kept emitting for 17 minutes, and the deploy restarted the daemon under
|
|
64
|
+
// it. Events that are not evidence of work are in NOT_PROVIDER_ACTIVITY_EVENTS
|
|
65
|
+
// below, because one that recurs would hold every deploy off.
|
|
66
|
+
// tests/daemon-idle.test.js and tests/provider-custom-events-overlap.test.js put
|
|
67
|
+
// every forwarded session event (proxied, built-in transient, and each
|
|
68
|
+
// provider's `customEvents`) in exactly one of the two lists, and check that
|
|
69
|
+
// every name here is emitted somewhere.
|
|
70
|
+
export const PROVIDER_ACTIVITY_EVENTS = Object.freeze([
|
|
71
|
+
'stream_start', 'stream_delta', 'stream_end', 'message',
|
|
72
|
+
'tool_start', 'tool_input_delta', 'tool_result', 'result', 'stopped',
|
|
73
|
+
'user_question', 'multi_question_intervention', 'background_tasks_changed',
|
|
74
|
+
'agent_spawned', 'agent_event', 'agent_completed',
|
|
75
|
+
'plan_started', 'plan_ready',
|
|
76
|
+
])
|
|
77
|
+
const PROVIDER_ACTIVITY_EVENT_SET = new Set(PROVIDER_ACTIVITY_EVENTS)
|
|
78
|
+
|
|
79
|
+
// #8743: forwarded session events that do NOT stamp provider activity.
|
|
80
|
+
export const NOT_PROVIDER_ACTIVITY_EVENTS = Object.freeze([
|
|
81
|
+
// a boot or respawn handshake, and often the daemon's own failure, repeatable
|
|
82
|
+
// in a crash/respawn loop
|
|
83
|
+
'ready', 'error',
|
|
84
|
+
// a prompt waiting on a human: the idle verdict counts it as pending already
|
|
85
|
+
'permission_request', 'permission_resolved', 'permission_expired',
|
|
86
|
+
// the user's input queue, not the provider (queued input is a restart blocker)
|
|
87
|
+
'message_queued', 'message_dequeued',
|
|
88
|
+
// derived from the tool and shell events, and recomputed on sweeps
|
|
89
|
+
'activity_delta', 'activity_snapshot', 'background_work_changed', 'busy_cleared',
|
|
90
|
+
// configuration, environment and daemon housekeeping
|
|
91
|
+
'mcp_servers', 'skill_changed', 'skill_trust_request', 'skill_trust_granted',
|
|
92
|
+
'inactivity_warning', 'stdin_dropped_totals', 'setup_log', 'respawn_exhausted',
|
|
93
|
+
// #8700: a session's thinking level changed or was reported — a model switch,
|
|
94
|
+
// a setting, or Claude Code's report at the start of a turn the turn's own
|
|
95
|
+
// stream already stamps
|
|
96
|
+
'thinking_level_changed',
|
|
97
|
+
])
|
|
98
|
+
|
|
99
|
+
// #9241: classifying a session event as "assistant output" for the stop-before-reply
|
|
100
|
+
// marker. A turn the user Stops before ANY output gets a replayable marker; a Stop
|
|
101
|
+
// after output stays quiet (#8461). The classification is FAIL-SAFE: only the names
|
|
102
|
+
// in TURN_QUIET_EVENTS are known not to be output, so a new or unclassified event
|
|
103
|
+
// counts as output, which suppresses the marker -- today's behaviour -- rather than
|
|
104
|
+
// minting a wrong "stopped before a reply" over a turn that had begun. The two lists
|
|
105
|
+
// below must between them cover every forwarded session event
|
|
106
|
+
// (PROVIDER_ACTIVITY_EVENTS + NOT_PROVIDER_ACTIVITY_EVENTS) and name nothing that is
|
|
107
|
+
// not emitted; tests/stop-before-reply-roster.test.js checks both directions.
|
|
108
|
+
// Conditional on payload: `stream_delta` (empty text) and `message` (system type or
|
|
109
|
+
// empty content) are quiet; see `eventCountsAsTurnOutput`.
|
|
110
|
+
export const TURN_QUIET_EVENTS = Object.freeze([
|
|
111
|
+
// `stream_start` opens an EMPTY slot (claude-tui emits it at turn start, #4010);
|
|
112
|
+
// its `stream_end` closes it
|
|
113
|
+
'stream_start', 'stream_end',
|
|
114
|
+
// turn bookkeeping
|
|
115
|
+
'turn_state', 'result', 'stopped', 'ready', 'busy_cleared', 'declaration_turn',
|
|
116
|
+
'tool_input_recorded', 'models_updated',
|
|
117
|
+
// permission and queue bookkeeping (a prompt still open at Stop counts through
|
|
118
|
+
// getPendingPermissionCount, and `permission_request` itself is output)
|
|
119
|
+
'permission_resolved', 'permission_expired', 'message_queued', 'message_dequeued',
|
|
120
|
+
// derived or recomputed state
|
|
121
|
+
'activity_delta', 'activity_snapshot', 'background_work_changed', 'background_tasks_changed',
|
|
122
|
+
// configuration, environment and daemon housekeeping
|
|
123
|
+
'mcp_servers', 'skill_changed', 'skill_trust_request', 'skill_trust_granted',
|
|
124
|
+
'inactivity_warning', 'stdin_dropped_totals', 'setup_log', 'respawn_exhausted',
|
|
125
|
+
'thinking_level_changed',
|
|
126
|
+
// claude-tui's raw PTY mirror (prompt echo, redraws, a resize) is the SCREEN, not the
|
|
127
|
+
// reply: see ClaudeTuiSession's hook drain for the signal that is (#9241)
|
|
128
|
+
'terminal_output', 'terminal_resize',
|
|
129
|
+
// the embedded user shell is not the model
|
|
130
|
+
'shell_spawned', 'shell_exited',
|
|
131
|
+
])
|
|
132
|
+
const TURN_QUIET_EVENT_SET = new Set(TURN_QUIET_EVENTS)
|
|
133
|
+
|
|
134
|
+
// #9241: events that ARE output, declared so the roster test forces a decision for
|
|
135
|
+
// each new event. Not read at runtime: everything outside TURN_QUIET_EVENTS counts.
|
|
136
|
+
export const TURN_OUTPUT_EVENTS = Object.freeze([
|
|
137
|
+
'stream_delta', 'message', 'tool_start', 'tool_input_delta', 'tool_result',
|
|
138
|
+
'user_question', 'multi_question_intervention', 'permission_request', 'error',
|
|
139
|
+
'agent_spawned', 'agent_event', 'agent_completed', 'plan_started', 'plan_ready',
|
|
140
|
+
'assistant_response',
|
|
141
|
+
])
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* #9241: does this session event show the model began answering? Fail-safe (see
|
|
145
|
+
* TURN_QUIET_EVENTS): unknown names and unrecognised payload shapes count.
|
|
146
|
+
*
|
|
147
|
+
* @param {string} event
|
|
148
|
+
* @param {*} data
|
|
149
|
+
* @returns {boolean}
|
|
150
|
+
*/
|
|
151
|
+
export function eventCountsAsTurnOutput(event, data) {
|
|
152
|
+
if (TURN_QUIET_EVENT_SET.has(event)) return false
|
|
153
|
+
if (event === 'stream_delta') return !(typeof data?.delta === 'string' && data.delta === '')
|
|
154
|
+
if (event === 'message') {
|
|
155
|
+
if (data?.type === 'system') return false
|
|
156
|
+
return !(typeof data?.content === 'string' && data.content === '')
|
|
157
|
+
}
|
|
158
|
+
return true
|
|
159
|
+
}
|
|
160
|
+
|
|
43
161
|
// #5936 (epic #5935): explicit overflow cap for the shared outgoing-message
|
|
44
162
|
// queue (`_outgoingQueue`). Replaces the SDK's hard-coded mid-turn cap of 3
|
|
45
163
|
// (#5711) with one bounded, surfaced limit shared by SDK + CLI. A send-while-
|
|
@@ -48,6 +166,51 @@ export const SESSION_PREAMBLE_MAX_LENGTH = 4000
|
|
|
48
166
|
// burst of owner follow-ups while still bounding memory if a client wedges.
|
|
49
167
|
export const OUTGOING_QUEUE_MAX = 10
|
|
50
168
|
|
|
169
|
+
/**
|
|
170
|
+
* #8281: handoff-blocker codes that are reported but advisory. A caller decides
|
|
171
|
+
* whether they block; every other code is hard.
|
|
172
|
+
*/
|
|
173
|
+
export const SOFT_HANDOFF_BLOCKER_CODES = Object.freeze(new Set(['background_shells']))
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Report the provider's input-admission boundary without waiting for the turn.
|
|
177
|
+
* Async sendMessage implementations call this before their first await when
|
|
178
|
+
* possible, or later when an async transport handshake proves admission.
|
|
179
|
+
*/
|
|
180
|
+
/** #9242: the admission shape for a send refused by its own predicate after provider preparation. */
|
|
181
|
+
export const NOT_ADMITTED_ADMISSION = Object.freeze({
|
|
182
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
183
|
+
reason: 'not_admitted', message: 'The input was no longer admitted after preparation; it was not dispatched.',
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
export function reportInputAdmission(sendOptions, admission) {
|
|
187
|
+
const callback = sendOptions?.onInputAdmission
|
|
188
|
+
if (typeof callback === 'function') callback(admission)
|
|
189
|
+
return admission
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* #8038 (extracted from #8030's `_refuseTurnBeforeDispatch`): the shared
|
|
194
|
+
* admission shape for an input the binary gate refused before anything was
|
|
195
|
+
* dispatched — a per-turn provider's turn (SdkSession, JsonlSubprocessSession)
|
|
196
|
+
* OR a persistent provider's spawn/respawn (CliSession, ClaudeTuiSession).
|
|
197
|
+
* Exported so both refusal paths report the identical wire shape instead of a
|
|
198
|
+
* hand-rolled second literal drifting from this one.
|
|
199
|
+
*
|
|
200
|
+
* `_refuseTurnBeforeDispatch` below is the ORIGINAL caller and its wire shape
|
|
201
|
+
* must stay byte-identical — this is a pure extraction, not a behavior change.
|
|
202
|
+
*
|
|
203
|
+
* @param {Error & { code?: string }} [err]
|
|
204
|
+
* @returns {{status: string, delivery: string, retrySafe: boolean, reason: string, message: string}}
|
|
205
|
+
*/
|
|
206
|
+
export function spawnRefusalAdmission(err) {
|
|
207
|
+
return {
|
|
208
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
209
|
+
reason: err?.code || 'turn_refused',
|
|
210
|
+
message: 'The provider refused this turn before it was dispatched; see the session error for the cause.',
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
51
214
|
// #3884 / #3749 / #3899: default SOFT inactivity warning (ms). Activity-based
|
|
52
215
|
// — every provider event (SDK iterator message, CLI stdout JSONL line)
|
|
53
216
|
// resets the timer; the window only bounds *silent stretches*, not wall-
|
|
@@ -130,11 +293,15 @@ export const BASE_SESSION_OPT_KEYS = [
|
|
|
130
293
|
'promptEvaluatorSkipPattern',
|
|
131
294
|
'chroxyContextHint',
|
|
132
295
|
'sessionPreamble',
|
|
296
|
+
'projectInstructions',
|
|
133
297
|
'resultTimeoutMs',
|
|
134
298
|
'hardTimeoutMs',
|
|
135
299
|
'streamStallTimeoutMs',
|
|
136
300
|
'backgroundShellHardQuiesceMs',
|
|
137
301
|
'permissionRuleStore',
|
|
302
|
+
// #8035: see the ctor param doc below — closes the middle-layer trap for
|
|
303
|
+
// JsonlSubprocessSession's picker subclasses (Gemini/Codex-exec).
|
|
304
|
+
'spawnPreflight',
|
|
138
305
|
]
|
|
139
306
|
|
|
140
307
|
// #5367: pick the BaseSession opts out of a subclass's full opts bag and merge
|
|
@@ -242,6 +409,31 @@ function normalizeResultDuration(payload) {
|
|
|
242
409
|
}
|
|
243
410
|
|
|
244
411
|
export class BaseSession extends EventEmitter {
|
|
412
|
+
/** Binary version observed by this live runtime, or `unknown`. */
|
|
413
|
+
get providerBinaryVersion() {
|
|
414
|
+
return 'unknown'
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Whether the RUNNING process was launched with project settings loaded (claude-cli
|
|
419
|
+
* and claude-tui set this at each launch). `undefined` for a provider that does not
|
|
420
|
+
* record it.
|
|
421
|
+
* @returns {boolean|undefined}
|
|
422
|
+
*/
|
|
423
|
+
get launchedWithProject() { return this._launchedWithProject }
|
|
424
|
+
|
|
425
|
+
/** Runtime-negotiated capability states; static UI capabilities are separate. */
|
|
426
|
+
get providerRuntimeCapabilities() {
|
|
427
|
+
return {}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** Provider-owned restart locator; generic persistence never reconstructs it. */
|
|
431
|
+
get nativeResumeState() { return null }
|
|
432
|
+
|
|
433
|
+
get providerInstructionProjection() {
|
|
434
|
+
return this._projectInstructionProjection
|
|
435
|
+
}
|
|
436
|
+
|
|
245
437
|
/**
|
|
246
438
|
* Custom event names emitted by this provider class that should be proxied
|
|
247
439
|
* by SessionManager in addition to the built-in PROXIED_EVENTS list.
|
|
@@ -320,6 +512,9 @@ export class BaseSession extends EventEmitter {
|
|
|
320
512
|
// SESSION_PREAMBLE_MAX_LENGTH on construction. Empty string (or any
|
|
321
513
|
// non-string input) is the byte-identical-to-pre-#4660 default.
|
|
322
514
|
sessionPreamble,
|
|
515
|
+
// #7835: separately bounded required project policy. This does not share
|
|
516
|
+
// the 4k user-preamble or runtime-skill pruning budgets.
|
|
517
|
+
projectInstructions,
|
|
323
518
|
// #3749 / #3884 / #3899: configurable SOFT-warning timeout (the
|
|
324
519
|
// inactivity safety net). Subclasses arm this timer; when it fires
|
|
325
520
|
// they emit an `inactivity_warning` event so the client can render
|
|
@@ -351,6 +546,20 @@ export class BaseSession extends EventEmitter {
|
|
|
351
546
|
// hand it to their PermissionManager so an `allowAlways` decision persists a
|
|
352
547
|
// project-scoped rule and new sessions in the same cwd seed from it.
|
|
353
548
|
permissionRuleStore,
|
|
549
|
+
// #8035: per-spawn binary re-verification gate. SessionManager wires this
|
|
550
|
+
// to `_verifyPinnedSpawn` (re-runs the full binary gate against the EXACT
|
|
551
|
+
// path create-time preflight verified) whenever preflight ran and the
|
|
552
|
+
// provider isn't containerised. Lives on BaseSession — not read directly
|
|
553
|
+
// by a subclass's opts bag — so every picker subclass built via
|
|
554
|
+
// `buildBaseSessionOpts` (GeminiSession, CodexSession, …) inherits it for
|
|
555
|
+
// free; reading `opts.spawnPreflight` in a middle layer instead would hit
|
|
556
|
+
// the trap documented in [[feedback_jsonl_subprocess_middle_layer]] and
|
|
557
|
+
// `BASE_SESSION_OPT_KEYS` above is what the opt-forwarding lint checks.
|
|
558
|
+
// null when absent — callers fall back to a plain
|
|
559
|
+
// `this.constructor.resolvedBinary` read via `_gatedSpawnBinary` below,
|
|
560
|
+
// same as pre-#8030/#8035 (a direct constructor call that bypasses
|
|
561
|
+
// SessionManager, or a test).
|
|
562
|
+
spawnPreflight,
|
|
354
563
|
} = {}) {
|
|
355
564
|
super()
|
|
356
565
|
this.cwd = cwd || process.cwd()
|
|
@@ -358,6 +567,17 @@ export class BaseSession extends EventEmitter {
|
|
|
358
567
|
// Read by the in-process permission providers when they build their
|
|
359
568
|
// PermissionManager; null on providers/tests that don't wire it.
|
|
360
569
|
this._permissionRuleStore = permissionRuleStore || null
|
|
570
|
+
// #8035 — see the ctor param doc above. Stored here (not in SdkSession, not
|
|
571
|
+
// read ad hoc off `opts` in JsonlSubprocessSession) so both the per-turn SDK
|
|
572
|
+
// exec and the per-turn subprocess spawn (Gemini/Codex-exec) share one
|
|
573
|
+
// source of truth via `_gatedSpawnBinary` below.
|
|
574
|
+
this._spawnPreflight = typeof spawnPreflight === 'function' ? spawnPreflight : null
|
|
575
|
+
// #8038 — latched by `_refuseSpawn` when a (re)spawn attempt's binary gate
|
|
576
|
+
// (CliSession._spawnPersistentProcess, ClaudeTuiSession._spawnPty /
|
|
577
|
+
// _respawnPty) throws instead of returning a verified path. null means
|
|
578
|
+
// "no refusal outstanding" — the normal state, and the state after a
|
|
579
|
+
// revival succeeds. See `_refuseSpawn`'s doc for the full contract.
|
|
580
|
+
this._spawnRefusal = null
|
|
361
581
|
this.model = model || null
|
|
362
582
|
// Actual model the underlying CLI/SDK reports at init time. May differ
|
|
363
583
|
// from `this.model` (the user's requested override) when no override
|
|
@@ -368,13 +588,14 @@ export class BaseSession extends EventEmitter {
|
|
|
368
588
|
// Set by subclasses in their init handlers (#3687).
|
|
369
589
|
this.bootedModel = null
|
|
370
590
|
this.permissionMode = permissionMode || 'approve'
|
|
591
|
+
assertProviderPermissionModeSupported(this.constructor, this.permissionMode)
|
|
371
592
|
// #3185: per-session toggle for the auto-evaluator chain (parent epic
|
|
372
593
|
// #3068). Default `false` — the existing manual `evaluate_draft` flow
|
|
373
594
|
// (PR #3089) is unaffected by this flag. Coerced to a strict boolean
|
|
374
595
|
// here so JSON.stringify produces `true`/`false` (not `1`/`null`) on
|
|
375
596
|
// the auth_ok / session_list wires.
|
|
376
597
|
this.promptEvaluator = !!promptEvaluator
|
|
377
|
-
// #3639: per-session regex source string used by `
|
|
598
|
+
// #3639: per-session regex source string used by `shouldSkipEvaluatorAsync`
|
|
378
599
|
// to extend the default continuation/ack skip list. Mirrors the
|
|
379
600
|
// server-wide `config.promptEvaluatorSkipPattern` from #3187 but is
|
|
380
601
|
// evaluated FIRST in input-handlers.js so a per-session override
|
|
@@ -398,9 +619,39 @@ export class BaseSession extends EventEmitter {
|
|
|
398
619
|
// smuggle in unbounded text. The runtime setter (setSessionPreamble)
|
|
399
620
|
// does the same coercion and reports rejection on type mismatch.
|
|
400
621
|
this.sessionPreamble = _coerceSessionPreambleOpt(sessionPreamble)
|
|
622
|
+
this.projectInstructions = typeof projectInstructions === 'string' ? projectInstructions : ''
|
|
623
|
+
const projectInstructionBytes = Buffer.byteLength(this.projectInstructions, 'utf8')
|
|
624
|
+
if (projectInstructionBytes > PROJECT_INSTRUCTION_BUDGET_BYTES) {
|
|
625
|
+
throw new Error(`projectInstructions exceeds ${PROJECT_INSTRUCTION_BUDGET_BYTES} UTF-8 bytes`)
|
|
626
|
+
}
|
|
627
|
+
this._projectInstructionProjection = {
|
|
628
|
+
status: this.projectInstructions ? 'delivered' : 'unknown',
|
|
629
|
+
enforcement: 'instructional',
|
|
630
|
+
compilerVersion: '1',
|
|
631
|
+
budgetBytes: this.projectInstructions ? PROJECT_INSTRUCTION_BUDGET_BYTES : 0,
|
|
632
|
+
totalBytes: projectInstructionBytes,
|
|
633
|
+
sources: [], rules: [], includedRequiredRuleIds: [],
|
|
634
|
+
}
|
|
401
635
|
|
|
402
|
-
this.
|
|
636
|
+
this._busyFlag = false
|
|
403
637
|
this._processReady = false
|
|
638
|
+
// #8743: when the provider last produced output, on the monotonic
|
|
639
|
+
// `_providerActivityClock()`. null until it first does. See noteProviderActivity.
|
|
640
|
+
this._providerActivityAtMs = null
|
|
641
|
+
// #7382: outstanding hook-routed permission prompts, by requestId. Hoisted
|
|
642
|
+
// from CliSession, where it was written for #2831 and stayed provider-local
|
|
643
|
+
// through #7375/#7379 — so claude-tui, then DEFAULT_PROVIDER, which routes
|
|
644
|
+
// its prompts through the SAME permission-hook.sh into the SAME daemon map,
|
|
645
|
+
// silently had none of it. `ws-permissions` guards its calls with
|
|
646
|
+
// `typeof ownerSession.notifyPermissionPending === 'function'`, so the
|
|
647
|
+
// missing methods were not an error — they were a skip, which is the
|
|
648
|
+
// success-and-not-checking shape in docs/false-safety-guards.md.
|
|
649
|
+
//
|
|
650
|
+
// Lives here so a THIRD hook-routed provider inherits it rather than
|
|
651
|
+
// re-implementing it. A derived-roster test (hook-routed-permission-
|
|
652
|
+
// bookkeeping.test.js) fails if any `*-session.js` that mints a
|
|
653
|
+
// `_hookSecret` lacks the API.
|
|
654
|
+
this._pendingPermissionIds = new Set()
|
|
404
655
|
// #5375: user-initiated stop vs crash. Set by interrupt() (markIntentionalStop),
|
|
405
656
|
// captured-and-cleared by the provider's close/error handler
|
|
406
657
|
// (_consumeIntentionalStop) so a clean stop is not reported as an error.
|
|
@@ -410,6 +661,31 @@ export class BaseSession extends EventEmitter {
|
|
|
410
661
|
// `finally` safety-net clear (the interrupt-races-result case), and collapsing
|
|
411
662
|
// them would reopen that race.
|
|
412
663
|
this._intentionalStop = false
|
|
664
|
+
// #7376: a Stop was requested while THIS turn was running. Unlike
|
|
665
|
+
// `_intentionalStop` (consumed by the child-close / query-catch handler, and
|
|
666
|
+
// not armed at all when the provider acknowledges the interrupt with a
|
|
667
|
+
// normal `result`), this one lives exactly as long as the turn: set by
|
|
668
|
+
// `_noteTurnStopRequested`, read by the orphan sweep, and reset by
|
|
669
|
+
// `_clearMessageState`. It is what lets a Stop that COMPLETES normally still
|
|
670
|
+
// tag the tools it cut off as `user_stop`.
|
|
671
|
+
this._stopRequestedThisTurn = false
|
|
672
|
+
// #8461: per Stop REQUEST (reset by `markIntentionalStop`, not per turn): a
|
|
673
|
+
// `stopped` event has gone out for it, and the one `emit('result')` sent in
|
|
674
|
+
// place of the Stopped chip, which a later `stopped` for the same Stop (the
|
|
675
|
+
// CLI child's exit, a late abort rejection) must not repeat.
|
|
676
|
+
this._stoppedSinceStopRequest = false
|
|
677
|
+
this._stopAckedByResult = false
|
|
678
|
+
// #9241: per TURN (reset on the busy false->true edge, NOT in `_clearMessageState`,
|
|
679
|
+
// which claude-cli runs BEFORE its terminal `result`/`stopped`): a Stop came in
|
|
680
|
+
// through the `interrupt` message (`markStopRequested`; `_stopRequestedThisTurn`
|
|
681
|
+
// also covers the scheduler and orchestration, which never arm this), the model
|
|
682
|
+
// produced output (set by the emit() override and `_noteTurnOutput`), the marker
|
|
683
|
+
// went out (`_stopMarkerEmitted`), or the turn's terminal event settled the
|
|
684
|
+
// question (`_stopMarkerMinted`).
|
|
685
|
+
this._stopMarkerArmed = false
|
|
686
|
+
this._turnOutputSeen = false
|
|
687
|
+
this._stopMarkerMinted = false
|
|
688
|
+
this._stopMarkerEmitted = false
|
|
413
689
|
// #4307/#5177/#5247/#5265: pending background-shell tracking + the reaping
|
|
414
690
|
// sweep live in BackgroundShellTracker (#5376). BaseSession composes one and
|
|
415
691
|
// delegates the public surface (trackBackgroundShell / clearBackgroundShell /
|
|
@@ -443,6 +719,22 @@ export class BaseSession extends EventEmitter {
|
|
|
443
719
|
// forever AND persist the orphan to session-state.json. Companion
|
|
444
720
|
// path: SessionMessageHistory.sweepUnresolvedToolStarts (#4617/#4619)
|
|
445
721
|
// catches stragglers at restore-time as a backstop.
|
|
722
|
+
//
|
|
723
|
+
// #7346: entries may also carry a finalized `input` field, set via
|
|
724
|
+
// `_recordToolInput` once the provider knows the tool's full input
|
|
725
|
+
// (CliSession: parsed `content_block_stop` buffer; SdkSession: the
|
|
726
|
+
// full assistant-message `block.input`, no buffering needed). Both
|
|
727
|
+
// `content_block_start`'s `tool_start` and the Anthropic wire
|
|
728
|
+
// protocol's `content_block_start` for a tool_use carry `input: null`
|
|
729
|
+
// — the finalized value only exists once the block closes — so this
|
|
730
|
+
// is the one place both providers can stash it for `tool-result.js`'s
|
|
731
|
+
// `emitToolResults` to read back (`_getTrackedToolInput`) and attach
|
|
732
|
+
// to the matching `tool_result`, which lets the client (and
|
|
733
|
+
// persisted history, via session-message-history.js) backfill the
|
|
734
|
+
// `tool_start` entry that was `input: null` when first emitted.
|
|
735
|
+
// BYOK never calls `_trackToolStart`, so this map stays empty there
|
|
736
|
+
// and `_getTrackedToolInput` always returns `undefined` — BYOK's
|
|
737
|
+
// `tool_result` is unaffected.
|
|
446
738
|
this._inFlightToolStarts = new Map()
|
|
447
739
|
// #5160: per-session activity registry (Control Room). A thin unifying
|
|
448
740
|
// layer that maps the signals BaseSession already emits (tool_start /
|
|
@@ -501,6 +793,10 @@ export class BaseSession extends EventEmitter {
|
|
|
501
793
|
// input_conflict gate) — by the time a send reaches the queue it is the
|
|
502
794
|
// owner's own follow-up, never a way around primary-client arbitration.
|
|
503
795
|
this._outgoingQueue = []
|
|
796
|
+
// #8281: prompts `dequeueNextOutgoing()` has shifted off the queue whose
|
|
797
|
+
// deferred send (process.nextTick) has not begun yet. A counter, not a
|
|
798
|
+
// boolean, so two shifts landing before the tick cannot clear each other.
|
|
799
|
+
this._dequeuesInFlight = 0
|
|
504
800
|
this._activeAgents = new Map()
|
|
505
801
|
this._resultTimeout = null
|
|
506
802
|
// #3899: parallel hard-cap setTimeout handle. Armed alongside
|
|
@@ -592,6 +888,110 @@ export class BaseSession extends EventEmitter {
|
|
|
592
888
|
}
|
|
593
889
|
}
|
|
594
890
|
|
|
891
|
+
/**
|
|
892
|
+
* #8035 — the one spawn-path helper every per-turn provider (SdkSession,
|
|
893
|
+
* JsonlSubprocessSession's Gemini/Codex-exec subclasses) uses instead of
|
|
894
|
+
* reading `this.constructor.resolvedBinary` directly. With a gate wired
|
|
895
|
+
* (`_spawnPreflight`, set from SessionManager's `spawnPreflight` opt — see
|
|
896
|
+
* the ctor doc above), it re-runs the full binary-provenance gate against
|
|
897
|
+
* the exact path create-time preflight verified and returns THAT path,
|
|
898
|
+
* pinned regardless of what `resolvedBinary` would resolve to right now.
|
|
899
|
+
* Without a gate (no SessionManager, a direct constructor call, most
|
|
900
|
+
* tests), it falls back to the plain static read — the pre-#8030 behavior.
|
|
901
|
+
*
|
|
902
|
+
* A non-string or empty result would leave the caller launching an
|
|
903
|
+
* unverified binary (e.g. the SDK falling back to its own bundled claude),
|
|
904
|
+
* so that case throws instead of returning — `PROVIDER_BINARY_UNVERIFIED`,
|
|
905
|
+
* with `binaryLabel` in the message so the two callers keep their own
|
|
906
|
+
* wording (SdkSession passes 'claude'; JsonlSubprocessSession passes
|
|
907
|
+
* `Klass.providerName`). Any error the gate itself throws (
|
|
908
|
+
* `PROVIDER_BINARY_PROVENANCE`, `PROVIDER_BINARY_QUARANTINED`,
|
|
909
|
+
* `PROVIDER_BINARY_NOT_FOUND`, …) propagates unchanged — this method adds
|
|
910
|
+
* exactly one new failure mode, it doesn't wrap existing ones.
|
|
911
|
+
*
|
|
912
|
+
* @param {string} binaryLabel — human name for the empty-path error text
|
|
913
|
+
* @returns {string} the verified path to spawn
|
|
914
|
+
* @throws {Error} PROVIDER_BINARY_UNVERIFIED, or whatever the gate throws
|
|
915
|
+
*/
|
|
916
|
+
_gatedSpawnBinary(binaryLabel) {
|
|
917
|
+
const path = this._spawnPreflight ? this._spawnPreflight() : this.constructor.resolvedBinary
|
|
918
|
+
if (typeof path !== 'string' || path.length === 0) {
|
|
919
|
+
const err = new Error(`No verified ${binaryLabel} binary path is available for this turn.`)
|
|
920
|
+
err.code = 'PROVIDER_BINARY_UNVERIFIED'
|
|
921
|
+
throw err
|
|
922
|
+
}
|
|
923
|
+
return path
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/**
|
|
927
|
+
* #8035 — the shared refusal path for a turn the binary gate stopped
|
|
928
|
+
* BEFORE dispatch (paired with `_gatedSpawnBinary` above). Hoisted out of
|
|
929
|
+
* SdkSession (#8030) so JsonlSubprocessSession's per-turn spawn gets the
|
|
930
|
+
* same wire shape rather than a hand-rolled second copy.
|
|
931
|
+
*
|
|
932
|
+
* Deliberately does NOT run any error-text rewriter: a provenance message
|
|
933
|
+
* embeds a hex hash prefix (e.g. "...a4291b0c...") that can match a
|
|
934
|
+
* rate-limit ("429") or auth ("401") pattern in a text-classification table
|
|
935
|
+
* and get silently rewritten into a wrong, misleading message instead of
|
|
936
|
+
* the real cause (see SdkSession's #8030 comment on `_enrichErrorMessage`).
|
|
937
|
+
*
|
|
938
|
+
* @param {Error & { code?: string }} err
|
|
939
|
+
* @param {object} sendOptions — this turn's sendMessage options (for the admission callback)
|
|
940
|
+
* @param {{ error: Function }} logger — the caller's logger (`this._log || log`)
|
|
941
|
+
*/
|
|
942
|
+
_refuseTurnBeforeDispatch(err, sendOptions, logger) {
|
|
943
|
+
logger.error(`Turn refused before dispatch: ${err.message}`)
|
|
944
|
+
// An uncoded throw (e.g. from a subclass's augment hook) is not a
|
|
945
|
+
// binary-verification failure, so it gets a neutral code.
|
|
946
|
+
this.emit('error', { code: err.code || 'TURN_REFUSED', message: err.message })
|
|
947
|
+
// #8038: extracted to spawnRefusalAdmission() so CliSession/ClaudeTuiSession's
|
|
948
|
+
// spawn-refusal-on-send path reports the identical wire shape — see that
|
|
949
|
+
// function's doc. Byte-identical to the pre-#8038 inline literal.
|
|
950
|
+
reportInputAdmission(sendOptions, spawnRefusalAdmission(err))
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
/**
|
|
954
|
+
* #8038 — the shared refusal path for a (re)SPAWN the binary gate stopped,
|
|
955
|
+
* as opposed to `_refuseTurnBeforeDispatch` above (which refuses a single
|
|
956
|
+
* TURN on a provider that spawns fresh per turn). CliSession's
|
|
957
|
+
* `_spawnPersistentProcess` and ClaudeTuiSession's `_respawnPty` call this
|
|
958
|
+
* when `_gatedSpawnBinary` (or, for the TUI native route, the equivalent
|
|
959
|
+
* `_connectionRuntimePreflight` re-check) throws instead of returning a
|
|
960
|
+
* verified path — nothing was spawned, so there is no child/PTY error to
|
|
961
|
+
* report through the normal exit-handling path. #8044: the TUI native
|
|
962
|
+
* route's `claude auth status` verdict (logged out, a non-first-party route,
|
|
963
|
+
* unreadable status) is refused the same way, also before any spawn.
|
|
964
|
+
* #8057 is the one post-spawn case: the native endpoint-marker verdict
|
|
965
|
+
* arrives after the PTY launched, so `_spawnPty` kills and drops that PTY
|
|
966
|
+
* first and the refusal then follows these same semantics — no live child
|
|
967
|
+
* remains, and no exit-handling path reports it either.
|
|
968
|
+
*
|
|
969
|
+
* Latches `this._spawnRefusal = err` so:
|
|
970
|
+
* - the provider's own respawn machinery can tell "the gate refused this
|
|
971
|
+
* attempt" apart from "the child/PTY actually died" and skip scheduling
|
|
972
|
+
* a backoff timer for a spawn that was never going to happen anyway
|
|
973
|
+
* (which would otherwise burn the bounded respawn budget into a
|
|
974
|
+
* misleading `respawn_exhausted` / "failed to stay alive");
|
|
975
|
+
* - the next `sendMessage` re-runs the gate once (CliSession via
|
|
976
|
+
* `_restartAfterStop`, ClaudeTuiSession via `_respawnPty`) and, if it
|
|
977
|
+
* refuses again, rejects THAT input with `spawnRefusalAdmission` instead
|
|
978
|
+
* of queuing it behind a child that will never start.
|
|
979
|
+
*
|
|
980
|
+
* Emits the SAME coded `error` shape `_refuseTurnBeforeDispatch` does
|
|
981
|
+
* (`code: err.code || …, message: err.message`) with NO error-text
|
|
982
|
+
* rewriter — see that method's doc for why (a provenance message embeds a
|
|
983
|
+
* hex hash that can spuriously match a 429/401 text-classification
|
|
984
|
+
* pattern and get rewritten into a wrong, misleading message).
|
|
985
|
+
*
|
|
986
|
+
* @param {Error & { code?: string }} err
|
|
987
|
+
* @param {{ error: Function }} logger — the caller's logger (`this._log || log`)
|
|
988
|
+
*/
|
|
989
|
+
_refuseSpawn(err, logger) {
|
|
990
|
+
this._spawnRefusal = err
|
|
991
|
+
logger.error(`Spawn refused: ${err.message}`)
|
|
992
|
+
this.emit('error', { code: err?.code || 'SPAWN_REFUSED', message: err.message })
|
|
993
|
+
}
|
|
994
|
+
|
|
595
995
|
/**
|
|
596
996
|
* #5376: delegate to SkillsManager. Kept as a session method because
|
|
597
997
|
* settings-handlers.js calls `session._loadSkills()` to rebuild after a
|
|
@@ -658,6 +1058,34 @@ export class BaseSession extends EventEmitter {
|
|
|
658
1058
|
return this._skillsManager.deactivateSkill(skillName)
|
|
659
1059
|
}
|
|
660
1060
|
|
|
1061
|
+
/**
|
|
1062
|
+
* #8259: the model is mid-turn. Every provider assigns `_isBusy = true` when it
|
|
1063
|
+
* dispatches a turn to its backend (including a queued follow-up when the queue
|
|
1064
|
+
* flushes) and BaseSession clears it at every turn end, so this accessor is the
|
|
1065
|
+
* ONE place a turn starting or ending is observable. A change emits
|
|
1066
|
+
* `turn_state` `{ active }` (internal: not in the proxied event list) so the
|
|
1067
|
+
* SessionManager can persist "a turn was in flight" and, after a daemon
|
|
1068
|
+
* restart, tell a turn that was cut off from one that merely has no `result`
|
|
1069
|
+
* in its history.
|
|
1070
|
+
*/
|
|
1071
|
+
get _isBusy() {
|
|
1072
|
+
return this._busyFlag === true
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
set _isBusy(value) {
|
|
1076
|
+
const next = !!value
|
|
1077
|
+
if (this._busyFlag === next) return
|
|
1078
|
+
this._busyFlag = next
|
|
1079
|
+
if (next) {
|
|
1080
|
+
// #9241: a new turn starts with a clean slate for the stop-before-reply marker.
|
|
1081
|
+
this._stopMarkerArmed = false
|
|
1082
|
+
this._turnOutputSeen = false
|
|
1083
|
+
this._stopMarkerMinted = false
|
|
1084
|
+
this._stopMarkerEmitted = false
|
|
1085
|
+
}
|
|
1086
|
+
this.emit('turn_state', { active: next })
|
|
1087
|
+
}
|
|
1088
|
+
|
|
661
1089
|
/**
|
|
662
1090
|
* #4307: a session is "running" — i.e. NOT idle, NOT subject to
|
|
663
1091
|
* `SessionTimeoutManager` reaping — when EITHER:
|
|
@@ -686,6 +1114,131 @@ export class BaseSession extends EventEmitter {
|
|
|
686
1114
|
return this._backgroundShellTracker.size > 0
|
|
687
1115
|
}
|
|
688
1116
|
|
|
1117
|
+
/**
|
|
1118
|
+
* #8302: the model is mid-turn. The first half of `isRunning`, exposed alone
|
|
1119
|
+
* so a publisher can tell "working" from "held busy by a background shell".
|
|
1120
|
+
* @returns {boolean}
|
|
1121
|
+
*/
|
|
1122
|
+
get turnActive() {
|
|
1123
|
+
return !!this._isBusy
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
/**
|
|
1127
|
+
* #8302: how many background shells the tracker holds. The tracker's `size`,
|
|
1128
|
+
* which counts shells the advisory mtime sweep has hidden from
|
|
1129
|
+
* `getPendingBackgroundShells()` (they still hold `isRunning` true).
|
|
1130
|
+
* @returns {number}
|
|
1131
|
+
*/
|
|
1132
|
+
get backgroundShellCount() {
|
|
1133
|
+
return this._backgroundShellTracker.size
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
/**
|
|
1137
|
+
* #8281: a prompt has left `_outgoingQueue` (see `dequeueNextOutgoing`) but its
|
|
1138
|
+
* deferred send has not begun. For that one tick the session is not busy AND
|
|
1139
|
+
* the queue is empty, yet a turn is about to start.
|
|
1140
|
+
* @returns {boolean}
|
|
1141
|
+
*/
|
|
1142
|
+
get hasDequeueInFlight() {
|
|
1143
|
+
return this._dequeuesInFlight > 0
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
/**
|
|
1147
|
+
* #8281: is a turn in flight from the point of view of a handoff? Defaults to
|
|
1148
|
+
* `turnActive`. A provider whose turn exists before `_isBusy` is set (or
|
|
1149
|
+
* before its backend id is known) overrides this rather than the base class
|
|
1150
|
+
* learning provider internals.
|
|
1151
|
+
* @returns {boolean}
|
|
1152
|
+
*/
|
|
1153
|
+
_hasTurnInFlight() {
|
|
1154
|
+
return this.turnActive
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
/**
|
|
1158
|
+
* #8281: ids of every permission prompt waiting on a human for this session,
|
|
1159
|
+
* deduped across the same sources `getPendingPermissionCount()` counts:
|
|
1160
|
+
* the hook-routed ids (`_pendingPermissionIds`, CLI / TUI, registered by
|
|
1161
|
+
* ws-permissions through `notifyPermissionPending`), the in-process map
|
|
1162
|
+
* installed as `_pendingPermissions` when it is a Map, and the
|
|
1163
|
+
* PermissionManager's own ids. EMPTY when none of them holds anything.
|
|
1164
|
+
* @returns {string[]}
|
|
1165
|
+
*/
|
|
1166
|
+
getPendingPermissionIds() {
|
|
1167
|
+
const ids = new Set(this._pendingPermissionIds)
|
|
1168
|
+
if (this._pendingPermissions instanceof Map) {
|
|
1169
|
+
for (const id of this._pendingPermissions.keys()) ids.add(id)
|
|
1170
|
+
}
|
|
1171
|
+
for (const id of this._permissions?.getPendingPermissionIds?.() ?? []) ids.add(id)
|
|
1172
|
+
return Array.from(ids)
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
/**
|
|
1176
|
+
* #8281: prompts accepted by the provider that wait in a queue other than
|
|
1177
|
+
* `_outgoingQueue` (or have left one with the send deferred). Default 0; a
|
|
1178
|
+
* provider with a second queue overrides it. Counted as `queued_prompts`.
|
|
1179
|
+
* @returns {number}
|
|
1180
|
+
*/
|
|
1181
|
+
_extraQueuedPromptCount() {
|
|
1182
|
+
return 0
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
/**
|
|
1186
|
+
* #8281: why a handoff must not start from this session right now. An empty
|
|
1187
|
+
* array means nothing in THIS session can still act. Each entry is
|
|
1188
|
+
* `{ code, detail? }`; codes:
|
|
1189
|
+
*
|
|
1190
|
+
* - `turn_active` a turn is in flight (`_hasTurnInFlight`)
|
|
1191
|
+
* - `queued_prompts` prompts wait in the outgoing queue, or one has left
|
|
1192
|
+
* it and its send has not begun (`hasDequeueInFlight`)
|
|
1193
|
+
* - `pending_permission` an approval is waiting (`getPendingPermissionIds`)
|
|
1194
|
+
* - `pending_question` an AskUserQuestion is waiting (`getPendingQuestions`)
|
|
1195
|
+
* - `active_agents` subagents are running (`getActiveAgents`)
|
|
1196
|
+
* - `not_ready` the provider process is not ready
|
|
1197
|
+
* - `destroying` the session is being torn down
|
|
1198
|
+
* - `background_shells` SOFT: tracked background shells exist; the entry's
|
|
1199
|
+
* detail carries `soft: true` (see
|
|
1200
|
+
* `SOFT_HANDOFF_BLOCKER_CODES`). It is reported, and the
|
|
1201
|
+
* caller decides whether it blocks.
|
|
1202
|
+
*
|
|
1203
|
+
* Does NOT see what lives outside the session: the prompt evaluator and
|
|
1204
|
+
* scheduler/orchestration ownership. `SessionManager.
|
|
1205
|
+
* getHandoffBlockers` adds those. `isRunning` is unchanged and unrelated.
|
|
1206
|
+
*
|
|
1207
|
+
* @returns {{ code: string, detail?: object }[]}
|
|
1208
|
+
*/
|
|
1209
|
+
getHandoffBlockers() {
|
|
1210
|
+
const blockers = []
|
|
1211
|
+
if (this._destroying) blockers.push({ code: 'destroying' })
|
|
1212
|
+
if (!this._processReady) blockers.push({ code: 'not_ready' })
|
|
1213
|
+
if (this._hasTurnInFlight()) blockers.push({ code: 'turn_active' })
|
|
1214
|
+
const queued = this._outgoingQueue.length + this._dequeuesInFlight + this._extraQueuedPromptCount()
|
|
1215
|
+
if (queued > 0) blockers.push({ code: 'queued_prompts', detail: { count: queued } })
|
|
1216
|
+
const permissionIds = this.getPendingPermissionIds()
|
|
1217
|
+
if (permissionIds.length > 0) {
|
|
1218
|
+
blockers.push({ code: 'pending_permission', detail: { requestIds: permissionIds } })
|
|
1219
|
+
}
|
|
1220
|
+
const questions = this.getPendingQuestions()
|
|
1221
|
+
if (questions.length > 0) {
|
|
1222
|
+
blockers.push({ code: 'pending_question', detail: { count: questions.length } })
|
|
1223
|
+
}
|
|
1224
|
+
const agents = this._activeAgents.size
|
|
1225
|
+
if (agents > 0) blockers.push({ code: 'active_agents', detail: { count: agents } })
|
|
1226
|
+
const shells = this.backgroundShellCount
|
|
1227
|
+
if (shells > 0) blockers.push({ code: 'background_shells', detail: { count: shells, soft: true } })
|
|
1228
|
+
return blockers
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
/**
|
|
1232
|
+
* #8302: why `isRunning` is true — `'turn'`, `'background-shells'` (idle model,
|
|
1233
|
+
* tracked shells only), or `null` when the session is not busy. Derived from
|
|
1234
|
+
* `isRunning` itself so a subclass that overrides it (the user shell's PTY
|
|
1235
|
+
* liveness) keeps `busyReason === null <=> !isRunning`.
|
|
1236
|
+
* @returns {'turn'|'background-shells'|null}
|
|
1237
|
+
*/
|
|
1238
|
+
get busyReason() {
|
|
1239
|
+
return deriveBusyReason(this.isRunning, this.turnActive, this.backgroundShellCount)
|
|
1240
|
+
}
|
|
1241
|
+
|
|
689
1242
|
/**
|
|
690
1243
|
* #4307: read-only snapshot of pending background shells.
|
|
691
1244
|
* #5376: delegates to BackgroundShellTracker.
|
|
@@ -781,6 +1334,8 @@ export class BaseSession extends EventEmitter {
|
|
|
781
1334
|
dequeueNextOutgoing() {
|
|
782
1335
|
if (this._destroying || this._outgoingQueue.length === 0) return null
|
|
783
1336
|
const item = this._outgoingQueue.shift()
|
|
1337
|
+
// #8281: the item is off the queue but not yet sent; see `hasDequeueInFlight`.
|
|
1338
|
+
this._dequeuesInFlight++
|
|
784
1339
|
const clientMessageId = typeof item.sendOptions?.clientMessageId === 'string'
|
|
785
1340
|
? item.sendOptions.clientMessageId
|
|
786
1341
|
: undefined
|
|
@@ -795,7 +1350,25 @@ export class BaseSession extends EventEmitter {
|
|
|
795
1350
|
// dequeue ahead of the result that triggered it.
|
|
796
1351
|
const remaining = this._outgoingQueue.length
|
|
797
1352
|
process.nextTick(() => {
|
|
1353
|
+
// #8281: the deferred send begins here. Cleared FIRST so every exit below
|
|
1354
|
+
// (destroyed, admission refused, sent) leaves the counter balanced.
|
|
1355
|
+
this._dequeuesInFlight = Math.max(0, this._dequeuesInFlight - 1)
|
|
798
1356
|
if (this._destroying) return
|
|
1357
|
+
// #8301: an item that carries `sendOptions.admitAtFlush` is re-checked HERE,
|
|
1358
|
+
// at the moment it would be dispatched — after the preceding turn's
|
|
1359
|
+
// `result` has been broadcast and processed on every turn-end path. Its
|
|
1360
|
+
// admission at enqueue time can be stale by then (the result can trip the
|
|
1361
|
+
// cost-budget pause). The predicate is a LOCAL callback: it is never put on
|
|
1362
|
+
// the wire (`message_queued` carries only id/text/length) and the queue is
|
|
1363
|
+
// not persisted. Typed input does not set it, so its behaviour is unchanged.
|
|
1364
|
+
// A refusal — or a throwing predicate, which fails safe — cancels just this
|
|
1365
|
+
// item and goes on to consider the next, so the queue keeps draining.
|
|
1366
|
+
if (!this._admitQueuedItem(item)) {
|
|
1367
|
+
this.emit('message_dequeued', { clientMessageId, queueLength: remaining, reason: 'cancelled' })
|
|
1368
|
+
;(this._log || log).warn(`Dropped queued follow-up at flush: admission refused (${remaining} remaining)`)
|
|
1369
|
+
this._continueDrainAfterRefusal()
|
|
1370
|
+
return
|
|
1371
|
+
}
|
|
799
1372
|
this.emit('message_dequeued', { clientMessageId, queueLength: remaining, reason: 'flush' })
|
|
800
1373
|
;(this._log || log).info(`Dequeuing follow-up message (${remaining} remaining)`)
|
|
801
1374
|
this.sendMessage(item.prompt, item.attachments, item.sendOptions)
|
|
@@ -803,6 +1376,75 @@ export class BaseSession extends EventEmitter {
|
|
|
803
1376
|
return item
|
|
804
1377
|
}
|
|
805
1378
|
|
|
1379
|
+
/**
|
|
1380
|
+
* #8301: the refused item held this turn's drain slot, so keep draining. The
|
|
1381
|
+
* default continues with the next outgoing item. A provider with a second
|
|
1382
|
+
* queue behind `_outgoingQueue` (CliSession's startup queue) overrides this to
|
|
1383
|
+
* fall through to it, exactly as its own turn-end drain would have.
|
|
1384
|
+
*/
|
|
1385
|
+
_continueDrainAfterRefusal() {
|
|
1386
|
+
if (this._outgoingQueue.length && !this._destroying) this.dequeueNextOutgoing()
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
/**
|
|
1390
|
+
* #8301: evaluate a queued item's optional flush-time admission predicate.
|
|
1391
|
+
* No predicate means admitted (every typed input). A predicate that returns
|
|
1392
|
+
* anything but `true`, or throws, means NOT admitted.
|
|
1393
|
+
*
|
|
1394
|
+
* @param {{ sendOptions?: { admitAtFlush?: () => boolean } }} item
|
|
1395
|
+
* @returns {boolean}
|
|
1396
|
+
*/
|
|
1397
|
+
_admitQueuedItem(item) {
|
|
1398
|
+
// The connection that queued this follow-up may have ended while it waited:
|
|
1399
|
+
// a revoked or expired credential must not get its queued input dispatched.
|
|
1400
|
+
if (!stillAuthorized(item?.sendOptions?.isAuthorized)) return false
|
|
1401
|
+
return this._admitPreparedSend(item?.sendOptions)
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
/**
|
|
1405
|
+
* #9242: re-ask a send's admission predicate (`sendOptions.admitAtFlush`) at a
|
|
1406
|
+
* provider's POST-PREPARATION point — after any await between `sendMessage` entry
|
|
1407
|
+
* and the irreversible step (history mutation, query/stream dispatch). The flush
|
|
1408
|
+
* check covers a send that was queued; this covers one that was never queued but
|
|
1409
|
+
* waited inside the provider (project-settings scan, MCP prompt expansion). No
|
|
1410
|
+
* predicate means admitted, so every caller that passes none is unchanged. Anything
|
|
1411
|
+
* but `true`, or a throw, is a refusal; the CALLER must then release busy, report
|
|
1412
|
+
* the refusal and continue the queue. (TurnDriver's predicate wrapper ends its own
|
|
1413
|
+
* turn NOT_ADMITTED on a refusal.)
|
|
1414
|
+
*
|
|
1415
|
+
* @param {{ admitAtFlush?: () => boolean }} [sendOptions]
|
|
1416
|
+
* @returns {boolean}
|
|
1417
|
+
*/
|
|
1418
|
+
_admitPreparedSend(sendOptions) {
|
|
1419
|
+
const predicate = sendOptions?.admitAtFlush
|
|
1420
|
+
if (typeof predicate !== 'function') return true
|
|
1421
|
+
try {
|
|
1422
|
+
return predicate() === true
|
|
1423
|
+
} catch (err) {
|
|
1424
|
+
;(this._log || log).warn(`Send admission check threw; refusing the send: ${err?.message || err}`)
|
|
1425
|
+
return false
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
/**
|
|
1430
|
+
* #8301: why a DAEMON-authored turn (the CI wake) must not be handed to this
|
|
1431
|
+
* session right now, or `null` when it may. The provider's half of the one
|
|
1432
|
+
* refusal seam `SessionManager.daemonTurnRefusal` asks — before dispatch and
|
|
1433
|
+
* again when a queued wake is about to flush.
|
|
1434
|
+
*
|
|
1435
|
+
* This is a stricter question than "can the user type here": a typed input
|
|
1436
|
+
* may legitimately revive a stopped session or surface an error, but a
|
|
1437
|
+
* daemon wake that does so is a side effect nobody asked for. A provider
|
|
1438
|
+
* overrides it for the states in which `sendMessage` would do that (respawn,
|
|
1439
|
+
* discard the queue, report a user-visible error). The default is `null`: a
|
|
1440
|
+
* provider that has no such state is always willing.
|
|
1441
|
+
*
|
|
1442
|
+
* @returns {string|null} a short reason, or null
|
|
1443
|
+
*/
|
|
1444
|
+
daemonTurnRefusal() {
|
|
1445
|
+
return null
|
|
1446
|
+
}
|
|
1447
|
+
|
|
806
1448
|
/**
|
|
807
1449
|
* #5936: drop every queued outgoing message. Called by `interrupt()` so a
|
|
808
1450
|
* deliberate Stop cancels the owner's pending follow-ups rather than letting
|
|
@@ -933,7 +1575,26 @@ export class BaseSession extends EventEmitter {
|
|
|
933
1575
|
// and never call _destroyPendingBackgroundShells, so this is the
|
|
934
1576
|
// chokepoint that guarantees no provider leaks the recurring timer.
|
|
935
1577
|
this._stopBackgroundShellSweep()
|
|
936
|
-
|
|
1578
|
+
// #7340: drop EVERY tracked subagent, foreground and backgrounded alike.
|
|
1579
|
+
// Before #7340 the turn-end sweep guaranteed this map was empty by the
|
|
1580
|
+
// time a session was torn down; agents that outlive their turn break that
|
|
1581
|
+
// guarantee, so the same chokepoint that stops the shell sweep clears
|
|
1582
|
+
// them. A destroy landing MID-TURN also has foreground agents tracked,
|
|
1583
|
+
// which is why this is an unconditional clear and not a filtered one --
|
|
1584
|
+
// the `backgroundConfirmed` predicate belongs to the turn-end sweep, where the
|
|
1585
|
+
// question is "did this outlive its turn", not to teardown, where there
|
|
1586
|
+
// is no next turn for anything to outlive. No `agent_completed` emit: the
|
|
1587
|
+
// session is being destroyed, its clients drop its state wholesale, and
|
|
1588
|
+
// the listeners come off on the next line anyway.
|
|
1589
|
+
this._activeAgents.clear()
|
|
1590
|
+
const removed = super.removeAllListeners()
|
|
1591
|
+
// A turn aborted by this teardown can still emit 'error' after the
|
|
1592
|
+
// listeners are gone; with none attached that throws ERR_UNHANDLED_ERROR.
|
|
1593
|
+
// SessionManager.destroySession adds a no-op listener, but the provider's
|
|
1594
|
+
// own destroy() ends here and would drop it. Re-add it for a session that
|
|
1595
|
+
// is being destroyed.
|
|
1596
|
+
if (this._destroying) super.on('error', () => {})
|
|
1597
|
+
return removed
|
|
937
1598
|
}
|
|
938
1599
|
return super.removeAllListeners(eventName)
|
|
939
1600
|
}
|
|
@@ -948,15 +1609,93 @@ export class BaseSession extends EventEmitter {
|
|
|
948
1609
|
this._activity.setSessionId(sessionId)
|
|
949
1610
|
}
|
|
950
1611
|
|
|
951
|
-
/**
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
1612
|
+
/** Project durable session intent into the existing activity tree. */
|
|
1613
|
+
setDeclaredStatusActivity(status) {
|
|
1614
|
+
this._activity.onDeclaredStatus(status)
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
getDecisionActivityState() {
|
|
1618
|
+
return this._activity.getDecisionState()
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
restoreDeclaredStatusActivity(status, state) {
|
|
1622
|
+
this._activity.restoreDecisionState(status, state)
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
/** Full current tree for fresh subscribers and resync. */
|
|
956
1626
|
getActivitySnapshot() {
|
|
957
1627
|
return this._activity.getSnapshotMessage()
|
|
958
1628
|
}
|
|
959
1629
|
|
|
1630
|
+
/**
|
|
1631
|
+
* #7340: the subagents this session is currently tracking, as the wire
|
|
1632
|
+
* fields of an `agent_spawned` message.
|
|
1633
|
+
*
|
|
1634
|
+
* Serves the same purpose `getActivitySnapshot()` does for the Control Room
|
|
1635
|
+
* tree, for the surface that has no tree: `agent_spawned` / `agent_completed`
|
|
1636
|
+
* are transient (`builtinTransient` in SessionManager) and are NOT replayed
|
|
1637
|
+
* from history, so both clients WIPE `activeAgents` at `history_replay_start`
|
|
1638
|
+
* and nothing put it back. That was harmless while no agent outlived its
|
|
1639
|
+
* turn; once one does, a 2s cellular drop or a tab switch returned the
|
|
1640
|
+
* session to `idle` with subagents still running -- #7340's exact symptom,
|
|
1641
|
+
* reached a different way.
|
|
1642
|
+
*
|
|
1643
|
+
* Re-emitting the live set AFTER the replay makes the wipe a snapshot
|
|
1644
|
+
* REPLACE rather than a loss: the wipe clears whatever the client held
|
|
1645
|
+
* (including a completion it missed while offline, which is why the wipe is
|
|
1646
|
+
* kept rather than carved out the way #4466 did for `activeTools`), and this
|
|
1647
|
+
* re-asserts what is actually running. Both clients dedupe `agent_spawned`
|
|
1648
|
+
* by `toolUseId`, so re-emitting to a client that never lost the entry is a
|
|
1649
|
+
* no-op.
|
|
1650
|
+
*
|
|
1651
|
+
* Projected to the three fields `event-normalizer` puts on the wire -- the
|
|
1652
|
+
* record's `background` / `backgroundConfirmed` are server-side bookkeeping
|
|
1653
|
+
* and must not start leaking to clients through this path.
|
|
1654
|
+
*
|
|
1655
|
+
* @returns {{ toolUseId: string, description: string, startedAt: number }[]}
|
|
1656
|
+
*/
|
|
1657
|
+
getActiveAgents() {
|
|
1658
|
+
// Keyed by the MAP KEY, not `agent.toolUseId` -- the same invariant
|
|
1659
|
+
// `_completeAgents` states. A record whose field drifted from its key would
|
|
1660
|
+
// otherwise be re-announced under one id and completed under another, and
|
|
1661
|
+
// the client's dedupe and its filter would key on different ids, leaving a
|
|
1662
|
+
// badge entry nothing can clear.
|
|
1663
|
+
return Array.from(this._activeAgents, ([toolUseId, { description, startedAt }]) => ({
|
|
1664
|
+
toolUseId,
|
|
1665
|
+
description,
|
|
1666
|
+
startedAt,
|
|
1667
|
+
}))
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
/**
|
|
1671
|
+
* #7457: the AskUserQuestion prompts this session's turn is still BLOCKED on.
|
|
1672
|
+
*
|
|
1673
|
+
* Read by `ws-history.resendPendingQuestions`, which re-sends each one as a
|
|
1674
|
+
* LIVE `user_question` frame after every replay's `history_replay_end`. Until
|
|
1675
|
+
* then the only path a pending question had to a reconnecting client was the
|
|
1676
|
+
* history replay itself -- and `history_replay_end`'s sweep stamps every
|
|
1677
|
+
* replay-delivered prompt `answered: '(resolved)'`, so an ordinary reconnect
|
|
1678
|
+
* destroyed the answer path for a question the agent was still waiting on.
|
|
1679
|
+
*
|
|
1680
|
+
* Deliberately a READ-THROUGH to whatever store the provider already uses to
|
|
1681
|
+
* hold the blocked resolver -- `PermissionManager._pendingUserAnswer` for the
|
|
1682
|
+
* in-process providers, `_pendingUserAnswers` for claude-tui,
|
|
1683
|
+
* `_pendingQuestion` for cli-session. A mirrored copy would need a lifecycle
|
|
1684
|
+
* of its own, and a leaked mirror entry re-delivers a dead question to every
|
|
1685
|
+
* client that ever connects again; a read-through cannot leak, because the
|
|
1686
|
+
* record IS the thing blocking the turn.
|
|
1687
|
+
*
|
|
1688
|
+
* The default is EMPTY, not "unsupported": a provider with no question
|
|
1689
|
+
* surface has nothing pending, and `resendPendingQuestions` calls this
|
|
1690
|
+
* unguarded -- a feature-detect that can never fail only converts a future
|
|
1691
|
+
* regression into a silent no-op (docs/false-safety-guards.md).
|
|
1692
|
+
*
|
|
1693
|
+
* @returns {{ toolUseId: string, questions: object[] }[]}
|
|
1694
|
+
*/
|
|
1695
|
+
getPendingQuestions() {
|
|
1696
|
+
return []
|
|
1697
|
+
}
|
|
1698
|
+
|
|
960
1699
|
/**
|
|
961
1700
|
* #6832: last-known `mcp_servers` payload, wrapped as the wire message
|
|
962
1701
|
* shape (`{ type: 'mcp_servers', servers }`). Served to a fresh subscriber
|
|
@@ -1030,6 +1769,22 @@ export class BaseSession extends EventEmitter {
|
|
|
1030
1769
|
return this._backgroundShellTracker._isBackgroundShellQuiesced(entry)
|
|
1031
1770
|
}
|
|
1032
1771
|
|
|
1772
|
+
/**
|
|
1773
|
+
* #7611: forget every pending background shell WITHOUT tearing the session
|
|
1774
|
+
* down — for a provider that has just killed the process tree the shells
|
|
1775
|
+
* lived in and is about to start a fresh one. Unlike
|
|
1776
|
+
* `_destroyPendingBackgroundShells` it leaves the activity registry and the
|
|
1777
|
+
* intra-turn command map alone (the session carries on, and those belong to
|
|
1778
|
+
* the turn machinery), and it emits `background_work_changed` so the banner
|
|
1779
|
+
* drops the dead shells. delegates to BackgroundShellTracker.clearAll().
|
|
1780
|
+
*
|
|
1781
|
+
* @returns {number} how many pending shells were forgotten
|
|
1782
|
+
* @private
|
|
1783
|
+
*/
|
|
1784
|
+
_clearPendingBackgroundShells() {
|
|
1785
|
+
return this._backgroundShellTracker.clearAll()
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1033
1788
|
/**
|
|
1034
1789
|
* #4307: clear the pending map on session destroy. Pulled into a
|
|
1035
1790
|
* helper so subclasses can call it from their own `destroy()` after
|
|
@@ -1111,6 +1866,78 @@ export class BaseSession extends EventEmitter {
|
|
|
1111
1866
|
*/
|
|
1112
1867
|
markIntentionalStop() {
|
|
1113
1868
|
this._intentionalStop = true
|
|
1869
|
+
// #8461: a new Stop request is acknowledged on its own.
|
|
1870
|
+
this._stoppedSinceStopRequest = false
|
|
1871
|
+
this._stopAckedByResult = false
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
/**
|
|
1875
|
+
* #8374/#8430: the USER pressed Stop. Record it on the session's permission
|
|
1876
|
+
* manager for the rest of the turn, so the abort that follows resolves the
|
|
1877
|
+
* prompts open now -- and any raised before the abort lands -- as `stopped`
|
|
1878
|
+
* rather than `aborted`. Called by the `interrupt` message handler only -- never
|
|
1879
|
+
* from a provider's `interrupt()`, which the scheduler and teardown also call --
|
|
1880
|
+
* because a turn failed by a stalled stream or a dead provider process aborts
|
|
1881
|
+
* the same controller and is not a Stop. A Stop pressed with no turn running and no
|
|
1882
|
+
* prompt open records nothing (there is nothing for it to cancel), and a session with no
|
|
1883
|
+
* in-process permission manager has nothing to record on.
|
|
1884
|
+
* Cleared by `_clearMessageState`, which every turn end reaches.
|
|
1885
|
+
*/
|
|
1886
|
+
markUserStopInFlight() {
|
|
1887
|
+
// A turn is running, or a prompt is still open (a stalled turn's query can
|
|
1888
|
+
// outlive its busy flag and raise one): either way there is something for
|
|
1889
|
+
// this Stop to cancel. Otherwise there is nothing to label.
|
|
1890
|
+
if (!this._isBusy && !this._permissions?.hasPendingPrompt?.()) return
|
|
1891
|
+
this._permissions?.markUserStopInFlight?.()
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1894
|
+
/**
|
|
1895
|
+
* #9241: a Stop came in through the `interrupt` message (the dashboard, the app, or
|
|
1896
|
+
* an agent-control client: the marker's wording is neutral, so who pressed it does
|
|
1897
|
+
* not matter). Separate from `markUserStopInFlight` (permission labelling) and
|
|
1898
|
+
* `_noteTurnStopRequested` (anyone's `interrupt()`, including the scheduler's and
|
|
1899
|
+
* orchestration's, which must never leave a marker). Called by the `interrupt`
|
|
1900
|
+
* message handler only. A no-op when idle, so a Stop between turns cannot leak into
|
|
1901
|
+
* the next one; idempotent for a double Stop. A prompt still open counts as output
|
|
1902
|
+
* too (hook-routed ones are also latched when they are registered).
|
|
1903
|
+
*/
|
|
1904
|
+
markStopRequested() {
|
|
1905
|
+
if (!this._isBusy) return
|
|
1906
|
+
this._stopMarkerArmed = true
|
|
1907
|
+
if (this.getPendingPermissionCount() > 0) this._turnOutputSeen = true
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
/**
|
|
1911
|
+
* #9241: a provider's own evidence that the model began answering, for output that
|
|
1912
|
+
* does not reach `emit` as a classified event (claude-tui's structured events lag
|
|
1913
|
+
* its screen, see ClaudeTuiSession's hook drain).
|
|
1914
|
+
*/
|
|
1915
|
+
_noteTurnOutput() {
|
|
1916
|
+
this._turnOutputSeen = true
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1919
|
+
/**
|
|
1920
|
+
* #9241: should the terminal event now being emitted for this turn carry the
|
|
1921
|
+
* stop-before-reply marker? True once per turn, only for a Stop that came in
|
|
1922
|
+
* through `interrupt` before any output, never while the session is being torn
|
|
1923
|
+
* down. The CALLER also needs the provider's explicit word that the turn ended
|
|
1924
|
+
* BECAUSE of the requested stop (`stopRequested` on its stop-path event, or its own
|
|
1925
|
+
* `turnOutcome: 'stopped'`): a stall watchdog, a timeout or an error after the Stop
|
|
1926
|
+
* ends the turn too, and is not a Stop.
|
|
1927
|
+
*/
|
|
1928
|
+
_shouldMintStopBeforeReply() {
|
|
1929
|
+
return this._stopMarkerArmed && !this._turnOutputSeen && !this._stopMarkerMinted && !this._destroying
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
/**
|
|
1933
|
+
* #7376: record that a Stop was requested during the turn that is running
|
|
1934
|
+
* now. A no-op when idle, so a Stop pressed between turns cannot leak into the
|
|
1935
|
+
* next one. Called by the providers whose `interrupt()` can be acknowledged by
|
|
1936
|
+
* a NORMAL `result` (claude-cli, claude-sdk) rather than only by a child exit
|
|
1937
|
+
* or a thrown abort; the flag is turn-scoped and reset by `_clearMessageState`.
|
|
1938
|
+
*/
|
|
1939
|
+
_noteTurnStopRequested() {
|
|
1940
|
+
if (this._isBusy) this._stopRequestedThisTurn = true
|
|
1114
1941
|
}
|
|
1115
1942
|
|
|
1116
1943
|
/**
|
|
@@ -1173,6 +2000,9 @@ export class BaseSession extends EventEmitter {
|
|
|
1173
2000
|
if (!ALLOWED_PERMISSION_MODE_IDS.has(mode)) {
|
|
1174
2001
|
return false
|
|
1175
2002
|
}
|
|
2003
|
+
if (!getProviderPermissionModeSupport(this.constructor, mode).supported) {
|
|
2004
|
+
return false
|
|
2005
|
+
}
|
|
1176
2006
|
// 'auto' is the panic-button: a user mid-turn (i.e. _isBusy=true)
|
|
1177
2007
|
// staring at a permission prompt should be able to flip to bypass and
|
|
1178
2008
|
// have it actually take effect. The non-auto modes still defer until
|
|
@@ -1283,10 +2113,10 @@ export class BaseSession extends EventEmitter {
|
|
|
1283
2113
|
* stored value changes and `false` for either invalid input or a
|
|
1284
2114
|
* redundant set — same idempotent contract as `setPromptEvaluator`.
|
|
1285
2115
|
*
|
|
1286
|
-
* The compiled regex itself isn't stored: `
|
|
2116
|
+
* The compiled regex itself isn't stored: `shouldSkipEvaluatorAsync` owns
|
|
1287
2117
|
* the compile cache (LRU keyed by source string) so a stale per-session
|
|
1288
2118
|
* pattern won't pin a closure here. The validation done here is
|
|
1289
|
-
* defence-in-depth — `
|
|
2119
|
+
* defence-in-depth — `shouldSkipEvaluatorAsync` also try/catches its own
|
|
1290
2120
|
* compile, so a session that somehow ends up with a bad source still
|
|
1291
2121
|
* fails-open to default-only skip rules.
|
|
1292
2122
|
*
|
|
@@ -1317,10 +2147,6 @@ export class BaseSession extends EventEmitter {
|
|
|
1317
2147
|
return true
|
|
1318
2148
|
}
|
|
1319
2149
|
|
|
1320
|
-
/**
|
|
1321
|
-
* Clear per-message state. Subclasses should call super._clearMessageState()
|
|
1322
|
-
* and then clear their own additional state (plan mode, pending permissions, etc.).
|
|
1323
|
-
*/
|
|
1324
2150
|
/**
|
|
1325
2151
|
* Parse a JSONL line from a subprocess stdout.
|
|
1326
2152
|
* Returns the parsed object or null if the line is empty or invalid JSON.
|
|
@@ -1413,22 +2239,46 @@ export class BaseSession extends EventEmitter {
|
|
|
1413
2239
|
*/
|
|
1414
2240
|
_buildSystemPrompt() {
|
|
1415
2241
|
const skillsText = typeof this._skillsText === 'string' ? this._skillsText : ''
|
|
1416
|
-
// Order (#4660 + #3805):
|
|
1417
|
-
//
|
|
1418
|
-
//
|
|
1419
|
-
//
|
|
2242
|
+
// Order (#7835 + #4660 + #3805): verified required project policy → user
|
|
2243
|
+
// preamble → chroxy hint → skills text. Required policy has its own budget
|
|
2244
|
+
// and cannot be displaced by optional/prunable context. The user-authored
|
|
2245
|
+
// preamble still precedes the canned hint and runtime-skills bucket.
|
|
1420
2246
|
//
|
|
1421
2247
|
// When BOTH the preamble is empty AND the chroxy hint is OFF, the
|
|
1422
2248
|
// return value is byte-identical to pre-#3805 (skillsText only) so
|
|
1423
2249
|
// existing users see no observable behaviour change. Each layer is
|
|
1424
2250
|
// joined by `\n\n` so the model sees clean paragraph breaks.
|
|
1425
2251
|
const parts = []
|
|
2252
|
+
if (this.projectInstructions) parts.push(this.projectInstructions)
|
|
1426
2253
|
if (this.sessionPreamble) parts.push(this.sessionPreamble)
|
|
1427
2254
|
if (this.chroxyContextHint) parts.push(CHROXY_CONTEXT_HINT_TEXT)
|
|
1428
2255
|
if (skillsText) parts.push(skillsText)
|
|
1429
2256
|
return parts.length === 0 ? '' : parts.join('\n\n')
|
|
1430
2257
|
}
|
|
1431
2258
|
|
|
2259
|
+
_installProjectInstructionProjection(projection) {
|
|
2260
|
+
if (!projection) {
|
|
2261
|
+
this.projectInstructions = ''
|
|
2262
|
+
this._projectInstructionProjection = {
|
|
2263
|
+
status: 'unknown', enforcement: 'instructional', compilerVersion: '1', budgetBytes: 0, totalBytes: 0,
|
|
2264
|
+
sources: [], rules: [], includedRequiredRuleIds: [],
|
|
2265
|
+
}
|
|
2266
|
+
return
|
|
2267
|
+
}
|
|
2268
|
+
const bytes = Buffer.byteLength(projection.text, 'utf8')
|
|
2269
|
+
if (bytes !== projection.totalBytes || bytes > projection.budgetBytes
|
|
2270
|
+
|| projection.budgetBytes > PROJECT_INSTRUCTION_BUDGET_BYTES) {
|
|
2271
|
+
throw new Error('Invalid project-instruction projection byte metadata')
|
|
2272
|
+
}
|
|
2273
|
+
this.projectInstructions = projection.text
|
|
2274
|
+
this._projectInstructionProjection = {
|
|
2275
|
+
status: 'delivered', enforcement: 'instructional', compilerVersion: projection.compilerVersion,
|
|
2276
|
+
budgetBytes: projection.budgetBytes, totalBytes: projection.totalBytes,
|
|
2277
|
+
sources: projection.sources, rules: projection.rules,
|
|
2278
|
+
includedRequiredRuleIds: projection.includedRequiredRuleIds,
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
|
|
1432
2282
|
/**
|
|
1433
2283
|
* Return the formatted skills text for prepending to the first user
|
|
1434
2284
|
* message (Codex, Gemini default; any provider when a skill declares
|
|
@@ -1510,6 +2360,78 @@ export class BaseSession extends EventEmitter {
|
|
|
1510
2360
|
this._inFlightToolStarts.delete(toolUseId)
|
|
1511
2361
|
}
|
|
1512
2362
|
|
|
2363
|
+
/**
|
|
2364
|
+
* #7346: attach the finalized tool input onto the in-flight tracking
|
|
2365
|
+
* entry created by `_trackToolStart`, so `_getTrackedToolInput` can
|
|
2366
|
+
* hand it back to `tool-result.js`'s `emitToolResults` when the
|
|
2367
|
+
* matching `tool_result` fires. No-op when the toolUseId isn't
|
|
2368
|
+
* tracked (already resolved/swept, or `_trackToolStart` was never
|
|
2369
|
+
* called for this provider — e.g. BYOK).
|
|
2370
|
+
*
|
|
2371
|
+
* #8135/#8136 (review on #7346): this is the ONE choke point both
|
|
2372
|
+
* providers' finalized-input capture flows through
|
|
2373
|
+
* (`cli-session.js`'s `_captureFinalizedToolInput`,
|
|
2374
|
+
* `sdk-session.js`'s `_handleToolUseBlock`), so it runs every input
|
|
2375
|
+
* through `sanitizeToolInput` (`redaction.js`, the same #6029 floor
|
|
2376
|
+
* `permission-manager.js`/`ws-permissions.js` already apply on the
|
|
2377
|
+
* permission-request path) BEFORE storing it — never the raw value.
|
|
2378
|
+
* That one call does double duty: it redacts secret-shaped values
|
|
2379
|
+
* (key-name AND value-shape passes, recursively) and caps the
|
|
2380
|
+
* serialized size to `MAX_INPUT_CHARS` (10KB, the existing broadcast
|
|
2381
|
+
* cap — falling back to a `{ _truncated, summary }` shape when the
|
|
2382
|
+
* whole object is oversized), so a 100KB+ `Write`/`Edit` input can
|
|
2383
|
+
* never reach `_getTrackedToolInput`, `tool_result`, or the persisted
|
|
2384
|
+
* `tool_start` history entry ungated. Every reader of this map
|
|
2385
|
+
* therefore gets an already-safe value for free — there is no second
|
|
2386
|
+
* place that needs to sanitize or cap.
|
|
2387
|
+
*
|
|
2388
|
+
* Returns the sanitized value (not just `undefined`) so a caller that
|
|
2389
|
+
* wants to deliver it somewhere else too (e.g. a single-shot
|
|
2390
|
+
* `tool_input_delta` for the in-flight view) doesn't need a redundant
|
|
2391
|
+
* `_getTrackedToolInput` round-trip.
|
|
2392
|
+
*
|
|
2393
|
+
* @param {string} toolUseId
|
|
2394
|
+
* @param {unknown} input - the finalized (fully parsed) tool input
|
|
2395
|
+
* @returns {unknown} the sanitized value that was stored (or `input`
|
|
2396
|
+
* unchanged if `toolUseId` wasn't tracked — still sanitized, just
|
|
2397
|
+
* not stored anywhere)
|
|
2398
|
+
*/
|
|
2399
|
+
_recordToolInput(toolUseId, input) {
|
|
2400
|
+
const sanitized = sanitizeToolInput(input)
|
|
2401
|
+
if (typeof toolUseId !== 'string' || toolUseId.length === 0) return sanitized
|
|
2402
|
+
const entry = this._inFlightToolStarts.get(toolUseId)
|
|
2403
|
+
if (entry) {
|
|
2404
|
+
entry.input = sanitized
|
|
2405
|
+
// #8371: tell the owner of the history ring buffer right now, not at
|
|
2406
|
+
// result time. The `tool_start` entry was recorded with `input: null`
|
|
2407
|
+
// and a replay (session switch, dashboard reload) during a still-running
|
|
2408
|
+
// tool would otherwise show no INPUT until the result lands. Only for a
|
|
2409
|
+
// TRACKED id (BYOK never tracks, so its streamed partials never reach
|
|
2410
|
+
// here) and only the sanitised value -- never the raw input.
|
|
2411
|
+
if (sanitized !== null && sanitized !== undefined) {
|
|
2412
|
+
this.emit('tool_input_recorded', { toolUseId, input: sanitized })
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
return sanitized
|
|
2416
|
+
}
|
|
2417
|
+
|
|
2418
|
+
/**
|
|
2419
|
+
* #7346: read back the finalized tool input recorded via
|
|
2420
|
+
* `_recordToolInput`, if any. Returns `undefined` when nothing was
|
|
2421
|
+
* recorded — either the toolUseId isn't tracked at all (BYOK never
|
|
2422
|
+
* calls `_trackToolStart`, so this is always `undefined` there and
|
|
2423
|
+
* `tool_result` stays exactly as it was) or `_recordToolInput` was
|
|
2424
|
+
* never called for it (parse failure / overflow discard on the CLI
|
|
2425
|
+
* path). Already sanitized/capped — see `_recordToolInput`.
|
|
2426
|
+
*
|
|
2427
|
+
* @param {string} toolUseId
|
|
2428
|
+
* @returns {unknown}
|
|
2429
|
+
*/
|
|
2430
|
+
_getTrackedToolInput(toolUseId) {
|
|
2431
|
+
if (typeof toolUseId !== 'string' || toolUseId.length === 0) return undefined
|
|
2432
|
+
return this._inFlightToolStarts.get(toolUseId)?.input
|
|
2433
|
+
}
|
|
2434
|
+
|
|
1513
2435
|
/**
|
|
1514
2436
|
* #4628: sweep any tool_starts that never got their matching
|
|
1515
2437
|
* tool_result and emit synthetic tool_result events for each.
|
|
@@ -1524,24 +2446,69 @@ export class BaseSession extends EventEmitter {
|
|
|
1524
2446
|
* are diagnostic hints — the wire schema strips them on parse but
|
|
1525
2447
|
* they stay grep-able on disk in the persisted history.
|
|
1526
2448
|
*
|
|
2449
|
+
* #7376: when `reason` is a turn-TERMINATION reason (a permission-mode
|
|
2450
|
+
* switch, Stop, a crash, a watchdog — see `TURN_TERMINATION_REASONS`), the
|
|
2451
|
+
* tool did not fail, its turn was ended underneath it. The result then also
|
|
2452
|
+
* carries `terminatedReason` (the one diagnostic-adjacent field that IS on
|
|
2453
|
+
* the wire, `ServerToolResultSchema.terminatedReason`) and says so in its
|
|
2454
|
+
* text, so a client can render "cut off by the turn ending; check whether it took effect" instead of
|
|
2455
|
+
* the failure styling. Every other sweep reason (the natural turn end that
|
|
2456
|
+
* simply never saw a result) says only that the tool did not finish
|
|
2457
|
+
* (#8252) and carries no `terminatedReason`: those really are
|
|
2458
|
+
* indistinguishable from a failure.
|
|
2459
|
+
*
|
|
1527
2460
|
* @param {string} reason — short identifier for the sweep cause
|
|
1528
2461
|
* @returns {number} count of sweeps emitted
|
|
1529
2462
|
*/
|
|
1530
|
-
_sweepUnresolvedToolStarts(reason = 'stream_completed_without_result') {
|
|
2463
|
+
_sweepUnresolvedToolStarts(reason = 'stream_completed_without_result', exempt = null, { completion } = {}) {
|
|
1531
2464
|
if (this._inFlightToolStarts.size === 0) return 0
|
|
1532
|
-
|
|
1533
|
-
|
|
2465
|
+
// #7376: a Stop the provider acknowledged with a NORMAL result reaches here
|
|
2466
|
+
// with a generic reason, because the path that ended the turn did not know a
|
|
2467
|
+
// Stop had been requested. The turn-scoped flag does, and the tools still
|
|
2468
|
+
// unresolved were cut off by it.
|
|
2469
|
+
//
|
|
2470
|
+
// ONLY on a normal completion -- the caller says so with
|
|
2471
|
+
// `completion: 'normal'`, and nothing else is inferred. A failure cleanup
|
|
2472
|
+
// (a query that threw, a child that died, a destroy) has already observed
|
|
2473
|
+
// its own outcome, and a Stop that lands while it is still awaiting
|
|
2474
|
+
// something (the SDK's container classification) must not relabel that
|
|
2475
|
+
// outcome as the user's doing. An explicit termination reason is never
|
|
2476
|
+
// overridden either.
|
|
2477
|
+
if (completion === 'normal' && this._stopRequestedThisTurn && !isTurnTerminationReason(reason)) {
|
|
2478
|
+
reason = 'user_stop'
|
|
2479
|
+
}
|
|
2480
|
+
let count = 0
|
|
2481
|
+
for (const [toolUseId] of [...this._inFlightToolStarts]) {
|
|
2482
|
+
// #7340: a confirmed-backgrounded subagent that has not reported back is
|
|
2483
|
+
// NOT an orphan -- it is running. Synthesising an `isError` result for it
|
|
2484
|
+
// would report a failure that did not happen and terminate its activity
|
|
2485
|
+
// node. Its `tool_start` stays in flight, to be swept by whichever turn
|
|
2486
|
+
// end or death path finally does complete it.
|
|
2487
|
+
if (exempt && exempt.has(toolUseId)) continue
|
|
2488
|
+
count++
|
|
2489
|
+
this._inFlightToolStarts.delete(toolUseId)
|
|
2490
|
+
const terminated = isTurnTerminationReason(reason)
|
|
1534
2491
|
this.emit('tool_result', {
|
|
1535
2492
|
toolUseId,
|
|
1536
|
-
|
|
2493
|
+
// #8252: plain words only. The sweep reason is a slug and the fact that
|
|
2494
|
+
// the daemon fabricated this result is bookkeeping, so neither is in the
|
|
2495
|
+
// text a person reads. They stay on the in-process event as `reason` and
|
|
2496
|
+
// `synthetic` for listeners on the session; the wire
|
|
2497
|
+
// (`event-normalizer.js`) and the persisted history
|
|
2498
|
+
// (`session-message-history.js`) carry only `isError` and
|
|
2499
|
+
// `terminatedReason`, so a non-terminated sweep's slug does not leave the
|
|
2500
|
+
// process. The tool's name is already on the row.
|
|
2501
|
+
result: terminated
|
|
2502
|
+
? describeTurnTermination(reason).summary
|
|
2503
|
+
: UNFINISHED_TOOL_RESULT_TEXT,
|
|
1537
2504
|
truncated: false,
|
|
1538
2505
|
synthetic: true,
|
|
1539
2506
|
interrupted: true,
|
|
1540
2507
|
isError: true,
|
|
1541
2508
|
reason,
|
|
2509
|
+
...(terminated ? { terminatedReason: reason } : {}),
|
|
1542
2510
|
})
|
|
1543
2511
|
}
|
|
1544
|
-
this._inFlightToolStarts.clear()
|
|
1545
2512
|
return count
|
|
1546
2513
|
}
|
|
1547
2514
|
|
|
@@ -1556,9 +2523,12 @@ export class BaseSession extends EventEmitter {
|
|
|
1556
2523
|
*
|
|
1557
2524
|
* @param {object} payload — the result event payload ({cost, duration, usage, sessionId})
|
|
1558
2525
|
* @param {string} [sweepReason] — optional override for the sweep reason
|
|
2526
|
+
* @param {{ completion?: 'normal' }} [opts] — #7376: `completion: 'normal'`
|
|
2527
|
+
* says the turn ended with the provider's own `result`; see
|
|
2528
|
+
* `_sweepUnresolvedToolStarts` for what that permits.
|
|
1559
2529
|
*/
|
|
1560
|
-
_emitResult(payload, sweepReason = 'stream_completed_without_result') {
|
|
1561
|
-
this._sweepUnresolvedToolStarts(sweepReason)
|
|
2530
|
+
_emitResult(payload, sweepReason = 'stream_completed_without_result', opts = {}) {
|
|
2531
|
+
this._sweepUnresolvedToolStarts(sweepReason, null, opts)
|
|
1562
2532
|
// queueLength is stamped centrally in the emit() override below (#6627/#6706).
|
|
1563
2533
|
this.emit('result', payload)
|
|
1564
2534
|
}
|
|
@@ -1591,18 +2561,501 @@ export class BaseSession extends EventEmitter {
|
|
|
1591
2561
|
* @returns {boolean} whether the event had listeners (EventEmitter contract)
|
|
1592
2562
|
*/
|
|
1593
2563
|
emit(event, ...args) {
|
|
2564
|
+
if (PROVIDER_ACTIVITY_EVENT_SET.has(event)) this.noteProviderActivity()
|
|
2565
|
+
if (eventCountsAsTurnOutput(event, args[0])) this._turnOutputSeen = true
|
|
2566
|
+
if (event === 'stopped') {
|
|
2567
|
+
// #8461: this Stop was already confirmed in place of the chip; not twice.
|
|
2568
|
+
if (this._stopAckedByResult) {
|
|
2569
|
+
this._stopAckedByResult = false
|
|
2570
|
+
return false
|
|
2571
|
+
}
|
|
2572
|
+
// #9241: a Stop that ends the turn with no `result` (SDK abort, claude-cli child
|
|
2573
|
+
// exit, ACP, jsonl subprocess) leaves nothing in history. When the provider says
|
|
2574
|
+
// this `stopped` IS the requested stop (`stopRequested`, set on its stop path
|
|
2575
|
+
// only: not on a watchdog, a timeout or an error that was converted to
|
|
2576
|
+
// `stopped`), mint the marker first, so the client idles on it and `stopped`
|
|
2577
|
+
// follows.
|
|
2578
|
+
// Read through a local alias on purpose: the features-gate scanner
|
|
2579
|
+
// (config-supported-keys-docs.test.js) flags `X[0].stopRequested === true` as a
|
|
2580
|
+
// gate shape, a false positive for this internal signal.
|
|
2581
|
+
const stoppedPayload = args[0]
|
|
2582
|
+
const explicit = !!stoppedPayload && typeof stoppedPayload === 'object' && stoppedPayload.stopRequested === true
|
|
2583
|
+
if (stoppedPayload && typeof stoppedPayload === 'object' && 'stopRequested' in stoppedPayload) {
|
|
2584
|
+
const { stopRequested: _signal, ...rest } = stoppedPayload
|
|
2585
|
+
args[0] = rest // internal: never on the wire
|
|
2586
|
+
}
|
|
2587
|
+
if (explicit && this._shouldMintStopBeforeReply()) this._emitStopBeforeReplyResult()
|
|
2588
|
+
this._stoppedSinceStopRequest = true
|
|
2589
|
+
}
|
|
2590
|
+
let ackStop = false
|
|
1594
2591
|
if (event === 'result') {
|
|
1595
2592
|
let payload = args[0]
|
|
1596
2593
|
if (payload && typeof payload === 'object' && payload.queueLength === undefined) {
|
|
1597
2594
|
payload = { ...payload, queueLength: this._outgoingQueue ? this._outgoingQueue.length : 0 }
|
|
1598
2595
|
}
|
|
1599
2596
|
payload = normalizeResultDuration(payload)
|
|
2597
|
+
// #7326: the wire carries a closed vocabulary. Anything else a provider
|
|
2598
|
+
// puts on `turnOutcome` is dropped here rather than left to fail the
|
|
2599
|
+
// client's parse of the whole `result` frame.
|
|
2600
|
+
if (payload && typeof payload === 'object' && payload.turnOutcome !== undefined && !isTurnOutcome(payload.turnOutcome)) {
|
|
2601
|
+
const { turnOutcome: _dropped, ...rest } = payload
|
|
2602
|
+
payload = rest
|
|
2603
|
+
}
|
|
2604
|
+
// #8461: a requested Stop (the user's, or the scheduler's / orchestration
|
|
2605
|
+
// watchdog's, which also call `interrupt()`) is acknowledged by
|
|
2606
|
+
// `session_stopped` on every provider whose `interrupt()` ends the turn with
|
|
2607
|
+
// a `stopped` event (ACP, Codex, Gemini, ...). claude-sdk and claude-cli can
|
|
2608
|
+
// instead answer it with a NORMAL `result` carrying `terminal_reason:
|
|
2609
|
+
// aborted_*`, which maps to `stopped`; and then the SDK's catch branch (the
|
|
2610
|
+
// `stopped` emit) never runs. Left alone, only those two providers would
|
|
2611
|
+
// show a "Stopped" chip for a Stop that was asked for. The chip is for a turn
|
|
2612
|
+
// that ended UNDER the caller, so it is dropped and the quiet `stopped`
|
|
2613
|
+
// confirmation is sent in its place (once per Stop request, see
|
|
2614
|
+
// `_stoppedSinceStopRequest`). An agent that cancelled on its own (ACP
|
|
2615
|
+
// `cancelled`) keeps its chip.
|
|
2616
|
+
this._stopAckedByResult = false
|
|
2617
|
+
// #7072: a result whose outcome is `stopped` is terminal but NOT a success,
|
|
2618
|
+
// and an orchestration TurnDriver hears nothing else for the turn -- the
|
|
2619
|
+
// `stopped` that follows it (acknowledgement below, or a provider's own) lands
|
|
2620
|
+
// after the driver has already settled. Mark it here, before the chip is
|
|
2621
|
+
// dropped for a requested Stop, so every provider that maps an abort onto a
|
|
2622
|
+
// result gets it. Internal only: event-normalizer whitelists the wire fields.
|
|
2623
|
+
if (payload && typeof payload === 'object' && payload.turnOutcome === 'stopped' && payload.interrupted !== true) {
|
|
2624
|
+
payload = { ...payload, interrupted: true }
|
|
2625
|
+
}
|
|
2626
|
+
if (payload && typeof payload === 'object' && payload.turnOutcome === 'stopped' && this._stopRequestedThisTurn) {
|
|
2627
|
+
const { turnOutcome: _userStop, ...rest } = payload
|
|
2628
|
+
payload = rest
|
|
2629
|
+
ackStop = !this._stoppedSinceStopRequest
|
|
2630
|
+
// #9241: the chip is dropped for a Stop that was asked for, but a Stop
|
|
2631
|
+
// before any output gets the quiet marker in its place, and ONLY when the
|
|
2632
|
+
// provider says by `stopRequested` that this result IS the Stop's end (a
|
|
2633
|
+
// BYOK upstream error that raced the abort also arrives as `stopped`).
|
|
2634
|
+
if (payload.stopRequested === true && this._shouldMintStopBeforeReply()) {
|
|
2635
|
+
payload = { ...payload, turnOutcome: 'stopped_before_output' }
|
|
2636
|
+
}
|
|
2637
|
+
} else if (payload && typeof payload === 'object' && payload.stopRequested === true
|
|
2638
|
+
&& payload.turnOutcome === undefined && this._shouldMintStopBeforeReply()) {
|
|
2639
|
+
// claude-cli's synthetic result for a Stop (child exit / 5 s safety timer): it
|
|
2640
|
+
// clears message state first and carries `interrupted` with no outcome, and
|
|
2641
|
+
// says by `stopRequested` that the Stop is why (its stall watchdogs use the
|
|
2642
|
+
// same shape and do not).
|
|
2643
|
+
payload = { ...payload, turnOutcome: 'stopped_before_output' }
|
|
2644
|
+
}
|
|
2645
|
+
if (payload && typeof payload === 'object' && 'stopRequested' in payload) {
|
|
2646
|
+
const { stopRequested: _signal, ...rest } = payload
|
|
2647
|
+
payload = rest // internal: never on the wire
|
|
2648
|
+
}
|
|
2649
|
+
if (payload && typeof payload === 'object' && payload.turnOutcome === 'stopped_before_output') {
|
|
2650
|
+
this._stopMarkerEmitted = true
|
|
2651
|
+
}
|
|
2652
|
+
// #9241: the turn's terminal `result` settles the marker, minted or not, so a
|
|
2653
|
+
// `stopped` that follows it never mints a second one.
|
|
2654
|
+
if (this._stopMarkerArmed) this._stopMarkerMinted = true
|
|
2655
|
+
// #7326: a marked outcome (anything but `completed`) becomes a chip in the
|
|
2656
|
+
// transcript, and the chip needs an identity that the live `result` frame
|
|
2657
|
+
// and the history entry replayed later AGREE on -- a `result` has no id, and
|
|
2658
|
+
// without one a reconnect that replays the turn the client already watched
|
|
2659
|
+
// would add a second chip. The timestamp is stamped ONCE, here, and both
|
|
2660
|
+
// the event normalizer and the history ring read it off this payload.
|
|
2661
|
+
if (payload && typeof payload === 'object' && isTurnOutcome(payload.turnOutcome) && payload.turnOutcome !== 'completed'
|
|
2662
|
+
&& typeof payload.timestamp !== 'number') {
|
|
2663
|
+
payload = { ...payload, timestamp: Date.now() }
|
|
2664
|
+
}
|
|
1600
2665
|
if (payload !== args[0]) args[0] = payload
|
|
1601
2666
|
}
|
|
1602
|
-
|
|
2667
|
+
const delivered = super.emit(event, ...args)
|
|
2668
|
+
if (ackStop) {
|
|
2669
|
+
this._stoppedSinceStopRequest = true
|
|
2670
|
+
this._stopAckedByResult = true
|
|
2671
|
+
super.emit('stopped', {})
|
|
2672
|
+
}
|
|
2673
|
+
return delivered
|
|
1603
2674
|
}
|
|
1604
2675
|
|
|
1605
|
-
|
|
2676
|
+
/**
|
|
2677
|
+
* #9241: emit the stop-before-reply marker as the turn's own `result`. Not billed
|
|
2678
|
+
* (`cost: null`), and internal-only `interrupted` as on every synthetic terminal
|
|
2679
|
+
* result (#7072). Goes through emit() so it is stamped, normalised, recorded in
|
|
2680
|
+
* history and idles the client like any other result.
|
|
2681
|
+
*/
|
|
2682
|
+
_emitStopBeforeReplyResult() {
|
|
2683
|
+
this.emit('result', {
|
|
2684
|
+
cost: null, duration: null, usage: null, sessionId: this._sessionId,
|
|
2685
|
+
turnOutcome: 'stopped_before_output', interrupted: true,
|
|
2686
|
+
})
|
|
2687
|
+
}
|
|
2688
|
+
|
|
2689
|
+
/**
|
|
2690
|
+
* How many permission requests are waiting on a human for this session,
|
|
2691
|
+
* across both routes: the hook-routed ids (CLI / TUI, #2831) and the
|
|
2692
|
+
* in-process PermissionManager's map that `wirePermissionManager` installs
|
|
2693
|
+
* as `_pendingPermissions` (SDK / BYOK / Codex).
|
|
2694
|
+
*
|
|
2695
|
+
* A read-only count for callers outside the session — the idle-only
|
|
2696
|
+
* auto-deploy probe (#8324) — so they never reach into either private field.
|
|
2697
|
+
*
|
|
2698
|
+
* @returns {number}
|
|
2699
|
+
*/
|
|
2700
|
+
getPendingPermissionCount() {
|
|
2701
|
+
const inProcess = this._pendingPermissions instanceof Map ? this._pendingPermissions.size : 0
|
|
2702
|
+
return this._pendingPermissionIds.size + inProcess
|
|
2703
|
+
}
|
|
2704
|
+
|
|
2705
|
+
/**
|
|
2706
|
+
* #8743: record that the provider just produced output. The emit() override
|
|
2707
|
+
* calls it for every PROVIDER_ACTIVITY_EVENTS event; a provider calls it
|
|
2708
|
+
* directly for input that maps to no event (a Codex sub-agent's notifications,
|
|
2709
|
+
* or a straggler from a turn codex already ended), which is exactly the
|
|
2710
|
+
* activity the turn bookkeeping cannot see.
|
|
2711
|
+
*/
|
|
2712
|
+
noteProviderActivity() {
|
|
2713
|
+
this._providerActivityAtMs = this._providerActivityClock()
|
|
2714
|
+
}
|
|
2715
|
+
|
|
2716
|
+
/**
|
|
2717
|
+
* #8743: the clock `noteProviderActivity` stamps with. Monotonic, so a wall
|
|
2718
|
+
* clock step cannot make recent activity look old. A test replaces it on the
|
|
2719
|
+
* instance to move time.
|
|
2720
|
+
* @returns {number}
|
|
2721
|
+
*/
|
|
2722
|
+
_providerActivityClock() {
|
|
2723
|
+
return Math.trunc(performance.now())
|
|
2724
|
+
}
|
|
2725
|
+
|
|
2726
|
+
/**
|
|
2727
|
+
* #8743: how long ago the provider last produced output, in ms, or null when
|
|
2728
|
+
* it has not since this session object was created. The idle-only auto-deploy
|
|
2729
|
+
* holds off a restart while this is recent (daemon-idle-state.js).
|
|
2730
|
+
* @returns {number|null}
|
|
2731
|
+
*/
|
|
2732
|
+
get providerActivityAgeMs() {
|
|
2733
|
+
if (this._providerActivityAtMs === null) return null
|
|
2734
|
+
return Math.max(0, this._providerActivityClock() - this._providerActivityAtMs)
|
|
2735
|
+
}
|
|
2736
|
+
|
|
2737
|
+
/**
|
|
2738
|
+
* Work a daemon restart would lose that `isBusy` does not report (#8324).
|
|
2739
|
+
*
|
|
2740
|
+
* `isBusy` is "a turn is running or a background shell is tracked". A restart
|
|
2741
|
+
* can also cut off a background agent that outlived its turn (`_activeAgents`
|
|
2742
|
+
* keeps it after `_clearMessageState({ turnEndedCleanly: true })`) and input
|
|
2743
|
+
* the session has accepted but not yet dispatched (`_outgoingQueue`, which
|
|
2744
|
+
* every provider shares for mid-turn sends). Subclasses with a queue or an
|
|
2745
|
+
* input path of their own extend this list; they call `super` first.
|
|
2746
|
+
*
|
|
2747
|
+
* Fail-closed contract for callers: an empty array means nothing blocks a
|
|
2748
|
+
* restart, so an override must never return `[]` merely because it could not
|
|
2749
|
+
* check — throw instead.
|
|
2750
|
+
*
|
|
2751
|
+
* @returns {string[]} human-readable reasons; empty = nothing blocks a restart
|
|
2752
|
+
*/
|
|
2753
|
+
getRestartBlockers() {
|
|
2754
|
+
const reasons = []
|
|
2755
|
+
const agents = this._activeAgents.size
|
|
2756
|
+
if (agents > 0) reasons.push(`${agents} active background agent(s)`)
|
|
2757
|
+
const queued = this._outgoingQueue.length
|
|
2758
|
+
if (queued > 0) reasons.push(`${queued} queued message(s) not yet dispatched`)
|
|
2759
|
+
return reasons
|
|
2760
|
+
}
|
|
2761
|
+
|
|
2762
|
+
/**
|
|
2763
|
+
* A hook-routed permission request belonging to this session is outstanding.
|
|
2764
|
+
* Called by ws-permissions when the hook's POST /permission is parked (#2831).
|
|
2765
|
+
*/
|
|
2766
|
+
notifyPermissionPending(requestId) {
|
|
2767
|
+
if (!requestId || this._pendingPermissionIds.has(requestId)) return
|
|
2768
|
+
this._pendingPermissionIds.add(requestId)
|
|
2769
|
+
// #9241: a prompt the model raised is output, and a hook-routed one never passes
|
|
2770
|
+
// through emit(): latch it here, so one answered before the Stop still counts.
|
|
2771
|
+
this._turnOutputSeen = true
|
|
2772
|
+
if (this._pendingPermissionIds.size === 1) this._onFirstPermissionPending()
|
|
2773
|
+
}
|
|
2774
|
+
|
|
2775
|
+
/**
|
|
2776
|
+
* A hook-routed permission resolved (allow / deny / expired). Called by
|
|
2777
|
+
* ws-permissions' shared cleanup on every resolution path.
|
|
2778
|
+
*/
|
|
2779
|
+
notifyPermissionResolved(requestId) {
|
|
2780
|
+
if (!requestId || !this._pendingPermissionIds.has(requestId)) return
|
|
2781
|
+
this._pendingPermissionIds.delete(requestId)
|
|
2782
|
+
if (this._pendingPermissionIds.size === 0) this._onLastPermissionResolved()
|
|
2783
|
+
}
|
|
2784
|
+
|
|
2785
|
+
/**
|
|
2786
|
+
* Emit `permission_expired` for every prompt this session is still blocked on,
|
|
2787
|
+
* then drop the bookkeeping (#2831, #7375, generalised in #7382).
|
|
2788
|
+
*
|
|
2789
|
+
* A prompt outlives its turn on BOTH sides and neither says so: the client
|
|
2790
|
+
* card stays live until its own expiry, and the daemon's HTTP entry is not
|
|
2791
|
+
* released by the child dying, because killing the child does not signal the
|
|
2792
|
+
* hook's `curl` grandchild. Emitting here drives both — the clients retire the
|
|
2793
|
+
* card, and #7381's `release_permission` after-effect releases the daemon
|
|
2794
|
+
* entry so a reconnect cannot resurrect it.
|
|
2795
|
+
*
|
|
2796
|
+
* Call it from the provider's turn-end FUNNEL, not from hand-enumerated death
|
|
2797
|
+
* sites. Enumerating by hand is what missed the plain `result` path and the
|
|
2798
|
+
* interrupt-safety timeout in #7375.
|
|
2799
|
+
*
|
|
2800
|
+
* @param {string} message Reason forwarded on the wire (clients log it; the
|
|
2801
|
+
* user-visible copy is fixed client-side). Falsy or empty is coerced to a
|
|
2802
|
+
* generic reason — the wire schema declares `message: z.string()`, so an
|
|
2803
|
+
* empty one would fail validation at the client.
|
|
2804
|
+
*/
|
|
2805
|
+
_expirePendingPermissions(message) {
|
|
2806
|
+
if (this._pendingPermissionIds.size === 0) return
|
|
2807
|
+
// The doc below used to say `message` must be non-empty "because the wire
|
|
2808
|
+
// schema requires it" and then not enforce it — a comment describing a
|
|
2809
|
+
// stronger guarantee than the code delivers, which is the defect class this
|
|
2810
|
+
// whole change belongs to. ServerPermissionExpiredSchema declares
|
|
2811
|
+
// `message: z.string()`, so a caller passing '' or undefined would emit a
|
|
2812
|
+
// frame that fails validation at the client. Default rather than throw: the
|
|
2813
|
+
// callers are turn-teardown paths, and taking a session down over a missing
|
|
2814
|
+
// log string would be a worse failure than a generic one.
|
|
2815
|
+
const reason = typeof message === 'string' && message.length > 0
|
|
2816
|
+
? message
|
|
2817
|
+
: 'Permission request expired (the turn it belonged to ended)'
|
|
2818
|
+
for (const requestId of this._pendingPermissionIds) {
|
|
2819
|
+
this.emit('permission_expired', { requestId, message: reason })
|
|
2820
|
+
}
|
|
2821
|
+
this._pendingPermissionIds.clear()
|
|
2822
|
+
this._onPendingPermissionsAbandoned()
|
|
2823
|
+
}
|
|
2824
|
+
|
|
2825
|
+
/**
|
|
2826
|
+
* Timer hooks for the pending-permission lifecycle. No-ops by default: the
|
|
2827
|
+
* bookkeeping above is provider-agnostic, but "don't time out while the user
|
|
2828
|
+
* is being asked" is not — CliSession pauses its inactivity trio, while
|
|
2829
|
+
* ClaudeTuiSession suspends only its silence backstops (for these prompts
|
|
2830
|
+
* and, through its own mechanism, for a pending AskUserQuestion) and
|
|
2831
|
+
* deliberately keeps its hard cap armed.
|
|
2832
|
+
*
|
|
2833
|
+
* Kept as THREE hooks rather than one because the abandon path must NOT
|
|
2834
|
+
* re-arm: the turn it belonged to is over. Collapsing them re-creates the
|
|
2835
|
+
* #7375 regression where a cleared pause left the safety timers wedged.
|
|
2836
|
+
*/
|
|
2837
|
+
_onFirstPermissionPending() {}
|
|
2838
|
+
_onLastPermissionResolved() {}
|
|
2839
|
+
_onPendingPermissionsAbandoned() {}
|
|
2840
|
+
|
|
2841
|
+
/**
|
|
2842
|
+
* #7340: finalize a tracked subagent by its `tool_use_id` -- the ONE
|
|
2843
|
+
* implementation of "this agent is done". Drops it from `_activeAgents` and
|
|
2844
|
+
* balances its `agent_spawned` with a matching `agent_completed`.
|
|
2845
|
+
*
|
|
2846
|
+
* Idempotent (guarded on `has`), which is what lets an optimistic finalize
|
|
2847
|
+
* and the provider's natural terminal signal both call it without emitting a
|
|
2848
|
+
* duplicate completion.
|
|
2849
|
+
*
|
|
2850
|
+
* This matters more since backgrounded agents stopped being swept at turn
|
|
2851
|
+
* end: the sweep used to be a backstop that eventually cleared everything, so
|
|
2852
|
+
* a missed finalize was invisible. It is now the ONLY way a backgrounded
|
|
2853
|
+
* agent clears, and a provider that tracks a background spawn without wiring
|
|
2854
|
+
* a terminal signal leaves the session claiming to be working forever.
|
|
2855
|
+
*
|
|
2856
|
+
* @param {unknown} toolUseId
|
|
2857
|
+
* @param {{ reason?: string }} [opts]
|
|
2858
|
+
* @protected
|
|
2859
|
+
*/
|
|
2860
|
+
_completeAgent(toolUseId, { reason } = {}) {
|
|
2861
|
+
if (typeof toolUseId !== 'string' || !toolUseId) return
|
|
2862
|
+
if (!this._activeAgents.has(toolUseId)) return
|
|
2863
|
+
this._activeAgents.delete(toolUseId)
|
|
2864
|
+
// #7396: `reason` is present only when the session ENDED the agent itself
|
|
2865
|
+
// (a watchdog gave up waiting for the provider's signal) rather than the
|
|
2866
|
+
// provider reporting it finished. In-process only: the wire message is built
|
|
2867
|
+
// field by field in event-normalizer and carries just the id.
|
|
2868
|
+
this.emit('agent_completed', reason ? { toolUseId, reason } : { toolUseId })
|
|
2869
|
+
}
|
|
2870
|
+
|
|
2871
|
+
/**
|
|
2872
|
+
* #7340: complete tracked subagents in bulk and report which ones survived.
|
|
2873
|
+
*
|
|
2874
|
+
* The ONE implementation of "drain the agent map", shared by the turn-end
|
|
2875
|
+
* sweep and by the provider-death sites that cannot reach that sweep. Emits a
|
|
2876
|
+
* balancing `agent_completed` for every agent it drops, so a client's badge
|
|
2877
|
+
* clears whichever route got here.
|
|
2878
|
+
*
|
|
2879
|
+
* `exempt` is the set of ids to spare, computed ONCE by `_clearMessageState`
|
|
2880
|
+
* and shared with the orphan sweep so the two cannot disagree about what is
|
|
2881
|
+
* still running. Default empty -- a bare call is a total drain, which is what
|
|
2882
|
+
* every death path wants.
|
|
2883
|
+
*
|
|
2884
|
+
* Keyed by the MAP KEY, not `agent.toolUseId`: a record whose field has
|
|
2885
|
+
* drifted from its key would otherwise leak and complete the wrong id.
|
|
2886
|
+
*
|
|
2887
|
+
* Every agent it completes emits `agent_completed`, which the registry turns
|
|
2888
|
+
* into a node termination AND a clearing of that agent's outlives-turn mark
|
|
2889
|
+
* -- which is what lets `ActivityRegistry.reset()` simply read the marks
|
|
2890
|
+
* afterwards instead of being handed a second copy of this predicate.
|
|
2891
|
+
*
|
|
2892
|
+
* @param {{ exempt?: Set<string> }} [opts]
|
|
2893
|
+
* @protected
|
|
2894
|
+
*/
|
|
2895
|
+
_completeAgents({ exempt = null } = {}) {
|
|
2896
|
+
for (const toolUseId of [...this._activeAgents.keys()]) {
|
|
2897
|
+
if (exempt && exempt.has(toolUseId)) continue
|
|
2898
|
+
this._activeAgents.delete(toolUseId)
|
|
2899
|
+
this.emit('agent_completed', { toolUseId })
|
|
2900
|
+
}
|
|
2901
|
+
}
|
|
2902
|
+
|
|
2903
|
+
/**
|
|
2904
|
+
* #7340: record a spawned subagent and announce it. Shared by every provider
|
|
2905
|
+
* that reads the Agent/Task tool off a Claude Code stream, so the record
|
|
2906
|
+
* shape (notably `backgroundConfirmed`, which decides whether the turn-end
|
|
2907
|
+
* sweep may complete it) cannot drift between them.
|
|
2908
|
+
*
|
|
2909
|
+
* Re-registering an already-tracked id UPGRADES the record rather than
|
|
2910
|
+
* replacing it, and re-emits nothing. That is the `task_started` case: the
|
|
2911
|
+
* tool_use block arrives first and carries `run_in_background`, then
|
|
2912
|
+
* `task_started` arrives with `is_backgrounded`. Whichever order they land
|
|
2913
|
+
* in, exactly one `agent_spawned` is emitted.
|
|
2914
|
+
*
|
|
2915
|
+
* TWO fields, because the two producers do not carry the same authority and
|
|
2916
|
+
* collapsing them is what would strand an agent:
|
|
2917
|
+
*
|
|
2918
|
+
* - `background` -- best-known value. The tool input's `run_in_background`
|
|
2919
|
+
* is the model's REQUEST; `task_started`'s `is_backgrounded` is what the
|
|
2920
|
+
* provider actually did. (`is_backgrounded` is ABSENT on a foreground
|
|
2921
|
+
* spawn, not `false`, so every producer compares with a strict `=== true`
|
|
2922
|
+
* -- that derivation is what the parser tests pin.)
|
|
2923
|
+
* - `backgroundConfirmed` -- set ONLY from `task_started` (`authoritative:
|
|
2924
|
+
* true`). This, not `background`, is what exempts an agent from the
|
|
2925
|
+
* turn-end sweep, and the reason is a liveness one rather than a
|
|
2926
|
+
* correctness one: `task_notification` is the ONLY signal that clears a
|
|
2927
|
+
* backgrounded agent, and a provider build that emits no task lifecycle
|
|
2928
|
+
* messages at all emits neither. `task_started` having arrived is
|
|
2929
|
+
* therefore the evidence that a terminal signal CAN arrive. Exempting on
|
|
2930
|
+
* the model's unconfirmed request would pin such a session as "working"
|
|
2931
|
+
* until the provider dies -- which #7340 names as the worse failure.
|
|
2932
|
+
* (`cancelActivity` already feature-detects those builds the same way.)
|
|
2933
|
+
*
|
|
2934
|
+
* The upgrade is asymmetric for the same reason. A non-authoritative signal
|
|
2935
|
+
* may only raise `background` (`false` never overwrites `true`), because the
|
|
2936
|
+
* two producers can land in either order and the tool input carries no news
|
|
2937
|
+
* when it disagrees. An authoritative one OVERWRITES in both directions --
|
|
2938
|
+
* `task_started` is the provider's own account and must be able to correct
|
|
2939
|
+
* the model's request DOWNWARD, or an agent the model asked to background
|
|
2940
|
+
* and the provider ran in the foreground is exempted from the sweep it needs.
|
|
2941
|
+
*
|
|
2942
|
+
* @param {{ toolUseId: string, description?: string, background?: boolean, authoritative?: boolean, startedAt?: number }} info
|
|
2943
|
+
* @protected
|
|
2944
|
+
*/
|
|
2945
|
+
_trackAgent({ toolUseId, description = 'Background task', background = false, authoritative = false, startedAt = Date.now() } = {}) {
|
|
2946
|
+
if (typeof toolUseId !== 'string' || !toolUseId) return
|
|
2947
|
+
const existing = this._activeAgents.get(toolUseId)
|
|
2948
|
+
if (existing) {
|
|
2949
|
+
if (authoritative === true) {
|
|
2950
|
+
existing.background = background === true
|
|
2951
|
+
existing.backgroundConfirmed = background === true
|
|
2952
|
+
// #7340: the registry is TOLD, never left to re-derive. This is the
|
|
2953
|
+
// upgrade path -- `task_started` landing after the tool_use block --
|
|
2954
|
+
// and it emits no event, so without this call the activity node would
|
|
2955
|
+
// never learn that it outlives its turn.
|
|
2956
|
+
this._activity.setAgentOutlivesTurn(toolUseId, existing.backgroundConfirmed)
|
|
2957
|
+
} else if (background === true) {
|
|
2958
|
+
existing.background = true
|
|
2959
|
+
}
|
|
2960
|
+
return
|
|
2961
|
+
}
|
|
2962
|
+
// Clamp HERE, not in each caller. `task_started`'s `description` is
|
|
2963
|
+
// provider-supplied and reaches the wire verbatim via `agent_spawned`;
|
|
2964
|
+
// only the tool-input path was clamped before, so the second producer
|
|
2965
|
+
// #7340 added would have shipped an unbounded field (the wire schema
|
|
2966
|
+
// declares `description: z.string().optional()` with no max, so nothing
|
|
2967
|
+
// downstream would have caught it either).
|
|
2968
|
+
const agentInfo = {
|
|
2969
|
+
toolUseId,
|
|
2970
|
+
description: String(description).slice(0, AGENT_DESCRIPTION_MAX),
|
|
2971
|
+
startedAt,
|
|
2972
|
+
background: background === true,
|
|
2973
|
+
backgroundConfirmed: authoritative === true && background === true,
|
|
2974
|
+
}
|
|
2975
|
+
this._activeAgents.set(toolUseId, agentInfo)
|
|
2976
|
+
this.emit('agent_spawned', agentInfo)
|
|
2977
|
+
// #7340: after the spawn, so the node exists to be marked. The other
|
|
2978
|
+
// arrival order (`task_started` first) is handled by the upgrade above.
|
|
2979
|
+
if (agentInfo.backgroundConfirmed) this._activity.setAgentOutlivesTurn(toolUseId, true)
|
|
2980
|
+
}
|
|
2981
|
+
|
|
2982
|
+
/**
|
|
2983
|
+
* #7340 / #7396: the subagents that outlive a turn end -- `null` (nothing
|
|
2984
|
+
* survives, a total drain) unless the provider itself reported the turn over.
|
|
2985
|
+
*
|
|
2986
|
+
* The ONE implementation of the survival predicate, shared by
|
|
2987
|
+
* `_clearMessageState` and by providers whose turn end does not run through it
|
|
2988
|
+
* (claude-tui's Stop-hook path). A second copy of "backgroundConfirmed and the
|
|
2989
|
+
* turn ended cleanly" is how two providers come to disagree about what
|
|
2990
|
+
* "survives" means. Opt-IN for the same reason `_clearMessageState`'s
|
|
2991
|
+
* `turnEndedCleanly` is: a caller that forgets to pass it gets the sweep.
|
|
2992
|
+
*
|
|
2993
|
+
* @param {boolean} turnEndedCleanly
|
|
2994
|
+
* @returns {Set<string> | null}
|
|
2995
|
+
* @protected
|
|
2996
|
+
*/
|
|
2997
|
+
_survivingAgentIds(turnEndedCleanly) {
|
|
2998
|
+
if (turnEndedCleanly !== true) return null
|
|
2999
|
+
return new Set(
|
|
3000
|
+
[...this._activeAgents]
|
|
3001
|
+
.filter(([, agent]) => agent?.backgroundConfirmed === true)
|
|
3002
|
+
.map(([toolUseId]) => toolUseId),
|
|
3003
|
+
)
|
|
3004
|
+
}
|
|
3005
|
+
|
|
3006
|
+
/**
|
|
3007
|
+
* Clear per-message state at the end of a turn.
|
|
3008
|
+
*
|
|
3009
|
+
* @param {{ turnEndedCleanly?: boolean }} [opts]
|
|
3010
|
+
* `turnEndedCleanly` says the PROVIDER IS STILL ALIVE and reported the turn
|
|
3011
|
+
* over itself -- the stream-json `result` message, and nothing else. It is
|
|
3012
|
+
* the only thing that permits a confirmed-backgrounded subagent to survive
|
|
3013
|
+
* the sweep below (#7340).
|
|
3014
|
+
*
|
|
3015
|
+
* It is opt-IN, and that direction is the whole safety argument. Fourteen
|
|
3016
|
+
* call sites reach this method and all but two are a provider that DIED --
|
|
3017
|
+
* Stop/SIGINT, a child crash, `_killAndRespawn`, the SDK hard timeout,
|
|
3018
|
+
* stream-stall recovery, `interrupt()`, `destroy()`, a failed stdin write.
|
|
3019
|
+
* `task_notification` can never arrive on any of them, so an agent exempted
|
|
3020
|
+
* there is stranded and the session claims to be working for the rest of
|
|
3021
|
+
* the daemon's life. Defaulting to the sweep means a call site nobody
|
|
3022
|
+
* updated -- including a death path added years from now -- inherits the
|
|
3023
|
+
* RECOVERABLE failure (a badge cleared early) rather than the unrecoverable
|
|
3024
|
+
* one. #7340 names stuck-busy as the worse of the two, and it is.
|
|
3025
|
+
*
|
|
3026
|
+
* Subclasses that override this MUST forward the opts to `super`. One that
|
|
3027
|
+
* drops them fails safe (it sweeps), which is why the forwarding is a
|
|
3028
|
+
* correctness nicety here rather than a hazard.
|
|
3029
|
+
*
|
|
3030
|
+
* @param {{ turnEndedCleanly?: boolean, terminatedReason?: string, completion?: 'normal' }} [opts]
|
|
3031
|
+
* `completion: 'normal'` (#7376) says the turn ended with the provider's own
|
|
3032
|
+
* `result`. Only then may a Stop requested during the turn tag the tools it
|
|
3033
|
+
* left unresolved as `user_stop`: every other caller is a failure or teardown
|
|
3034
|
+
* path that has already observed its own outcome, and keeps it.
|
|
3035
|
+
*
|
|
3036
|
+
* `terminatedReason` (#7376) is WHY the turn is being ended underneath
|
|
3037
|
+
* whatever tool is still in flight -- a `TURN_TERMINATION_REASONS` value
|
|
3038
|
+
* (`permission_mode_switch`, `user_stop`, `process_exit`, ...). It becomes
|
|
3039
|
+
* the orphan sweep's reason, so the synthetic `tool_result` of each such
|
|
3040
|
+
* tool says "the turn was terminated" rather than looking like a failed
|
|
3041
|
+
* command. The CALLER supplies it, never this method: it is shared by every
|
|
3042
|
+
* death path (and Stop, where the user already knows why), so inferring it
|
|
3043
|
+
* here would mislabel. Omitted on the paths that have no considered cause --
|
|
3044
|
+
* those keep the generic `message_state_cleared` sweep.
|
|
3045
|
+
*/
|
|
3046
|
+
_clearMessageState({ turnEndedCleanly = false, terminatedReason, completion } = {}) {
|
|
3047
|
+
// #7382 (review): expire HERE, so inheriting the bookkeeping also inherits
|
|
3048
|
+
// the BEHAVIOUR. Hoisting the API alone bought a new provider the methods
|
|
3049
|
+
// and none of the wiring — and the roster guard, which only checked that
|
|
3050
|
+
// the methods existed, passed for a provider that never called them. A
|
|
3051
|
+
// check that passes for everything is #7273's shape.
|
|
3052
|
+
//
|
|
3053
|
+
// Idempotent (no-op on an empty set), so providers that already expired at
|
|
3054
|
+
// an earlier point in their teardown are unaffected.
|
|
3055
|
+
this._expirePendingPermissions('Permission request expired (the turn it belonged to ended before it was answered)')
|
|
3056
|
+
// #8430: a user Stop belongs to the turn it was pressed on. Every turn end,
|
|
3057
|
+
// abort and failure included, reaches here, so the next turn starts clear.
|
|
3058
|
+
this._permissions?.clearUserStopInFlight?.()
|
|
1606
3059
|
this._isBusy = false
|
|
1607
3060
|
this._currentMessageId = null
|
|
1608
3061
|
|
|
@@ -1623,15 +3076,34 @@ export class BaseSession extends EventEmitter {
|
|
|
1623
3076
|
// with a synthetic tool_result rather than silently dropped — so
|
|
1624
3077
|
// the dashboard's activeTools clears whether result fires next or
|
|
1625
3078
|
// never fires at all.
|
|
1626
|
-
this
|
|
1627
|
-
|
|
1628
|
-
//
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
3079
|
+
// #7340: the ids that will outlive this turn, computed ONCE and shared by
|
|
3080
|
+
// all three sweeps below so they cannot disagree. Empty on every
|
|
3081
|
+
// provider-death path, which is what makes those a total drain.
|
|
3082
|
+
//
|
|
3083
|
+
// Computed BEFORE the orphan sweep, and that ordering is load-bearing: the
|
|
3084
|
+
// sweep fabricates a `tool_result` with `isError: true` for every
|
|
3085
|
+
// unresolved `tool_start`, and a backgrounded subagent that has not
|
|
3086
|
+
// reported back yet looks exactly like an orphan. Sweeping it told the
|
|
3087
|
+
// client the subagent had failed -- while it was running fine -- and ended
|
|
3088
|
+
// its activity node on the way past.
|
|
3089
|
+
const survivingAgents = this._survivingAgentIds(turnEndedCleanly)
|
|
3090
|
+
|
|
3091
|
+
this._sweepUnresolvedToolStarts(
|
|
3092
|
+
isTurnTerminationReason(terminatedReason) ? terminatedReason : 'message_state_cleared',
|
|
3093
|
+
survivingAgents,
|
|
3094
|
+
{ completion },
|
|
3095
|
+
)
|
|
3096
|
+
// #7376: the turn is over; a Stop requested during it must not tag the next.
|
|
3097
|
+
this._stopRequestedThisTurn = false
|
|
3098
|
+
|
|
3099
|
+
// #7340: complete the tracked subagents this turn end owns, and no more.
|
|
3100
|
+
// A confirmed-backgrounded subagent deliberately outlives its turn, so
|
|
3101
|
+
// completing it here would report finished work that is still running --
|
|
3102
|
+
// which is the bug #7340 was filed for. It survives ONLY when the provider
|
|
3103
|
+
// itself said the turn ended (see `turnEndedCleanly` above); on every death
|
|
3104
|
+
// path the sweep stays total, because the signal that would clear it later
|
|
3105
|
+
// can no longer arrive.
|
|
3106
|
+
this._completeAgents({ exempt: survivingAgents })
|
|
1635
3107
|
|
|
1636
3108
|
// #5160: turn-end reconciliation for the activity registry. Ends any
|
|
1637
3109
|
// tool/agent/blocked node still marked running/blocked (orphans the
|
|
@@ -1640,6 +3112,18 @@ export class BaseSession extends EventEmitter {
|
|
|
1640
3112
|
// terminate their nodes first; reset() is the belt-and-braces sweep for
|
|
1641
3113
|
// anything the canonical signals didn't clear. Shell nodes survive
|
|
1642
3114
|
// turn-end (#4307) and clear via background_work_changed.
|
|
3115
|
+
//
|
|
3116
|
+
// #7340: an agent that survived the sweep must survive `reset()` too, or
|
|
3117
|
+
// the two surfaces disagree -- AgentMonitorPanel says running while the
|
|
3118
|
+
// Control Room tree says done, and `cancelActivity` answers `not-found`
|
|
3119
|
+
// for the entire time the subagent runs. #4307 set this precedent one
|
|
3120
|
+
// branch above for shells, for the same reason.
|
|
3121
|
+
//
|
|
3122
|
+
// No argument: the registry reads its own outlives-turn marks, and
|
|
3123
|
+
// `_completeAgents` above has just cleared the mark of every agent it
|
|
3124
|
+
// completed (via `agent_completed`). So the set it spares is exactly the
|
|
3125
|
+
// set that survived here -- by construction rather than by a second copy
|
|
3126
|
+
// of the predicate.
|
|
1643
3127
|
this._activity.reset()
|
|
1644
3128
|
|
|
1645
3129
|
if (this._resultTimeout) {
|