@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/byok-session.js
CHANGED
|
@@ -15,10 +15,11 @@
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import Anthropic, { APIUserAbortError } from '@anthropic-ai/sdk'
|
|
18
|
-
import {
|
|
19
|
-
import { homedir } from 'os'
|
|
18
|
+
import { assertAuthorized, stillAuthorized } from './connection-authority.js'
|
|
20
19
|
import { performance } from 'node:perf_hooks'
|
|
21
|
-
import { BaseSession, buildBaseSessionOpts } from './base-session.js'
|
|
20
|
+
import { BaseSession, buildBaseSessionOpts, reportInputAdmission } from './base-session.js'
|
|
21
|
+
import { BYOK_CUSTOMIZATION } from './provider-customization.js'
|
|
22
|
+
import { loadByokInstructionPolicy } from './instruction-policy.js'
|
|
22
23
|
import { synthesizeModelUsage } from './usage-normalize.js'
|
|
23
24
|
import { PermissionManager, wirePermissionManager } from './permission-manager.js'
|
|
24
25
|
import { createLogger } from './logger.js'
|
|
@@ -37,9 +38,11 @@ import { executeBuiltinTool } from './byok-tool-executor.js'
|
|
|
37
38
|
import {
|
|
38
39
|
addMcpServerToConfig,
|
|
39
40
|
defaultClaudeConfigPath,
|
|
40
|
-
|
|
41
|
+
discoverMcpServerSpecs,
|
|
42
|
+
mcpWriteScopeToSource,
|
|
41
43
|
planAddMcpServerToConfig,
|
|
42
44
|
removeMcpServerFromConfig,
|
|
45
|
+
mcpSourceToWriteScope,
|
|
43
46
|
toMcpServerMetadata,
|
|
44
47
|
validateMcpServerNameForRemoval,
|
|
45
48
|
validateNewMcpServerName,
|
|
@@ -53,6 +56,8 @@ import {
|
|
|
53
56
|
withTrustStoreLock,
|
|
54
57
|
} from './byok-mcp-trust.js'
|
|
55
58
|
import { getSubagentProfile, SUBAGENT_PROFILE_NAMES } from './byok-subagent-profiles.js'
|
|
59
|
+
import { configPath } from './config-dir.js'
|
|
60
|
+
import { turnOutcomeField, outcomeFromByokTurn } from './turn-outcome.js'
|
|
56
61
|
|
|
57
62
|
const log = createLogger('byok-session')
|
|
58
63
|
|
|
@@ -73,6 +78,15 @@ const MAX_HISTORY_TURNS = 50
|
|
|
73
78
|
// up an unbounded API bill.
|
|
74
79
|
const MAX_TOOL_ROUNDS = 25
|
|
75
80
|
|
|
81
|
+
// #8559: the assistant turn kept in history when a requested Stop lands before the
|
|
82
|
+
// model streamed any text. The API refuses an empty text block, and leaving the
|
|
83
|
+
// assistant slot out would put the stopped prompt and the next one back to back.
|
|
84
|
+
const STOPPED_BEFORE_TEXT = '[Interrupted by the user before any reply was produced.]'
|
|
85
|
+
// ...and the tool_result answering a tool_use whose result the Stop kept from being
|
|
86
|
+
// recorded. It may already have run (an earlier tool in the same round can complete
|
|
87
|
+
// before a later one throws), so the model is told to check, not that it did not run.
|
|
88
|
+
const STOPPED_BEFORE_TOOL = 'Interrupted by the user before this result was recorded. The tool may or may not have run; check its effects before running it again.'
|
|
89
|
+
|
|
76
90
|
// TTL for the per-session realpath cache used by validatePathWithinCwd
|
|
77
91
|
// in the tool executor. The cwd shouldn't change mid-session, but caching
|
|
78
92
|
// for 30s strikes a balance between safety (re-stat to catch a swap) and
|
|
@@ -109,9 +123,40 @@ function boundMcpPromptExpansionText(text, cap = MCP_PROMPT_EXPANSION_DISPLAY_CA
|
|
|
109
123
|
if (s.length <= cap) return { text: s, truncated: false }
|
|
110
124
|
const sliceLen = Math.max(0, cap - MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX.length)
|
|
111
125
|
return { text: `${s.slice(0, sliceLen)}${MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX}`, truncated: true }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Provider factories that add a layer above ClaudeByokSession must preserve
|
|
129
|
+
// both the BaseSession contract and BYOK's own constructor-only options. The
|
|
130
|
+
// BaseSession picker alone intentionally cannot know about MCP discovery or
|
|
131
|
+
// project-instruction loading, so using it directly in a BYOK subclass would
|
|
132
|
+
// silently drop those controls before ClaudeByokSession can consume them.
|
|
133
|
+
export const BYOK_SESSION_LOCAL_OPT_KEYS = Object.freeze([
|
|
134
|
+
'mcpConfigPath',
|
|
135
|
+
'disabledMcpServers',
|
|
136
|
+
'mcpToolCallTimeoutMs',
|
|
137
|
+
'mcpStartCapMs',
|
|
138
|
+
'_mcpConfigFsync',
|
|
139
|
+
'loadProjectInstructions',
|
|
140
|
+
'_instructionPolicyLoader',
|
|
141
|
+
'_machineInstructionPath',
|
|
142
|
+
'_machineInstructionRoot',
|
|
143
|
+
])
|
|
144
|
+
|
|
145
|
+
export function buildByokSessionOpts(fullOpts = {}, overrides = {}) {
|
|
146
|
+
const picked = buildBaseSessionOpts(fullOpts)
|
|
147
|
+
for (const key of BYOK_SESSION_LOCAL_OPT_KEYS) {
|
|
148
|
+
if (key in fullOpts) picked[key] = fullOpts[key]
|
|
149
|
+
}
|
|
150
|
+
return { ...picked, ...overrides }
|
|
112
151
|
}
|
|
113
152
|
|
|
114
153
|
export class ClaudeByokSession extends BaseSession {
|
|
154
|
+
static get customizationDescriptor() {
|
|
155
|
+
return BYOK_CUSTOMIZATION
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
static agentConnectionRoutes = ['api']
|
|
159
|
+
static agentConnectionCredentialKey = 'ANTHROPIC_API_KEY'
|
|
115
160
|
// #5858: Claude-family flag — single source of truth for isClaudeProvider().
|
|
116
161
|
// DockerByokSession (docker-byok) extends this and correctly inherits it.
|
|
117
162
|
// NOTE: non-Claude providers that ALSO extend this for the agent loop
|
|
@@ -174,6 +219,8 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
174
219
|
// PermissionManager (same machinery as claude-sdk).
|
|
175
220
|
permissions: true,
|
|
176
221
|
inProcessPermissions: true,
|
|
222
|
+
permissionFloor: true,
|
|
223
|
+
autoPermissionMode: true,
|
|
177
224
|
modelSwitch: true,
|
|
178
225
|
permissionModeSwitch: true,
|
|
179
226
|
planMode: false,
|
|
@@ -184,6 +231,12 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
184
231
|
// Thinking config supported by the SDK but not wired through the
|
|
185
232
|
// chroxy UI yet — leave off until the toggle lands.
|
|
186
233
|
thinkingLevel: false,
|
|
234
|
+
// #7725: BYOK builds its own request and never calls
|
|
235
|
+
// detectThinkingKeyword — the magic words reach the model as plain prose.
|
|
236
|
+
// Inherited by the anthropic-compatible / openai-compatible factories,
|
|
237
|
+
// DeepSeek, Ollama and docker-byok, which all extend this class.
|
|
238
|
+
thinkingKeywords: false,
|
|
239
|
+
thinkingLevelEffective: false, // #8700: no report of the applied level
|
|
187
240
|
streaming: true,
|
|
188
241
|
// We rebuild the system prompt on every turn from
|
|
189
242
|
// _buildSystemPrompt(), so an activate/deactivate of a skill
|
|
@@ -198,8 +251,15 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
198
251
|
}
|
|
199
252
|
|
|
200
253
|
static get customEvents() {
|
|
201
|
-
// tool_start / tool_result
|
|
202
|
-
//
|
|
254
|
+
// #8574: `tool_start` / `tool_result` are deliberately NOT listed. They are
|
|
255
|
+
// PROXIED events (session-manager.js PROXIED_SESSION_EVENTS): the proxied
|
|
256
|
+
// listener forwards them AND records them to history, so listing them
|
|
257
|
+
// here added a second, transient listener and every frame reached the
|
|
258
|
+
// client twice. tool-events-overlap guard:
|
|
259
|
+
// tests/provider-custom-events-overlap.test.js.
|
|
260
|
+
//
|
|
261
|
+
// tool_input_delta is surfaced per turn for the dashboard's tool-call
|
|
262
|
+
// bubble UI. permission_request /
|
|
203
263
|
// user_question / permission_resolved are re-emitted from
|
|
204
264
|
// PermissionManager and already known to the SessionManager
|
|
205
265
|
// forwarding pipeline, but list them here so the capability matrix
|
|
@@ -224,7 +284,7 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
224
284
|
// accumulator and the final summary text becomes the parent's
|
|
225
285
|
// Task tool_result content; replaying it as a nested event would
|
|
226
286
|
// double-render the same content.
|
|
227
|
-
return ['
|
|
287
|
+
return ['tool_input_delta', 'agent_spawned', 'agent_completed', 'agent_event']
|
|
228
288
|
}
|
|
229
289
|
|
|
230
290
|
/**
|
|
@@ -237,7 +297,7 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
237
297
|
label: 'Claude (BYOK)',
|
|
238
298
|
credentials: {
|
|
239
299
|
envVars: ['ANTHROPIC_API_KEY'],
|
|
240
|
-
hint: `set ANTHROPIC_API_KEY or save it in ${
|
|
300
|
+
hint: `set ANTHROPIC_API_KEY or save it in ${configPath('credentials.json')} (mode 0600)`,
|
|
241
301
|
optional: false,
|
|
242
302
|
},
|
|
243
303
|
}
|
|
@@ -319,18 +379,28 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
319
379
|
* overrides (system prompt, settings) can be added as distinct named opts when
|
|
320
380
|
* any of them are actually used.
|
|
321
381
|
* @param {number} [opts.mcpToolCallTimeoutMs] Per-tools/call timeout; null/undefined = MCPClient default (30s).
|
|
382
|
+
* @param {Function} [opts._mcpConfigFsync] TEST-ONLY (#7070): `(target, { isDir }) => void` fsync
|
|
383
|
+
* seam forwarded to the MCP-config remove write, so a test can fail the post-rename directory
|
|
384
|
+
* fsync. Production never passes it; undefined keeps the real `fsyncForDurability`.
|
|
322
385
|
*/
|
|
323
386
|
constructor(opts = {}) {
|
|
324
387
|
super(buildBaseSessionOpts(opts, { provider: opts.provider || 'claude-byok' }))
|
|
325
388
|
// Anthropic SDK client; lazily instantiated in start() so unit tests
|
|
326
389
|
// can stub it via this._client = ... before start().
|
|
327
390
|
this._client = null
|
|
391
|
+
this._instructionPolicyLoader = opts._instructionPolicyLoader || loadByokInstructionPolicy
|
|
392
|
+
this._loadProjectInstructions = opts.loadProjectInstructions === true || Boolean(opts._instructionPolicyLoader)
|
|
393
|
+
this._machineInstructionPath = opts._machineInstructionPath
|
|
394
|
+
this._machineInstructionRoot = opts._machineInstructionRoot
|
|
395
|
+
this._instructionPolicyLoaded = false
|
|
328
396
|
// In-memory conversation history. Each entry is a Claude API message
|
|
329
397
|
// ({ role: 'user'|'assistant', content: <string|array> }). The SDK
|
|
330
398
|
// accepts either shape for user/assistant turns.
|
|
331
399
|
this._history = []
|
|
332
400
|
// AbortController for the active stream so interrupt() can cancel.
|
|
333
401
|
this._abortController = null
|
|
402
|
+
// #8553: this turn's abort was driven by a parent session (see interrupt()).
|
|
403
|
+
this._abortCascaded = false
|
|
334
404
|
|
|
335
405
|
// PermissionManager + event re-emission via the shared wiring (P2-9) so the
|
|
336
406
|
// dashboard / mobile permission UI and the audit log work uniformly across
|
|
@@ -363,24 +433,20 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
363
433
|
// pair" — not "one warn per current model."
|
|
364
434
|
this._pricingWarnedModels = new Set()
|
|
365
435
|
|
|
366
|
-
// #
|
|
367
|
-
// `
|
|
368
|
-
//
|
|
369
|
-
//
|
|
370
|
-
// on `content_block_stop
|
|
371
|
-
//
|
|
372
|
-
// the
|
|
373
|
-
//
|
|
374
|
-
//
|
|
375
|
-
//
|
|
376
|
-
this._streamingIndexToToolUseId = new Map()
|
|
377
|
-
|
|
378
|
-
// #6756: per-stream index → thinking messageId, mirroring the toolUseId map
|
|
379
|
-
// above. The translated `thinking_delta` events carry only the block index;
|
|
380
|
-
// this maps each thinking block's index to the distinct thinking id we open
|
|
381
|
-
// on its first delta so subsequent deltas + the content_block_stop route
|
|
382
|
-
// correctly. Cleared alongside `_streamingIndexToToolUseId`.
|
|
436
|
+
// #6756: per-stream index → thinking messageId. The translated
|
|
437
|
+
// `thinking_delta` events carry only the block index; this maps each
|
|
438
|
+
// thinking block's index to the distinct thinking id we open on its first
|
|
439
|
+
// delta so subsequent deltas + the content_block_stop route correctly.
|
|
440
|
+
// Entry is deleted on `content_block_stop`; the whole map is also cleared
|
|
441
|
+
// after each round and on every turn exit path. Kept inside the session
|
|
442
|
+
// (not the translator) per #4059's boundary call: the translator stays
|
|
443
|
+
// pure, stateful tracking lives here. (#8137 removed the matching
|
|
444
|
+
// index→toolUseId map: tool input is now read off `final.content`, so
|
|
445
|
+
// nothing resolves a streaming index back to a tool_use id any more.)
|
|
383
446
|
this._streamingIndexToThinkingId = new Map()
|
|
447
|
+
// #6630: the turn the thinking-stream counter below belongs to, and the counter.
|
|
448
|
+
this._thinkingSeqTurn = null
|
|
449
|
+
this._thinkingSeq = 0
|
|
384
450
|
|
|
385
451
|
// #6391 (chat-redesign footer-stat): thinking messageId → performance.now()
|
|
386
452
|
// when the reasoning block opened, so its content_block_stop can stamp the
|
|
@@ -438,6 +504,10 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
438
504
|
// leak into a future turn.
|
|
439
505
|
this._subagentUsageThisTurn = { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }
|
|
440
506
|
this._subagentCostThisTurn = 0
|
|
507
|
+
// #8569: tool_use ids whose `tool_result` event already went out this turn, so a
|
|
508
|
+
// Stop that settles `_history` with synthesized results closes only the rows
|
|
509
|
+
// still open and never emits a second result for a tool that has one.
|
|
510
|
+
this._toolResultsEmitted = new Set()
|
|
441
511
|
|
|
442
512
|
// #5018: per-session built-in tool allowlist. Set by _executeTaskTool
|
|
443
513
|
// ONLY on child sessions spawned with a `subagent_type` profile that
|
|
@@ -461,7 +531,21 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
461
531
|
// writes back to the SAME file this session read from (a test override or
|
|
462
532
|
// $CHROXY_CLAUDE_CONFIG must not be bypassed on the write half).
|
|
463
533
|
this._mcpConfigPath = opts.mcpConfigPath || defaultClaudeConfigPath()
|
|
464
|
-
|
|
534
|
+
// #7070: test-only fsync seam for the config write; see the constructor JSDoc.
|
|
535
|
+
this._mcpConfigFsync = opts._mcpConfigFsync
|
|
536
|
+
// #7112: `opts.mcpConfigPath === null` (a Task subagent, see
|
|
537
|
+
// `_executeTaskTool`) explicitly SKIPS discovery — the child does not
|
|
538
|
+
// parse a second copy of ~/.claude.json / <cwd>/.mcp.json and does not
|
|
539
|
+
// spawn its own fleet. `this.cwd` is set by the BaseSession super() call
|
|
540
|
+
// above, so it is available here. Resolves project scope
|
|
541
|
+
// (`projects[<realpath(cwd)>].mcpServers`), repo-local `.mcp.json`, and
|
|
542
|
+
// user root — the same three sources, in the same precedence order,
|
|
543
|
+
// `discoverConfiguredMcpServers` reads via the shared
|
|
544
|
+
// `readMcpSourcesInPrecedenceOrder` helper — instead of only ever
|
|
545
|
+
// reading the config's root `mcpServers` block.
|
|
546
|
+
const mcpConfig = opts.mcpConfigPath === null
|
|
547
|
+
? { servers: [], warnings: [] }
|
|
548
|
+
: discoverMcpServerSpecs(this.cwd, { configPath: this._mcpConfigPath })
|
|
465
549
|
for (const warning of mcpConfig.warnings) {
|
|
466
550
|
log.warn(`BYOK MCP config: ${warning}`)
|
|
467
551
|
}
|
|
@@ -535,7 +619,74 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
535
619
|
return getModelPricing(model)
|
|
536
620
|
}
|
|
537
621
|
|
|
622
|
+
/**
|
|
623
|
+
* #7012: lazily construct + start the MCP fleet from whatever is currently in
|
|
624
|
+
* `_mcpServerConfigs`, exactly once. Extracted out of `start()` (which was the
|
|
625
|
+
* ONLY caller pre-#7012) so `addMcpServer` can reach the same construction path:
|
|
626
|
+
* a session that started with zero configured MCP servers never created a
|
|
627
|
+
* fleet, so `addMcpServer`'s old `if (this._mcpFleet)` gate skipped the
|
|
628
|
+
* fleet-attach step entirely — the server was persisted but stayed
|
|
629
|
+
* unconnected until a restart. `addMcpServer` appends the new entry to
|
|
630
|
+
* `_mcpServerConfigs` BEFORE calling this, so the fleet's constructor (which
|
|
631
|
+
* spawns one client per config) picks the new server up directly; no separate
|
|
632
|
+
* `fleet.addServer()` call is needed on that path.
|
|
633
|
+
*
|
|
634
|
+
* Single-flight without extra bookkeeping: `this._mcpFleet` is assigned
|
|
635
|
+
* SYNCHRONOUSLY, before the `await fleet.start()` below — the same
|
|
636
|
+
* synchronous stretch that reads `_mcpServerConfigs` and decides whether to
|
|
637
|
+
* call this method (see `addMcpServer`). JS never preempts mid-synchronous-
|
|
638
|
+
* stretch, so two concurrent `addMcpServer` calls can never both observe
|
|
639
|
+
* `_mcpFleet` as null: whichever runs first sets it before yielding on the
|
|
640
|
+
* `await`, and the other sees it already set and falls through to the
|
|
641
|
+
* existing-fleet `fleet.addServer()` branch instead of racing a second
|
|
642
|
+
* `new MCPFleet(...)`.
|
|
643
|
+
*
|
|
644
|
+
* Guards:
|
|
645
|
+
* - zero configured servers → no fleet (mirrors the pre-#7012 `start()`
|
|
646
|
+
* guard — nothing to spawn).
|
|
647
|
+
* - `_destroying` → no fleet (a session torn down mid-add must not spawn a
|
|
648
|
+
* new MCP child that `destroy()` has already finished looking for).
|
|
649
|
+
*/
|
|
650
|
+
async _ensureMcpFleet() {
|
|
651
|
+
if (this._mcpFleet) return this._mcpFleet
|
|
652
|
+
if (this._destroying || this._mcpServerConfigs.length === 0) return null
|
|
653
|
+
// #4457: pass the session's PermissionManager so the fleet can
|
|
654
|
+
// emit a trust prompt for a not-yet-trusted spawn config (#7001: name +
|
|
655
|
+
// command + the full args + env).
|
|
656
|
+
// Tuples already trusted in ~/.chroxy/mcp-trust.json spawn directly
|
|
657
|
+
// with no prompt; denied tuples set state=DEAD without spawning.
|
|
658
|
+
// #4456: forward startCapMs override so operators can tune the
|
|
659
|
+
// session-start wall-clock cap. Passing undefined lets the fleet's
|
|
660
|
+
// constructor default (DEFAULT_FLEET_START_CAP_MS) win — exactly
|
|
661
|
+
// what we want when no override is in play.
|
|
662
|
+
const fleetOpts = { log, permissionManager: this._permissions }
|
|
663
|
+
if (this._mcpStartCapMs !== null) fleetOpts.startCapMs = this._mcpStartCapMs
|
|
664
|
+
// #6824: seed the fleet with the persisted parked set so a respawn skips
|
|
665
|
+
// starting servers the operator disabled before the restart.
|
|
666
|
+
fleetOpts.disabledServers = [...this._disabledMcpServers]
|
|
667
|
+
const fleet = new MCPFleet(this._mcpServerConfigs, fleetOpts)
|
|
668
|
+
this._mcpFleet = fleet
|
|
669
|
+
await fleet.start()
|
|
670
|
+
return fleet
|
|
671
|
+
}
|
|
672
|
+
|
|
538
673
|
async start() {
|
|
674
|
+
// API-driven BYOK providers have no vendor-native project-file discovery.
|
|
675
|
+
// Compile before client creation so malformed/over-budget policy cannot
|
|
676
|
+
// reach a model. Container cwd mapping is not yet verified.
|
|
677
|
+
if (this._loadProjectInstructions && !this._instructionPolicyLoaded && !this.constructor.capabilities?.containerized) {
|
|
678
|
+
const projection = await this._instructionPolicyLoader({
|
|
679
|
+
cwd: this.cwd,
|
|
680
|
+
...(this._machineInstructionPath !== undefined
|
|
681
|
+
? { machinePath: this._machineInstructionPath }
|
|
682
|
+
: {}),
|
|
683
|
+
...(this._machineInstructionRoot !== undefined
|
|
684
|
+
? { machineRoot: this._machineInstructionRoot }
|
|
685
|
+
: {}),
|
|
686
|
+
})
|
|
687
|
+
this._installProjectInstructionProjection(projection)
|
|
688
|
+
this._instructionPolicyLoaded = true
|
|
689
|
+
}
|
|
539
690
|
if (this._client === null) {
|
|
540
691
|
// Spike (BYOK direct) confirmed the SDK's standard constructor
|
|
541
692
|
// works fine; baseURL defaults to api.anthropic.com.
|
|
@@ -565,24 +716,10 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
565
716
|
// tools, identical to a server missing from config. We deliberately
|
|
566
717
|
// wait for fleet.start() so this.mcpServers + tools list are stable
|
|
567
718
|
// by the time we emit 'ready'.
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
// Tuples already trusted in ~/.chroxy/mcp-trust.json spawn directly
|
|
573
|
-
// with no prompt; denied tuples set state=DEAD without spawning.
|
|
574
|
-
// #4456: forward startCapMs override so operators can tune the
|
|
575
|
-
// session-start wall-clock cap. Passing undefined lets the fleet's
|
|
576
|
-
// constructor default (DEFAULT_FLEET_START_CAP_MS) win — exactly
|
|
577
|
-
// what we want when no override is in play.
|
|
578
|
-
const fleetOpts = { log, permissionManager: this._permissions }
|
|
579
|
-
if (this._mcpStartCapMs !== null) fleetOpts.startCapMs = this._mcpStartCapMs
|
|
580
|
-
// #6824: seed the fleet with the persisted parked set so a respawn skips
|
|
581
|
-
// starting servers the operator disabled before the restart.
|
|
582
|
-
fleetOpts.disabledServers = [...this._disabledMcpServers]
|
|
583
|
-
this._mcpFleet = new MCPFleet(this._mcpServerConfigs, fleetOpts)
|
|
584
|
-
await this._mcpFleet.start()
|
|
585
|
-
}
|
|
719
|
+
// #7012: extracted into _ensureMcpFleet so addMcpServer can reach the
|
|
720
|
+
// SAME construction path for a session that started with zero MCP
|
|
721
|
+
// servers configured (previously only start() ever created a fleet).
|
|
722
|
+
await this._ensureMcpFleet()
|
|
586
723
|
|
|
587
724
|
this._processReady = true
|
|
588
725
|
this.emit('ready', { sessionId: null, model: this.model, tools: [] })
|
|
@@ -605,11 +742,14 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
605
742
|
if (this._mcpFleet) return this._mcpFleet.getServerStatuses()
|
|
606
743
|
return this._mcpServerConfigs.map((cfg) => {
|
|
607
744
|
const disabled = this._disabledMcpServers.has(cfg.name)
|
|
745
|
+
const scope = mcpSourceToWriteScope(cfg.source)
|
|
608
746
|
return {
|
|
609
747
|
name: cfg.name,
|
|
610
748
|
status: disabled ? 'disabled' : 'configured',
|
|
611
749
|
enabled: !disabled,
|
|
612
750
|
canToggle: true,
|
|
751
|
+
// #7028: same rule as the fleet's snapshot — present only when known.
|
|
752
|
+
...(scope ? { scope } : {}),
|
|
613
753
|
}
|
|
614
754
|
})
|
|
615
755
|
}
|
|
@@ -738,9 +878,12 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
738
878
|
const store = loadTrustStore(trustPath, { log })
|
|
739
879
|
if (isTrusted(store, cfg)) return { allowed: true, prompted: false }
|
|
740
880
|
const isRemote = typeof cfg.url === 'string' && cfg.url.length > 0
|
|
881
|
+
// #7939: forward the scope this add targets (see mcpWriteScopeToSource
|
|
882
|
+
// above) so the pre-write trust prompt names where the server is being
|
|
883
|
+
// configured, same as a rediscovered spec's prompt would.
|
|
741
884
|
const trustReq = isRemote
|
|
742
|
-
? { name: cfg.name, url: cfg.url, headerKeys: Object.keys(cfg.headers || {}).sort() }
|
|
743
|
-
: { name: cfg.name, command: cfg.command, args: cfg.args, envKeys: Object.keys(cfg.env || {}).sort() }
|
|
885
|
+
? { name: cfg.name, url: cfg.url, headerKeys: Object.keys(cfg.headers || {}).sort(), source: cfg.source }
|
|
886
|
+
: { name: cfg.name, command: cfg.command, args: cfg.args, envKeys: Object.keys(cfg.env || {}).sort(), source: cfg.source }
|
|
744
887
|
const allowed = await pm.requestMcpTrust(trustReq)
|
|
745
888
|
if (allowed) recordTrust(cfg, trustPath)
|
|
746
889
|
return { allowed: allowed === true, prompted: true }
|
|
@@ -751,8 +894,15 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
751
894
|
* Build the in-memory fleet config from a normalized persisted entry, filling
|
|
752
895
|
* the shape defaults (`args`/`env` for stdio, `headers` for remote) the fleet
|
|
753
896
|
* and the trust key both read.
|
|
897
|
+
*
|
|
898
|
+
* #7939: optional `source` (an `MCP_SERVER_SOURCE` value) tags where this
|
|
899
|
+
* config came from — a discovered spec already carries one from
|
|
900
|
+
* `discoverMcpServerSpecs`, but a live `addMcpServer` entry has none until
|
|
901
|
+
* the caller derives it from the WRITE scope via `mcpWriteScopeToSource` and
|
|
902
|
+
* passes it here, so both paths converge on the same shape before either
|
|
903
|
+
* reaches the spawn-trust gate.
|
|
754
904
|
*/
|
|
755
|
-
static _mcpCfgFromEntry(name, entry) {
|
|
905
|
+
static _mcpCfgFromEntry(name, entry, { source } = {}) {
|
|
756
906
|
const cfg = { name, ...entry }
|
|
757
907
|
if (cfg.command !== undefined) {
|
|
758
908
|
cfg.args = Array.isArray(cfg.args) ? cfg.args : []
|
|
@@ -760,6 +910,7 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
760
910
|
} else {
|
|
761
911
|
cfg.headers = cfg.headers && typeof cfg.headers === 'object' ? cfg.headers : {}
|
|
762
912
|
}
|
|
913
|
+
if (source !== undefined) cfg.source = source
|
|
763
914
|
return cfg
|
|
764
915
|
}
|
|
765
916
|
|
|
@@ -788,7 +939,7 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
788
939
|
* duplicate name from a generic validation failure; `code: 'TRUST_DENIED'`
|
|
789
940
|
* distinguishes "the user said no" from a failure.
|
|
790
941
|
*/
|
|
791
|
-
async addMcpServer(name, config, scope = 'user') {
|
|
942
|
+
async addMcpServer(name, config, scope = 'user', { isAuthorized } = {}) {
|
|
792
943
|
const valid = validateNewMcpServerName(name)
|
|
793
944
|
if (!valid.ok) return { ok: false, error: valid.error }
|
|
794
945
|
|
|
@@ -807,7 +958,12 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
807
958
|
if (!planned.ok) return { ok: false, error: planned.error, code: planned.code }
|
|
808
959
|
|
|
809
960
|
// The candidate config, exactly as it would be persisted and spawned.
|
|
810
|
-
|
|
961
|
+
// #7939: tag it with the scope the user is adding it to (mapped onto the
|
|
962
|
+
// same MCP_SERVER_SOURCE vocabulary discovery uses) so the trust prompt
|
|
963
|
+
// for THIS add names its scope consistently with a rediscovered server.
|
|
964
|
+
const cfg = ClaudeByokSession._mcpCfgFromEntry(valid.name, planned.entry, {
|
|
965
|
+
source: mcpWriteScopeToSource(planned.scope),
|
|
966
|
+
})
|
|
811
967
|
|
|
812
968
|
const trust = await this._decideMcpSpawnTrust(cfg)
|
|
813
969
|
if (!trust.allowed) {
|
|
@@ -818,6 +974,9 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
818
974
|
}
|
|
819
975
|
}
|
|
820
976
|
|
|
977
|
+
// The trust prompt above was a wait: the requesting connection may have ended.
|
|
978
|
+
assertAuthorized(isAuthorized)
|
|
979
|
+
|
|
821
980
|
let written
|
|
822
981
|
try {
|
|
823
982
|
written = addMcpServerToConfig({
|
|
@@ -847,8 +1006,12 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
847
1006
|
// diverge. Normalization is pure over (name, config), so this is structurally
|
|
848
1007
|
// identical to the `cfg` the trust decision was made against — and if it ever
|
|
849
1008
|
// were not, the fleet's own gate below would see an untrusted config and
|
|
850
|
-
// prompt rather than spawn.
|
|
851
|
-
|
|
1009
|
+
// prompt rather than spawn. #7939: carries the same write-scope-derived
|
|
1010
|
+
// `source` as `cfg` above, so a live-added server's fleet re-prompt (the
|
|
1011
|
+
// backstop in `MCPFleet.addServer`/`_makeClient`) shows the identical scope.
|
|
1012
|
+
const persistedCfg = ClaudeByokSession._mcpCfgFromEntry(valid.name, written.entry, {
|
|
1013
|
+
source: mcpWriteScopeToSource(written.scope),
|
|
1014
|
+
})
|
|
852
1015
|
this._mcpServerConfigs = [...this._mcpServerConfigs, persistedCfg]
|
|
853
1016
|
this._refreshMcpServerMetadata()
|
|
854
1017
|
|
|
@@ -856,10 +1019,23 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
856
1019
|
if (this._mcpFleet) {
|
|
857
1020
|
const result = await this._mcpFleet.addServer(persistedCfg)
|
|
858
1021
|
if (result.status) status = result.status
|
|
1022
|
+
} else if (this._processReady) {
|
|
1023
|
+
// #7012: no fleet exists yet — either this is the session's first-ever
|
|
1024
|
+
// MCP server, or start() never spun one up because zero servers were
|
|
1025
|
+
// configured at start. `_mcpServerConfigs` already carries this server
|
|
1026
|
+
// (appended above), so `_ensureMcpFleet`'s constructor picks it up
|
|
1027
|
+
// directly; `fleet.addServer()` is not called on this path — see that
|
|
1028
|
+
// method's docstring for why.
|
|
1029
|
+
const fleet = await this._ensureMcpFleet()
|
|
1030
|
+
if (fleet) {
|
|
1031
|
+
const entry = fleet.getServerStatuses().find((s) => s.name === persistedCfg.name)
|
|
1032
|
+
if (entry?.status) status = entry.status
|
|
1033
|
+
}
|
|
859
1034
|
}
|
|
860
|
-
//
|
|
861
|
-
//
|
|
862
|
-
//
|
|
1035
|
+
// else: addMcpServer was called before start() (production only ever
|
|
1036
|
+
// reaches a started session — the WS handler requires one). Leave status
|
|
1037
|
+
// 'configured' and let start() pick the persisted entry up normally,
|
|
1038
|
+
// rather than spawning an MCP child ahead of `_processReady`.
|
|
863
1039
|
this._emitMcpServers()
|
|
864
1040
|
const result = { ok: true, status }
|
|
865
1041
|
if (written.warning) result.warning = written.warning
|
|
@@ -890,6 +1066,7 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
890
1066
|
scope,
|
|
891
1067
|
cwd: this.cwd,
|
|
892
1068
|
configPath: this._mcpConfigPath,
|
|
1069
|
+
_fsync: this._mcpConfigFsync,
|
|
893
1070
|
})
|
|
894
1071
|
} catch (err) {
|
|
895
1072
|
return { ok: false, error: `Failed to write MCP config: ${err?.message || String(err)}` }
|
|
@@ -930,19 +1107,39 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
930
1107
|
return [...this._disabledMcpServers].sort()
|
|
931
1108
|
}
|
|
932
1109
|
|
|
933
|
-
async sendMessage(prompt, attachments,
|
|
1110
|
+
async sendMessage(prompt, attachments, sendOptions = {}) {
|
|
934
1111
|
if (this._isBusy) {
|
|
935
1112
|
this.emit('error', { message: 'Already processing a message' })
|
|
1113
|
+
reportInputAdmission(sendOptions, {
|
|
1114
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
1115
|
+
reason: 'busy', message: 'The provider is already processing a message.',
|
|
1116
|
+
})
|
|
936
1117
|
return
|
|
937
1118
|
}
|
|
938
1119
|
if (this._destroying || !this._processReady || !this._client) {
|
|
939
1120
|
this.emit('error', { message: 'Session not ready' })
|
|
1121
|
+
reportInputAdmission(sendOptions, {
|
|
1122
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
1123
|
+
reason: 'not_runnable', message: 'The provider session is not ready to accept input.',
|
|
1124
|
+
})
|
|
1125
|
+
return
|
|
1126
|
+
}
|
|
1127
|
+
if (sendOptions.context && Array.isArray(attachments) && attachments.length > 0) {
|
|
1128
|
+
this.emit('error', {
|
|
1129
|
+
message: `BYOK provider does not yet materialise attachments (${attachments.length} dropped). Track follow-up: file-via-Read tool flow.`,
|
|
1130
|
+
})
|
|
1131
|
+
reportInputAdmission(sendOptions, {
|
|
1132
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
1133
|
+
reason: 'unsupported_attachments', message: 'This provider does not support image context.',
|
|
1134
|
+
})
|
|
940
1135
|
return
|
|
941
1136
|
}
|
|
942
1137
|
|
|
943
1138
|
// Claim busy up front so the async MCP-prompt resolution below can't race a
|
|
944
1139
|
// second concurrent send (isRunning stays true across the await window).
|
|
945
1140
|
this._isBusy = true
|
|
1141
|
+
// #8430: a new turn starts with no user Stop in flight, whatever the last one left.
|
|
1142
|
+
this._permissions.clearUserStopInFlight()
|
|
946
1143
|
|
|
947
1144
|
// #6823: MCP prompt-as-slash-command interception. A leading
|
|
948
1145
|
// `/mcp__<server>__<prompt>` that matches a connected MCP server's prompt
|
|
@@ -955,11 +1152,25 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
955
1152
|
if (mcpPromptMatch) {
|
|
956
1153
|
try {
|
|
957
1154
|
promptText = await this._resolveMcpPromptToText(mcpPromptMatch)
|
|
1155
|
+
if (!stillAuthorized(sendOptions.isAuthorized)) {
|
|
1156
|
+
this._isBusy = false
|
|
1157
|
+
this._permissions.clearUserStopInFlight()
|
|
1158
|
+
reportInputAdmission(sendOptions, {
|
|
1159
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
1160
|
+
reason: 'connection_not_authorized', message: 'The sending connection is no longer authorized; the input was not dispatched.',
|
|
1161
|
+
})
|
|
1162
|
+
return
|
|
1163
|
+
}
|
|
958
1164
|
} catch (err) {
|
|
959
1165
|
this._isBusy = false
|
|
1166
|
+
this._permissions.clearUserStopInFlight() // #8430: this turn ends here, off the _finishTurn path
|
|
960
1167
|
this.emit('error', {
|
|
961
1168
|
message: `MCP prompt /${mcpPromptMatch.prefixedName} failed: ${err?.message || String(err)}`,
|
|
962
1169
|
})
|
|
1170
|
+
reportInputAdmission(sendOptions, {
|
|
1171
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
1172
|
+
reason: 'prompt_resolution_failed', message: 'The provider prompt could not be resolved before dispatch.',
|
|
1173
|
+
})
|
|
963
1174
|
return
|
|
964
1175
|
}
|
|
965
1176
|
// #6845: honesty. The raw `/mcp__server__prompt` the user typed is NOT
|
|
@@ -1016,6 +1227,7 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1016
1227
|
? this._buildSystemPrompt()
|
|
1017
1228
|
: ''
|
|
1018
1229
|
|
|
1230
|
+
this._toolResultsEmitted.clear()
|
|
1019
1231
|
this.emit('stream_start', { messageId })
|
|
1020
1232
|
|
|
1021
1233
|
// Agent loop. Each iteration:
|
|
@@ -1055,6 +1267,13 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1055
1267
|
log.warn(`no pricing entry for model=${pricingModel}; result.cost will be 0 — update CLAUDE_PRICING_USD_PER_MTOK in models.js`)
|
|
1056
1268
|
}
|
|
1057
1269
|
let lastStopReason = null
|
|
1270
|
+
// #8461: set when the loop spends MAX_TOOL_ROUNDS; the forced summary round's
|
|
1271
|
+
// own `end_turn` overwrites lastStopReason, so the cap needs its own flag.
|
|
1272
|
+
let toolRoundCapReached = false
|
|
1273
|
+
// #7072: an interrupt that landed in the tool phase ends the loop below WITHOUT a
|
|
1274
|
+
// thrown abort, so the stream-phase catch never sees it. (A requested Stop that
|
|
1275
|
+
// lands in the stream phase reaches the same `result` through that catch, #8553.)
|
|
1276
|
+
let stoppedInToolPhase = false
|
|
1058
1277
|
// Snapshot the pre-turn history length so any stream-init failure (at
|
|
1059
1278
|
// any round) can rollback the entire turn atomically. We derive it
|
|
1060
1279
|
// from the current length minus the user message we just pushed at
|
|
@@ -1065,9 +1284,16 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1065
1284
|
// `user` turn back-to-back, soft-breaking the alternation invariant
|
|
1066
1285
|
// the API may tighten on in future.
|
|
1067
1286
|
const historyLengthBeforeSend = Math.max(0, this._history.length - 1)
|
|
1287
|
+
// #8559: text streamed by the round that is still in flight (not yet committed to
|
|
1288
|
+
// `_history`). A requested Stop mid-stream keeps it as a truncated assistant turn.
|
|
1289
|
+
let streamedText = ''
|
|
1290
|
+
// The summary round's instruction block (appended to the last tool_result turn)
|
|
1291
|
+
// while that round is in flight, so a requested Stop can take it back out.
|
|
1292
|
+
let pendingSummary = null
|
|
1068
1293
|
|
|
1069
1294
|
try {
|
|
1070
1295
|
for (let round = 0; round < MAX_TOOL_ROUNDS; round++) {
|
|
1296
|
+
streamedText = ''
|
|
1071
1297
|
let stream
|
|
1072
1298
|
try {
|
|
1073
1299
|
stream = this._client.messages.stream(
|
|
@@ -1094,14 +1320,25 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1094
1320
|
if (this._history.length > historyLengthBeforeSend) {
|
|
1095
1321
|
this._history.length = historyLengthBeforeSend
|
|
1096
1322
|
}
|
|
1323
|
+
if (round === 0) {
|
|
1324
|
+
reportInputAdmission(sendOptions, {
|
|
1325
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
1326
|
+
reason: 'stream_start_failed', message: 'The provider rejected the input before streaming began.',
|
|
1327
|
+
})
|
|
1328
|
+
}
|
|
1097
1329
|
throw err
|
|
1098
1330
|
}
|
|
1099
1331
|
|
|
1332
|
+
if (round === 0) {
|
|
1333
|
+
reportInputAdmission(sendOptions, { status: 'accepted', delivery: 'dispatch_started' })
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1100
1336
|
for await (const event of stream) {
|
|
1101
1337
|
const t = translateSdkEvent(event)
|
|
1102
1338
|
if (!t) continue
|
|
1103
1339
|
switch (t.kind) {
|
|
1104
1340
|
case 'stream_delta':
|
|
1341
|
+
streamedText += t.text
|
|
1105
1342
|
this.emit('stream_delta', { messageId, delta: t.text })
|
|
1106
1343
|
break
|
|
1107
1344
|
case 'thinking_delta': {
|
|
@@ -1113,7 +1350,18 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1113
1350
|
const idx = typeof t.index === 'number' ? t.index : 0
|
|
1114
1351
|
let thinkingId = this._streamingIndexToThinkingId.get(idx)
|
|
1115
1352
|
if (!thinkingId) {
|
|
1116
|
-
|
|
1353
|
+
// #6630: unique per thinking STREAM in the turn, not per block
|
|
1354
|
+
// index. The index restarts at 0 every tool round while the turn's
|
|
1355
|
+
// `messageId` does not, so `<turn>-thinking-<idx>` named a round-2
|
|
1356
|
+
// thought the same as the round-1 one: live, the client's accumulator
|
|
1357
|
+
// concatenated the two; the history (keyed by id) kept one. A counter
|
|
1358
|
+
// that runs for the whole turn keeps every stream's id its own, and
|
|
1359
|
+
// still ends in `-thinking-<n>` for the legacy classifier.
|
|
1360
|
+
if (this._thinkingSeqTurn !== messageId) {
|
|
1361
|
+
this._thinkingSeqTurn = messageId
|
|
1362
|
+
this._thinkingSeq = 0
|
|
1363
|
+
}
|
|
1364
|
+
thinkingId = `${messageId}-thinking-${this._thinkingSeq++}`
|
|
1117
1365
|
this._streamingIndexToThinkingId.set(idx, thinkingId)
|
|
1118
1366
|
// #6391 footer-stat: mark the block's start for the
|
|
1119
1367
|
// content_block_stop elapsed-time computation. #6943:
|
|
@@ -1159,55 +1407,24 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1159
1407
|
tool: t.toolName,
|
|
1160
1408
|
input: null,
|
|
1161
1409
|
})
|
|
1162
|
-
// #4080: track index→toolUseId so the upcoming
|
|
1163
|
-
// tool_input_delta events (which only carry the index)
|
|
1164
|
-
// can be re-tagged with the toolUseId before re-emit.
|
|
1165
|
-
if (typeof t.index === 'number' && t.toolUseId) {
|
|
1166
|
-
this._streamingIndexToToolUseId.set(t.index, t.toolUseId)
|
|
1167
|
-
}
|
|
1168
1410
|
break
|
|
1169
1411
|
}
|
|
1170
|
-
case 'tool_input_delta':
|
|
1171
|
-
// #
|
|
1172
|
-
//
|
|
1173
|
-
//
|
|
1174
|
-
//
|
|
1175
|
-
//
|
|
1176
|
-
//
|
|
1177
|
-
//
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
// (text deltas already went through stream_delta) or
|
|
1184
|
-
// for an index we never saw a start for (SDK reorder /
|
|
1185
|
-
// malformed event). Drop quietly — the accepted shape
|
|
1186
|
-
// for partial input is "may not arrive."
|
|
1187
|
-
break
|
|
1188
|
-
}
|
|
1189
|
-
if (this._pendingPermissionToolUseIds.has(toolUseId)) {
|
|
1190
|
-
// A permission prompt is pending for this exact
|
|
1191
|
-
// toolUseId — suppress the delta so the bubble doesn't
|
|
1192
|
-
// flicker between "running…" and partial-input while
|
|
1193
|
-
// the user is mid-decision. See constructor comment.
|
|
1194
|
-
break
|
|
1195
|
-
}
|
|
1196
|
-
this.emit('tool_input_delta', {
|
|
1197
|
-
messageId,
|
|
1198
|
-
toolUseId,
|
|
1199
|
-
partialJson: t.partial,
|
|
1200
|
-
})
|
|
1412
|
+
case 'tool_input_delta':
|
|
1413
|
+
// #8137: the SDK's raw `input_json_delta` chunks are
|
|
1414
|
+
// deliberately NOT forwarded — a secret can straddle chunk
|
|
1415
|
+
// boundaries (e.g. "export TOKEN=sk-" in one delta,
|
|
1416
|
+
// "ant-api03-…" in the next), and mid-stream partial JSON
|
|
1417
|
+
// generally isn't valid JSON, so it can't be parsed to run
|
|
1418
|
+
// `sanitizeToolInput`'s structured key/value passes over it
|
|
1419
|
+
// either. Matches the #8135 fix already applied to
|
|
1420
|
+
// cli-session.js / sdk-session.js: the sanitized FULL input
|
|
1421
|
+
// is instead delivered once, as a single `tool_input_delta`,
|
|
1422
|
+
// right after `stream.finalMessage()` resolves below — see
|
|
1423
|
+
// the loop over `toolBlocks` a few dozen lines down. Was
|
|
1424
|
+
// previously forwarded raw here (pre-#8137).
|
|
1201
1425
|
break
|
|
1202
|
-
}
|
|
1203
1426
|
case 'content_block_stop':
|
|
1204
|
-
// #4080: free the per-index slot as soon as the block
|
|
1205
|
-
// finishes so a long turn's map doesn't grow unbounded.
|
|
1206
|
-
// Safe to delete even if index isn't in the map — that
|
|
1207
|
-
// just means we never tracked this block (text) and the
|
|
1208
|
-
// lookup is a no-op.
|
|
1209
1427
|
if (typeof t.index === 'number') {
|
|
1210
|
-
this._streamingIndexToToolUseId.delete(t.index)
|
|
1211
1428
|
// #6756 — close the thinking stream for this block so the
|
|
1212
1429
|
// client finalises its "Thinking… → Thought" label.
|
|
1213
1430
|
const thinkingId = this._streamingIndexToThinkingId.get(t.index)
|
|
@@ -1251,11 +1468,10 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1251
1468
|
// #4080: defensive cleanup. content_block_stop should have
|
|
1252
1469
|
// drained every entry above, but if the stream ended on an
|
|
1253
1470
|
// error path or the SDK ever skips the stop event for a
|
|
1254
|
-
// block,
|
|
1255
|
-
//
|
|
1256
|
-
//
|
|
1257
|
-
//
|
|
1258
|
-
this._streamingIndexToToolUseId.clear()
|
|
1471
|
+
// block, a thinking entry would leak across rounds and a later
|
|
1472
|
+
// delta for index N could route to a STALE thinking id from the
|
|
1473
|
+
// previous round. Clear here so each round starts with empty
|
|
1474
|
+
// per-stream maps.
|
|
1259
1475
|
this._streamingIndexToThinkingId.clear()
|
|
1260
1476
|
this._thinkingStartMs.clear()
|
|
1261
1477
|
lastStopReason = final.stop_reason
|
|
@@ -1277,6 +1493,57 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1277
1493
|
// Append the assistant turn — full content array preserves
|
|
1278
1494
|
// tool_use blocks for the next round of conversation.
|
|
1279
1495
|
this._history.push({ role: 'assistant', content: final.content })
|
|
1496
|
+
streamedText = ''
|
|
1497
|
+
|
|
1498
|
+
// Computed once — reused below both for the finalized
|
|
1499
|
+
// tool_input_delta emission (#8137) and, if the round proceeds
|
|
1500
|
+
// past the stop_reason check, for tool execution.
|
|
1501
|
+
const toolBlocks = (final.content || []).filter((b) => b?.type === 'tool_use')
|
|
1502
|
+
|
|
1503
|
+
// #8137: deliver the SANITIZED full input for every tool_use
|
|
1504
|
+
// block as a single `tool_input_delta`, now that
|
|
1505
|
+
// `stream.finalMessage()` has resolved and the complete, parsed
|
|
1506
|
+
// input is known. This REPLACES the raw per-chunk
|
|
1507
|
+
// `input_json_delta` forwarding removed from the
|
|
1508
|
+
// `tool_input_delta` case above — a secret can straddle chunk
|
|
1509
|
+
// boundaries and mid-stream partial JSON can't be sanitized, so
|
|
1510
|
+
// the safe delivery point is "sanitize the complete parsed
|
|
1511
|
+
// value, then send it once" (mirrors the #8135 fix already
|
|
1512
|
+
// applied to cli-session.js's `_captureFinalizedToolInput` /
|
|
1513
|
+
// sdk-session.js's `_handleToolUseBlock`). Runs through
|
|
1514
|
+
// `_recordToolInput` (base-session.js), the same #6029
|
|
1515
|
+
// `sanitizeToolInput` floor already applied on the
|
|
1516
|
+
// permission_request path — BYOK never populates
|
|
1517
|
+
// `_inFlightToolStarts`, so the tracking half of
|
|
1518
|
+
// `_recordToolInput` is a no-op here, but the sanitize call
|
|
1519
|
+
// always runs. Emitted before the `lastStopReason` check below
|
|
1520
|
+
// so the client sees the tool's input even in the
|
|
1521
|
+
// (should-never-happen) case where the API pairs tool_use
|
|
1522
|
+
// content with a non-tool_use stop_reason.
|
|
1523
|
+
for (const block of toolBlocks) {
|
|
1524
|
+
const toolUseId = block?.id
|
|
1525
|
+
if (!toolUseId) continue
|
|
1526
|
+
if (this._pendingPermissionToolUseIds.has(toolUseId)) {
|
|
1527
|
+
// Defensive — mirrors the pre-#8137 per-chunk suppression
|
|
1528
|
+
// (see the constructor comment on
|
|
1529
|
+
// `_pendingPermissionToolUseIds`). Today permission gating
|
|
1530
|
+
// for this toolUseId can't start until AFTER this point in
|
|
1531
|
+
// the same round (`_processToolBlocks` runs later, below),
|
|
1532
|
+
// so this branch is unreachable in production; kept in case
|
|
1533
|
+
// a future refactor requests permission before a round's
|
|
1534
|
+
// tool inputs are surfaced.
|
|
1535
|
+
continue
|
|
1536
|
+
}
|
|
1537
|
+
const sanitizedInput = this._recordToolInput(toolUseId, block.input ?? null)
|
|
1538
|
+
// `null`/`undefined` means "known to have no input" — don't
|
|
1539
|
+
// ship a literal "null" chunk for it (mirrors sdk-session.js).
|
|
1540
|
+
if (sanitizedInput === null || sanitizedInput === undefined) continue
|
|
1541
|
+
this.emit('tool_input_delta', {
|
|
1542
|
+
messageId,
|
|
1543
|
+
toolUseId,
|
|
1544
|
+
partialJson: JSON.stringify(sanitizedInput),
|
|
1545
|
+
})
|
|
1546
|
+
}
|
|
1280
1547
|
|
|
1281
1548
|
if (lastStopReason !== 'tool_use') {
|
|
1282
1549
|
// Done — model wants no more tools. Break out and emit result.
|
|
@@ -1315,7 +1582,6 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1315
1582
|
// 'Interrupted' tool_result (same #4061 invariant). If it trips
|
|
1316
1583
|
// mid-execution, the shared AbortSignal propagates to
|
|
1317
1584
|
// executeBuiltinTool and any in-flight tool aborts cleanly.
|
|
1318
|
-
const toolBlocks = (final.content || []).filter((b) => b?.type === 'tool_use')
|
|
1319
1585
|
const toolResults = await this._processToolBlocks({ toolBlocks, messageId })
|
|
1320
1586
|
if (toolResults.length === 0) {
|
|
1321
1587
|
// stop_reason was tool_use but no tool_use blocks — defensive
|
|
@@ -1325,7 +1591,17 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1325
1591
|
}
|
|
1326
1592
|
this._history.push({ role: 'user', content: toolResults })
|
|
1327
1593
|
|
|
1328
|
-
if (this._abortController?.signal?.aborted)
|
|
1594
|
+
if (this._abortController?.signal?.aborted) {
|
|
1595
|
+
// #7072: the tool results above are committed to history (the #4061
|
|
1596
|
+
// invariant) and the turn's spend is real, so this still ends in a
|
|
1597
|
+
// `result` -- but one that says the turn was STOPPED, not a success. The
|
|
1598
|
+
// stream-phase abort throws into the catch below, which ends a REQUESTED
|
|
1599
|
+
// Stop in the same result (#8553); this path never throws. byok emits no
|
|
1600
|
+
// `stopped` of its own, so the result is the only terminal event an
|
|
1601
|
+
// orchestration TurnDriver hears (BaseSession.emit adds the quiet one).
|
|
1602
|
+
stoppedInToolPhase = true
|
|
1603
|
+
break
|
|
1604
|
+
}
|
|
1329
1605
|
|
|
1330
1606
|
if (round === MAX_TOOL_ROUNDS - 1) {
|
|
1331
1607
|
// #4063: instead of bailing silently, run ONE more text-only
|
|
@@ -1336,6 +1612,7 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1336
1612
|
// content block on the existing tool_result user turn rather
|
|
1337
1613
|
// than pushing a second user turn back-to-back.
|
|
1338
1614
|
log.warn(`hit MAX_TOOL_ROUNDS=${MAX_TOOL_ROUNDS} cap; running summary round`)
|
|
1615
|
+
toolRoundCapReached = true
|
|
1339
1616
|
|
|
1340
1617
|
// Emit a non-fatal error so the dashboard can render a warning
|
|
1341
1618
|
// banner. The session stays alive — the user can keep talking;
|
|
@@ -1364,6 +1641,8 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1364
1641
|
break
|
|
1365
1642
|
}
|
|
1366
1643
|
|
|
1644
|
+
pendingSummary = { turn: lastTurn, block: summaryInstruction }
|
|
1645
|
+
streamedText = ''
|
|
1367
1646
|
let summaryStream
|
|
1368
1647
|
try {
|
|
1369
1648
|
summaryStream = this._client.messages.stream(
|
|
@@ -1401,6 +1680,7 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1401
1680
|
if (!t) continue
|
|
1402
1681
|
switch (t.kind) {
|
|
1403
1682
|
case 'stream_delta':
|
|
1683
|
+
streamedText += t.text
|
|
1404
1684
|
this.emit('stream_delta', { messageId, delta: t.text })
|
|
1405
1685
|
break
|
|
1406
1686
|
case 'message_delta':
|
|
@@ -1427,6 +1707,8 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1427
1707
|
if (c !== null) { turnCost += c; turnCostKnown = true }
|
|
1428
1708
|
}
|
|
1429
1709
|
this._history.push({ role: 'assistant', content: summaryFinal.content })
|
|
1710
|
+
streamedText = ''
|
|
1711
|
+
pendingSummary = null
|
|
1430
1712
|
break
|
|
1431
1713
|
}
|
|
1432
1714
|
}
|
|
@@ -1455,27 +1737,16 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1455
1737
|
// keep their previous snapshot.
|
|
1456
1738
|
const finalRoundOccupancy = ClaudeByokSession._buildFinalRoundOccupancy(lastRoundUsage)
|
|
1457
1739
|
|
|
1458
|
-
this.
|
|
1459
|
-
this.emit('result', {
|
|
1460
|
-
sessionId: null,
|
|
1740
|
+
this._emitTurnResult({
|
|
1461
1741
|
messageId,
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
// turnUsage under the parent's model, which is CORRECT today because
|
|
1471
|
-
// children hard-inherit the parent model (see _executeTaskTool). If a
|
|
1472
|
-
// per-profile model override ever lands (#5018's deferred AC), that
|
|
1473
|
-
// change must split this map by actual child model (#5020).
|
|
1474
|
-
modelUsage: synthesizeModelUsage(
|
|
1475
|
-
this.model || this._defaultModel,
|
|
1476
|
-
turnUsage,
|
|
1477
|
-
turnCostKnown ? turnCost : null,
|
|
1478
|
-
),
|
|
1742
|
+
lastStopReason,
|
|
1743
|
+
toolRoundCapReached,
|
|
1744
|
+
interrupted: stoppedInToolPhase,
|
|
1745
|
+
turnStartedAt,
|
|
1746
|
+
turnUsage,
|
|
1747
|
+
turnCost,
|
|
1748
|
+
turnCostKnown,
|
|
1749
|
+
finalRoundOccupancy,
|
|
1479
1750
|
})
|
|
1480
1751
|
} catch (err) {
|
|
1481
1752
|
// #4118: extend the synchronous stream-init rollback (#4109) to
|
|
@@ -1496,7 +1767,17 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1496
1767
|
// Truncating to historyLengthBeforeSend is idempotent: if the
|
|
1497
1768
|
// inner stream-init catch already truncated (round-0 path), the
|
|
1498
1769
|
// length is already at or below the snapshot and this is a no-op.
|
|
1499
|
-
|
|
1770
|
+
//
|
|
1771
|
+
// #8559: the exception is a Stop somebody requested while the model was
|
|
1772
|
+
// STREAMING. The tool-phase Stop above keeps the prompt and every completed
|
|
1773
|
+
// round, so this one does too: the user asked for the turn to END, not to be
|
|
1774
|
+
// erased, and the next prompt ("what did I just ask?") needs it. Every other
|
|
1775
|
+
// abort (a destroy, a parent's cascade) and every provider error keeps the
|
|
1776
|
+
// rollback: nobody asked for those turns to count.
|
|
1777
|
+
const requestedStop = this._isRequestedStop(err)
|
|
1778
|
+
if (requestedStop) {
|
|
1779
|
+
this._commitStoppedStream({ streamedText, historyLengthBeforeSend, pendingSummary, messageId })
|
|
1780
|
+
} else if (this._history.length > historyLengthBeforeSend) {
|
|
1500
1781
|
this._history.length = historyLengthBeforeSend
|
|
1501
1782
|
}
|
|
1502
1783
|
// #5020: fold any subagent (Task tool) usage + cost into the
|
|
@@ -1512,6 +1793,25 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1512
1793
|
turnUsage.cache_creation_input_tokens += this._subagentUsageThisTurn.cache_creation_input_tokens
|
|
1513
1794
|
turnCost += this._subagentCostThisTurn
|
|
1514
1795
|
if (this._subagentCostThisTurn > 0) turnCostKnown = true
|
|
1796
|
+
// #8553: a Stop somebody requested that lands while the model is STREAMING
|
|
1797
|
+
// ends the turn exactly as the tool-phase one does (#7072): one `result`
|
|
1798
|
+
// that says it was stopped, then the quiet `stopped` BaseSession.emit adds
|
|
1799
|
+
// for it, and no `error`. The rollback and the usage fold above already ran
|
|
1800
|
+
// and are the same either way.
|
|
1801
|
+
if (requestedStop) {
|
|
1802
|
+
this._emitTurnResult({
|
|
1803
|
+
messageId,
|
|
1804
|
+
lastStopReason,
|
|
1805
|
+
toolRoundCapReached,
|
|
1806
|
+
interrupted: true,
|
|
1807
|
+
turnStartedAt,
|
|
1808
|
+
turnUsage,
|
|
1809
|
+
turnCost,
|
|
1810
|
+
turnCostKnown,
|
|
1811
|
+
finalRoundOccupancy: ClaudeByokSession._buildFinalRoundOccupancy(lastRoundUsage),
|
|
1812
|
+
})
|
|
1813
|
+
return
|
|
1814
|
+
}
|
|
1515
1815
|
this.emit('stream_end', { messageId })
|
|
1516
1816
|
this._emitTurnError(messageId, err, 'STREAM_ERROR', {
|
|
1517
1817
|
usage: turnUsage,
|
|
@@ -1529,12 +1829,11 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1529
1829
|
} finally {
|
|
1530
1830
|
// #4080: per-turn isolation guarantee. The per-round clear after
|
|
1531
1831
|
// finalMessage() above runs on the success path; an iteration or
|
|
1532
|
-
// finalMessage() throw skips it and would leak stale
|
|
1533
|
-
//
|
|
1534
|
-
//
|
|
1535
|
-
//
|
|
1536
|
-
//
|
|
1537
|
-
this._streamingIndexToToolUseId.clear()
|
|
1832
|
+
// finalMessage() throw skips it and would leak stale per-index
|
|
1833
|
+
// entries into the next turn (mis-routing the next stream's
|
|
1834
|
+
// thinking deltas). Clearing here drains them on every exit path
|
|
1835
|
+
// — success, error, abort, hard timeout. Safe to call when
|
|
1836
|
+
// already empty.
|
|
1538
1837
|
this._streamingIndexToThinkingId.clear()
|
|
1539
1838
|
this._thinkingStartMs.clear()
|
|
1540
1839
|
this._finishTurn()
|
|
@@ -1574,19 +1873,11 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1574
1873
|
// inter-phase guard fires when startIndex === 0, but only the
|
|
1575
1874
|
// blocks that *would* have executed in phase 2 need filling).
|
|
1576
1875
|
if (toolResults[j]) continue
|
|
1577
|
-
|
|
1578
|
-
this.emit('tool_result', {
|
|
1876
|
+
toolResults[j] = this._interruptedToolResult({
|
|
1579
1877
|
messageId,
|
|
1580
|
-
toolUseId:
|
|
1581
|
-
result: interrupted,
|
|
1582
|
-
isError: true,
|
|
1583
|
-
})
|
|
1584
|
-
toolResults[j] = {
|
|
1585
|
-
type: 'tool_result',
|
|
1586
|
-
tool_use_id: remaining.id,
|
|
1878
|
+
toolUseId: toolBlocks[j].id,
|
|
1587
1879
|
content: interrupted,
|
|
1588
|
-
|
|
1589
|
-
}
|
|
1880
|
+
})
|
|
1590
1881
|
}
|
|
1591
1882
|
}
|
|
1592
1883
|
|
|
@@ -1682,6 +1973,8 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1682
1973
|
input,
|
|
1683
1974
|
signal,
|
|
1684
1975
|
this.permissionMode,
|
|
1976
|
+
undefined,
|
|
1977
|
+
toolUseId,
|
|
1685
1978
|
)
|
|
1686
1979
|
} catch (err) {
|
|
1687
1980
|
// permission_request was rejected (timeout, abort, etc.). Surface
|
|
@@ -1724,7 +2017,7 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1724
2017
|
|
|
1725
2018
|
if (resolvedDecision.behavior !== 'allow') {
|
|
1726
2019
|
const msg = resolvedDecision.message || 'Permission denied by user.'
|
|
1727
|
-
this.
|
|
2020
|
+
this._emitToolResult({
|
|
1728
2021
|
messageId,
|
|
1729
2022
|
toolUseId,
|
|
1730
2023
|
result: msg,
|
|
@@ -1771,7 +2064,7 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1771
2064
|
}
|
|
1772
2065
|
const { content, isError } = dispatchResult
|
|
1773
2066
|
|
|
1774
|
-
this.
|
|
2067
|
+
this._emitToolResult({
|
|
1775
2068
|
messageId,
|
|
1776
2069
|
toolUseId,
|
|
1777
2070
|
result: content,
|
|
@@ -1916,10 +2209,12 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1916
2209
|
// `description`, `startedAt`). The toolUseId matches the parent
|
|
1917
2210
|
// turn's tool_use block id so the dashboard correlates the spawn
|
|
1918
2211
|
// with the open tool_call bubble.
|
|
2212
|
+
// #7340: byok's Task tool AWAITS its child in-process (the tool result is
|
|
2213
|
+
// the child's answer), so a byok subagent can never outlive its turn —
|
|
2214
|
+
// `background: false` is a statement of fact here, not a default, and it
|
|
2215
|
+
// keeps byok agents eligible for the turn-end orphan sweep.
|
|
1919
2216
|
const startedAt = Date.now()
|
|
1920
|
-
|
|
1921
|
-
this._activeAgents.set(toolUseId, agentInfo)
|
|
1922
|
-
this.emit('agent_spawned', agentInfo)
|
|
2217
|
+
this._trackAgent({ toolUseId, description, background: false, startedAt })
|
|
1923
2218
|
|
|
1924
2219
|
// Build a child session. Reuse this session's already-resolved
|
|
1925
2220
|
// client so the API key resolution + Anthropic constructor only
|
|
@@ -1958,7 +2253,14 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1958
2253
|
cwd: this.cwd,
|
|
1959
2254
|
model: this.model || this._defaultModel,
|
|
1960
2255
|
mcpConfigPath: null,
|
|
2256
|
+
projectInstructions: this.projectInstructions,
|
|
1961
2257
|
})
|
|
2258
|
+
if (this.providerInstructionProjection?.status === 'delivered') {
|
|
2259
|
+
child._installProjectInstructionProjection({
|
|
2260
|
+
...this.providerInstructionProjection,
|
|
2261
|
+
text: this.projectInstructions,
|
|
2262
|
+
})
|
|
2263
|
+
}
|
|
1962
2264
|
// Skip start()'s credential resolution — share the parent's client
|
|
1963
2265
|
// so the child uses the same API key path. Also avoids a duplicate
|
|
1964
2266
|
// credentials.json read which could rate-limit on disk for parallel
|
|
@@ -2137,7 +2439,7 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
2137
2439
|
// already iterates _subagentSessions, but this listener also
|
|
2138
2440
|
// catches the micro-race when the signal aborts between the
|
|
2139
2441
|
// top-of-function check and child.sendMessage's first await.
|
|
2140
|
-
const onAbort = () => { try { child.interrupt() } catch { /* noop */ } }
|
|
2442
|
+
const onAbort = () => { try { child.interrupt({ cascaded: true }) } catch { /* noop */ } }
|
|
2141
2443
|
if (signal) {
|
|
2142
2444
|
if (signal.aborted) onAbort()
|
|
2143
2445
|
else signal.addEventListener('abort', onAbort, { once: true })
|
|
@@ -2236,10 +2538,19 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
2236
2538
|
* @param {object} payload
|
|
2237
2539
|
*/
|
|
2238
2540
|
_emitAgentEvent(parentToolUseId, type, payload) {
|
|
2541
|
+
let wirePayload = payload ?? {}
|
|
2542
|
+
// #8397: `recordDescription` is an in-process field of the child's
|
|
2543
|
+
// `permission_request` (read by the session that owns the prompt to record
|
|
2544
|
+
// its outcome), not part of the wire shape. Every child relay passes through
|
|
2545
|
+
// here, so it is dropped here, once.
|
|
2546
|
+
if (type === 'permission_request' && wirePayload && typeof wirePayload === 'object' && 'recordDescription' in wirePayload) {
|
|
2547
|
+
const { recordDescription: _internal, ...rest } = wirePayload
|
|
2548
|
+
wirePayload = rest
|
|
2549
|
+
}
|
|
2239
2550
|
this.emit('agent_event', {
|
|
2240
2551
|
parentToolUseId,
|
|
2241
2552
|
type,
|
|
2242
|
-
payload:
|
|
2553
|
+
payload: wirePayload,
|
|
2243
2554
|
})
|
|
2244
2555
|
}
|
|
2245
2556
|
|
|
@@ -2476,7 +2787,7 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
2476
2787
|
* PermissionManager which resolves the pending Promise in
|
|
2477
2788
|
* handlePermission() above.
|
|
2478
2789
|
*/
|
|
2479
|
-
respondToPermission(requestId, decision, editedInput, reason) {
|
|
2790
|
+
respondToPermission(requestId, decision, editedInput, reason, scope) {
|
|
2480
2791
|
// #5056: if this requestId belongs to a Task subagent (its pending
|
|
2481
2792
|
// entry lives in the CHILD's PermissionManager, not ours), forward
|
|
2482
2793
|
// the decision to that child. ws-permissions only ever calls the
|
|
@@ -2487,23 +2798,30 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
2487
2798
|
// already authorized against the parent session by ws-permissions.
|
|
2488
2799
|
const child = this._subagentPermissionRouting.get(requestId)
|
|
2489
2800
|
if (child) {
|
|
2490
|
-
// Drop the routing entry first so a duplicate/late response can't
|
|
2491
|
-
// re-resolve a stale id. The child also emits permission_resolved
|
|
2492
|
-
// which our relay listener uses to clear the same entry — deleting
|
|
2493
|
-
// here too is idempotent and closes the lifetime tightly.
|
|
2494
|
-
this._subagentPermissionRouting.delete(requestId)
|
|
2495
2801
|
// #6543: forward the operator's per-hunk editedInput to the child too.
|
|
2496
2802
|
// #6773: the deny `reason` forwards to the child as well.
|
|
2497
|
-
|
|
2803
|
+
// #8517: so does the session-scope label.
|
|
2804
|
+
const resolved = child.respondToPermission(requestId, decision, editedInput, reason, scope)
|
|
2805
|
+
// Drop the routing entry once the child has taken the response, so a
|
|
2806
|
+
// duplicate/late response can't re-resolve a stale id. The child also emits
|
|
2807
|
+
// permission_resolved which our relay listener uses to clear the same entry
|
|
2808
|
+
// — deleting here too is idempotent and closes the lifetime tightly.
|
|
2809
|
+
// #8446: NOT before the call. A child that REFUSES an edit throws with its
|
|
2810
|
+
// request still pending, and the caller's follow-up deny must find the route
|
|
2811
|
+
// to reach it; a route dropped first sent that deny to this manager, which
|
|
2812
|
+
// does not hold the request, and the child waited out its timeout.
|
|
2813
|
+
this._subagentPermissionRouting.delete(requestId)
|
|
2814
|
+
return resolved
|
|
2498
2815
|
}
|
|
2499
|
-
return this._permissions.respondToPermission(requestId, decision, editedInput, reason)
|
|
2816
|
+
return this._permissions.respondToPermission(requestId, decision, editedInput, reason, scope)
|
|
2500
2817
|
}
|
|
2501
2818
|
|
|
2502
2819
|
/**
|
|
2503
2820
|
* Response to an AskUserQuestion tool. Same forwarding pattern.
|
|
2504
2821
|
*/
|
|
2505
|
-
respondToQuestion(text, answersMap) {
|
|
2506
|
-
|
|
2822
|
+
respondToQuestion(text, answersMap, toolUseId) {
|
|
2823
|
+
// #8460: the id lets the manager refuse an answer meant for a different question.
|
|
2824
|
+
return this._permissions.respondToQuestion(text, answersMap, toolUseId)
|
|
2507
2825
|
}
|
|
2508
2826
|
|
|
2509
2827
|
/**
|
|
@@ -2544,6 +2862,141 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
2544
2862
|
}
|
|
2545
2863
|
}
|
|
2546
2864
|
|
|
2865
|
+
/**
|
|
2866
|
+
* #8553: the one way a turn's terminal `result` is built and sent, for the
|
|
2867
|
+
* normal ending and for a requested Stop alike (tool phase #7072, stream phase
|
|
2868
|
+
* #8553). `interrupted` makes the outcome `stopped` and marks the result
|
|
2869
|
+
* terminal-but-not-successful; BaseSession.emit turns that into the quiet
|
|
2870
|
+
* `stopped` when the Stop was requested. Emits `stream_end` first.
|
|
2871
|
+
*/
|
|
2872
|
+
_emitTurnResult({
|
|
2873
|
+
messageId, lastStopReason, toolRoundCapReached, interrupted,
|
|
2874
|
+
turnStartedAt, turnUsage, turnCost, turnCostKnown, finalRoundOccupancy,
|
|
2875
|
+
}) {
|
|
2876
|
+
this.emit('stream_end', { messageId })
|
|
2877
|
+
this.emit('result', {
|
|
2878
|
+
sessionId: null,
|
|
2879
|
+
messageId,
|
|
2880
|
+
stopReason: lastStopReason,
|
|
2881
|
+
// #7326: the provider-neutral form of the stop reason above, for the wire.
|
|
2882
|
+
// (A different key on purpose: `stopReason` is the raw Anthropic string.)
|
|
2883
|
+
...turnOutcomeField(outcomeFromByokTurn({ stopReason: lastStopReason, toolRoundCapReached, interrupted })),
|
|
2884
|
+
// #7072: terminal but not successful (internal; not on the wire).
|
|
2885
|
+
...(interrupted ? { interrupted: true } : {}),
|
|
2886
|
+
duration: Date.now() - turnStartedAt,
|
|
2887
|
+
usage: turnUsage,
|
|
2888
|
+
...(finalRoundOccupancy ? { contextOccupancy: finalRoundOccupancy } : {}),
|
|
2889
|
+
// #5630: emit null when no round produced a known cost so the UI
|
|
2890
|
+
// shows "n/a" instead of a misleading $0.00.
|
|
2891
|
+
cost: turnCostKnown ? turnCost : null,
|
|
2892
|
+
// #6692: single-model split. Task-subagent usage is folded into
|
|
2893
|
+
// turnUsage under the parent's model, which is CORRECT today because
|
|
2894
|
+
// children hard-inherit the parent model (see _executeTaskTool). If a
|
|
2895
|
+
// per-profile model override ever lands (#5018's deferred AC), that
|
|
2896
|
+
// change must split this map by actual child model (#5020).
|
|
2897
|
+
modelUsage: synthesizeModelUsage(
|
|
2898
|
+
this.model || this._defaultModel,
|
|
2899
|
+
turnUsage,
|
|
2900
|
+
turnCostKnown ? turnCost : null,
|
|
2901
|
+
),
|
|
2902
|
+
})
|
|
2903
|
+
}
|
|
2904
|
+
|
|
2905
|
+
/** True when `err` is the abort of an in-flight stream (see _emitTurnError). */
|
|
2906
|
+
_isAbortError(err) {
|
|
2907
|
+
return err instanceof APIUserAbortError ||
|
|
2908
|
+
err?.name === 'AbortError' ||
|
|
2909
|
+
!!this._abortController?.signal?.aborted
|
|
2910
|
+
}
|
|
2911
|
+
|
|
2912
|
+
/**
|
|
2913
|
+
* #8553: did somebody ASK for the abort `err` reports? True only for an abort
|
|
2914
|
+
* that came through interrupt() (the user, the scheduler, the orchestration
|
|
2915
|
+
* watchdog). Not a teardown (destroy() calls interrupt() too, but nobody is
|
|
2916
|
+
* waiting for a stopped turn), and not the abort a parent's Stop cascades to
|
|
2917
|
+
* its Task subagent, which the parent reports as the subagent's failure.
|
|
2918
|
+
*/
|
|
2919
|
+
_isRequestedStop(err) {
|
|
2920
|
+
return this._isAbortError(err) &&
|
|
2921
|
+
this._stopRequestedThisTurn &&
|
|
2922
|
+
!this._destroying &&
|
|
2923
|
+
!this._abortCascaded
|
|
2924
|
+
}
|
|
2925
|
+
|
|
2926
|
+
/**
|
|
2927
|
+
* Emit a `tool_result` event and remember its tool_use id for the turn (#8569).
|
|
2928
|
+
* Every tool_result event this session sends goes through here, so "has this tool
|
|
2929
|
+
* been closed on the client?" has one answer.
|
|
2930
|
+
*/
|
|
2931
|
+
_emitToolResult({ messageId, toolUseId, result, isError }) {
|
|
2932
|
+
this._toolResultsEmitted.add(toolUseId)
|
|
2933
|
+
this.emit('tool_result', { messageId, toolUseId, result, isError })
|
|
2934
|
+
}
|
|
2935
|
+
|
|
2936
|
+
/**
|
|
2937
|
+
* The synthesized `is_error` tool_result for a tool the user's Stop kept from
|
|
2938
|
+
* running to a result: emits the closing event for the client's tool row and
|
|
2939
|
+
* returns the content block that answers the tool_use in `_history`. The one
|
|
2940
|
+
* place that shape lives -- the tool-phase Stop (`_processToolBlocks`) and the
|
|
2941
|
+
* Stop that threw between the history pushes (`_commitStoppedStream`) both use it.
|
|
2942
|
+
*/
|
|
2943
|
+
_interruptedToolResult({ messageId, toolUseId, content }) {
|
|
2944
|
+
this._emitToolResult({ messageId, toolUseId, result: content, isError: true })
|
|
2945
|
+
return { type: 'tool_result', tool_use_id: toolUseId, content, is_error: true }
|
|
2946
|
+
}
|
|
2947
|
+
|
|
2948
|
+
/**
|
|
2949
|
+
* #8559: settle `_history` after a requested Stop that ended the turn by a throw.
|
|
2950
|
+
*
|
|
2951
|
+
* Whatever the tail is, it leaves `_history` a VALID conversation (the next
|
|
2952
|
+
* request is never rejected for it) and keeps the prompt and the completed work:
|
|
2953
|
+
*
|
|
2954
|
+
* - `user` tail (the stop cut a stream short; the in-flight round's assistant
|
|
2955
|
+
* turn is only committed once its stream finishes): close it with an assistant
|
|
2956
|
+
* turn holding the text that did stream -- what Claude Code keeps -- so the
|
|
2957
|
+
* next request alternates strictly. Only text is kept: a half-streamed
|
|
2958
|
+
* tool_use has no result to pair with. With no text at all a placeholder
|
|
2959
|
+
* stands in, because an empty text block is refused.
|
|
2960
|
+
* - `assistant` tail with tool_use blocks (the stop threw between the round's
|
|
2961
|
+
* assistant push and its tool_result push): the tool_use would be unanswered,
|
|
2962
|
+
* which the API refuses on every later request, so answer each with a
|
|
2963
|
+
* synthesized is_error tool_result, as the tool-phase Stop does (#4061). The
|
|
2964
|
+
* rounds before it stay too; rolling back instead would drop the prompt.
|
|
2965
|
+
* Each also gets the `tool_result` event that closes its row on the client
|
|
2966
|
+
* (#8569), unless its real result already went out.
|
|
2967
|
+
* - `assistant` tail without tool_use: already a valid end, left alone.
|
|
2968
|
+
*
|
|
2969
|
+
* A no-op only when the turn is already rolled back (a stream-init failure).
|
|
2970
|
+
*/
|
|
2971
|
+
_commitStoppedStream({ streamedText, historyLengthBeforeSend, pendingSummary, messageId }) {
|
|
2972
|
+
if (this._history.length <= historyLengthBeforeSend) return
|
|
2973
|
+
const tail = this._history[this._history.length - 1]
|
|
2974
|
+
if (tail?.role === 'assistant') {
|
|
2975
|
+
const uses = Array.isArray(tail.content) ? tail.content.filter((b) => b?.type === 'tool_use') : []
|
|
2976
|
+
if (uses.length > 0) {
|
|
2977
|
+
// #8569: the client opened a row for each of these on `tool_start`, and only
|
|
2978
|
+
// a `tool_result` event closes it. Emit the same interrupted result the
|
|
2979
|
+
// tool-phase Stop does, except for a tool whose real result already went out.
|
|
2980
|
+
this._history.push({
|
|
2981
|
+
role: 'user',
|
|
2982
|
+
content: uses.map((b) => (this._toolResultsEmitted.has(b.id)
|
|
2983
|
+
? { type: 'tool_result', tool_use_id: b.id, content: STOPPED_BEFORE_TOOL, is_error: true }
|
|
2984
|
+
: this._interruptedToolResult({ messageId, toolUseId: b.id, content: STOPPED_BEFORE_TOOL }))),
|
|
2985
|
+
})
|
|
2986
|
+
}
|
|
2987
|
+
return
|
|
2988
|
+
}
|
|
2989
|
+
if (pendingSummary && pendingSummary.turn === tail && Array.isArray(tail.content)) {
|
|
2990
|
+
// The summary round never ran to completion: take its instruction back out so
|
|
2991
|
+
// the next turn is not told to stop using tools.
|
|
2992
|
+
tail.content = tail.content.filter((b) => b !== pendingSummary.block)
|
|
2993
|
+
}
|
|
2994
|
+
this._history.push({
|
|
2995
|
+
role: 'assistant',
|
|
2996
|
+
content: [{ type: 'text', text: streamedText.trim() ? streamedText : STOPPED_BEFORE_TEXT }],
|
|
2997
|
+
})
|
|
2998
|
+
}
|
|
2999
|
+
|
|
2547
3000
|
_emitTurnError(messageId, err, fallbackCode, partials) {
|
|
2548
3001
|
// #4057: SDK v0.81+ throws `APIUserAbortError` (not the generic
|
|
2549
3002
|
// `AbortError`) when an in-flight messages.stream sees its signal
|
|
@@ -2563,11 +3016,7 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
2563
3016
|
// so additional fields propagate without a wire-side schema change.
|
|
2564
3017
|
// Optional / undefined-safe: pre-#5020 call sites pass nothing and
|
|
2565
3018
|
// the fields are simply absent on the event payload.
|
|
2566
|
-
|
|
2567
|
-
err instanceof APIUserAbortError ||
|
|
2568
|
-
err?.name === 'AbortError' ||
|
|
2569
|
-
this._abortController?.signal?.aborted
|
|
2570
|
-
if (aborted) {
|
|
3019
|
+
if (this._isAbortError(err)) {
|
|
2571
3020
|
this.emit('error', {
|
|
2572
3021
|
messageId,
|
|
2573
3022
|
message: 'Interrupted by user',
|
|
@@ -2587,6 +3036,9 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
2587
3036
|
}
|
|
2588
3037
|
|
|
2589
3038
|
_finishTurn() {
|
|
3039
|
+
// #8430: a user Stop belongs to the turn it was pressed on; BYOK's teardown
|
|
3040
|
+
// does not go through BaseSession._clearMessageState, so clear it here.
|
|
3041
|
+
this._permissions.clearUserStopInFlight()
|
|
2590
3042
|
this._isBusy = false
|
|
2591
3043
|
this._currentMessageId = null
|
|
2592
3044
|
this._abortController = null
|
|
@@ -2595,10 +3047,31 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
2595
3047
|
// fired and the fold-in step above was skipped.
|
|
2596
3048
|
this._subagentUsageThisTurn = { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }
|
|
2597
3049
|
this._subagentCostThisTurn = 0
|
|
3050
|
+
// #7072/#8461: this teardown skips BaseSession._clearMessageState, so the
|
|
3051
|
+
// turn-scoped Stop request (see interrupt()) is cleared here, or it would tag
|
|
3052
|
+
// the NEXT turn's own abort as a requested Stop.
|
|
3053
|
+
this._stopRequestedThisTurn = false
|
|
3054
|
+
this._abortCascaded = false
|
|
3055
|
+
this._clearIntentionalStop()
|
|
2598
3056
|
}
|
|
2599
3057
|
|
|
2600
|
-
|
|
3058
|
+
/**
|
|
3059
|
+
* @param {{ cascaded?: boolean }} [opts] `cascaded`: the parent session is
|
|
3060
|
+
* stopping this Task subagent (its own Stop reaching it, or a cancel of this
|
|
3061
|
+
* one node), rather than a Stop of this session (#8553).
|
|
3062
|
+
*/
|
|
3063
|
+
interrupt({ cascaded = false } = {}) {
|
|
2601
3064
|
if (!this._isBusy) return
|
|
3065
|
+
if (cascaded) this._abortCascaded = true
|
|
3066
|
+
// #7072/#8461/#8553: a Stop somebody requested (the user, the scheduler, the
|
|
3067
|
+
// orchestration watchdog) is acknowledged by one quiet `stopped` instead of a
|
|
3068
|
+
// "Stopped" chip, exactly as on claude-sdk and claude-cli. Both phases end in a
|
|
3069
|
+
// `result` (see sendMessage): the tool-phase abort never throws, and the
|
|
3070
|
+
// stream-phase one is turned into the same result by the catch, so
|
|
3071
|
+
// BaseSession.emit drops the chip and sends the confirmation, after marking the
|
|
3072
|
+
// result `interrupted`.
|
|
3073
|
+
this.markIntentionalStop()
|
|
3074
|
+
this._noteTurnStopRequested()
|
|
2602
3075
|
if (this._abortController) {
|
|
2603
3076
|
this._abortController.abort()
|
|
2604
3077
|
}
|
|
@@ -2608,7 +3081,7 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
2608
3081
|
// _executeTaskTool's awaited promise resolve and the parent's
|
|
2609
3082
|
// outer agent loop can finish the user-facing result event.
|
|
2610
3083
|
for (const child of this._subagentSessions.values()) {
|
|
2611
|
-
try { child.interrupt() } catch (err) {
|
|
3084
|
+
try { child.interrupt({ cascaded: true }) } catch (err) {
|
|
2612
3085
|
log.warn(`subagent interrupt failed: ${err?.message || err}`)
|
|
2613
3086
|
}
|
|
2614
3087
|
}
|
|
@@ -2651,7 +3124,9 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
2651
3124
|
// optimistically finalize the node, matching the SDK path's best-effort
|
|
2652
3125
|
// stopTask contract.
|
|
2653
3126
|
try {
|
|
2654
|
-
|
|
3127
|
+
// A cancel of one node reaches the subagent like the parent's own Stop
|
|
3128
|
+
// does: the parent reports it as the subagent's failure (#8553).
|
|
3129
|
+
child.interrupt({ cascaded: true })
|
|
2655
3130
|
} catch (err) {
|
|
2656
3131
|
log.warn(`subagent cancel failed for ${activityId}: ${err?.message || err}`)
|
|
2657
3132
|
return { ok: false, reason: 'stop-failed', error: err?.message || String(err) }
|
|
@@ -2669,13 +3144,14 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
2669
3144
|
* completion don't double-emit. Mirrors SdkSession's helper of the same name
|
|
2670
3145
|
* (minus the task-id map, which byok doesn't have).
|
|
2671
3146
|
*
|
|
3147
|
+
* #7340: the body is now BaseSession's `_completeAgent` — same guard, same
|
|
3148
|
+
* emit, ONE implementation shared with SdkSession and CliSession. Kept as a
|
|
3149
|
+
* named wrapper because #5274's callers and the cancel path read by this name.
|
|
3150
|
+
*
|
|
2672
3151
|
* @param {string} toolUseId
|
|
2673
3152
|
*/
|
|
2674
3153
|
_finalizeAgentByToolUseId(toolUseId) {
|
|
2675
|
-
|
|
2676
|
-
if (!this._activeAgents.has(toolUseId)) return
|
|
2677
|
-
this._activeAgents.delete(toolUseId)
|
|
2678
|
-
this.emit('agent_completed', { toolUseId })
|
|
3154
|
+
this._completeAgent(toolUseId)
|
|
2679
3155
|
}
|
|
2680
3156
|
|
|
2681
3157
|
// #5374: no setModel override needed — BaseSession.setModel updates the
|
|
@@ -2750,7 +3226,6 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
2750
3226
|
// #4080: same-rationale teardown — both maps are bounded by the
|
|
2751
3227
|
// active stream / outstanding permission count, but any external
|
|
2752
3228
|
// reference (test capture, future export) would keep them alive.
|
|
2753
|
-
this._streamingIndexToToolUseId.clear()
|
|
2754
3229
|
this._streamingIndexToThinkingId.clear()
|
|
2755
3230
|
this._thinkingStartMs.clear()
|
|
2756
3231
|
this._pendingPermissionToolUseIds.clear()
|