@chroxy/server 0.11.0 → 0.11.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +204 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1203 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +92 -7
- package/src/byok-mcp-config.js +628 -121
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +3 -3
- package/src/byok-session.js +650 -175
- package/src/byok-tool-executor.js +2662 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +53 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +211 -88
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3513 -287
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +68 -39
- package/src/cli/server-cmd.js +48 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1066 -121
- package/src/cli.js +4 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1454 -79
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +450 -27
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +286 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +23 -19
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +172 -3
- package/src/docker-session.js +284 -10
- package/src/doctor.js +767 -61
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +151 -233
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +535 -68
- package/src/handlers/checkpoint-handlers.js +39 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +57 -13
- package/src/handlers/input-handlers.js +685 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/scheduler-handlers.js +88 -14
- package/src/handlers/session-handlers.js +542 -20
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +330 -42
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +127 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +289 -82
- package/src/jsonl-subprocess-session.js +92 -8
- package/src/keychain.js +1 -1
- package/src/logger.js +63 -17
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +12 -4
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +64 -23
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +80 -33
- package/src/orchestration/permission-gate.js +13 -1
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/turn-driver.js +44 -20
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1357 -42
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +712 -83
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +122 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +159 -43
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +207 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +318 -26
- package/src/scheduler.js +73 -3
- package/src/sdk-session.js +2060 -187
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +524 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3491 -312
- package/src/session-message-history.js +722 -16
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-token-store.js +17 -8
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +23 -11
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +22 -11
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +137 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +133 -37
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +360 -16
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +7 -2
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +331 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +329 -39
- package/src/ws-handler-context.js +70 -2
- package/src/ws-history.js +940 -172
- package/src/ws-message-handlers.js +17 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +643 -96
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
package/src/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,47 @@ 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
|
+
|
|
43
99
|
// #5936 (epic #5935): explicit overflow cap for the shared outgoing-message
|
|
44
100
|
// queue (`_outgoingQueue`). Replaces the SDK's hard-coded mid-turn cap of 3
|
|
45
101
|
// (#5711) with one bounded, surfaced limit shared by SDK + CLI. A send-while-
|
|
@@ -48,6 +104,39 @@ export const SESSION_PREAMBLE_MAX_LENGTH = 4000
|
|
|
48
104
|
// burst of owner follow-ups while still bounding memory if a client wedges.
|
|
49
105
|
export const OUTGOING_QUEUE_MAX = 10
|
|
50
106
|
|
|
107
|
+
/**
|
|
108
|
+
* Report the provider's input-admission boundary without waiting for the turn.
|
|
109
|
+
* Async sendMessage implementations call this before their first await when
|
|
110
|
+
* possible, or later when an async transport handshake proves admission.
|
|
111
|
+
*/
|
|
112
|
+
export function reportInputAdmission(sendOptions, admission) {
|
|
113
|
+
const callback = sendOptions?.onInputAdmission
|
|
114
|
+
if (typeof callback === 'function') callback(admission)
|
|
115
|
+
return admission
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* #8038 (extracted from #8030's `_refuseTurnBeforeDispatch`): the shared
|
|
120
|
+
* admission shape for an input the binary gate refused before anything was
|
|
121
|
+
* dispatched — a per-turn provider's turn (SdkSession, JsonlSubprocessSession)
|
|
122
|
+
* OR a persistent provider's spawn/respawn (CliSession, ClaudeTuiSession).
|
|
123
|
+
* Exported so both refusal paths report the identical wire shape instead of a
|
|
124
|
+
* hand-rolled second literal drifting from this one.
|
|
125
|
+
*
|
|
126
|
+
* `_refuseTurnBeforeDispatch` below is the ORIGINAL caller and its wire shape
|
|
127
|
+
* must stay byte-identical — this is a pure extraction, not a behavior change.
|
|
128
|
+
*
|
|
129
|
+
* @param {Error & { code?: string }} [err]
|
|
130
|
+
* @returns {{status: string, delivery: string, retrySafe: boolean, reason: string, message: string}}
|
|
131
|
+
*/
|
|
132
|
+
export function spawnRefusalAdmission(err) {
|
|
133
|
+
return {
|
|
134
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
135
|
+
reason: err?.code || 'turn_refused',
|
|
136
|
+
message: 'The provider refused this turn before it was dispatched; see the session error for the cause.',
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
51
140
|
// #3884 / #3749 / #3899: default SOFT inactivity warning (ms). Activity-based
|
|
52
141
|
// — every provider event (SDK iterator message, CLI stdout JSONL line)
|
|
53
142
|
// resets the timer; the window only bounds *silent stretches*, not wall-
|
|
@@ -130,11 +219,15 @@ export const BASE_SESSION_OPT_KEYS = [
|
|
|
130
219
|
'promptEvaluatorSkipPattern',
|
|
131
220
|
'chroxyContextHint',
|
|
132
221
|
'sessionPreamble',
|
|
222
|
+
'projectInstructions',
|
|
133
223
|
'resultTimeoutMs',
|
|
134
224
|
'hardTimeoutMs',
|
|
135
225
|
'streamStallTimeoutMs',
|
|
136
226
|
'backgroundShellHardQuiesceMs',
|
|
137
227
|
'permissionRuleStore',
|
|
228
|
+
// #8035: see the ctor param doc below — closes the middle-layer trap for
|
|
229
|
+
// JsonlSubprocessSession's picker subclasses (Gemini/Codex-exec).
|
|
230
|
+
'spawnPreflight',
|
|
138
231
|
]
|
|
139
232
|
|
|
140
233
|
// #5367: pick the BaseSession opts out of a subclass's full opts bag and merge
|
|
@@ -242,6 +335,23 @@ function normalizeResultDuration(payload) {
|
|
|
242
335
|
}
|
|
243
336
|
|
|
244
337
|
export class BaseSession extends EventEmitter {
|
|
338
|
+
/** Binary version observed by this live runtime, or `unknown`. */
|
|
339
|
+
get providerBinaryVersion() {
|
|
340
|
+
return 'unknown'
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Runtime-negotiated capability states; static UI capabilities are separate. */
|
|
344
|
+
get providerRuntimeCapabilities() {
|
|
345
|
+
return {}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** Provider-owned restart locator; generic persistence never reconstructs it. */
|
|
349
|
+
get nativeResumeState() { return null }
|
|
350
|
+
|
|
351
|
+
get providerInstructionProjection() {
|
|
352
|
+
return this._projectInstructionProjection
|
|
353
|
+
}
|
|
354
|
+
|
|
245
355
|
/**
|
|
246
356
|
* Custom event names emitted by this provider class that should be proxied
|
|
247
357
|
* by SessionManager in addition to the built-in PROXIED_EVENTS list.
|
|
@@ -320,6 +430,9 @@ export class BaseSession extends EventEmitter {
|
|
|
320
430
|
// SESSION_PREAMBLE_MAX_LENGTH on construction. Empty string (or any
|
|
321
431
|
// non-string input) is the byte-identical-to-pre-#4660 default.
|
|
322
432
|
sessionPreamble,
|
|
433
|
+
// #7835: separately bounded required project policy. This does not share
|
|
434
|
+
// the 4k user-preamble or runtime-skill pruning budgets.
|
|
435
|
+
projectInstructions,
|
|
323
436
|
// #3749 / #3884 / #3899: configurable SOFT-warning timeout (the
|
|
324
437
|
// inactivity safety net). Subclasses arm this timer; when it fires
|
|
325
438
|
// they emit an `inactivity_warning` event so the client can render
|
|
@@ -351,6 +464,20 @@ export class BaseSession extends EventEmitter {
|
|
|
351
464
|
// hand it to their PermissionManager so an `allowAlways` decision persists a
|
|
352
465
|
// project-scoped rule and new sessions in the same cwd seed from it.
|
|
353
466
|
permissionRuleStore,
|
|
467
|
+
// #8035: per-spawn binary re-verification gate. SessionManager wires this
|
|
468
|
+
// to `_verifyPinnedSpawn` (re-runs the full binary gate against the EXACT
|
|
469
|
+
// path create-time preflight verified) whenever preflight ran and the
|
|
470
|
+
// provider isn't containerised. Lives on BaseSession — not read directly
|
|
471
|
+
// by a subclass's opts bag — so every picker subclass built via
|
|
472
|
+
// `buildBaseSessionOpts` (GeminiSession, CodexSession, …) inherits it for
|
|
473
|
+
// free; reading `opts.spawnPreflight` in a middle layer instead would hit
|
|
474
|
+
// the trap documented in [[feedback_jsonl_subprocess_middle_layer]] and
|
|
475
|
+
// `BASE_SESSION_OPT_KEYS` above is what the opt-forwarding lint checks.
|
|
476
|
+
// null when absent — callers fall back to a plain
|
|
477
|
+
// `this.constructor.resolvedBinary` read via `_gatedSpawnBinary` below,
|
|
478
|
+
// same as pre-#8030/#8035 (a direct constructor call that bypasses
|
|
479
|
+
// SessionManager, or a test).
|
|
480
|
+
spawnPreflight,
|
|
354
481
|
} = {}) {
|
|
355
482
|
super()
|
|
356
483
|
this.cwd = cwd || process.cwd()
|
|
@@ -358,6 +485,17 @@ export class BaseSession extends EventEmitter {
|
|
|
358
485
|
// Read by the in-process permission providers when they build their
|
|
359
486
|
// PermissionManager; null on providers/tests that don't wire it.
|
|
360
487
|
this._permissionRuleStore = permissionRuleStore || null
|
|
488
|
+
// #8035 — see the ctor param doc above. Stored here (not in SdkSession, not
|
|
489
|
+
// read ad hoc off `opts` in JsonlSubprocessSession) so both the per-turn SDK
|
|
490
|
+
// exec and the per-turn subprocess spawn (Gemini/Codex-exec) share one
|
|
491
|
+
// source of truth via `_gatedSpawnBinary` below.
|
|
492
|
+
this._spawnPreflight = typeof spawnPreflight === 'function' ? spawnPreflight : null
|
|
493
|
+
// #8038 — latched by `_refuseSpawn` when a (re)spawn attempt's binary gate
|
|
494
|
+
// (CliSession._spawnPersistentProcess, ClaudeTuiSession._spawnPty /
|
|
495
|
+
// _respawnPty) throws instead of returning a verified path. null means
|
|
496
|
+
// "no refusal outstanding" — the normal state, and the state after a
|
|
497
|
+
// revival succeeds. See `_refuseSpawn`'s doc for the full contract.
|
|
498
|
+
this._spawnRefusal = null
|
|
361
499
|
this.model = model || null
|
|
362
500
|
// Actual model the underlying CLI/SDK reports at init time. May differ
|
|
363
501
|
// from `this.model` (the user's requested override) when no override
|
|
@@ -368,13 +506,14 @@ export class BaseSession extends EventEmitter {
|
|
|
368
506
|
// Set by subclasses in their init handlers (#3687).
|
|
369
507
|
this.bootedModel = null
|
|
370
508
|
this.permissionMode = permissionMode || 'approve'
|
|
509
|
+
assertProviderPermissionModeSupported(this.constructor, this.permissionMode)
|
|
371
510
|
// #3185: per-session toggle for the auto-evaluator chain (parent epic
|
|
372
511
|
// #3068). Default `false` — the existing manual `evaluate_draft` flow
|
|
373
512
|
// (PR #3089) is unaffected by this flag. Coerced to a strict boolean
|
|
374
513
|
// here so JSON.stringify produces `true`/`false` (not `1`/`null`) on
|
|
375
514
|
// the auth_ok / session_list wires.
|
|
376
515
|
this.promptEvaluator = !!promptEvaluator
|
|
377
|
-
// #3639: per-session regex source string used by `
|
|
516
|
+
// #3639: per-session regex source string used by `shouldSkipEvaluatorAsync`
|
|
378
517
|
// to extend the default continuation/ack skip list. Mirrors the
|
|
379
518
|
// server-wide `config.promptEvaluatorSkipPattern` from #3187 but is
|
|
380
519
|
// evaluated FIRST in input-handlers.js so a per-session override
|
|
@@ -398,9 +537,39 @@ export class BaseSession extends EventEmitter {
|
|
|
398
537
|
// smuggle in unbounded text. The runtime setter (setSessionPreamble)
|
|
399
538
|
// does the same coercion and reports rejection on type mismatch.
|
|
400
539
|
this.sessionPreamble = _coerceSessionPreambleOpt(sessionPreamble)
|
|
540
|
+
this.projectInstructions = typeof projectInstructions === 'string' ? projectInstructions : ''
|
|
541
|
+
const projectInstructionBytes = Buffer.byteLength(this.projectInstructions, 'utf8')
|
|
542
|
+
if (projectInstructionBytes > PROJECT_INSTRUCTION_BUDGET_BYTES) {
|
|
543
|
+
throw new Error(`projectInstructions exceeds ${PROJECT_INSTRUCTION_BUDGET_BYTES} UTF-8 bytes`)
|
|
544
|
+
}
|
|
545
|
+
this._projectInstructionProjection = {
|
|
546
|
+
status: this.projectInstructions ? 'delivered' : 'unknown',
|
|
547
|
+
enforcement: 'instructional',
|
|
548
|
+
compilerVersion: '1',
|
|
549
|
+
budgetBytes: this.projectInstructions ? PROJECT_INSTRUCTION_BUDGET_BYTES : 0,
|
|
550
|
+
totalBytes: projectInstructionBytes,
|
|
551
|
+
sources: [], rules: [], includedRequiredRuleIds: [],
|
|
552
|
+
}
|
|
401
553
|
|
|
402
|
-
this.
|
|
554
|
+
this._busyFlag = false
|
|
403
555
|
this._processReady = false
|
|
556
|
+
// #8743: when the provider last produced output, on the monotonic
|
|
557
|
+
// `_providerActivityClock()`. null until it first does. See noteProviderActivity.
|
|
558
|
+
this._providerActivityAtMs = null
|
|
559
|
+
// #7382: outstanding hook-routed permission prompts, by requestId. Hoisted
|
|
560
|
+
// from CliSession, where it was written for #2831 and stayed provider-local
|
|
561
|
+
// through #7375/#7379 — so claude-tui, then DEFAULT_PROVIDER, which routes
|
|
562
|
+
// its prompts through the SAME permission-hook.sh into the SAME daemon map,
|
|
563
|
+
// silently had none of it. `ws-permissions` guards its calls with
|
|
564
|
+
// `typeof ownerSession.notifyPermissionPending === 'function'`, so the
|
|
565
|
+
// missing methods were not an error — they were a skip, which is the
|
|
566
|
+
// success-and-not-checking shape in docs/false-safety-guards.md.
|
|
567
|
+
//
|
|
568
|
+
// Lives here so a THIRD hook-routed provider inherits it rather than
|
|
569
|
+
// re-implementing it. A derived-roster test (hook-routed-permission-
|
|
570
|
+
// bookkeeping.test.js) fails if any `*-session.js` that mints a
|
|
571
|
+
// `_hookSecret` lacks the API.
|
|
572
|
+
this._pendingPermissionIds = new Set()
|
|
404
573
|
// #5375: user-initiated stop vs crash. Set by interrupt() (markIntentionalStop),
|
|
405
574
|
// captured-and-cleared by the provider's close/error handler
|
|
406
575
|
// (_consumeIntentionalStop) so a clean stop is not reported as an error.
|
|
@@ -410,6 +579,20 @@ export class BaseSession extends EventEmitter {
|
|
|
410
579
|
// `finally` safety-net clear (the interrupt-races-result case), and collapsing
|
|
411
580
|
// them would reopen that race.
|
|
412
581
|
this._intentionalStop = false
|
|
582
|
+
// #7376: a Stop was requested while THIS turn was running. Unlike
|
|
583
|
+
// `_intentionalStop` (consumed by the child-close / query-catch handler, and
|
|
584
|
+
// not armed at all when the provider acknowledges the interrupt with a
|
|
585
|
+
// normal `result`), this one lives exactly as long as the turn: set by
|
|
586
|
+
// `_noteTurnStopRequested`, read by the orphan sweep, and reset by
|
|
587
|
+
// `_clearMessageState`. It is what lets a Stop that COMPLETES normally still
|
|
588
|
+
// tag the tools it cut off as `user_stop`.
|
|
589
|
+
this._stopRequestedThisTurn = false
|
|
590
|
+
// #8461: per Stop REQUEST (reset by `markIntentionalStop`, not per turn): a
|
|
591
|
+
// `stopped` event has gone out for it, and the one `emit('result')` sent in
|
|
592
|
+
// place of the Stopped chip, which a later `stopped` for the same Stop (the
|
|
593
|
+
// CLI child's exit, a late abort rejection) must not repeat.
|
|
594
|
+
this._stoppedSinceStopRequest = false
|
|
595
|
+
this._stopAckedByResult = false
|
|
413
596
|
// #4307/#5177/#5247/#5265: pending background-shell tracking + the reaping
|
|
414
597
|
// sweep live in BackgroundShellTracker (#5376). BaseSession composes one and
|
|
415
598
|
// delegates the public surface (trackBackgroundShell / clearBackgroundShell /
|
|
@@ -443,6 +626,22 @@ export class BaseSession extends EventEmitter {
|
|
|
443
626
|
// forever AND persist the orphan to session-state.json. Companion
|
|
444
627
|
// path: SessionMessageHistory.sweepUnresolvedToolStarts (#4617/#4619)
|
|
445
628
|
// catches stragglers at restore-time as a backstop.
|
|
629
|
+
//
|
|
630
|
+
// #7346: entries may also carry a finalized `input` field, set via
|
|
631
|
+
// `_recordToolInput` once the provider knows the tool's full input
|
|
632
|
+
// (CliSession: parsed `content_block_stop` buffer; SdkSession: the
|
|
633
|
+
// full assistant-message `block.input`, no buffering needed). Both
|
|
634
|
+
// `content_block_start`'s `tool_start` and the Anthropic wire
|
|
635
|
+
// protocol's `content_block_start` for a tool_use carry `input: null`
|
|
636
|
+
// — the finalized value only exists once the block closes — so this
|
|
637
|
+
// is the one place both providers can stash it for `tool-result.js`'s
|
|
638
|
+
// `emitToolResults` to read back (`_getTrackedToolInput`) and attach
|
|
639
|
+
// to the matching `tool_result`, which lets the client (and
|
|
640
|
+
// persisted history, via session-message-history.js) backfill the
|
|
641
|
+
// `tool_start` entry that was `input: null` when first emitted.
|
|
642
|
+
// BYOK never calls `_trackToolStart`, so this map stays empty there
|
|
643
|
+
// and `_getTrackedToolInput` always returns `undefined` — BYOK's
|
|
644
|
+
// `tool_result` is unaffected.
|
|
446
645
|
this._inFlightToolStarts = new Map()
|
|
447
646
|
// #5160: per-session activity registry (Control Room). A thin unifying
|
|
448
647
|
// layer that maps the signals BaseSession already emits (tool_start /
|
|
@@ -592,6 +791,110 @@ export class BaseSession extends EventEmitter {
|
|
|
592
791
|
}
|
|
593
792
|
}
|
|
594
793
|
|
|
794
|
+
/**
|
|
795
|
+
* #8035 — the one spawn-path helper every per-turn provider (SdkSession,
|
|
796
|
+
* JsonlSubprocessSession's Gemini/Codex-exec subclasses) uses instead of
|
|
797
|
+
* reading `this.constructor.resolvedBinary` directly. With a gate wired
|
|
798
|
+
* (`_spawnPreflight`, set from SessionManager's `spawnPreflight` opt — see
|
|
799
|
+
* the ctor doc above), it re-runs the full binary-provenance gate against
|
|
800
|
+
* the exact path create-time preflight verified and returns THAT path,
|
|
801
|
+
* pinned regardless of what `resolvedBinary` would resolve to right now.
|
|
802
|
+
* Without a gate (no SessionManager, a direct constructor call, most
|
|
803
|
+
* tests), it falls back to the plain static read — the pre-#8030 behavior.
|
|
804
|
+
*
|
|
805
|
+
* A non-string or empty result would leave the caller launching an
|
|
806
|
+
* unverified binary (e.g. the SDK falling back to its own bundled claude),
|
|
807
|
+
* so that case throws instead of returning — `PROVIDER_BINARY_UNVERIFIED`,
|
|
808
|
+
* with `binaryLabel` in the message so the two callers keep their own
|
|
809
|
+
* wording (SdkSession passes 'claude'; JsonlSubprocessSession passes
|
|
810
|
+
* `Klass.providerName`). Any error the gate itself throws (
|
|
811
|
+
* `PROVIDER_BINARY_PROVENANCE`, `PROVIDER_BINARY_QUARANTINED`,
|
|
812
|
+
* `PROVIDER_BINARY_NOT_FOUND`, …) propagates unchanged — this method adds
|
|
813
|
+
* exactly one new failure mode, it doesn't wrap existing ones.
|
|
814
|
+
*
|
|
815
|
+
* @param {string} binaryLabel — human name for the empty-path error text
|
|
816
|
+
* @returns {string} the verified path to spawn
|
|
817
|
+
* @throws {Error} PROVIDER_BINARY_UNVERIFIED, or whatever the gate throws
|
|
818
|
+
*/
|
|
819
|
+
_gatedSpawnBinary(binaryLabel) {
|
|
820
|
+
const path = this._spawnPreflight ? this._spawnPreflight() : this.constructor.resolvedBinary
|
|
821
|
+
if (typeof path !== 'string' || path.length === 0) {
|
|
822
|
+
const err = new Error(`No verified ${binaryLabel} binary path is available for this turn.`)
|
|
823
|
+
err.code = 'PROVIDER_BINARY_UNVERIFIED'
|
|
824
|
+
throw err
|
|
825
|
+
}
|
|
826
|
+
return path
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/**
|
|
830
|
+
* #8035 — the shared refusal path for a turn the binary gate stopped
|
|
831
|
+
* BEFORE dispatch (paired with `_gatedSpawnBinary` above). Hoisted out of
|
|
832
|
+
* SdkSession (#8030) so JsonlSubprocessSession's per-turn spawn gets the
|
|
833
|
+
* same wire shape rather than a hand-rolled second copy.
|
|
834
|
+
*
|
|
835
|
+
* Deliberately does NOT run any error-text rewriter: a provenance message
|
|
836
|
+
* embeds a hex hash prefix (e.g. "...a4291b0c...") that can match a
|
|
837
|
+
* rate-limit ("429") or auth ("401") pattern in a text-classification table
|
|
838
|
+
* and get silently rewritten into a wrong, misleading message instead of
|
|
839
|
+
* the real cause (see SdkSession's #8030 comment on `_enrichErrorMessage`).
|
|
840
|
+
*
|
|
841
|
+
* @param {Error & { code?: string }} err
|
|
842
|
+
* @param {object} sendOptions — this turn's sendMessage options (for the admission callback)
|
|
843
|
+
* @param {{ error: Function }} logger — the caller's logger (`this._log || log`)
|
|
844
|
+
*/
|
|
845
|
+
_refuseTurnBeforeDispatch(err, sendOptions, logger) {
|
|
846
|
+
logger.error(`Turn refused before dispatch: ${err.message}`)
|
|
847
|
+
// An uncoded throw (e.g. from a subclass's augment hook) is not a
|
|
848
|
+
// binary-verification failure, so it gets a neutral code.
|
|
849
|
+
this.emit('error', { code: err.code || 'TURN_REFUSED', message: err.message })
|
|
850
|
+
// #8038: extracted to spawnRefusalAdmission() so CliSession/ClaudeTuiSession's
|
|
851
|
+
// spawn-refusal-on-send path reports the identical wire shape — see that
|
|
852
|
+
// function's doc. Byte-identical to the pre-#8038 inline literal.
|
|
853
|
+
reportInputAdmission(sendOptions, spawnRefusalAdmission(err))
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
/**
|
|
857
|
+
* #8038 — the shared refusal path for a (re)SPAWN the binary gate stopped,
|
|
858
|
+
* as opposed to `_refuseTurnBeforeDispatch` above (which refuses a single
|
|
859
|
+
* TURN on a provider that spawns fresh per turn). CliSession's
|
|
860
|
+
* `_spawnPersistentProcess` and ClaudeTuiSession's `_respawnPty` call this
|
|
861
|
+
* when `_gatedSpawnBinary` (or, for the TUI native route, the equivalent
|
|
862
|
+
* `_connectionRuntimePreflight` re-check) throws instead of returning a
|
|
863
|
+
* verified path — nothing was spawned, so there is no child/PTY error to
|
|
864
|
+
* report through the normal exit-handling path. #8044: the TUI native
|
|
865
|
+
* route's `claude auth status` verdict (logged out, a non-first-party route,
|
|
866
|
+
* unreadable status) is refused the same way, also before any spawn.
|
|
867
|
+
* #8057 is the one post-spawn case: the native endpoint-marker verdict
|
|
868
|
+
* arrives after the PTY launched, so `_spawnPty` kills and drops that PTY
|
|
869
|
+
* first and the refusal then follows these same semantics — no live child
|
|
870
|
+
* remains, and no exit-handling path reports it either.
|
|
871
|
+
*
|
|
872
|
+
* Latches `this._spawnRefusal = err` so:
|
|
873
|
+
* - the provider's own respawn machinery can tell "the gate refused this
|
|
874
|
+
* attempt" apart from "the child/PTY actually died" and skip scheduling
|
|
875
|
+
* a backoff timer for a spawn that was never going to happen anyway
|
|
876
|
+
* (which would otherwise burn the bounded respawn budget into a
|
|
877
|
+
* misleading `respawn_exhausted` / "failed to stay alive");
|
|
878
|
+
* - the next `sendMessage` re-runs the gate once (CliSession via
|
|
879
|
+
* `_restartAfterStop`, ClaudeTuiSession via `_respawnPty`) and, if it
|
|
880
|
+
* refuses again, rejects THAT input with `spawnRefusalAdmission` instead
|
|
881
|
+
* of queuing it behind a child that will never start.
|
|
882
|
+
*
|
|
883
|
+
* Emits the SAME coded `error` shape `_refuseTurnBeforeDispatch` does
|
|
884
|
+
* (`code: err.code || …, message: err.message`) with NO error-text
|
|
885
|
+
* rewriter — see that method's doc for why (a provenance message embeds a
|
|
886
|
+
* hex hash that can spuriously match a 429/401 text-classification
|
|
887
|
+
* pattern and get rewritten into a wrong, misleading message).
|
|
888
|
+
*
|
|
889
|
+
* @param {Error & { code?: string }} err
|
|
890
|
+
* @param {{ error: Function }} logger — the caller's logger (`this._log || log`)
|
|
891
|
+
*/
|
|
892
|
+
_refuseSpawn(err, logger) {
|
|
893
|
+
this._spawnRefusal = err
|
|
894
|
+
logger.error(`Spawn refused: ${err.message}`)
|
|
895
|
+
this.emit('error', { code: err?.code || 'SPAWN_REFUSED', message: err.message })
|
|
896
|
+
}
|
|
897
|
+
|
|
595
898
|
/**
|
|
596
899
|
* #5376: delegate to SkillsManager. Kept as a session method because
|
|
597
900
|
* settings-handlers.js calls `session._loadSkills()` to rebuild after a
|
|
@@ -658,6 +961,27 @@ export class BaseSession extends EventEmitter {
|
|
|
658
961
|
return this._skillsManager.deactivateSkill(skillName)
|
|
659
962
|
}
|
|
660
963
|
|
|
964
|
+
/**
|
|
965
|
+
* #8259: the model is mid-turn. Every provider assigns `_isBusy = true` when it
|
|
966
|
+
* dispatches a turn to its backend (including a queued follow-up when the queue
|
|
967
|
+
* flushes) and BaseSession clears it at every turn end, so this accessor is the
|
|
968
|
+
* ONE place a turn starting or ending is observable. A change emits
|
|
969
|
+
* `turn_state` `{ active }` (internal: not in the proxied event list) so the
|
|
970
|
+
* SessionManager can persist "a turn was in flight" and, after a daemon
|
|
971
|
+
* restart, tell a turn that was cut off from one that merely has no `result`
|
|
972
|
+
* in its history.
|
|
973
|
+
*/
|
|
974
|
+
get _isBusy() {
|
|
975
|
+
return this._busyFlag === true
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
set _isBusy(value) {
|
|
979
|
+
const next = !!value
|
|
980
|
+
if (this._busyFlag === next) return
|
|
981
|
+
this._busyFlag = next
|
|
982
|
+
this.emit('turn_state', { active: next })
|
|
983
|
+
}
|
|
984
|
+
|
|
661
985
|
/**
|
|
662
986
|
* #4307: a session is "running" — i.e. NOT idle, NOT subject to
|
|
663
987
|
* `SessionTimeoutManager` reaping — when EITHER:
|
|
@@ -686,6 +1010,36 @@ export class BaseSession extends EventEmitter {
|
|
|
686
1010
|
return this._backgroundShellTracker.size > 0
|
|
687
1011
|
}
|
|
688
1012
|
|
|
1013
|
+
/**
|
|
1014
|
+
* #8302: the model is mid-turn. The first half of `isRunning`, exposed alone
|
|
1015
|
+
* so a publisher can tell "working" from "held busy by a background shell".
|
|
1016
|
+
* @returns {boolean}
|
|
1017
|
+
*/
|
|
1018
|
+
get turnActive() {
|
|
1019
|
+
return !!this._isBusy
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
/**
|
|
1023
|
+
* #8302: how many background shells the tracker holds. The tracker's `size`,
|
|
1024
|
+
* which counts shells the advisory mtime sweep has hidden from
|
|
1025
|
+
* `getPendingBackgroundShells()` (they still hold `isRunning` true).
|
|
1026
|
+
* @returns {number}
|
|
1027
|
+
*/
|
|
1028
|
+
get backgroundShellCount() {
|
|
1029
|
+
return this._backgroundShellTracker.size
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
/**
|
|
1033
|
+
* #8302: why `isRunning` is true — `'turn'`, `'background-shells'` (idle model,
|
|
1034
|
+
* tracked shells only), or `null` when the session is not busy. Derived from
|
|
1035
|
+
* `isRunning` itself so a subclass that overrides it (the user shell's PTY
|
|
1036
|
+
* liveness) keeps `busyReason === null <=> !isRunning`.
|
|
1037
|
+
* @returns {'turn'|'background-shells'|null}
|
|
1038
|
+
*/
|
|
1039
|
+
get busyReason() {
|
|
1040
|
+
return deriveBusyReason(this.isRunning, this.turnActive, this.backgroundShellCount)
|
|
1041
|
+
}
|
|
1042
|
+
|
|
689
1043
|
/**
|
|
690
1044
|
* #4307: read-only snapshot of pending background shells.
|
|
691
1045
|
* #5376: delegates to BackgroundShellTracker.
|
|
@@ -796,6 +1150,21 @@ export class BaseSession extends EventEmitter {
|
|
|
796
1150
|
const remaining = this._outgoingQueue.length
|
|
797
1151
|
process.nextTick(() => {
|
|
798
1152
|
if (this._destroying) return
|
|
1153
|
+
// #8301: an item that carries `sendOptions.admitAtFlush` is re-checked HERE,
|
|
1154
|
+
// at the moment it would be dispatched — after the preceding turn's
|
|
1155
|
+
// `result` has been broadcast and processed on every turn-end path. Its
|
|
1156
|
+
// admission at enqueue time can be stale by then (the result can trip the
|
|
1157
|
+
// cost-budget pause). The predicate is a LOCAL callback: it is never put on
|
|
1158
|
+
// the wire (`message_queued` carries only id/text/length) and the queue is
|
|
1159
|
+
// not persisted. Typed input does not set it, so its behaviour is unchanged.
|
|
1160
|
+
// A refusal — or a throwing predicate, which fails safe — cancels just this
|
|
1161
|
+
// item and goes on to consider the next, so the queue keeps draining.
|
|
1162
|
+
if (!this._admitQueuedItem(item)) {
|
|
1163
|
+
this.emit('message_dequeued', { clientMessageId, queueLength: remaining, reason: 'cancelled' })
|
|
1164
|
+
;(this._log || log).warn(`Dropped queued follow-up at flush: admission refused (${remaining} remaining)`)
|
|
1165
|
+
this._continueDrainAfterRefusal()
|
|
1166
|
+
return
|
|
1167
|
+
}
|
|
799
1168
|
this.emit('message_dequeued', { clientMessageId, queueLength: remaining, reason: 'flush' })
|
|
800
1169
|
;(this._log || log).info(`Dequeuing follow-up message (${remaining} remaining)`)
|
|
801
1170
|
this.sendMessage(item.prompt, item.attachments, item.sendOptions)
|
|
@@ -803,6 +1172,57 @@ export class BaseSession extends EventEmitter {
|
|
|
803
1172
|
return item
|
|
804
1173
|
}
|
|
805
1174
|
|
|
1175
|
+
/**
|
|
1176
|
+
* #8301: the refused item held this turn's drain slot, so keep draining. The
|
|
1177
|
+
* default continues with the next outgoing item. A provider with a second
|
|
1178
|
+
* queue behind `_outgoingQueue` (CliSession's startup queue) overrides this to
|
|
1179
|
+
* fall through to it, exactly as its own turn-end drain would have.
|
|
1180
|
+
*/
|
|
1181
|
+
_continueDrainAfterRefusal() {
|
|
1182
|
+
if (this._outgoingQueue.length && !this._destroying) this.dequeueNextOutgoing()
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
/**
|
|
1186
|
+
* #8301: evaluate a queued item's optional flush-time admission predicate.
|
|
1187
|
+
* No predicate means admitted (every typed input). A predicate that returns
|
|
1188
|
+
* anything but `true`, or throws, means NOT admitted.
|
|
1189
|
+
*
|
|
1190
|
+
* @param {{ sendOptions?: { admitAtFlush?: () => boolean } }} item
|
|
1191
|
+
* @returns {boolean}
|
|
1192
|
+
*/
|
|
1193
|
+
_admitQueuedItem(item) {
|
|
1194
|
+
// The connection that queued this follow-up may have ended while it waited:
|
|
1195
|
+
// a revoked or expired credential must not get its queued input dispatched.
|
|
1196
|
+
if (!stillAuthorized(item?.sendOptions?.isAuthorized)) return false
|
|
1197
|
+
const predicate = item?.sendOptions?.admitAtFlush
|
|
1198
|
+
if (typeof predicate !== 'function') return true
|
|
1199
|
+
try {
|
|
1200
|
+
return predicate() === true
|
|
1201
|
+
} catch (err) {
|
|
1202
|
+
;(this._log || log).warn(`Queued follow-up admission check threw; dropping it: ${err?.message || err}`)
|
|
1203
|
+
return false
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
/**
|
|
1208
|
+
* #8301: why a DAEMON-authored turn (the CI wake) must not be handed to this
|
|
1209
|
+
* session right now, or `null` when it may. The provider's half of the one
|
|
1210
|
+
* refusal seam `SessionManager.daemonTurnRefusal` asks — before dispatch and
|
|
1211
|
+
* again when a queued wake is about to flush.
|
|
1212
|
+
*
|
|
1213
|
+
* This is a stricter question than "can the user type here": a typed input
|
|
1214
|
+
* may legitimately revive a stopped session or surface an error, but a
|
|
1215
|
+
* daemon wake that does so is a side effect nobody asked for. A provider
|
|
1216
|
+
* overrides it for the states in which `sendMessage` would do that (respawn,
|
|
1217
|
+
* discard the queue, report a user-visible error). The default is `null`: a
|
|
1218
|
+
* provider that has no such state is always willing.
|
|
1219
|
+
*
|
|
1220
|
+
* @returns {string|null} a short reason, or null
|
|
1221
|
+
*/
|
|
1222
|
+
daemonTurnRefusal() {
|
|
1223
|
+
return null
|
|
1224
|
+
}
|
|
1225
|
+
|
|
806
1226
|
/**
|
|
807
1227
|
* #5936: drop every queued outgoing message. Called by `interrupt()` so a
|
|
808
1228
|
* deliberate Stop cancels the owner's pending follow-ups rather than letting
|
|
@@ -933,7 +1353,26 @@ export class BaseSession extends EventEmitter {
|
|
|
933
1353
|
// and never call _destroyPendingBackgroundShells, so this is the
|
|
934
1354
|
// chokepoint that guarantees no provider leaks the recurring timer.
|
|
935
1355
|
this._stopBackgroundShellSweep()
|
|
936
|
-
|
|
1356
|
+
// #7340: drop EVERY tracked subagent, foreground and backgrounded alike.
|
|
1357
|
+
// Before #7340 the turn-end sweep guaranteed this map was empty by the
|
|
1358
|
+
// time a session was torn down; agents that outlive their turn break that
|
|
1359
|
+
// guarantee, so the same chokepoint that stops the shell sweep clears
|
|
1360
|
+
// them. A destroy landing MID-TURN also has foreground agents tracked,
|
|
1361
|
+
// which is why this is an unconditional clear and not a filtered one --
|
|
1362
|
+
// the `backgroundConfirmed` predicate belongs to the turn-end sweep, where the
|
|
1363
|
+
// question is "did this outlive its turn", not to teardown, where there
|
|
1364
|
+
// is no next turn for anything to outlive. No `agent_completed` emit: the
|
|
1365
|
+
// session is being destroyed, its clients drop its state wholesale, and
|
|
1366
|
+
// the listeners come off on the next line anyway.
|
|
1367
|
+
this._activeAgents.clear()
|
|
1368
|
+
const removed = super.removeAllListeners()
|
|
1369
|
+
// A turn aborted by this teardown can still emit 'error' after the
|
|
1370
|
+
// listeners are gone; with none attached that throws ERR_UNHANDLED_ERROR.
|
|
1371
|
+
// SessionManager.destroySession adds a no-op listener, but the provider's
|
|
1372
|
+
// own destroy() ends here and would drop it. Re-add it for a session that
|
|
1373
|
+
// is being destroyed.
|
|
1374
|
+
if (this._destroying) super.on('error', () => {})
|
|
1375
|
+
return removed
|
|
937
1376
|
}
|
|
938
1377
|
return super.removeAllListeners(eventName)
|
|
939
1378
|
}
|
|
@@ -948,15 +1387,93 @@ export class BaseSession extends EventEmitter {
|
|
|
948
1387
|
this._activity.setSessionId(sessionId)
|
|
949
1388
|
}
|
|
950
1389
|
|
|
951
|
-
/**
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
1390
|
+
/** Project durable session intent into the existing activity tree. */
|
|
1391
|
+
setDeclaredStatusActivity(status) {
|
|
1392
|
+
this._activity.onDeclaredStatus(status)
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
getDecisionActivityState() {
|
|
1396
|
+
return this._activity.getDecisionState()
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
restoreDeclaredStatusActivity(status, state) {
|
|
1400
|
+
this._activity.restoreDecisionState(status, state)
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
/** Full current tree for fresh subscribers and resync. */
|
|
956
1404
|
getActivitySnapshot() {
|
|
957
1405
|
return this._activity.getSnapshotMessage()
|
|
958
1406
|
}
|
|
959
1407
|
|
|
1408
|
+
/**
|
|
1409
|
+
* #7340: the subagents this session is currently tracking, as the wire
|
|
1410
|
+
* fields of an `agent_spawned` message.
|
|
1411
|
+
*
|
|
1412
|
+
* Serves the same purpose `getActivitySnapshot()` does for the Control Room
|
|
1413
|
+
* tree, for the surface that has no tree: `agent_spawned` / `agent_completed`
|
|
1414
|
+
* are transient (`builtinTransient` in SessionManager) and are NOT replayed
|
|
1415
|
+
* from history, so both clients WIPE `activeAgents` at `history_replay_start`
|
|
1416
|
+
* and nothing put it back. That was harmless while no agent outlived its
|
|
1417
|
+
* turn; once one does, a 2s cellular drop or a tab switch returned the
|
|
1418
|
+
* session to `idle` with subagents still running -- #7340's exact symptom,
|
|
1419
|
+
* reached a different way.
|
|
1420
|
+
*
|
|
1421
|
+
* Re-emitting the live set AFTER the replay makes the wipe a snapshot
|
|
1422
|
+
* REPLACE rather than a loss: the wipe clears whatever the client held
|
|
1423
|
+
* (including a completion it missed while offline, which is why the wipe is
|
|
1424
|
+
* kept rather than carved out the way #4466 did for `activeTools`), and this
|
|
1425
|
+
* re-asserts what is actually running. Both clients dedupe `agent_spawned`
|
|
1426
|
+
* by `toolUseId`, so re-emitting to a client that never lost the entry is a
|
|
1427
|
+
* no-op.
|
|
1428
|
+
*
|
|
1429
|
+
* Projected to the three fields `event-normalizer` puts on the wire -- the
|
|
1430
|
+
* record's `background` / `backgroundConfirmed` are server-side bookkeeping
|
|
1431
|
+
* and must not start leaking to clients through this path.
|
|
1432
|
+
*
|
|
1433
|
+
* @returns {{ toolUseId: string, description: string, startedAt: number }[]}
|
|
1434
|
+
*/
|
|
1435
|
+
getActiveAgents() {
|
|
1436
|
+
// Keyed by the MAP KEY, not `agent.toolUseId` -- the same invariant
|
|
1437
|
+
// `_completeAgents` states. A record whose field drifted from its key would
|
|
1438
|
+
// otherwise be re-announced under one id and completed under another, and
|
|
1439
|
+
// the client's dedupe and its filter would key on different ids, leaving a
|
|
1440
|
+
// badge entry nothing can clear.
|
|
1441
|
+
return Array.from(this._activeAgents, ([toolUseId, { description, startedAt }]) => ({
|
|
1442
|
+
toolUseId,
|
|
1443
|
+
description,
|
|
1444
|
+
startedAt,
|
|
1445
|
+
}))
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
/**
|
|
1449
|
+
* #7457: the AskUserQuestion prompts this session's turn is still BLOCKED on.
|
|
1450
|
+
*
|
|
1451
|
+
* Read by `ws-history.resendPendingQuestions`, which re-sends each one as a
|
|
1452
|
+
* LIVE `user_question` frame after every replay's `history_replay_end`. Until
|
|
1453
|
+
* then the only path a pending question had to a reconnecting client was the
|
|
1454
|
+
* history replay itself -- and `history_replay_end`'s sweep stamps every
|
|
1455
|
+
* replay-delivered prompt `answered: '(resolved)'`, so an ordinary reconnect
|
|
1456
|
+
* destroyed the answer path for a question the agent was still waiting on.
|
|
1457
|
+
*
|
|
1458
|
+
* Deliberately a READ-THROUGH to whatever store the provider already uses to
|
|
1459
|
+
* hold the blocked resolver -- `PermissionManager._pendingUserAnswer` for the
|
|
1460
|
+
* in-process providers, `_pendingUserAnswers` for claude-tui,
|
|
1461
|
+
* `_pendingQuestion` for cli-session. A mirrored copy would need a lifecycle
|
|
1462
|
+
* of its own, and a leaked mirror entry re-delivers a dead question to every
|
|
1463
|
+
* client that ever connects again; a read-through cannot leak, because the
|
|
1464
|
+
* record IS the thing blocking the turn.
|
|
1465
|
+
*
|
|
1466
|
+
* The default is EMPTY, not "unsupported": a provider with no question
|
|
1467
|
+
* surface has nothing pending, and `resendPendingQuestions` calls this
|
|
1468
|
+
* unguarded -- a feature-detect that can never fail only converts a future
|
|
1469
|
+
* regression into a silent no-op (docs/false-safety-guards.md).
|
|
1470
|
+
*
|
|
1471
|
+
* @returns {{ toolUseId: string, questions: object[] }[]}
|
|
1472
|
+
*/
|
|
1473
|
+
getPendingQuestions() {
|
|
1474
|
+
return []
|
|
1475
|
+
}
|
|
1476
|
+
|
|
960
1477
|
/**
|
|
961
1478
|
* #6832: last-known `mcp_servers` payload, wrapped as the wire message
|
|
962
1479
|
* shape (`{ type: 'mcp_servers', servers }`). Served to a fresh subscriber
|
|
@@ -1030,6 +1547,22 @@ export class BaseSession extends EventEmitter {
|
|
|
1030
1547
|
return this._backgroundShellTracker._isBackgroundShellQuiesced(entry)
|
|
1031
1548
|
}
|
|
1032
1549
|
|
|
1550
|
+
/**
|
|
1551
|
+
* #7611: forget every pending background shell WITHOUT tearing the session
|
|
1552
|
+
* down — for a provider that has just killed the process tree the shells
|
|
1553
|
+
* lived in and is about to start a fresh one. Unlike
|
|
1554
|
+
* `_destroyPendingBackgroundShells` it leaves the activity registry and the
|
|
1555
|
+
* intra-turn command map alone (the session carries on, and those belong to
|
|
1556
|
+
* the turn machinery), and it emits `background_work_changed` so the banner
|
|
1557
|
+
* drops the dead shells. delegates to BackgroundShellTracker.clearAll().
|
|
1558
|
+
*
|
|
1559
|
+
* @returns {number} how many pending shells were forgotten
|
|
1560
|
+
* @private
|
|
1561
|
+
*/
|
|
1562
|
+
_clearPendingBackgroundShells() {
|
|
1563
|
+
return this._backgroundShellTracker.clearAll()
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1033
1566
|
/**
|
|
1034
1567
|
* #4307: clear the pending map on session destroy. Pulled into a
|
|
1035
1568
|
* helper so subclasses can call it from their own `destroy()` after
|
|
@@ -1111,6 +1644,40 @@ export class BaseSession extends EventEmitter {
|
|
|
1111
1644
|
*/
|
|
1112
1645
|
markIntentionalStop() {
|
|
1113
1646
|
this._intentionalStop = true
|
|
1647
|
+
// #8461: a new Stop request is acknowledged on its own.
|
|
1648
|
+
this._stoppedSinceStopRequest = false
|
|
1649
|
+
this._stopAckedByResult = false
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1652
|
+
/**
|
|
1653
|
+
* #8374/#8430: the USER pressed Stop. Record it on the session's permission
|
|
1654
|
+
* manager for the rest of the turn, so the abort that follows resolves the
|
|
1655
|
+
* prompts open now -- and any raised before the abort lands -- as `stopped`
|
|
1656
|
+
* rather than `aborted`. Called by the `interrupt` message handler only -- never
|
|
1657
|
+
* from a provider's `interrupt()`, which the scheduler and teardown also call --
|
|
1658
|
+
* because a turn failed by a stalled stream or a dead provider process aborts
|
|
1659
|
+
* the same controller and is not a Stop. A Stop pressed with no turn running and no
|
|
1660
|
+
* prompt open records nothing (there is nothing for it to cancel), and a session with no
|
|
1661
|
+
* in-process permission manager has nothing to record on.
|
|
1662
|
+
* Cleared by `_clearMessageState`, which every turn end reaches.
|
|
1663
|
+
*/
|
|
1664
|
+
markUserStopInFlight() {
|
|
1665
|
+
// A turn is running, or a prompt is still open (a stalled turn's query can
|
|
1666
|
+
// outlive its busy flag and raise one): either way there is something for
|
|
1667
|
+
// this Stop to cancel. Otherwise there is nothing to label.
|
|
1668
|
+
if (!this._isBusy && !this._permissions?.hasPendingPrompt?.()) return
|
|
1669
|
+
this._permissions?.markUserStopInFlight?.()
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
/**
|
|
1673
|
+
* #7376: record that a Stop was requested during the turn that is running
|
|
1674
|
+
* now. A no-op when idle, so a Stop pressed between turns cannot leak into the
|
|
1675
|
+
* next one. Called by the providers whose `interrupt()` can be acknowledged by
|
|
1676
|
+
* a NORMAL `result` (claude-cli, claude-sdk) rather than only by a child exit
|
|
1677
|
+
* or a thrown abort; the flag is turn-scoped and reset by `_clearMessageState`.
|
|
1678
|
+
*/
|
|
1679
|
+
_noteTurnStopRequested() {
|
|
1680
|
+
if (this._isBusy) this._stopRequestedThisTurn = true
|
|
1114
1681
|
}
|
|
1115
1682
|
|
|
1116
1683
|
/**
|
|
@@ -1173,6 +1740,9 @@ export class BaseSession extends EventEmitter {
|
|
|
1173
1740
|
if (!ALLOWED_PERMISSION_MODE_IDS.has(mode)) {
|
|
1174
1741
|
return false
|
|
1175
1742
|
}
|
|
1743
|
+
if (!getProviderPermissionModeSupport(this.constructor, mode).supported) {
|
|
1744
|
+
return false
|
|
1745
|
+
}
|
|
1176
1746
|
// 'auto' is the panic-button: a user mid-turn (i.e. _isBusy=true)
|
|
1177
1747
|
// staring at a permission prompt should be able to flip to bypass and
|
|
1178
1748
|
// have it actually take effect. The non-auto modes still defer until
|
|
@@ -1283,10 +1853,10 @@ export class BaseSession extends EventEmitter {
|
|
|
1283
1853
|
* stored value changes and `false` for either invalid input or a
|
|
1284
1854
|
* redundant set — same idempotent contract as `setPromptEvaluator`.
|
|
1285
1855
|
*
|
|
1286
|
-
* The compiled regex itself isn't stored: `
|
|
1856
|
+
* The compiled regex itself isn't stored: `shouldSkipEvaluatorAsync` owns
|
|
1287
1857
|
* the compile cache (LRU keyed by source string) so a stale per-session
|
|
1288
1858
|
* pattern won't pin a closure here. The validation done here is
|
|
1289
|
-
* defence-in-depth — `
|
|
1859
|
+
* defence-in-depth — `shouldSkipEvaluatorAsync` also try/catches its own
|
|
1290
1860
|
* compile, so a session that somehow ends up with a bad source still
|
|
1291
1861
|
* fails-open to default-only skip rules.
|
|
1292
1862
|
*
|
|
@@ -1317,10 +1887,6 @@ export class BaseSession extends EventEmitter {
|
|
|
1317
1887
|
return true
|
|
1318
1888
|
}
|
|
1319
1889
|
|
|
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
1890
|
/**
|
|
1325
1891
|
* Parse a JSONL line from a subprocess stdout.
|
|
1326
1892
|
* Returns the parsed object or null if the line is empty or invalid JSON.
|
|
@@ -1413,22 +1979,46 @@ export class BaseSession extends EventEmitter {
|
|
|
1413
1979
|
*/
|
|
1414
1980
|
_buildSystemPrompt() {
|
|
1415
1981
|
const skillsText = typeof this._skillsText === 'string' ? this._skillsText : ''
|
|
1416
|
-
// Order (#4660 + #3805):
|
|
1417
|
-
//
|
|
1418
|
-
//
|
|
1419
|
-
//
|
|
1982
|
+
// Order (#7835 + #4660 + #3805): verified required project policy → user
|
|
1983
|
+
// preamble → chroxy hint → skills text. Required policy has its own budget
|
|
1984
|
+
// and cannot be displaced by optional/prunable context. The user-authored
|
|
1985
|
+
// preamble still precedes the canned hint and runtime-skills bucket.
|
|
1420
1986
|
//
|
|
1421
1987
|
// When BOTH the preamble is empty AND the chroxy hint is OFF, the
|
|
1422
1988
|
// return value is byte-identical to pre-#3805 (skillsText only) so
|
|
1423
1989
|
// existing users see no observable behaviour change. Each layer is
|
|
1424
1990
|
// joined by `\n\n` so the model sees clean paragraph breaks.
|
|
1425
1991
|
const parts = []
|
|
1992
|
+
if (this.projectInstructions) parts.push(this.projectInstructions)
|
|
1426
1993
|
if (this.sessionPreamble) parts.push(this.sessionPreamble)
|
|
1427
1994
|
if (this.chroxyContextHint) parts.push(CHROXY_CONTEXT_HINT_TEXT)
|
|
1428
1995
|
if (skillsText) parts.push(skillsText)
|
|
1429
1996
|
return parts.length === 0 ? '' : parts.join('\n\n')
|
|
1430
1997
|
}
|
|
1431
1998
|
|
|
1999
|
+
_installProjectInstructionProjection(projection) {
|
|
2000
|
+
if (!projection) {
|
|
2001
|
+
this.projectInstructions = ''
|
|
2002
|
+
this._projectInstructionProjection = {
|
|
2003
|
+
status: 'unknown', enforcement: 'instructional', compilerVersion: '1', budgetBytes: 0, totalBytes: 0,
|
|
2004
|
+
sources: [], rules: [], includedRequiredRuleIds: [],
|
|
2005
|
+
}
|
|
2006
|
+
return
|
|
2007
|
+
}
|
|
2008
|
+
const bytes = Buffer.byteLength(projection.text, 'utf8')
|
|
2009
|
+
if (bytes !== projection.totalBytes || bytes > projection.budgetBytes
|
|
2010
|
+
|| projection.budgetBytes > PROJECT_INSTRUCTION_BUDGET_BYTES) {
|
|
2011
|
+
throw new Error('Invalid project-instruction projection byte metadata')
|
|
2012
|
+
}
|
|
2013
|
+
this.projectInstructions = projection.text
|
|
2014
|
+
this._projectInstructionProjection = {
|
|
2015
|
+
status: 'delivered', enforcement: 'instructional', compilerVersion: projection.compilerVersion,
|
|
2016
|
+
budgetBytes: projection.budgetBytes, totalBytes: projection.totalBytes,
|
|
2017
|
+
sources: projection.sources, rules: projection.rules,
|
|
2018
|
+
includedRequiredRuleIds: projection.includedRequiredRuleIds,
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
|
|
1432
2022
|
/**
|
|
1433
2023
|
* Return the formatted skills text for prepending to the first user
|
|
1434
2024
|
* message (Codex, Gemini default; any provider when a skill declares
|
|
@@ -1510,6 +2100,78 @@ export class BaseSession extends EventEmitter {
|
|
|
1510
2100
|
this._inFlightToolStarts.delete(toolUseId)
|
|
1511
2101
|
}
|
|
1512
2102
|
|
|
2103
|
+
/**
|
|
2104
|
+
* #7346: attach the finalized tool input onto the in-flight tracking
|
|
2105
|
+
* entry created by `_trackToolStart`, so `_getTrackedToolInput` can
|
|
2106
|
+
* hand it back to `tool-result.js`'s `emitToolResults` when the
|
|
2107
|
+
* matching `tool_result` fires. No-op when the toolUseId isn't
|
|
2108
|
+
* tracked (already resolved/swept, or `_trackToolStart` was never
|
|
2109
|
+
* called for this provider — e.g. BYOK).
|
|
2110
|
+
*
|
|
2111
|
+
* #8135/#8136 (review on #7346): this is the ONE choke point both
|
|
2112
|
+
* providers' finalized-input capture flows through
|
|
2113
|
+
* (`cli-session.js`'s `_captureFinalizedToolInput`,
|
|
2114
|
+
* `sdk-session.js`'s `_handleToolUseBlock`), so it runs every input
|
|
2115
|
+
* through `sanitizeToolInput` (`redaction.js`, the same #6029 floor
|
|
2116
|
+
* `permission-manager.js`/`ws-permissions.js` already apply on the
|
|
2117
|
+
* permission-request path) BEFORE storing it — never the raw value.
|
|
2118
|
+
* That one call does double duty: it redacts secret-shaped values
|
|
2119
|
+
* (key-name AND value-shape passes, recursively) and caps the
|
|
2120
|
+
* serialized size to `MAX_INPUT_CHARS` (10KB, the existing broadcast
|
|
2121
|
+
* cap — falling back to a `{ _truncated, summary }` shape when the
|
|
2122
|
+
* whole object is oversized), so a 100KB+ `Write`/`Edit` input can
|
|
2123
|
+
* never reach `_getTrackedToolInput`, `tool_result`, or the persisted
|
|
2124
|
+
* `tool_start` history entry ungated. Every reader of this map
|
|
2125
|
+
* therefore gets an already-safe value for free — there is no second
|
|
2126
|
+
* place that needs to sanitize or cap.
|
|
2127
|
+
*
|
|
2128
|
+
* Returns the sanitized value (not just `undefined`) so a caller that
|
|
2129
|
+
* wants to deliver it somewhere else too (e.g. a single-shot
|
|
2130
|
+
* `tool_input_delta` for the in-flight view) doesn't need a redundant
|
|
2131
|
+
* `_getTrackedToolInput` round-trip.
|
|
2132
|
+
*
|
|
2133
|
+
* @param {string} toolUseId
|
|
2134
|
+
* @param {unknown} input - the finalized (fully parsed) tool input
|
|
2135
|
+
* @returns {unknown} the sanitized value that was stored (or `input`
|
|
2136
|
+
* unchanged if `toolUseId` wasn't tracked — still sanitized, just
|
|
2137
|
+
* not stored anywhere)
|
|
2138
|
+
*/
|
|
2139
|
+
_recordToolInput(toolUseId, input) {
|
|
2140
|
+
const sanitized = sanitizeToolInput(input)
|
|
2141
|
+
if (typeof toolUseId !== 'string' || toolUseId.length === 0) return sanitized
|
|
2142
|
+
const entry = this._inFlightToolStarts.get(toolUseId)
|
|
2143
|
+
if (entry) {
|
|
2144
|
+
entry.input = sanitized
|
|
2145
|
+
// #8371: tell the owner of the history ring buffer right now, not at
|
|
2146
|
+
// result time. The `tool_start` entry was recorded with `input: null`
|
|
2147
|
+
// and a replay (session switch, dashboard reload) during a still-running
|
|
2148
|
+
// tool would otherwise show no INPUT until the result lands. Only for a
|
|
2149
|
+
// TRACKED id (BYOK never tracks, so its streamed partials never reach
|
|
2150
|
+
// here) and only the sanitised value -- never the raw input.
|
|
2151
|
+
if (sanitized !== null && sanitized !== undefined) {
|
|
2152
|
+
this.emit('tool_input_recorded', { toolUseId, input: sanitized })
|
|
2153
|
+
}
|
|
2154
|
+
}
|
|
2155
|
+
return sanitized
|
|
2156
|
+
}
|
|
2157
|
+
|
|
2158
|
+
/**
|
|
2159
|
+
* #7346: read back the finalized tool input recorded via
|
|
2160
|
+
* `_recordToolInput`, if any. Returns `undefined` when nothing was
|
|
2161
|
+
* recorded — either the toolUseId isn't tracked at all (BYOK never
|
|
2162
|
+
* calls `_trackToolStart`, so this is always `undefined` there and
|
|
2163
|
+
* `tool_result` stays exactly as it was) or `_recordToolInput` was
|
|
2164
|
+
* never called for it (parse failure / overflow discard on the CLI
|
|
2165
|
+
* path). Already sanitized/capped — see `_recordToolInput`.
|
|
2166
|
+
*
|
|
2167
|
+
* @param {string} toolUseId
|
|
2168
|
+
* @returns {unknown}
|
|
2169
|
+
*/
|
|
2170
|
+
_getTrackedToolInput(toolUseId) {
|
|
2171
|
+
if (typeof toolUseId !== 'string' || toolUseId.length === 0) return undefined
|
|
2172
|
+
return this._inFlightToolStarts.get(toolUseId)?.input
|
|
2173
|
+
}
|
|
2174
|
+
|
|
1513
2175
|
/**
|
|
1514
2176
|
* #4628: sweep any tool_starts that never got their matching
|
|
1515
2177
|
* tool_result and emit synthetic tool_result events for each.
|
|
@@ -1524,24 +2186,69 @@ export class BaseSession extends EventEmitter {
|
|
|
1524
2186
|
* are diagnostic hints — the wire schema strips them on parse but
|
|
1525
2187
|
* they stay grep-able on disk in the persisted history.
|
|
1526
2188
|
*
|
|
2189
|
+
* #7376: when `reason` is a turn-TERMINATION reason (a permission-mode
|
|
2190
|
+
* switch, Stop, a crash, a watchdog — see `TURN_TERMINATION_REASONS`), the
|
|
2191
|
+
* tool did not fail, its turn was ended underneath it. The result then also
|
|
2192
|
+
* carries `terminatedReason` (the one diagnostic-adjacent field that IS on
|
|
2193
|
+
* the wire, `ServerToolResultSchema.terminatedReason`) and says so in its
|
|
2194
|
+
* text, so a client can render "cut off by the turn ending; check whether it took effect" instead of
|
|
2195
|
+
* the failure styling. Every other sweep reason (the natural turn end that
|
|
2196
|
+
* simply never saw a result) says only that the tool did not finish
|
|
2197
|
+
* (#8252) and carries no `terminatedReason`: those really are
|
|
2198
|
+
* indistinguishable from a failure.
|
|
2199
|
+
*
|
|
1527
2200
|
* @param {string} reason — short identifier for the sweep cause
|
|
1528
2201
|
* @returns {number} count of sweeps emitted
|
|
1529
2202
|
*/
|
|
1530
|
-
_sweepUnresolvedToolStarts(reason = 'stream_completed_without_result') {
|
|
2203
|
+
_sweepUnresolvedToolStarts(reason = 'stream_completed_without_result', exempt = null, { completion } = {}) {
|
|
1531
2204
|
if (this._inFlightToolStarts.size === 0) return 0
|
|
1532
|
-
|
|
1533
|
-
|
|
2205
|
+
// #7376: a Stop the provider acknowledged with a NORMAL result reaches here
|
|
2206
|
+
// with a generic reason, because the path that ended the turn did not know a
|
|
2207
|
+
// Stop had been requested. The turn-scoped flag does, and the tools still
|
|
2208
|
+
// unresolved were cut off by it.
|
|
2209
|
+
//
|
|
2210
|
+
// ONLY on a normal completion -- the caller says so with
|
|
2211
|
+
// `completion: 'normal'`, and nothing else is inferred. A failure cleanup
|
|
2212
|
+
// (a query that threw, a child that died, a destroy) has already observed
|
|
2213
|
+
// its own outcome, and a Stop that lands while it is still awaiting
|
|
2214
|
+
// something (the SDK's container classification) must not relabel that
|
|
2215
|
+
// outcome as the user's doing. An explicit termination reason is never
|
|
2216
|
+
// overridden either.
|
|
2217
|
+
if (completion === 'normal' && this._stopRequestedThisTurn && !isTurnTerminationReason(reason)) {
|
|
2218
|
+
reason = 'user_stop'
|
|
2219
|
+
}
|
|
2220
|
+
let count = 0
|
|
2221
|
+
for (const [toolUseId] of [...this._inFlightToolStarts]) {
|
|
2222
|
+
// #7340: a confirmed-backgrounded subagent that has not reported back is
|
|
2223
|
+
// NOT an orphan -- it is running. Synthesising an `isError` result for it
|
|
2224
|
+
// would report a failure that did not happen and terminate its activity
|
|
2225
|
+
// node. Its `tool_start` stays in flight, to be swept by whichever turn
|
|
2226
|
+
// end or death path finally does complete it.
|
|
2227
|
+
if (exempt && exempt.has(toolUseId)) continue
|
|
2228
|
+
count++
|
|
2229
|
+
this._inFlightToolStarts.delete(toolUseId)
|
|
2230
|
+
const terminated = isTurnTerminationReason(reason)
|
|
1534
2231
|
this.emit('tool_result', {
|
|
1535
2232
|
toolUseId,
|
|
1536
|
-
|
|
2233
|
+
// #8252: plain words only. The sweep reason is a slug and the fact that
|
|
2234
|
+
// the daemon fabricated this result is bookkeeping, so neither is in the
|
|
2235
|
+
// text a person reads. They stay on the in-process event as `reason` and
|
|
2236
|
+
// `synthetic` for listeners on the session; the wire
|
|
2237
|
+
// (`event-normalizer.js`) and the persisted history
|
|
2238
|
+
// (`session-message-history.js`) carry only `isError` and
|
|
2239
|
+
// `terminatedReason`, so a non-terminated sweep's slug does not leave the
|
|
2240
|
+
// process. The tool's name is already on the row.
|
|
2241
|
+
result: terminated
|
|
2242
|
+
? describeTurnTermination(reason).summary
|
|
2243
|
+
: UNFINISHED_TOOL_RESULT_TEXT,
|
|
1537
2244
|
truncated: false,
|
|
1538
2245
|
synthetic: true,
|
|
1539
2246
|
interrupted: true,
|
|
1540
2247
|
isError: true,
|
|
1541
2248
|
reason,
|
|
2249
|
+
...(terminated ? { terminatedReason: reason } : {}),
|
|
1542
2250
|
})
|
|
1543
2251
|
}
|
|
1544
|
-
this._inFlightToolStarts.clear()
|
|
1545
2252
|
return count
|
|
1546
2253
|
}
|
|
1547
2254
|
|
|
@@ -1556,9 +2263,12 @@ export class BaseSession extends EventEmitter {
|
|
|
1556
2263
|
*
|
|
1557
2264
|
* @param {object} payload — the result event payload ({cost, duration, usage, sessionId})
|
|
1558
2265
|
* @param {string} [sweepReason] — optional override for the sweep reason
|
|
2266
|
+
* @param {{ completion?: 'normal' }} [opts] — #7376: `completion: 'normal'`
|
|
2267
|
+
* says the turn ended with the provider's own `result`; see
|
|
2268
|
+
* `_sweepUnresolvedToolStarts` for what that permits.
|
|
1559
2269
|
*/
|
|
1560
|
-
_emitResult(payload, sweepReason = 'stream_completed_without_result') {
|
|
1561
|
-
this._sweepUnresolvedToolStarts(sweepReason)
|
|
2270
|
+
_emitResult(payload, sweepReason = 'stream_completed_without_result', opts = {}) {
|
|
2271
|
+
this._sweepUnresolvedToolStarts(sweepReason, null, opts)
|
|
1562
2272
|
// queueLength is stamped centrally in the emit() override below (#6627/#6706).
|
|
1563
2273
|
this.emit('result', payload)
|
|
1564
2274
|
}
|
|
@@ -1591,18 +2301,444 @@ export class BaseSession extends EventEmitter {
|
|
|
1591
2301
|
* @returns {boolean} whether the event had listeners (EventEmitter contract)
|
|
1592
2302
|
*/
|
|
1593
2303
|
emit(event, ...args) {
|
|
2304
|
+
if (PROVIDER_ACTIVITY_EVENT_SET.has(event)) this.noteProviderActivity()
|
|
2305
|
+
if (event === 'stopped') {
|
|
2306
|
+
// #8461: this Stop was already confirmed in place of the chip; not twice.
|
|
2307
|
+
if (this._stopAckedByResult) {
|
|
2308
|
+
this._stopAckedByResult = false
|
|
2309
|
+
return false
|
|
2310
|
+
}
|
|
2311
|
+
this._stoppedSinceStopRequest = true
|
|
2312
|
+
}
|
|
2313
|
+
let ackStop = false
|
|
1594
2314
|
if (event === 'result') {
|
|
1595
2315
|
let payload = args[0]
|
|
1596
2316
|
if (payload && typeof payload === 'object' && payload.queueLength === undefined) {
|
|
1597
2317
|
payload = { ...payload, queueLength: this._outgoingQueue ? this._outgoingQueue.length : 0 }
|
|
1598
2318
|
}
|
|
1599
2319
|
payload = normalizeResultDuration(payload)
|
|
2320
|
+
// #7326: the wire carries a closed vocabulary. Anything else a provider
|
|
2321
|
+
// puts on `turnOutcome` is dropped here rather than left to fail the
|
|
2322
|
+
// client's parse of the whole `result` frame.
|
|
2323
|
+
if (payload && typeof payload === 'object' && payload.turnOutcome !== undefined && !isTurnOutcome(payload.turnOutcome)) {
|
|
2324
|
+
const { turnOutcome: _dropped, ...rest } = payload
|
|
2325
|
+
payload = rest
|
|
2326
|
+
}
|
|
2327
|
+
// #8461: a requested Stop (the user's, or the scheduler's / orchestration
|
|
2328
|
+
// watchdog's, which also call `interrupt()`) is acknowledged by
|
|
2329
|
+
// `session_stopped` on every provider whose `interrupt()` ends the turn with
|
|
2330
|
+
// a `stopped` event (ACP, Codex, Gemini, ...). claude-sdk and claude-cli can
|
|
2331
|
+
// instead answer it with a NORMAL `result` carrying `terminal_reason:
|
|
2332
|
+
// aborted_*`, which maps to `stopped`; and then the SDK's catch branch (the
|
|
2333
|
+
// `stopped` emit) never runs. Left alone, only those two providers would
|
|
2334
|
+
// show a "Stopped" chip for a Stop that was asked for. The chip is for a turn
|
|
2335
|
+
// that ended UNDER the caller, so it is dropped and the quiet `stopped`
|
|
2336
|
+
// confirmation is sent in its place (once per Stop request, see
|
|
2337
|
+
// `_stoppedSinceStopRequest`). An agent that cancelled on its own (ACP
|
|
2338
|
+
// `cancelled`) keeps its chip.
|
|
2339
|
+
this._stopAckedByResult = false
|
|
2340
|
+
// #7072: a result whose outcome is `stopped` is terminal but NOT a success,
|
|
2341
|
+
// and an orchestration TurnDriver hears nothing else for the turn -- the
|
|
2342
|
+
// `stopped` that follows it (acknowledgement below, or a provider's own) lands
|
|
2343
|
+
// after the driver has already settled. Mark it here, before the chip is
|
|
2344
|
+
// dropped for a requested Stop, so every provider that maps an abort onto a
|
|
2345
|
+
// result gets it. Internal only: event-normalizer whitelists the wire fields.
|
|
2346
|
+
if (payload && typeof payload === 'object' && payload.turnOutcome === 'stopped' && payload.interrupted !== true) {
|
|
2347
|
+
payload = { ...payload, interrupted: true }
|
|
2348
|
+
}
|
|
2349
|
+
if (payload && typeof payload === 'object' && payload.turnOutcome === 'stopped' && this._stopRequestedThisTurn) {
|
|
2350
|
+
const { turnOutcome: _userStop, ...rest } = payload
|
|
2351
|
+
payload = rest
|
|
2352
|
+
ackStop = !this._stoppedSinceStopRequest
|
|
2353
|
+
}
|
|
2354
|
+
// #7326: a marked outcome (anything but `completed`) becomes a chip in the
|
|
2355
|
+
// transcript, and the chip needs an identity that the live `result` frame
|
|
2356
|
+
// and the history entry replayed later AGREE on -- a `result` has no id, and
|
|
2357
|
+
// without one a reconnect that replays the turn the client already watched
|
|
2358
|
+
// would add a second chip. The timestamp is stamped ONCE, here, and both
|
|
2359
|
+
// the event normalizer and the history ring read it off this payload.
|
|
2360
|
+
if (payload && typeof payload === 'object' && isTurnOutcome(payload.turnOutcome) && payload.turnOutcome !== 'completed'
|
|
2361
|
+
&& typeof payload.timestamp !== 'number') {
|
|
2362
|
+
payload = { ...payload, timestamp: Date.now() }
|
|
2363
|
+
}
|
|
1600
2364
|
if (payload !== args[0]) args[0] = payload
|
|
1601
2365
|
}
|
|
1602
|
-
|
|
2366
|
+
const delivered = super.emit(event, ...args)
|
|
2367
|
+
if (ackStop) {
|
|
2368
|
+
this._stoppedSinceStopRequest = true
|
|
2369
|
+
this._stopAckedByResult = true
|
|
2370
|
+
super.emit('stopped', {})
|
|
2371
|
+
}
|
|
2372
|
+
return delivered
|
|
2373
|
+
}
|
|
2374
|
+
|
|
2375
|
+
/**
|
|
2376
|
+
* How many permission requests are waiting on a human for this session,
|
|
2377
|
+
* across both routes: the hook-routed ids (CLI / TUI, #2831) and the
|
|
2378
|
+
* in-process PermissionManager's map that `wirePermissionManager` installs
|
|
2379
|
+
* as `_pendingPermissions` (SDK / BYOK / Codex).
|
|
2380
|
+
*
|
|
2381
|
+
* A read-only count for callers outside the session — the idle-only
|
|
2382
|
+
* auto-deploy probe (#8324) — so they never reach into either private field.
|
|
2383
|
+
*
|
|
2384
|
+
* @returns {number}
|
|
2385
|
+
*/
|
|
2386
|
+
getPendingPermissionCount() {
|
|
2387
|
+
const inProcess = this._pendingPermissions instanceof Map ? this._pendingPermissions.size : 0
|
|
2388
|
+
return this._pendingPermissionIds.size + inProcess
|
|
2389
|
+
}
|
|
2390
|
+
|
|
2391
|
+
/**
|
|
2392
|
+
* #8743: record that the provider just produced output. The emit() override
|
|
2393
|
+
* calls it for every PROVIDER_ACTIVITY_EVENTS event; a provider calls it
|
|
2394
|
+
* directly for input that maps to no event (a Codex sub-agent's notifications,
|
|
2395
|
+
* or a straggler from a turn codex already ended), which is exactly the
|
|
2396
|
+
* activity the turn bookkeeping cannot see.
|
|
2397
|
+
*/
|
|
2398
|
+
noteProviderActivity() {
|
|
2399
|
+
this._providerActivityAtMs = this._providerActivityClock()
|
|
2400
|
+
}
|
|
2401
|
+
|
|
2402
|
+
/**
|
|
2403
|
+
* #8743: the clock `noteProviderActivity` stamps with. Monotonic, so a wall
|
|
2404
|
+
* clock step cannot make recent activity look old. A test replaces it on the
|
|
2405
|
+
* instance to move time.
|
|
2406
|
+
* @returns {number}
|
|
2407
|
+
*/
|
|
2408
|
+
_providerActivityClock() {
|
|
2409
|
+
return Math.trunc(performance.now())
|
|
2410
|
+
}
|
|
2411
|
+
|
|
2412
|
+
/**
|
|
2413
|
+
* #8743: how long ago the provider last produced output, in ms, or null when
|
|
2414
|
+
* it has not since this session object was created. The idle-only auto-deploy
|
|
2415
|
+
* holds off a restart while this is recent (daemon-idle-state.js).
|
|
2416
|
+
* @returns {number|null}
|
|
2417
|
+
*/
|
|
2418
|
+
get providerActivityAgeMs() {
|
|
2419
|
+
if (this._providerActivityAtMs === null) return null
|
|
2420
|
+
return Math.max(0, this._providerActivityClock() - this._providerActivityAtMs)
|
|
2421
|
+
}
|
|
2422
|
+
|
|
2423
|
+
/**
|
|
2424
|
+
* Work a daemon restart would lose that `isBusy` does not report (#8324).
|
|
2425
|
+
*
|
|
2426
|
+
* `isBusy` is "a turn is running or a background shell is tracked". A restart
|
|
2427
|
+
* can also cut off a background agent that outlived its turn (`_activeAgents`
|
|
2428
|
+
* keeps it after `_clearMessageState({ turnEndedCleanly: true })`) and input
|
|
2429
|
+
* the session has accepted but not yet dispatched (`_outgoingQueue`, which
|
|
2430
|
+
* every provider shares for mid-turn sends). Subclasses with a queue or an
|
|
2431
|
+
* input path of their own extend this list; they call `super` first.
|
|
2432
|
+
*
|
|
2433
|
+
* Fail-closed contract for callers: an empty array means nothing blocks a
|
|
2434
|
+
* restart, so an override must never return `[]` merely because it could not
|
|
2435
|
+
* check — throw instead.
|
|
2436
|
+
*
|
|
2437
|
+
* @returns {string[]} human-readable reasons; empty = nothing blocks a restart
|
|
2438
|
+
*/
|
|
2439
|
+
getRestartBlockers() {
|
|
2440
|
+
const reasons = []
|
|
2441
|
+
const agents = this._activeAgents.size
|
|
2442
|
+
if (agents > 0) reasons.push(`${agents} active background agent(s)`)
|
|
2443
|
+
const queued = this._outgoingQueue.length
|
|
2444
|
+
if (queued > 0) reasons.push(`${queued} queued message(s) not yet dispatched`)
|
|
2445
|
+
return reasons
|
|
2446
|
+
}
|
|
2447
|
+
|
|
2448
|
+
/**
|
|
2449
|
+
* A hook-routed permission request belonging to this session is outstanding.
|
|
2450
|
+
* Called by ws-permissions when the hook's POST /permission is parked (#2831).
|
|
2451
|
+
*/
|
|
2452
|
+
notifyPermissionPending(requestId) {
|
|
2453
|
+
if (!requestId || this._pendingPermissionIds.has(requestId)) return
|
|
2454
|
+
this._pendingPermissionIds.add(requestId)
|
|
2455
|
+
if (this._pendingPermissionIds.size === 1) this._onFirstPermissionPending()
|
|
2456
|
+
}
|
|
2457
|
+
|
|
2458
|
+
/**
|
|
2459
|
+
* A hook-routed permission resolved (allow / deny / expired). Called by
|
|
2460
|
+
* ws-permissions' shared cleanup on every resolution path.
|
|
2461
|
+
*/
|
|
2462
|
+
notifyPermissionResolved(requestId) {
|
|
2463
|
+
if (!requestId || !this._pendingPermissionIds.has(requestId)) return
|
|
2464
|
+
this._pendingPermissionIds.delete(requestId)
|
|
2465
|
+
if (this._pendingPermissionIds.size === 0) this._onLastPermissionResolved()
|
|
2466
|
+
}
|
|
2467
|
+
|
|
2468
|
+
/**
|
|
2469
|
+
* Emit `permission_expired` for every prompt this session is still blocked on,
|
|
2470
|
+
* then drop the bookkeeping (#2831, #7375, generalised in #7382).
|
|
2471
|
+
*
|
|
2472
|
+
* A prompt outlives its turn on BOTH sides and neither says so: the client
|
|
2473
|
+
* card stays live until its own expiry, and the daemon's HTTP entry is not
|
|
2474
|
+
* released by the child dying, because killing the child does not signal the
|
|
2475
|
+
* hook's `curl` grandchild. Emitting here drives both — the clients retire the
|
|
2476
|
+
* card, and #7381's `release_permission` after-effect releases the daemon
|
|
2477
|
+
* entry so a reconnect cannot resurrect it.
|
|
2478
|
+
*
|
|
2479
|
+
* Call it from the provider's turn-end FUNNEL, not from hand-enumerated death
|
|
2480
|
+
* sites. Enumerating by hand is what missed the plain `result` path and the
|
|
2481
|
+
* interrupt-safety timeout in #7375.
|
|
2482
|
+
*
|
|
2483
|
+
* @param {string} message Reason forwarded on the wire (clients log it; the
|
|
2484
|
+
* user-visible copy is fixed client-side). Falsy or empty is coerced to a
|
|
2485
|
+
* generic reason — the wire schema declares `message: z.string()`, so an
|
|
2486
|
+
* empty one would fail validation at the client.
|
|
2487
|
+
*/
|
|
2488
|
+
_expirePendingPermissions(message) {
|
|
2489
|
+
if (this._pendingPermissionIds.size === 0) return
|
|
2490
|
+
// The doc below used to say `message` must be non-empty "because the wire
|
|
2491
|
+
// schema requires it" and then not enforce it — a comment describing a
|
|
2492
|
+
// stronger guarantee than the code delivers, which is the defect class this
|
|
2493
|
+
// whole change belongs to. ServerPermissionExpiredSchema declares
|
|
2494
|
+
// `message: z.string()`, so a caller passing '' or undefined would emit a
|
|
2495
|
+
// frame that fails validation at the client. Default rather than throw: the
|
|
2496
|
+
// callers are turn-teardown paths, and taking a session down over a missing
|
|
2497
|
+
// log string would be a worse failure than a generic one.
|
|
2498
|
+
const reason = typeof message === 'string' && message.length > 0
|
|
2499
|
+
? message
|
|
2500
|
+
: 'Permission request expired (the turn it belonged to ended)'
|
|
2501
|
+
for (const requestId of this._pendingPermissionIds) {
|
|
2502
|
+
this.emit('permission_expired', { requestId, message: reason })
|
|
2503
|
+
}
|
|
2504
|
+
this._pendingPermissionIds.clear()
|
|
2505
|
+
this._onPendingPermissionsAbandoned()
|
|
1603
2506
|
}
|
|
1604
2507
|
|
|
1605
|
-
|
|
2508
|
+
/**
|
|
2509
|
+
* Timer hooks for the pending-permission lifecycle. No-ops by default: the
|
|
2510
|
+
* bookkeeping above is provider-agnostic, but "don't time out while the user
|
|
2511
|
+
* is being asked" is not — CliSession pauses its inactivity trio, while
|
|
2512
|
+
* ClaudeTuiSession suspends only its silence backstops (for these prompts
|
|
2513
|
+
* and, through its own mechanism, for a pending AskUserQuestion) and
|
|
2514
|
+
* deliberately keeps its hard cap armed.
|
|
2515
|
+
*
|
|
2516
|
+
* Kept as THREE hooks rather than one because the abandon path must NOT
|
|
2517
|
+
* re-arm: the turn it belonged to is over. Collapsing them re-creates the
|
|
2518
|
+
* #7375 regression where a cleared pause left the safety timers wedged.
|
|
2519
|
+
*/
|
|
2520
|
+
_onFirstPermissionPending() {}
|
|
2521
|
+
_onLastPermissionResolved() {}
|
|
2522
|
+
_onPendingPermissionsAbandoned() {}
|
|
2523
|
+
|
|
2524
|
+
/**
|
|
2525
|
+
* #7340: finalize a tracked subagent by its `tool_use_id` -- the ONE
|
|
2526
|
+
* implementation of "this agent is done". Drops it from `_activeAgents` and
|
|
2527
|
+
* balances its `agent_spawned` with a matching `agent_completed`.
|
|
2528
|
+
*
|
|
2529
|
+
* Idempotent (guarded on `has`), which is what lets an optimistic finalize
|
|
2530
|
+
* and the provider's natural terminal signal both call it without emitting a
|
|
2531
|
+
* duplicate completion.
|
|
2532
|
+
*
|
|
2533
|
+
* This matters more since backgrounded agents stopped being swept at turn
|
|
2534
|
+
* end: the sweep used to be a backstop that eventually cleared everything, so
|
|
2535
|
+
* a missed finalize was invisible. It is now the ONLY way a backgrounded
|
|
2536
|
+
* agent clears, and a provider that tracks a background spawn without wiring
|
|
2537
|
+
* a terminal signal leaves the session claiming to be working forever.
|
|
2538
|
+
*
|
|
2539
|
+
* @param {unknown} toolUseId
|
|
2540
|
+
* @param {{ reason?: string }} [opts]
|
|
2541
|
+
* @protected
|
|
2542
|
+
*/
|
|
2543
|
+
_completeAgent(toolUseId, { reason } = {}) {
|
|
2544
|
+
if (typeof toolUseId !== 'string' || !toolUseId) return
|
|
2545
|
+
if (!this._activeAgents.has(toolUseId)) return
|
|
2546
|
+
this._activeAgents.delete(toolUseId)
|
|
2547
|
+
// #7396: `reason` is present only when the session ENDED the agent itself
|
|
2548
|
+
// (a watchdog gave up waiting for the provider's signal) rather than the
|
|
2549
|
+
// provider reporting it finished. In-process only: the wire message is built
|
|
2550
|
+
// field by field in event-normalizer and carries just the id.
|
|
2551
|
+
this.emit('agent_completed', reason ? { toolUseId, reason } : { toolUseId })
|
|
2552
|
+
}
|
|
2553
|
+
|
|
2554
|
+
/**
|
|
2555
|
+
* #7340: complete tracked subagents in bulk and report which ones survived.
|
|
2556
|
+
*
|
|
2557
|
+
* The ONE implementation of "drain the agent map", shared by the turn-end
|
|
2558
|
+
* sweep and by the provider-death sites that cannot reach that sweep. Emits a
|
|
2559
|
+
* balancing `agent_completed` for every agent it drops, so a client's badge
|
|
2560
|
+
* clears whichever route got here.
|
|
2561
|
+
*
|
|
2562
|
+
* `exempt` is the set of ids to spare, computed ONCE by `_clearMessageState`
|
|
2563
|
+
* and shared with the orphan sweep so the two cannot disagree about what is
|
|
2564
|
+
* still running. Default empty -- a bare call is a total drain, which is what
|
|
2565
|
+
* every death path wants.
|
|
2566
|
+
*
|
|
2567
|
+
* Keyed by the MAP KEY, not `agent.toolUseId`: a record whose field has
|
|
2568
|
+
* drifted from its key would otherwise leak and complete the wrong id.
|
|
2569
|
+
*
|
|
2570
|
+
* Every agent it completes emits `agent_completed`, which the registry turns
|
|
2571
|
+
* into a node termination AND a clearing of that agent's outlives-turn mark
|
|
2572
|
+
* -- which is what lets `ActivityRegistry.reset()` simply read the marks
|
|
2573
|
+
* afterwards instead of being handed a second copy of this predicate.
|
|
2574
|
+
*
|
|
2575
|
+
* @param {{ exempt?: Set<string> }} [opts]
|
|
2576
|
+
* @protected
|
|
2577
|
+
*/
|
|
2578
|
+
_completeAgents({ exempt = null } = {}) {
|
|
2579
|
+
for (const toolUseId of [...this._activeAgents.keys()]) {
|
|
2580
|
+
if (exempt && exempt.has(toolUseId)) continue
|
|
2581
|
+
this._activeAgents.delete(toolUseId)
|
|
2582
|
+
this.emit('agent_completed', { toolUseId })
|
|
2583
|
+
}
|
|
2584
|
+
}
|
|
2585
|
+
|
|
2586
|
+
/**
|
|
2587
|
+
* #7340: record a spawned subagent and announce it. Shared by every provider
|
|
2588
|
+
* that reads the Agent/Task tool off a Claude Code stream, so the record
|
|
2589
|
+
* shape (notably `backgroundConfirmed`, which decides whether the turn-end
|
|
2590
|
+
* sweep may complete it) cannot drift between them.
|
|
2591
|
+
*
|
|
2592
|
+
* Re-registering an already-tracked id UPGRADES the record rather than
|
|
2593
|
+
* replacing it, and re-emits nothing. That is the `task_started` case: the
|
|
2594
|
+
* tool_use block arrives first and carries `run_in_background`, then
|
|
2595
|
+
* `task_started` arrives with `is_backgrounded`. Whichever order they land
|
|
2596
|
+
* in, exactly one `agent_spawned` is emitted.
|
|
2597
|
+
*
|
|
2598
|
+
* TWO fields, because the two producers do not carry the same authority and
|
|
2599
|
+
* collapsing them is what would strand an agent:
|
|
2600
|
+
*
|
|
2601
|
+
* - `background` -- best-known value. The tool input's `run_in_background`
|
|
2602
|
+
* is the model's REQUEST; `task_started`'s `is_backgrounded` is what the
|
|
2603
|
+
* provider actually did. (`is_backgrounded` is ABSENT on a foreground
|
|
2604
|
+
* spawn, not `false`, so every producer compares with a strict `=== true`
|
|
2605
|
+
* -- that derivation is what the parser tests pin.)
|
|
2606
|
+
* - `backgroundConfirmed` -- set ONLY from `task_started` (`authoritative:
|
|
2607
|
+
* true`). This, not `background`, is what exempts an agent from the
|
|
2608
|
+
* turn-end sweep, and the reason is a liveness one rather than a
|
|
2609
|
+
* correctness one: `task_notification` is the ONLY signal that clears a
|
|
2610
|
+
* backgrounded agent, and a provider build that emits no task lifecycle
|
|
2611
|
+
* messages at all emits neither. `task_started` having arrived is
|
|
2612
|
+
* therefore the evidence that a terminal signal CAN arrive. Exempting on
|
|
2613
|
+
* the model's unconfirmed request would pin such a session as "working"
|
|
2614
|
+
* until the provider dies -- which #7340 names as the worse failure.
|
|
2615
|
+
* (`cancelActivity` already feature-detects those builds the same way.)
|
|
2616
|
+
*
|
|
2617
|
+
* The upgrade is asymmetric for the same reason. A non-authoritative signal
|
|
2618
|
+
* may only raise `background` (`false` never overwrites `true`), because the
|
|
2619
|
+
* two producers can land in either order and the tool input carries no news
|
|
2620
|
+
* when it disagrees. An authoritative one OVERWRITES in both directions --
|
|
2621
|
+
* `task_started` is the provider's own account and must be able to correct
|
|
2622
|
+
* the model's request DOWNWARD, or an agent the model asked to background
|
|
2623
|
+
* and the provider ran in the foreground is exempted from the sweep it needs.
|
|
2624
|
+
*
|
|
2625
|
+
* @param {{ toolUseId: string, description?: string, background?: boolean, authoritative?: boolean, startedAt?: number }} info
|
|
2626
|
+
* @protected
|
|
2627
|
+
*/
|
|
2628
|
+
_trackAgent({ toolUseId, description = 'Background task', background = false, authoritative = false, startedAt = Date.now() } = {}) {
|
|
2629
|
+
if (typeof toolUseId !== 'string' || !toolUseId) return
|
|
2630
|
+
const existing = this._activeAgents.get(toolUseId)
|
|
2631
|
+
if (existing) {
|
|
2632
|
+
if (authoritative === true) {
|
|
2633
|
+
existing.background = background === true
|
|
2634
|
+
existing.backgroundConfirmed = background === true
|
|
2635
|
+
// #7340: the registry is TOLD, never left to re-derive. This is the
|
|
2636
|
+
// upgrade path -- `task_started` landing after the tool_use block --
|
|
2637
|
+
// and it emits no event, so without this call the activity node would
|
|
2638
|
+
// never learn that it outlives its turn.
|
|
2639
|
+
this._activity.setAgentOutlivesTurn(toolUseId, existing.backgroundConfirmed)
|
|
2640
|
+
} else if (background === true) {
|
|
2641
|
+
existing.background = true
|
|
2642
|
+
}
|
|
2643
|
+
return
|
|
2644
|
+
}
|
|
2645
|
+
// Clamp HERE, not in each caller. `task_started`'s `description` is
|
|
2646
|
+
// provider-supplied and reaches the wire verbatim via `agent_spawned`;
|
|
2647
|
+
// only the tool-input path was clamped before, so the second producer
|
|
2648
|
+
// #7340 added would have shipped an unbounded field (the wire schema
|
|
2649
|
+
// declares `description: z.string().optional()` with no max, so nothing
|
|
2650
|
+
// downstream would have caught it either).
|
|
2651
|
+
const agentInfo = {
|
|
2652
|
+
toolUseId,
|
|
2653
|
+
description: String(description).slice(0, AGENT_DESCRIPTION_MAX),
|
|
2654
|
+
startedAt,
|
|
2655
|
+
background: background === true,
|
|
2656
|
+
backgroundConfirmed: authoritative === true && background === true,
|
|
2657
|
+
}
|
|
2658
|
+
this._activeAgents.set(toolUseId, agentInfo)
|
|
2659
|
+
this.emit('agent_spawned', agentInfo)
|
|
2660
|
+
// #7340: after the spawn, so the node exists to be marked. The other
|
|
2661
|
+
// arrival order (`task_started` first) is handled by the upgrade above.
|
|
2662
|
+
if (agentInfo.backgroundConfirmed) this._activity.setAgentOutlivesTurn(toolUseId, true)
|
|
2663
|
+
}
|
|
2664
|
+
|
|
2665
|
+
/**
|
|
2666
|
+
* #7340 / #7396: the subagents that outlive a turn end -- `null` (nothing
|
|
2667
|
+
* survives, a total drain) unless the provider itself reported the turn over.
|
|
2668
|
+
*
|
|
2669
|
+
* The ONE implementation of the survival predicate, shared by
|
|
2670
|
+
* `_clearMessageState` and by providers whose turn end does not run through it
|
|
2671
|
+
* (claude-tui's Stop-hook path). A second copy of "backgroundConfirmed and the
|
|
2672
|
+
* turn ended cleanly" is how two providers come to disagree about what
|
|
2673
|
+
* "survives" means. Opt-IN for the same reason `_clearMessageState`'s
|
|
2674
|
+
* `turnEndedCleanly` is: a caller that forgets to pass it gets the sweep.
|
|
2675
|
+
*
|
|
2676
|
+
* @param {boolean} turnEndedCleanly
|
|
2677
|
+
* @returns {Set<string> | null}
|
|
2678
|
+
* @protected
|
|
2679
|
+
*/
|
|
2680
|
+
_survivingAgentIds(turnEndedCleanly) {
|
|
2681
|
+
if (turnEndedCleanly !== true) return null
|
|
2682
|
+
return new Set(
|
|
2683
|
+
[...this._activeAgents]
|
|
2684
|
+
.filter(([, agent]) => agent?.backgroundConfirmed === true)
|
|
2685
|
+
.map(([toolUseId]) => toolUseId),
|
|
2686
|
+
)
|
|
2687
|
+
}
|
|
2688
|
+
|
|
2689
|
+
/**
|
|
2690
|
+
* Clear per-message state at the end of a turn.
|
|
2691
|
+
*
|
|
2692
|
+
* @param {{ turnEndedCleanly?: boolean }} [opts]
|
|
2693
|
+
* `turnEndedCleanly` says the PROVIDER IS STILL ALIVE and reported the turn
|
|
2694
|
+
* over itself -- the stream-json `result` message, and nothing else. It is
|
|
2695
|
+
* the only thing that permits a confirmed-backgrounded subagent to survive
|
|
2696
|
+
* the sweep below (#7340).
|
|
2697
|
+
*
|
|
2698
|
+
* It is opt-IN, and that direction is the whole safety argument. Fourteen
|
|
2699
|
+
* call sites reach this method and all but two are a provider that DIED --
|
|
2700
|
+
* Stop/SIGINT, a child crash, `_killAndRespawn`, the SDK hard timeout,
|
|
2701
|
+
* stream-stall recovery, `interrupt()`, `destroy()`, a failed stdin write.
|
|
2702
|
+
* `task_notification` can never arrive on any of them, so an agent exempted
|
|
2703
|
+
* there is stranded and the session claims to be working for the rest of
|
|
2704
|
+
* the daemon's life. Defaulting to the sweep means a call site nobody
|
|
2705
|
+
* updated -- including a death path added years from now -- inherits the
|
|
2706
|
+
* RECOVERABLE failure (a badge cleared early) rather than the unrecoverable
|
|
2707
|
+
* one. #7340 names stuck-busy as the worse of the two, and it is.
|
|
2708
|
+
*
|
|
2709
|
+
* Subclasses that override this MUST forward the opts to `super`. One that
|
|
2710
|
+
* drops them fails safe (it sweeps), which is why the forwarding is a
|
|
2711
|
+
* correctness nicety here rather than a hazard.
|
|
2712
|
+
*
|
|
2713
|
+
* @param {{ turnEndedCleanly?: boolean, terminatedReason?: string, completion?: 'normal' }} [opts]
|
|
2714
|
+
* `completion: 'normal'` (#7376) says the turn ended with the provider's own
|
|
2715
|
+
* `result`. Only then may a Stop requested during the turn tag the tools it
|
|
2716
|
+
* left unresolved as `user_stop`: every other caller is a failure or teardown
|
|
2717
|
+
* path that has already observed its own outcome, and keeps it.
|
|
2718
|
+
*
|
|
2719
|
+
* `terminatedReason` (#7376) is WHY the turn is being ended underneath
|
|
2720
|
+
* whatever tool is still in flight -- a `TURN_TERMINATION_REASONS` value
|
|
2721
|
+
* (`permission_mode_switch`, `user_stop`, `process_exit`, ...). It becomes
|
|
2722
|
+
* the orphan sweep's reason, so the synthetic `tool_result` of each such
|
|
2723
|
+
* tool says "the turn was terminated" rather than looking like a failed
|
|
2724
|
+
* command. The CALLER supplies it, never this method: it is shared by every
|
|
2725
|
+
* death path (and Stop, where the user already knows why), so inferring it
|
|
2726
|
+
* here would mislabel. Omitted on the paths that have no considered cause --
|
|
2727
|
+
* those keep the generic `message_state_cleared` sweep.
|
|
2728
|
+
*/
|
|
2729
|
+
_clearMessageState({ turnEndedCleanly = false, terminatedReason, completion } = {}) {
|
|
2730
|
+
// #7382 (review): expire HERE, so inheriting the bookkeeping also inherits
|
|
2731
|
+
// the BEHAVIOUR. Hoisting the API alone bought a new provider the methods
|
|
2732
|
+
// and none of the wiring — and the roster guard, which only checked that
|
|
2733
|
+
// the methods existed, passed for a provider that never called them. A
|
|
2734
|
+
// check that passes for everything is #7273's shape.
|
|
2735
|
+
//
|
|
2736
|
+
// Idempotent (no-op on an empty set), so providers that already expired at
|
|
2737
|
+
// an earlier point in their teardown are unaffected.
|
|
2738
|
+
this._expirePendingPermissions('Permission request expired (the turn it belonged to ended before it was answered)')
|
|
2739
|
+
// #8430: a user Stop belongs to the turn it was pressed on. Every turn end,
|
|
2740
|
+
// abort and failure included, reaches here, so the next turn starts clear.
|
|
2741
|
+
this._permissions?.clearUserStopInFlight?.()
|
|
1606
2742
|
this._isBusy = false
|
|
1607
2743
|
this._currentMessageId = null
|
|
1608
2744
|
|
|
@@ -1623,15 +2759,34 @@ export class BaseSession extends EventEmitter {
|
|
|
1623
2759
|
// with a synthetic tool_result rather than silently dropped — so
|
|
1624
2760
|
// the dashboard's activeTools clears whether result fires next or
|
|
1625
2761
|
// never fires at all.
|
|
1626
|
-
this
|
|
1627
|
-
|
|
1628
|
-
//
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
2762
|
+
// #7340: the ids that will outlive this turn, computed ONCE and shared by
|
|
2763
|
+
// all three sweeps below so they cannot disagree. Empty on every
|
|
2764
|
+
// provider-death path, which is what makes those a total drain.
|
|
2765
|
+
//
|
|
2766
|
+
// Computed BEFORE the orphan sweep, and that ordering is load-bearing: the
|
|
2767
|
+
// sweep fabricates a `tool_result` with `isError: true` for every
|
|
2768
|
+
// unresolved `tool_start`, and a backgrounded subagent that has not
|
|
2769
|
+
// reported back yet looks exactly like an orphan. Sweeping it told the
|
|
2770
|
+
// client the subagent had failed -- while it was running fine -- and ended
|
|
2771
|
+
// its activity node on the way past.
|
|
2772
|
+
const survivingAgents = this._survivingAgentIds(turnEndedCleanly)
|
|
2773
|
+
|
|
2774
|
+
this._sweepUnresolvedToolStarts(
|
|
2775
|
+
isTurnTerminationReason(terminatedReason) ? terminatedReason : 'message_state_cleared',
|
|
2776
|
+
survivingAgents,
|
|
2777
|
+
{ completion },
|
|
2778
|
+
)
|
|
2779
|
+
// #7376: the turn is over; a Stop requested during it must not tag the next.
|
|
2780
|
+
this._stopRequestedThisTurn = false
|
|
2781
|
+
|
|
2782
|
+
// #7340: complete the tracked subagents this turn end owns, and no more.
|
|
2783
|
+
// A confirmed-backgrounded subagent deliberately outlives its turn, so
|
|
2784
|
+
// completing it here would report finished work that is still running --
|
|
2785
|
+
// which is the bug #7340 was filed for. It survives ONLY when the provider
|
|
2786
|
+
// itself said the turn ended (see `turnEndedCleanly` above); on every death
|
|
2787
|
+
// path the sweep stays total, because the signal that would clear it later
|
|
2788
|
+
// can no longer arrive.
|
|
2789
|
+
this._completeAgents({ exempt: survivingAgents })
|
|
1635
2790
|
|
|
1636
2791
|
// #5160: turn-end reconciliation for the activity registry. Ends any
|
|
1637
2792
|
// tool/agent/blocked node still marked running/blocked (orphans the
|
|
@@ -1640,6 +2795,18 @@ export class BaseSession extends EventEmitter {
|
|
|
1640
2795
|
// terminate their nodes first; reset() is the belt-and-braces sweep for
|
|
1641
2796
|
// anything the canonical signals didn't clear. Shell nodes survive
|
|
1642
2797
|
// turn-end (#4307) and clear via background_work_changed.
|
|
2798
|
+
//
|
|
2799
|
+
// #7340: an agent that survived the sweep must survive `reset()` too, or
|
|
2800
|
+
// the two surfaces disagree -- AgentMonitorPanel says running while the
|
|
2801
|
+
// Control Room tree says done, and `cancelActivity` answers `not-found`
|
|
2802
|
+
// for the entire time the subagent runs. #4307 set this precedent one
|
|
2803
|
+
// branch above for shells, for the same reason.
|
|
2804
|
+
//
|
|
2805
|
+
// No argument: the registry reads its own outlives-turn marks, and
|
|
2806
|
+
// `_completeAgents` above has just cleared the mark of every agent it
|
|
2807
|
+
// completed (via `agent_completed`). So the set it spares is exactly the
|
|
2808
|
+
// set that survived here -- by construction rather than by a second copy
|
|
2809
|
+
// of the predicate.
|
|
1643
2810
|
this._activity.reset()
|
|
1644
2811
|
|
|
1645
2812
|
if (this._resultTimeout) {
|