@chroxy/server 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +411 -14
- package/hooks/permission-hook.sh +253 -3
- package/package.json +8 -15
- package/sidecar/node_modules/.package-lock.json +29 -0
- package/sidecar/node_modules/ws/LICENSE +20 -0
- package/sidecar/node_modules/ws/README.md +548 -0
- package/sidecar/node_modules/ws/browser.js +8 -0
- package/sidecar/node_modules/ws/index.js +22 -0
- package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
- package/sidecar/node_modules/ws/lib/constants.js +19 -0
- package/sidecar/node_modules/ws/lib/event-target.js +292 -0
- package/sidecar/node_modules/ws/lib/extension.js +203 -0
- package/sidecar/node_modules/ws/lib/limiter.js +55 -0
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
- package/sidecar/node_modules/ws/lib/receiver.js +706 -0
- package/sidecar/node_modules/ws/lib/sender.js +602 -0
- package/sidecar/node_modules/ws/lib/stream.js +161 -0
- package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
- package/sidecar/node_modules/ws/lib/validation.js +152 -0
- package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
- package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
- package/sidecar/node_modules/ws/package.json +70 -0
- package/sidecar/node_modules/ws/wrapper.mjs +21 -0
- package/src/base-session.js +151 -6
- package/src/billing-budget.js +5 -1
- package/src/binary-provenance-trust.js +95 -0
- package/src/built-in-tools/file-ops.js +5 -4
- package/src/byok-mcp-client.js +1061 -13
- package/src/byok-mcp-config.js +1201 -4
- package/src/byok-mcp-fleet.js +374 -29
- package/src/byok-mcp-oauth-store.js +327 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +254 -37
- package/src/byok-session.js +789 -13
- package/src/byok-tool-executor.js +20 -13
- package/src/checkpoint-manager.js +33 -6
- package/src/chroxy-host-metadata.js +122 -0
- package/src/claude-stream-parser.js +56 -0
- package/src/claude-tui/pty-driver.js +54 -14
- package/src/claude-tui-session.js +106 -7
- package/src/cli/config-cmd.js +2 -2
- package/src/cli/deploy-cmd.js +1 -1
- package/src/cli/init-cmd.js +1 -1
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +775 -0
- package/src/cli/server-cmd.js +16 -1
- package/src/cli/service-cmd.js +39 -19
- package/src/cli/shared.js +7 -4
- package/src/cli/tokens-cmd.js +213 -0
- package/src/cli/tunnel-cmd.js +1 -1
- package/src/cli-session.js +66 -10
- package/src/cli.js +4 -0
- package/src/codex-app-server-session.js +671 -39
- package/src/codex-session.js +121 -18
- package/src/config.js +453 -27
- package/src/control-room/integrations.js +16 -10
- package/src/control-room/skills-inventory.js +6 -1
- package/src/control-room/survey.js +32 -0
- package/src/credential-store.js +256 -10
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
- package/src/diagnostics.js +3 -0
- package/src/docker-sdk-session.js +16 -1
- package/src/docker-session.js +9 -0
- package/src/doctor.js +19 -8
- package/src/environments/backends/docker.js +8 -0
- package/src/environments/backends/k8s.js +9 -0
- package/src/event-ingest.js +19 -1
- package/src/event-normalizer.js +354 -19
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +19 -2
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +42 -8
- package/src/handlers/checkpoint-handlers.js +126 -19
- package/src/handlers/control-room-handlers.js +48 -18
- package/src/handlers/conversation-handlers.js +127 -2
- package/src/handlers/credential-handlers.js +43 -2
- package/src/handlers/file-handlers.js +47 -3
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +4 -0
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +510 -0
- package/src/handlers/session-handlers.js +10 -2
- package/src/handlers/settings-handlers.js +510 -11
- package/src/handlers/token-handlers.js +11 -2
- package/src/http-routes.js +159 -0
- package/src/jsonl-reader.js +60 -6
- package/src/jsonl-subprocess-session.js +35 -6
- package/src/keychain.js +159 -12
- package/src/logger.js +182 -19
- package/src/notification-prefs.js +88 -6
- package/src/notifications/discord-webhook-sink.js +30 -1
- package/src/orchestration/build-manager.js +56 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +347 -0
- package/src/orchestration/orchestration-manager.js +1295 -0
- package/src/orchestration/permission-gate.js +109 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +205 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +398 -0
- package/src/pairing.js +146 -1
- package/src/permission-audit.js +79 -3
- package/src/permission-floor.js +455 -0
- package/src/permission-manager.js +492 -40
- package/src/permission-resolver.js +55 -7
- package/src/permission-rule-store.js +411 -0
- package/src/platform.js +367 -23
- package/src/providers.js +21 -2
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +653 -0
- package/src/scheduler.js +1029 -0
- package/src/sdk-session.js +338 -5
- package/src/server-cli/server-orchestrator.js +23 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli.js +238 -26
- package/src/server-identity.js +28 -4
- package/src/service.js +291 -33
- package/src/session-manager.js +417 -25
- package/src/session-message-history.js +27 -21
- package/src/session-title.js +168 -0
- package/src/session-token-store.js +60 -35
- package/src/skills-usage.js +20 -2
- package/src/statusline.js +584 -0
- package/src/subagent-counter.js +9 -1
- package/src/supervisor.js +77 -27
- package/src/token-manager.js +39 -9
- package/src/transcript-tasks.js +41 -6
- package/src/tunnel/cloudflare.js +115 -8
- package/src/tunnel/index.js +4 -1
- package/src/tunnel-check.js +1 -1
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +118 -0
- package/src/user-shell-session.js +98 -32
- package/src/utils/componentwise-resolver.js +205 -0
- package/src/utils/composite-key.js +45 -0
- package/src/utils/iso-datetime.js +51 -0
- package/src/utils/preflight.js +140 -28
- package/src/utils/spawn-env.js +8 -2
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +241 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/worktree-gc.js +4 -1
- package/src/ws-file-ops/browser.js +42 -11
- package/src/ws-file-ops/common.js +68 -1
- package/src/ws-file-ops/git.js +221 -3
- package/src/ws-file-ops/index.js +5 -0
- package/src/ws-file-ops/memory.js +358 -0
- package/src/ws-file-ops/reader.js +124 -0
- package/src/ws-forwarding.js +44 -16
- package/src/ws-handler-context.js +19 -0
- package/src/ws-history.js +84 -11
- package/src/ws-message-handlers.js +6 -0
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +285 -4
- package/src/ws-schemas.js +1 -0
- package/src/ws-server.js +301 -17
package/src/byok-session.js
CHANGED
|
@@ -17,7 +17,9 @@
|
|
|
17
17
|
import Anthropic, { APIUserAbortError } from '@anthropic-ai/sdk'
|
|
18
18
|
import { join } from 'path'
|
|
19
19
|
import { homedir } from 'os'
|
|
20
|
+
import { performance } from 'node:perf_hooks'
|
|
20
21
|
import { BaseSession, buildBaseSessionOpts } from './base-session.js'
|
|
22
|
+
import { synthesizeModelUsage } from './usage-normalize.js'
|
|
21
23
|
import { PermissionManager, wirePermissionManager } from './permission-manager.js'
|
|
22
24
|
import { createLogger } from './logger.js'
|
|
23
25
|
import { isOperatorTimeoutInRange } from './duration.js'
|
|
@@ -32,8 +34,24 @@ import { BILLING_CLASSES } from './billing-class.js'
|
|
|
32
34
|
import { translateSdkEvent } from './byok-event-translator.js'
|
|
33
35
|
import { BUILTIN_TOOLS, TASK_PERMISSION_MODE_LIST, TASK_PERMISSION_MODE_RANK } from './byok-tools.js'
|
|
34
36
|
import { executeBuiltinTool } from './byok-tool-executor.js'
|
|
35
|
-
import {
|
|
36
|
-
|
|
37
|
+
import {
|
|
38
|
+
addMcpServerToConfig,
|
|
39
|
+
defaultClaudeConfigPath,
|
|
40
|
+
loadClaudeMcpConfig,
|
|
41
|
+
planAddMcpServerToConfig,
|
|
42
|
+
removeMcpServerFromConfig,
|
|
43
|
+
toMcpServerMetadata,
|
|
44
|
+
validateMcpServerNameForRemoval,
|
|
45
|
+
validateNewMcpServerName,
|
|
46
|
+
} from './byok-mcp-config.js'
|
|
47
|
+
import { MCPFleet, MCP_TOOL_PREFIX, parseMcpToolName } from './byok-mcp-fleet.js'
|
|
48
|
+
import {
|
|
49
|
+
defaultTrustStorePath,
|
|
50
|
+
isTrusted,
|
|
51
|
+
loadTrustStore,
|
|
52
|
+
recordTrust,
|
|
53
|
+
withTrustStoreLock,
|
|
54
|
+
} from './byok-mcp-trust.js'
|
|
37
55
|
import { getSubagentProfile, SUBAGENT_PROFILE_NAMES } from './byok-subagent-profiles.js'
|
|
38
56
|
|
|
39
57
|
const log = createLogger('byok-session')
|
|
@@ -61,6 +79,38 @@ const MAX_TOOL_ROUNDS = 25
|
|
|
61
79
|
// performance (don't re-realpath the same cwd on every file op).
|
|
62
80
|
const CWD_CACHE_TTL_MS = 30_000
|
|
63
81
|
|
|
82
|
+
// #6845: display cap for the server-controlled MCP-prompt expansion surfaced
|
|
83
|
+
// in the transcript (the honesty marker). The FULL resolved text still goes to
|
|
84
|
+
// the model as the user turn — only the copy shown in the transcript is capped
|
|
85
|
+
// so a huge `prompts/get` response can't flood the chat. event-normalizer.js
|
|
86
|
+
// re-bounds at the wire boundary and store-core re-bounds again (defense in
|
|
87
|
+
// depth), mirroring the #6768 compact_boundary bounding chain.
|
|
88
|
+
const MCP_PROMPT_EXPANSION_DISPLAY_CAP = 4000
|
|
89
|
+
|
|
90
|
+
// Post-#6845-review fix (thread 2): the suffix names that the model still got
|
|
91
|
+
// the full text — mirrors event-normalizer.js's and store-core's wording so a
|
|
92
|
+
// reader sees the same honest note regardless of which layer's copy they're
|
|
93
|
+
// looking at (the marker component, the mobile/System-tab `content` fallback
|
|
94
|
+
// below, a wire-bypassing replay, etc).
|
|
95
|
+
const MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX = '\n…(truncated for display; full text sent to the model)'
|
|
96
|
+
|
|
97
|
+
// Bound an MCP-prompt expansion to the display cap, appending a truncation
|
|
98
|
+
// marker when it overflows. Returns the (possibly truncated) text plus a
|
|
99
|
+
// `truncated` flag so the renderer can badge it.
|
|
100
|
+
//
|
|
101
|
+
// Post-#6845-review fix (thread 2): previously sliced to `cap` and THEN
|
|
102
|
+
// appended the suffix, so the returned string could exceed `cap` by the
|
|
103
|
+
// suffix's length. The slice length now subtracts the suffix's own length so
|
|
104
|
+
// `text.length` (slice + suffix) never exceeds `cap` — computed from the
|
|
105
|
+
// suffix's actual `.length` rather than a hardcoded magic number, so this
|
|
106
|
+
// stays correct if the wording changes again.
|
|
107
|
+
function boundMcpPromptExpansionText(text, cap = MCP_PROMPT_EXPANSION_DISPLAY_CAP) {
|
|
108
|
+
const s = typeof text === 'string' ? text : String(text ?? '')
|
|
109
|
+
if (s.length <= cap) return { text: s, truncated: false }
|
|
110
|
+
const sliceLen = Math.max(0, cap - MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX.length)
|
|
111
|
+
return { text: `${s.slice(0, sliceLen)}${MCP_PROMPT_EXPANSION_TRUNCATION_SUFFIX}`, truncated: true }
|
|
112
|
+
}
|
|
113
|
+
|
|
64
114
|
export class ClaudeByokSession extends BaseSession {
|
|
65
115
|
// #5858: Claude-family flag — single source of truth for isClaudeProvider().
|
|
66
116
|
// DockerByokSession (docker-byok) extends this and correctly inherits it.
|
|
@@ -73,6 +123,43 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
73
123
|
return 'Claude (API key — BYOK)'
|
|
74
124
|
}
|
|
75
125
|
|
|
126
|
+
/**
|
|
127
|
+
* #6769: build the end-of-turn context-window OCCUPANCY snapshot from the
|
|
128
|
+
* FINAL agent-loop round's individual usage.
|
|
129
|
+
*
|
|
130
|
+
* That round's `input_tokens + cache_read_input_tokens +
|
|
131
|
+
* cache_creation_input_tokens` is exactly the prompt the API was last sent
|
|
132
|
+
* — i.e. the conversation's current size — so it is a true occupancy
|
|
133
|
+
* snapshot. The summed `turnUsage` billing aggregate is NOT (it re-counts
|
|
134
|
+
* the history once per round; a 5-round turn over-reads ≈5× — the #6816
|
|
135
|
+
* review finding). Output tokens are deliberately excluded (the coordinator
|
|
136
|
+
* contract pins the snapshot to the prompt side; the next turn's snapshot
|
|
137
|
+
* absorbs the reply), as is subagent usage (a child Task runs in its own
|
|
138
|
+
* separate window).
|
|
139
|
+
*
|
|
140
|
+
* Returns null when the turn produced no usable round usage (error before
|
|
141
|
+
* the first finalMessage(), or an endpoint that reports no usage — e.g. an
|
|
142
|
+
* anthropic-compatible server that omits the field). The result then emits
|
|
143
|
+
* WITHOUT `contextOccupancy` and clients keep their previous snapshot / dash.
|
|
144
|
+
*
|
|
145
|
+
* Static + pure so tests can pin the arithmetic without a live session;
|
|
146
|
+
* subclasses that reuse the agent loop (docker-byok, deepseek, ollama,
|
|
147
|
+
* anthropic-compatible) inherit it — wherever their endpoint reports real
|
|
148
|
+
* per-round usage, the snapshot is equally honest.
|
|
149
|
+
*
|
|
150
|
+
* @param {object|null} roundUsage — the final round's `final.usage`
|
|
151
|
+
* @returns {{totalTokens: number, source: 'final-round-prompt'}|null}
|
|
152
|
+
*/
|
|
153
|
+
static _buildFinalRoundOccupancy(roundUsage) {
|
|
154
|
+
if (!roundUsage || typeof roundUsage !== 'object') return null
|
|
155
|
+
const totalTokens =
|
|
156
|
+
(Number(roundUsage.input_tokens) || 0) +
|
|
157
|
+
(Number(roundUsage.cache_read_input_tokens) || 0) +
|
|
158
|
+
(Number(roundUsage.cache_creation_input_tokens) || 0)
|
|
159
|
+
if (!Number.isFinite(totalTokens) || totalTokens <= 0) return null
|
|
160
|
+
return { totalTokens, source: 'final-round-prompt' }
|
|
161
|
+
}
|
|
162
|
+
|
|
76
163
|
static get dataDir() {
|
|
77
164
|
// BYOK does NOT depend on ~/.claude — no claude binary, no OAuth.
|
|
78
165
|
// Returning null tells getProviderDataDirs() to skip this provider
|
|
@@ -103,6 +190,10 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
103
190
|
// takes effect on the next user message. Same property as the
|
|
104
191
|
// SDK provider.
|
|
105
192
|
skillToggle: true,
|
|
193
|
+
// #6888: BYOK shares SdkSession's PermissionManager/respondToPermission
|
|
194
|
+
// path — see the matching comment in sdk-session.js's capabilities. A
|
|
195
|
+
// deny reason genuinely reaches the agent as the tool's denial message.
|
|
196
|
+
denyReason: true,
|
|
106
197
|
}
|
|
107
198
|
}
|
|
108
199
|
|
|
@@ -244,7 +335,10 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
244
335
|
// PermissionManager + event re-emission via the shared wiring (P2-9) so the
|
|
245
336
|
// dashboard / mobile permission UI and the audit log work uniformly across
|
|
246
337
|
// providers. ByokSession passes no pause/resume hooks (no result-timeout).
|
|
247
|
-
|
|
338
|
+
// #6794 — pass cwd so the protected-path floor can resolve relative tool
|
|
339
|
+
// targets (.git/.claude/.env…) against this session's working directory.
|
|
340
|
+
// #6771 — pass the durable rule store (persistent per-project allow-always).
|
|
341
|
+
this._permissions = new PermissionManager({ log, cwd: this.cwd, ruleStore: this._permissionRuleStore })
|
|
248
342
|
wirePermissionManager(this, this._permissions)
|
|
249
343
|
|
|
250
344
|
// Realpath cache used by the tool executor's path-safety check. One
|
|
@@ -281,6 +375,21 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
281
375
|
// here.
|
|
282
376
|
this._streamingIndexToToolUseId = new Map()
|
|
283
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`.
|
|
383
|
+
this._streamingIndexToThinkingId = new Map()
|
|
384
|
+
|
|
385
|
+
// #6391 (chat-redesign footer-stat): thinking messageId → performance.now()
|
|
386
|
+
// when the reasoning block opened, so its content_block_stop can stamp the
|
|
387
|
+
// elapsed `thinkingDurationMs` on the thinking stream_end. Cleared alongside
|
|
388
|
+
// `_streamingIndexToThinkingId`. #6943: monotonic clock (perf_hooks), not
|
|
389
|
+
// Date.now() — wall-clock jumps (NTP step, manual change, DST) would
|
|
390
|
+
// otherwise clamp a backward jump to 0 or inflate a forward jump.
|
|
391
|
+
this._thinkingStartMs = new Map()
|
|
392
|
+
|
|
284
393
|
// #4080: toolUseIds whose permission_request is currently pending.
|
|
285
394
|
// Populated when this session re-emits permission_request (line
|
|
286
395
|
// ~165), drained on permission_resolved (line ~167). Consulted on
|
|
@@ -348,12 +457,28 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
348
457
|
// session only reads the `mcpServers` block, so a separate
|
|
349
458
|
// "whole Claude config" knob added no behavior over
|
|
350
459
|
// `mcpConfigPath` and had no callers. See constructor JSDoc.
|
|
460
|
+
// #6974: retain the resolved config path so the add/remove mutation path
|
|
461
|
+
// writes back to the SAME file this session read from (a test override or
|
|
462
|
+
// $CHROXY_CLAUDE_CONFIG must not be bypassed on the write half).
|
|
463
|
+
this._mcpConfigPath = opts.mcpConfigPath || defaultClaudeConfigPath()
|
|
351
464
|
const mcpConfig = loadClaudeMcpConfig(opts.mcpConfigPath)
|
|
352
465
|
for (const warning of mcpConfig.warnings) {
|
|
353
466
|
log.warn(`BYOK MCP config: ${warning}`)
|
|
354
467
|
}
|
|
355
468
|
this._mcpServerConfigs = mcpConfig.servers
|
|
356
469
|
this.mcpServers = Object.freeze(mcpConfig.servers.map(toMcpServerMetadata))
|
|
470
|
+
// #6824: per-session set of parked (disabled) MCP server names. Seeded from
|
|
471
|
+
// the persisted `disabledMcpServers` opt (session-manager forwards the
|
|
472
|
+
// restored set), filtered to names actually present in this session's
|
|
473
|
+
// config so a stale entry can't wedge. Threaded into the MCPFleet at
|
|
474
|
+
// start() (parked servers get no client) and round-tripped back to session
|
|
475
|
+
// state via `getDisabledMcpServers()`. Byok-local opt — read straight off
|
|
476
|
+
// `opts`, not a BaseSession key.
|
|
477
|
+
const configuredMcpNames = new Set(mcpConfig.servers.map((s) => s.name))
|
|
478
|
+
this._disabledMcpServers = new Set(
|
|
479
|
+
(Array.isArray(opts.disabledMcpServers) ? opts.disabledMcpServers : [])
|
|
480
|
+
.filter((name) => typeof name === 'string' && configuredMcpNames.has(name)),
|
|
481
|
+
)
|
|
357
482
|
// #4077: MCPFleet is lazy — created in start() only if servers exist.
|
|
358
483
|
// Held here so destroy() can tear down even if start() never ran.
|
|
359
484
|
this._mcpFleet = null
|
|
@@ -442,7 +567,8 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
442
567
|
// by the time we emit 'ready'.
|
|
443
568
|
if (this._mcpServerConfigs.length > 0 && this._mcpFleet === null) {
|
|
444
569
|
// #4457: pass the session's PermissionManager so the fleet can
|
|
445
|
-
// emit a trust prompt for
|
|
570
|
+
// emit a trust prompt for a not-yet-trusted spawn config (#7001: name +
|
|
571
|
+
// command + the full args + env).
|
|
446
572
|
// Tuples already trusted in ~/.chroxy/mcp-trust.json spawn directly
|
|
447
573
|
// with no prompt; denied tuples set state=DEAD without spawning.
|
|
448
574
|
// #4456: forward startCapMs override so operators can tune the
|
|
@@ -451,12 +577,357 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
451
577
|
// what we want when no override is in play.
|
|
452
578
|
const fleetOpts = { log, permissionManager: this._permissions }
|
|
453
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]
|
|
454
583
|
this._mcpFleet = new MCPFleet(this._mcpServerConfigs, fleetOpts)
|
|
455
584
|
await this._mcpFleet.start()
|
|
456
585
|
}
|
|
457
586
|
|
|
458
587
|
this._processReady = true
|
|
459
588
|
this.emit('ready', { sessionId: null, model: this.model, tools: [] })
|
|
589
|
+
// #6824: BYOK is the authoritative MCP lane — publish the live server list
|
|
590
|
+
// (with per-server enabled/canToggle) so the dashboard/mobile MCP views can
|
|
591
|
+
// render the enable/disable toggle. sdk/cli parse their list off the live
|
|
592
|
+
// stream; the BYOK fleet is in-daemon, so we emit it here after start().
|
|
593
|
+
this._emitMcpServers()
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* #6824: build the `mcp_servers` broadcast payload — one entry per configured
|
|
598
|
+
* server with `{ name, status, enabled, canToggle: true }`. When the fleet
|
|
599
|
+
* exists (the normal post-start case) its `getServerStatuses()` is
|
|
600
|
+
* authoritative (live states + parked servers). Before start() / when the
|
|
601
|
+
* fleet never spun up, fall back to the static config list so the payload is
|
|
602
|
+
* still coherent (parked → 'disabled', otherwise 'configured').
|
|
603
|
+
*/
|
|
604
|
+
_buildMcpServersPayload() {
|
|
605
|
+
if (this._mcpFleet) return this._mcpFleet.getServerStatuses()
|
|
606
|
+
return this._mcpServerConfigs.map((cfg) => {
|
|
607
|
+
const disabled = this._disabledMcpServers.has(cfg.name)
|
|
608
|
+
return {
|
|
609
|
+
name: cfg.name,
|
|
610
|
+
status: disabled ? 'disabled' : 'configured',
|
|
611
|
+
enabled: !disabled,
|
|
612
|
+
canToggle: true,
|
|
613
|
+
}
|
|
614
|
+
})
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* #6824: emit the current MCP server list to all subscribers. Best-effort —
|
|
619
|
+
* a throwing listener must not escape the ready / toggle paths this is called
|
|
620
|
+
* from (mirrors claude-tui-session `_emitConfiguredMcpServers`). No servers
|
|
621
|
+
* configured → nothing to publish.
|
|
622
|
+
*/
|
|
623
|
+
_emitMcpServers({ force = false } = {}) {
|
|
624
|
+
// #6974: `force` exists for the remove path. The zero-config early return
|
|
625
|
+
// is right on the ready path (nothing configured → nothing to publish), but
|
|
626
|
+
// removing the LAST configured server also lands on zero — and skipping the
|
|
627
|
+
// emit there would leave every client rendering the row we just deleted.
|
|
628
|
+
if (this._mcpServerConfigs.length === 0 && !force) return
|
|
629
|
+
try {
|
|
630
|
+
this.emit('mcp_servers', { servers: this._buildMcpServersPayload() })
|
|
631
|
+
} catch (err) {
|
|
632
|
+
log.warn(`BYOK MCP: mcp_servers emit failed: ${err?.message || err}`)
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/**
|
|
637
|
+
* #6824: enable or disable a single configured MCP server for this session.
|
|
638
|
+
* Delegates the park/unpark to the fleet (destroy-and-forget vs
|
|
639
|
+
* rebuild-through-trust-gate), updates the persisted parked set, and
|
|
640
|
+
* re-emits `mcp_servers` so every connected client converges. Returns
|
|
641
|
+
* `{ found, changed, status }` — `found: false` when `name` is not a
|
|
642
|
+
* configured server so the WS handler can surface a clean error.
|
|
643
|
+
*/
|
|
644
|
+
async setMcpServerEnabled(name, enabled) {
|
|
645
|
+
if (typeof name !== 'string' || !this._mcpServerConfigs.some((c) => c.name === name)) {
|
|
646
|
+
return { found: false, changed: false, status: null }
|
|
647
|
+
}
|
|
648
|
+
let result
|
|
649
|
+
if (this._mcpFleet) {
|
|
650
|
+
result = await this._mcpFleet.setEnabled(name, enabled)
|
|
651
|
+
// Sync the persisted set from the fleet's AUTHORITATIVE one rather than
|
|
652
|
+
// applying the requested state — the fleet's in-flight churn latch can
|
|
653
|
+
// legitimately ignore this toggle (changed:false while another park/
|
|
654
|
+
// unpark for the same server is awaiting), and blindly recording the
|
|
655
|
+
// request here would diverge what respawn honours from what actually ran.
|
|
656
|
+
this._disabledMcpServers = new Set(this._mcpFleet.disabledServers)
|
|
657
|
+
} else {
|
|
658
|
+
// Fleet not yet started (no servers spawned): just record intent so
|
|
659
|
+
// start() honours it. Treat as changed only if the set actually moves.
|
|
660
|
+
const was = this._disabledMcpServers.has(name)
|
|
661
|
+
result = { found: true, changed: was === enabled, status: enabled ? 'configured' : 'disabled' }
|
|
662
|
+
if (enabled) this._disabledMcpServers.delete(name)
|
|
663
|
+
else this._disabledMcpServers.add(name)
|
|
664
|
+
}
|
|
665
|
+
if (result.changed) this._emitMcpServers()
|
|
666
|
+
return result
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* #6822: submit a pasted OAuth authorization code for a remote MCP server that
|
|
671
|
+
* reported `oauth-required`. Delegates redemption + authenticated reconnect to
|
|
672
|
+
* the fleet, then re-emits `mcp_servers` so every client converges on the new
|
|
673
|
+
* status. Returns `{ found, ok?, status?, error? }`; `found: false` when the
|
|
674
|
+
* server isn't configured (or the fleet never started), so the WS handler can
|
|
675
|
+
* surface a clean error. The code + tokens never touch a log or the wire.
|
|
676
|
+
*/
|
|
677
|
+
async submitMcpAuthCode(name, code) {
|
|
678
|
+
if (typeof name !== 'string' || !this._mcpServerConfigs.some((c) => c.name === name)) {
|
|
679
|
+
return { found: false }
|
|
680
|
+
}
|
|
681
|
+
if (!this._mcpFleet) {
|
|
682
|
+
return { found: false }
|
|
683
|
+
}
|
|
684
|
+
const result = await this._mcpFleet.submitAuthCode(name, code)
|
|
685
|
+
if (result?.ok) this._emitMcpServers()
|
|
686
|
+
return result
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/**
|
|
690
|
+
* #6974: rebuild the frozen `mcpServers` metadata view after a config
|
|
691
|
+
* mutation. `this.mcpServers` is the read-only, credential-stripped list other
|
|
692
|
+
* surfaces read, so it must track `_mcpServerConfigs` on add/remove.
|
|
693
|
+
*/
|
|
694
|
+
_refreshMcpServerMetadata() {
|
|
695
|
+
this.mcpServers = Object.freeze(this._mcpServerConfigs.map(toMcpServerMetadata))
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/**
|
|
699
|
+
* The trust-store path this session's gates use. Resolved through
|
|
700
|
+
* `defaultTrustStorePath()` (which honours `CHROXY_MCP_TRUST_PATH`) so the
|
|
701
|
+
* session's pre-write gate and the fleet's spawn-time gate always agree on the
|
|
702
|
+
* same file — the fleet resolves it the same way when no override is passed.
|
|
703
|
+
*/
|
|
704
|
+
_mcpTrustStorePath() {
|
|
705
|
+
return defaultTrustStorePath()
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* #7001: obtain the user's SPAWN-TRUST decision for `cfg` BEFORE its config
|
|
710
|
+
* entry is persisted.
|
|
711
|
+
*
|
|
712
|
+
* Why this cannot be left to the fleet's spawn-time gate alone: the gate runs
|
|
713
|
+
* after the write, so a denial left the server configured. The user said "no",
|
|
714
|
+
* yet the entry stayed in `~/.claude.json` and re-prompted on every subsequent
|
|
715
|
+
* session start — one accidental "allow" (or a UI that auto-confirms) later and
|
|
716
|
+
* it runs. Deciding first means a denied add persists NOTHING.
|
|
717
|
+
*
|
|
718
|
+
* Same gate the fleet uses, so the two cannot disagree: same trust store, same
|
|
719
|
+
* `withTrustStoreLock` critical section (load → prompt → recordTrust), same
|
|
720
|
+
* `requestMcpTrust` payload shape (header/env VALUES never included). On allow
|
|
721
|
+
* the decision is recorded, so the fleet's own gate then sees `isTrusted` and
|
|
722
|
+
* does NOT prompt a second time for the same add.
|
|
723
|
+
*
|
|
724
|
+
* The lock is NOT held across the subsequent write/fleet-attach —
|
|
725
|
+
* `withTrustStoreLock` is not re-entrant and the fleet's gate takes it again.
|
|
726
|
+
*
|
|
727
|
+
* No PermissionManager → no gate, exactly as in `MCPFleet._makeClient` (#4457):
|
|
728
|
+
* there is no one to ask, and this must not become a hard failure for headless
|
|
729
|
+
* contexts that never had a trust prompt in the first place.
|
|
730
|
+
*
|
|
731
|
+
* @returns {Promise<{ allowed: boolean, prompted: boolean }>}
|
|
732
|
+
*/
|
|
733
|
+
async _decideMcpSpawnTrust(cfg) {
|
|
734
|
+
const pm = this._permissions
|
|
735
|
+
if (!pm || typeof pm.requestMcpTrust !== 'function') return { allowed: true, prompted: false }
|
|
736
|
+
const trustPath = this._mcpTrustStorePath()
|
|
737
|
+
return withTrustStoreLock(trustPath, async () => {
|
|
738
|
+
const store = loadTrustStore(trustPath, { log })
|
|
739
|
+
if (isTrusted(store, cfg)) return { allowed: true, prompted: false }
|
|
740
|
+
const isRemote = typeof cfg.url === 'string' && cfg.url.length > 0
|
|
741
|
+
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() }
|
|
744
|
+
const allowed = await pm.requestMcpTrust(trustReq)
|
|
745
|
+
if (allowed) recordTrust(cfg, trustPath)
|
|
746
|
+
return { allowed: allowed === true, prompted: true }
|
|
747
|
+
})
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* Build the in-memory fleet config from a normalized persisted entry, filling
|
|
752
|
+
* the shape defaults (`args`/`env` for stdio, `headers` for remote) the fleet
|
|
753
|
+
* and the trust key both read.
|
|
754
|
+
*/
|
|
755
|
+
static _mcpCfgFromEntry(name, entry) {
|
|
756
|
+
const cfg = { name, ...entry }
|
|
757
|
+
if (cfg.command !== undefined) {
|
|
758
|
+
cfg.args = Array.isArray(cfg.args) ? cfg.args : []
|
|
759
|
+
cfg.env = cfg.env && typeof cfg.env === 'object' ? cfg.env : {}
|
|
760
|
+
} else {
|
|
761
|
+
cfg.headers = cfg.headers && typeof cfg.headers === 'object' ? cfg.headers : {}
|
|
762
|
+
}
|
|
763
|
+
return cfg
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* #6974: add a brand-new MCP server — a CONFIG MUTATION, not a runtime toggle.
|
|
768
|
+
*
|
|
769
|
+
* Order (tightened by #7001):
|
|
770
|
+
* 1. validate + PLAN the write (`planAddMcpServerToConfig`) — every check the
|
|
771
|
+
* commit performs, no write. Yields the exact normalized entry that would
|
|
772
|
+
* be persisted, so the trust decision is made against precisely the config
|
|
773
|
+
* that would run, and a name that would fail (EXISTS / invalid) never
|
|
774
|
+
* raises a prompt.
|
|
775
|
+
* 2. obtain the spawn-trust decision for that entry. DENIED → return without
|
|
776
|
+
* writing anything: the user's config is untouched.
|
|
777
|
+
* 3. commit the config write — the durability commit point. If it fails,
|
|
778
|
+
* nothing about the live session changed.
|
|
779
|
+
* 4. only then attach to the live fleet, so a user can never end up with a
|
|
780
|
+
* running server that vanishes on restart.
|
|
781
|
+
*
|
|
782
|
+
* Adding is still not, by itself, permission to execute: step 2 IS that
|
|
783
|
+
* permission, and the fleet's independent gate re-checks it at spawn time (a
|
|
784
|
+
* config entry that is persisted but untrusted — e.g. hand-added to
|
|
785
|
+
* `~/.claude.json`, or trusted-then-tampered — still prompts).
|
|
786
|
+
*
|
|
787
|
+
* Returns `{ ok, error?, code?, status? }`. `code: 'EXISTS'` distinguishes a
|
|
788
|
+
* duplicate name from a generic validation failure; `code: 'TRUST_DENIED'`
|
|
789
|
+
* distinguishes "the user said no" from a failure.
|
|
790
|
+
*/
|
|
791
|
+
async addMcpServer(name, config, scope = 'user') {
|
|
792
|
+
const valid = validateNewMcpServerName(name)
|
|
793
|
+
if (!valid.ok) return { ok: false, error: valid.error }
|
|
794
|
+
|
|
795
|
+
let planned
|
|
796
|
+
try {
|
|
797
|
+
planned = planAddMcpServerToConfig({
|
|
798
|
+
name: valid.name,
|
|
799
|
+
config,
|
|
800
|
+
scope,
|
|
801
|
+
cwd: this.cwd,
|
|
802
|
+
configPath: this._mcpConfigPath,
|
|
803
|
+
})
|
|
804
|
+
} catch (err) {
|
|
805
|
+
return { ok: false, error: `Failed to read MCP config: ${err?.message || String(err)}` }
|
|
806
|
+
}
|
|
807
|
+
if (!planned.ok) return { ok: false, error: planned.error, code: planned.code }
|
|
808
|
+
|
|
809
|
+
// The candidate config, exactly as it would be persisted and spawned.
|
|
810
|
+
const cfg = ClaudeByokSession._mcpCfgFromEntry(valid.name, planned.entry)
|
|
811
|
+
|
|
812
|
+
const trust = await this._decideMcpSpawnTrust(cfg)
|
|
813
|
+
if (!trust.allowed) {
|
|
814
|
+
return {
|
|
815
|
+
ok: false,
|
|
816
|
+
code: 'TRUST_DENIED',
|
|
817
|
+
error: `Spawning MCP server '${valid.name}' was denied, so it was not added to the config.`,
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
let written
|
|
822
|
+
try {
|
|
823
|
+
written = addMcpServerToConfig({
|
|
824
|
+
name: valid.name,
|
|
825
|
+
config,
|
|
826
|
+
scope,
|
|
827
|
+
cwd: this.cwd,
|
|
828
|
+
configPath: this._mcpConfigPath,
|
|
829
|
+
})
|
|
830
|
+
} catch (err) {
|
|
831
|
+
// A throw here is an I/O failure (permissions, ENOSPC, a failed fsync) —
|
|
832
|
+
// the atomic writer leaves the original file intact, so the session is
|
|
833
|
+
// still coherent. Surface it without echoing config contents.
|
|
834
|
+
return { ok: false, error: `Failed to write MCP config: ${err?.message || String(err)}` }
|
|
835
|
+
}
|
|
836
|
+
if (!written.ok) return { ok: false, error: written.error, code: written.code }
|
|
837
|
+
|
|
838
|
+
// #7002: the config's existing mode is PRESERVED by design, so a
|
|
839
|
+
// group/world-readable `~/.claude.json` that just received `env`/`headers`
|
|
840
|
+
// (routinely API tokens) is a case where we are the party making things
|
|
841
|
+
// worse. Say so loudly in the daemon log — it never echoes a secret value —
|
|
842
|
+
// and hand it to the caller so a client can surface it too.
|
|
843
|
+
if (written.warning) log.warn(`BYOK MCP: ${written.warning}`)
|
|
844
|
+
|
|
845
|
+
// Mirror the persisted entry into the in-memory config list. `entry` is the
|
|
846
|
+
// NORMALIZED object that was actually written, so memory and disk cannot
|
|
847
|
+
// diverge. Normalization is pure over (name, config), so this is structurally
|
|
848
|
+
// identical to the `cfg` the trust decision was made against — and if it ever
|
|
849
|
+
// were not, the fleet's own gate below would see an untrusted config and
|
|
850
|
+
// prompt rather than spawn.
|
|
851
|
+
const persistedCfg = ClaudeByokSession._mcpCfgFromEntry(valid.name, written.entry)
|
|
852
|
+
this._mcpServerConfigs = [...this._mcpServerConfigs, persistedCfg]
|
|
853
|
+
this._refreshMcpServerMetadata()
|
|
854
|
+
|
|
855
|
+
let status = 'configured'
|
|
856
|
+
if (this._mcpFleet) {
|
|
857
|
+
const result = await this._mcpFleet.addServer(persistedCfg)
|
|
858
|
+
if (result.status) status = result.status
|
|
859
|
+
}
|
|
860
|
+
// No fleet yet (nothing was configured at start, so it was never created):
|
|
861
|
+
// the entry is persisted and `start()` will pick it up. Spinning a fleet up
|
|
862
|
+
// here would duplicate start()'s wiring for no gain.
|
|
863
|
+
this._emitMcpServers()
|
|
864
|
+
const result = { ok: true, status }
|
|
865
|
+
if (written.warning) result.warning = written.warning
|
|
866
|
+
return result
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
/**
|
|
870
|
+
* #6974: permanently remove a configured MCP server — the counterpart to
|
|
871
|
+
* `addMcpServer`, and distinct from `setMcpServerEnabled(name, false)` (which
|
|
872
|
+
* parks a server that stays configured).
|
|
873
|
+
*
|
|
874
|
+
* The config write is again the commit point and happens first: removal is a
|
|
875
|
+
* capability REDUCTION, so it must be durable before the live fleet stops
|
|
876
|
+
* enforcing it. `found: false` (absent from the requested scope) is reported
|
|
877
|
+
* without touching the fleet, so a mis-scoped remove cannot disconnect a
|
|
878
|
+
* server it did not remove from disk.
|
|
879
|
+
*
|
|
880
|
+
* Returns `{ ok, found?, error? }`.
|
|
881
|
+
*/
|
|
882
|
+
async removeMcpServer(name, scope = 'user') {
|
|
883
|
+
const valid = validateMcpServerNameForRemoval(name)
|
|
884
|
+
if (!valid.ok) return { ok: false, error: valid.error }
|
|
885
|
+
|
|
886
|
+
let written
|
|
887
|
+
try {
|
|
888
|
+
written = removeMcpServerFromConfig({
|
|
889
|
+
name: valid.name,
|
|
890
|
+
scope,
|
|
891
|
+
cwd: this.cwd,
|
|
892
|
+
configPath: this._mcpConfigPath,
|
|
893
|
+
})
|
|
894
|
+
} catch (err) {
|
|
895
|
+
return { ok: false, error: `Failed to write MCP config: ${err?.message || String(err)}` }
|
|
896
|
+
}
|
|
897
|
+
if (!written.ok) return { ok: false, error: written.error }
|
|
898
|
+
if (!written.found) return { ok: true, found: false }
|
|
899
|
+
|
|
900
|
+
this._mcpServerConfigs = this._mcpServerConfigs.filter((c) => c.name !== valid.name)
|
|
901
|
+
this._refreshMcpServerMetadata()
|
|
902
|
+
this._disabledMcpServers.delete(valid.name)
|
|
903
|
+
if (this._mcpFleet) await this._mcpFleet.removeServer(valid.name)
|
|
904
|
+
// force: removing the last configured server still has to publish the now-
|
|
905
|
+
// empty list, or clients keep rendering the row we just deleted.
|
|
906
|
+
this._emitMcpServers({ force: true })
|
|
907
|
+
// #7054/#7068: surface the durability caveat on the REDUCTION path. The
|
|
908
|
+
// removal IS in effect (fleet stopped, config rewritten), so this is a
|
|
909
|
+
// warning riding a success — not a failure. Mirrors addMcpServer's existing
|
|
910
|
+
// `warning` channel rather than inventing a second convention.
|
|
911
|
+
if (written.durabilityUnconfirmed) {
|
|
912
|
+
return {
|
|
913
|
+
ok: true,
|
|
914
|
+
found: true,
|
|
915
|
+
warning:
|
|
916
|
+
`The server was removed and is no longer running, but the config write could not be confirmed ` +
|
|
917
|
+
`durable (${written.durabilityUnconfirmed}) — a power loss could restore it on the next start. ` +
|
|
918
|
+
`Resolve the storage error and re-check.`,
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
return { ok: true, found: true }
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
/**
|
|
925
|
+
* #6824: the parked (disabled) server names, sorted, for persistence into
|
|
926
|
+
* session-state.json. Session-manager reads this in `_serializeSessionEntry`
|
|
927
|
+
* and forwards it back as `disabledMcpServers` on restore.
|
|
928
|
+
*/
|
|
929
|
+
getDisabledMcpServers() {
|
|
930
|
+
return [...this._disabledMcpServers].sort()
|
|
460
931
|
}
|
|
461
932
|
|
|
462
933
|
async sendMessage(prompt, attachments, _options = {}) {
|
|
@@ -469,7 +940,39 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
469
940
|
return
|
|
470
941
|
}
|
|
471
942
|
|
|
943
|
+
// Claim busy up front so the async MCP-prompt resolution below can't race a
|
|
944
|
+
// second concurrent send (isRunning stays true across the await window).
|
|
472
945
|
this._isBusy = true
|
|
946
|
+
|
|
947
|
+
// #6823: MCP prompt-as-slash-command interception. A leading
|
|
948
|
+
// `/mcp__<server>__<prompt>` that matches a connected MCP server's prompt
|
|
949
|
+
// is expanded via `prompts/get` and the returned messages become the user
|
|
950
|
+
// turn. On a resolution failure (bad args, dead server) we release busy and
|
|
951
|
+
// surface an error WITHOUT starting a turn. Plain text and non-MCP slash
|
|
952
|
+
// commands (`/clear`, etc.) pass through untouched.
|
|
953
|
+
let promptText = typeof prompt === 'string' ? prompt : String(prompt ?? '')
|
|
954
|
+
const mcpPromptMatch = this._matchMcpPromptCommand(promptText)
|
|
955
|
+
if (mcpPromptMatch) {
|
|
956
|
+
try {
|
|
957
|
+
promptText = await this._resolveMcpPromptToText(mcpPromptMatch)
|
|
958
|
+
} catch (err) {
|
|
959
|
+
this._isBusy = false
|
|
960
|
+
this.emit('error', {
|
|
961
|
+
message: `MCP prompt /${mcpPromptMatch.prefixedName} failed: ${err?.message || String(err)}`,
|
|
962
|
+
})
|
|
963
|
+
return
|
|
964
|
+
}
|
|
965
|
+
// #6845: honesty. The raw `/mcp__server__prompt` the user typed is NOT
|
|
966
|
+
// what the model receives — the SERVER-CONTROLLED expansion above is,
|
|
967
|
+
// injected as the user turn. Surface it in the transcript as a labeled
|
|
968
|
+
// system marker so the user can audit the actual injected content (a
|
|
969
|
+
// trusted-but-verbose, or later-compromised, MCP server could inject
|
|
970
|
+
// surprising text). Emitted before stream_start so it renders between the
|
|
971
|
+
// user's raw command echo and the assistant response. Never lets a marker
|
|
972
|
+
// failure break the turn — the message send is what matters.
|
|
973
|
+
this._emitMcpPromptExpansionMarker(mcpPromptMatch, promptText)
|
|
974
|
+
}
|
|
975
|
+
|
|
473
976
|
this._messageCounter += 1
|
|
474
977
|
const messageId = `${this._messageIdPrefix}-${this._messageCounter}`
|
|
475
978
|
this._currentMessageId = messageId
|
|
@@ -488,8 +991,10 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
488
991
|
// Build the user message. On the very first turn, prepend any skills
|
|
489
992
|
// text from BaseSession._buildPrependPrompt(). Subsequent turns are
|
|
490
993
|
// plain prompt text — skills that targeted `system` ride on the
|
|
491
|
-
// rebuilt systemPrompt instead.
|
|
492
|
-
|
|
994
|
+
// rebuilt systemPrompt instead. #6823: `promptText` is the MCP-prompt-
|
|
995
|
+
// expanded text when the input was a `/mcp__server__prompt` command, else
|
|
996
|
+
// the raw prompt.
|
|
997
|
+
let userText = promptText
|
|
493
998
|
if (this._history.length === 0) {
|
|
494
999
|
const prepend = typeof this._buildPrependPrompt === 'function'
|
|
495
1000
|
? this._buildPrependPrompt()
|
|
@@ -534,6 +1039,14 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
534
1039
|
// dashboard shows "n/a" rather than a misleading $0.00 — distinct from a
|
|
535
1040
|
// genuine zero-cost turn.
|
|
536
1041
|
let turnCostKnown = false
|
|
1042
|
+
// #6769: the FINAL round's individual usage — a true prompt-size SNAPSHOT
|
|
1043
|
+
// (that round's input + cache_read + cache_creation is exactly the
|
|
1044
|
+
// conversation as last sent to the API), unlike the summed `turnUsage`
|
|
1045
|
+
// above which re-counts the history once per round and must never feed
|
|
1046
|
+
// the context meter. Updated after every finalMessage() so whatever round
|
|
1047
|
+
// ends the turn (normal break, abort break, summary round) leaves its
|
|
1048
|
+
// snapshot here.
|
|
1049
|
+
let lastRoundUsage = null
|
|
537
1050
|
const pricingModel = this.model || this._defaultModel
|
|
538
1051
|
const pricing = this._getPricing(pricingModel)
|
|
539
1052
|
if (!pricing && !this._pricingWarnedModels.has(pricingModel)) {
|
|
@@ -591,6 +1104,26 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
591
1104
|
case 'stream_delta':
|
|
592
1105
|
this.emit('stream_delta', { messageId, delta: t.text })
|
|
593
1106
|
break
|
|
1107
|
+
case 'thinking_delta': {
|
|
1108
|
+
// #6756 — extended-thinking (reasoning) delta. The translator
|
|
1109
|
+
// already recognises `thinking_delta` (byok-event-translator.js);
|
|
1110
|
+
// previously it hit `default: break` and was dropped. Route it to
|
|
1111
|
+
// a distinct thinking id (opened lazily on the block's first
|
|
1112
|
+
// delta) so it streams into a `type: 'thinking'` bubble.
|
|
1113
|
+
const idx = typeof t.index === 'number' ? t.index : 0
|
|
1114
|
+
let thinkingId = this._streamingIndexToThinkingId.get(idx)
|
|
1115
|
+
if (!thinkingId) {
|
|
1116
|
+
thinkingId = `${messageId}-thinking-${idx}`
|
|
1117
|
+
this._streamingIndexToThinkingId.set(idx, thinkingId)
|
|
1118
|
+
// #6391 footer-stat: mark the block's start for the
|
|
1119
|
+
// content_block_stop elapsed-time computation. #6943:
|
|
1120
|
+
// performance.now() (monotonic), not Date.now().
|
|
1121
|
+
this._thinkingStartMs.set(thinkingId, performance.now())
|
|
1122
|
+
this.emit('stream_start', { messageId: thinkingId, thinking: true })
|
|
1123
|
+
}
|
|
1124
|
+
this.emit('stream_delta', { messageId: thinkingId, delta: t.text, thinking: true })
|
|
1125
|
+
break
|
|
1126
|
+
}
|
|
594
1127
|
case 'tool_start': {
|
|
595
1128
|
// Surface the tool_use opening to the dashboard so it can
|
|
596
1129
|
// render a tool-call bubble. Matches sdk-session.js /
|
|
@@ -671,10 +1204,32 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
671
1204
|
// #4080: free the per-index slot as soon as the block
|
|
672
1205
|
// finishes so a long turn's map doesn't grow unbounded.
|
|
673
1206
|
// Safe to delete even if index isn't in the map — that
|
|
674
|
-
// just means we never tracked this block (text
|
|
675
|
-
//
|
|
1207
|
+
// just means we never tracked this block (text) and the
|
|
1208
|
+
// lookup is a no-op.
|
|
676
1209
|
if (typeof t.index === 'number') {
|
|
677
1210
|
this._streamingIndexToToolUseId.delete(t.index)
|
|
1211
|
+
// #6756 — close the thinking stream for this block so the
|
|
1212
|
+
// client finalises its "Thinking… → Thought" label.
|
|
1213
|
+
const thinkingId = this._streamingIndexToThinkingId.get(t.index)
|
|
1214
|
+
if (thinkingId) {
|
|
1215
|
+
this._streamingIndexToThinkingId.delete(t.index)
|
|
1216
|
+
// #6391 footer-stat: elapsed monotonic time from the block's
|
|
1217
|
+
// open to now → the client's `thought for Xs` footer. Omit
|
|
1218
|
+
// when the start wasn't tracked so we never send a bogus 0.
|
|
1219
|
+
// No token count: Anthropic's usage folds thinking tokens
|
|
1220
|
+
// into output_tokens with no per-block breakdown (see
|
|
1221
|
+
// follow-up). #6943: startMs is a performance.now() sample
|
|
1222
|
+
// (monotonic, immune to wall-clock jumps), so elapsed can
|
|
1223
|
+
// never legitimately be negative — Math.max(0, …) is a
|
|
1224
|
+
// defensive floor only, not a correctness requirement.
|
|
1225
|
+
const startMs = this._thinkingStartMs.get(thinkingId)
|
|
1226
|
+
this._thinkingStartMs.delete(thinkingId)
|
|
1227
|
+
const streamEndMsg = { messageId: thinkingId, thinking: true }
|
|
1228
|
+
if (typeof startMs === 'number') {
|
|
1229
|
+
streamEndMsg.thinkingDurationMs = Math.max(0, Math.round(performance.now() - startMs))
|
|
1230
|
+
}
|
|
1231
|
+
this.emit('stream_end', streamEndMsg)
|
|
1232
|
+
}
|
|
678
1233
|
}
|
|
679
1234
|
break
|
|
680
1235
|
case 'message_delta':
|
|
@@ -701,8 +1256,13 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
701
1256
|
// toolUseId from the previous round. Clear here so each round
|
|
702
1257
|
// starts with an empty per-stream map.
|
|
703
1258
|
this._streamingIndexToToolUseId.clear()
|
|
1259
|
+
this._streamingIndexToThinkingId.clear()
|
|
1260
|
+
this._thinkingStartMs.clear()
|
|
704
1261
|
lastStopReason = final.stop_reason
|
|
705
1262
|
const roundUsage = final.usage || {}
|
|
1263
|
+
// #6769: keep the raw per-round usage — the LAST one standing at emit
|
|
1264
|
+
// time is the turn's occupancy snapshot.
|
|
1265
|
+
lastRoundUsage = roundUsage
|
|
706
1266
|
turnUsage.input_tokens += Number(roundUsage.input_tokens) || 0
|
|
707
1267
|
turnUsage.output_tokens += Number(roundUsage.output_tokens) || 0
|
|
708
1268
|
turnUsage.cache_read_input_tokens += Number(roundUsage.cache_read_input_tokens) || 0
|
|
@@ -854,6 +1414,9 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
854
1414
|
const summaryFinal = await summaryStream.finalMessage()
|
|
855
1415
|
lastStopReason = summaryFinal.stop_reason
|
|
856
1416
|
const sUsage = summaryFinal.usage || {}
|
|
1417
|
+
// #6769: the summary round is the turn's final API round — its
|
|
1418
|
+
// individual usage supersedes the previous round's snapshot.
|
|
1419
|
+
lastRoundUsage = sUsage
|
|
857
1420
|
turnUsage.input_tokens += Number(sUsage.input_tokens) || 0
|
|
858
1421
|
turnUsage.output_tokens += Number(sUsage.output_tokens) || 0
|
|
859
1422
|
turnUsage.cache_read_input_tokens += Number(sUsage.cache_read_input_tokens) || 0
|
|
@@ -883,6 +1446,15 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
883
1446
|
turnCost += this._subagentCostThisTurn
|
|
884
1447
|
if (this._subagentCostThisTurn > 0) turnCostKnown = true
|
|
885
1448
|
|
|
1449
|
+
// #6769: occupancy snapshot from the FINAL round's individual usage.
|
|
1450
|
+
// input + cache_read + cache_creation of that one API call = the
|
|
1451
|
+
// conversation as last sent (the true prompt size). Deliberately NOT
|
|
1452
|
+
// the summed turnUsage (over-reads ≈N× on an N-round turn) and
|
|
1453
|
+
// deliberately excludes subagent usage (a child Task runs in its own
|
|
1454
|
+
// window). Omitted when the turn produced no round usage — clients
|
|
1455
|
+
// keep their previous snapshot.
|
|
1456
|
+
const finalRoundOccupancy = ClaudeByokSession._buildFinalRoundOccupancy(lastRoundUsage)
|
|
1457
|
+
|
|
886
1458
|
this.emit('stream_end', { messageId })
|
|
887
1459
|
this.emit('result', {
|
|
888
1460
|
sessionId: null,
|
|
@@ -890,9 +1462,20 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
890
1462
|
stopReason: lastStopReason,
|
|
891
1463
|
duration: Date.now() - turnStartedAt,
|
|
892
1464
|
usage: turnUsage,
|
|
1465
|
+
...(finalRoundOccupancy ? { contextOccupancy: finalRoundOccupancy } : {}),
|
|
893
1466
|
// #5630: emit null when no round produced a known cost so the UI
|
|
894
1467
|
// shows "n/a" instead of a misleading $0.00.
|
|
895
1468
|
cost: turnCostKnown ? turnCost : null,
|
|
1469
|
+
// #6692: single-model split. Task-subagent usage is folded into
|
|
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
|
+
),
|
|
896
1479
|
})
|
|
897
1480
|
} catch (err) {
|
|
898
1481
|
// #4118: extend the synchronous stream-init rollback (#4109) to
|
|
@@ -935,6 +1518,13 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
935
1518
|
// #5630: null when no priced round committed before the error so the
|
|
936
1519
|
// partial-cost line shows "n/a" rather than $0.00.
|
|
937
1520
|
cost: turnCostKnown ? turnCost : null,
|
|
1521
|
+
// #6692: partial-spend turns get the same single-model split as the
|
|
1522
|
+
// success path so per-model accounting survives errored turns.
|
|
1523
|
+
modelUsage: synthesizeModelUsage(
|
|
1524
|
+
this.model || this._defaultModel,
|
|
1525
|
+
turnUsage,
|
|
1526
|
+
turnCostKnown ? turnCost : null,
|
|
1527
|
+
),
|
|
938
1528
|
})
|
|
939
1529
|
} finally {
|
|
940
1530
|
// #4080: per-turn isolation guarantee. The per-round clear after
|
|
@@ -945,6 +1535,8 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
945
1535
|
// them on every exit path — success, error, abort, hard timeout.
|
|
946
1536
|
// Safe to call when already empty.
|
|
947
1537
|
this._streamingIndexToToolUseId.clear()
|
|
1538
|
+
this._streamingIndexToThinkingId.clear()
|
|
1539
|
+
this._thinkingStartMs.clear()
|
|
948
1540
|
this._finishTurn()
|
|
949
1541
|
}
|
|
950
1542
|
}
|
|
@@ -1724,13 +2316,167 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1724
2316
|
}
|
|
1725
2317
|
}
|
|
1726
2318
|
|
|
2319
|
+
// -------------------------------------------------------------------------
|
|
2320
|
+
// #6823: MCP prompts (as slash commands) + resources (in the @-picker).
|
|
2321
|
+
// -------------------------------------------------------------------------
|
|
2322
|
+
|
|
2323
|
+
/**
|
|
2324
|
+
* Slash-command entries for every connected MCP server's prompts, namespaced
|
|
2325
|
+
* `mcp__<server>__<prompt>`. Merged into the session's slash-command surface
|
|
2326
|
+
* by the `list_slash_commands` handler + the connect-time auth_bootstrap
|
|
2327
|
+
* burst, so they render in SlashCommandPicker beside built-ins and markdown
|
|
2328
|
+
* skills. `source: 'mcp'` lets the picker badge/group them.
|
|
2329
|
+
*/
|
|
2330
|
+
getMcpPromptCommands() {
|
|
2331
|
+
if (!this._mcpFleet) return []
|
|
2332
|
+
return this._mcpFleet.prompts.map((p) => ({
|
|
2333
|
+
name: p.name,
|
|
2334
|
+
description: typeof p.description === 'string' ? p.description : '',
|
|
2335
|
+
source: 'mcp',
|
|
2336
|
+
}))
|
|
2337
|
+
}
|
|
2338
|
+
|
|
2339
|
+
/**
|
|
2340
|
+
* Read-only listing of every connected MCP server's resources for the
|
|
2341
|
+
* dashboard `@`-mention picker. Each entry carries the owning `server` so a
|
|
2342
|
+
* later read (`readMcpResource`) can route back by (server, uri).
|
|
2343
|
+
*/
|
|
2344
|
+
getMcpResources() {
|
|
2345
|
+
if (!this._mcpFleet) return []
|
|
2346
|
+
return this._mcpFleet.resources
|
|
2347
|
+
.map((r) => ({
|
|
2348
|
+
uri: typeof r.uri === 'string' ? r.uri : '',
|
|
2349
|
+
name: typeof r.name === 'string' && r.name ? r.name : (typeof r.uri === 'string' ? r.uri : ''),
|
|
2350
|
+
description: typeof r.description === 'string' ? r.description : undefined,
|
|
2351
|
+
mimeType: typeof r.mimeType === 'string' ? r.mimeType : undefined,
|
|
2352
|
+
server: r._mcpServer,
|
|
2353
|
+
}))
|
|
2354
|
+
.filter((r) => r.uri)
|
|
2355
|
+
}
|
|
2356
|
+
|
|
2357
|
+
/**
|
|
2358
|
+
* Read one MCP resource's contents (`resources/read`) routed by (server, uri).
|
|
2359
|
+
* Passthrough to the fleet; throws when no fleet exists or the read fails.
|
|
2360
|
+
*/
|
|
2361
|
+
async readMcpResource(serverName, uri) {
|
|
2362
|
+
if (!this._mcpFleet) throw new Error('No MCP servers configured for this session')
|
|
2363
|
+
return this._mcpFleet.readResource(serverName, uri, this._mcpToolCallTimeoutMs ?? undefined)
|
|
2364
|
+
}
|
|
2365
|
+
|
|
2366
|
+
/**
|
|
2367
|
+
* Parse a user input as an MCP prompt slash command. Returns a match
|
|
2368
|
+
* descriptor when the input is a leading `/mcp__<server>__<prompt>` that a
|
|
2369
|
+
* connected server actually advertises, else null (so plain text and non-MCP
|
|
2370
|
+
* slash commands like `/clear` pass through unchanged).
|
|
2371
|
+
*/
|
|
2372
|
+
_matchMcpPromptCommand(text) {
|
|
2373
|
+
if (!this._mcpFleet || typeof text !== 'string') return null
|
|
2374
|
+
if (!text.startsWith('/')) return null
|
|
2375
|
+
const body = text.slice(1)
|
|
2376
|
+
const wsIdx = body.search(/\s/)
|
|
2377
|
+
const name = wsIdx === -1 ? body : body.slice(0, wsIdx)
|
|
2378
|
+
const rest = wsIdx === -1 ? '' : body.slice(wsIdx + 1).trim()
|
|
2379
|
+
// Must parse as an mcp__server__name AND match a live prompt — otherwise a
|
|
2380
|
+
// stray `/mcp__whatever` typed by the user stays literal input.
|
|
2381
|
+
if (!parseMcpToolName(name)) return null
|
|
2382
|
+
const promptDef = this._mcpFleet.prompts.find((p) => p.name === name)
|
|
2383
|
+
if (!promptDef) return null
|
|
2384
|
+
return { prefixedName: name, rest, promptDef }
|
|
2385
|
+
}
|
|
2386
|
+
|
|
2387
|
+
/**
|
|
2388
|
+
* Resolve an MCP prompt command to the text injected as the user turn. Calls
|
|
2389
|
+
* `prompts/get` (with best-effort argument mapping) and flattens the returned
|
|
2390
|
+
* messages into text. No-argument prompts are first-class; when the prompt
|
|
2391
|
+
* declares arguments and the user supplied trailing text, that raw text maps
|
|
2392
|
+
* to the FIRST declared argument (a documented single-arg convenience — see
|
|
2393
|
+
* PR #6823). Throws (surfaced to the user) when the server errors or the
|
|
2394
|
+
* prompt yields no injectable text.
|
|
2395
|
+
*/
|
|
2396
|
+
async _resolveMcpPromptToText(match) {
|
|
2397
|
+
const declared = Array.isArray(match.promptDef?.arguments) ? match.promptDef.arguments : []
|
|
2398
|
+
let args
|
|
2399
|
+
// #6844 review: require a NON-EMPTY declared argument name — a server
|
|
2400
|
+
// advertising `arguments: [{ name: '' }]` (or whitespace) must not produce
|
|
2401
|
+
// a bogus `{ "": text }` argument map; treat it as no declared args and
|
|
2402
|
+
// call prompts/get without arguments.
|
|
2403
|
+
const firstArgName = typeof declared[0]?.name === 'string' && declared[0].name.trim()
|
|
2404
|
+
? declared[0].name
|
|
2405
|
+
: null
|
|
2406
|
+
if (firstArgName && match.rest) {
|
|
2407
|
+
args = { [firstArgName]: match.rest }
|
|
2408
|
+
}
|
|
2409
|
+
const result = await this._mcpFleet.getPrompt(
|
|
2410
|
+
match.prefixedName,
|
|
2411
|
+
args,
|
|
2412
|
+
this._mcpToolCallTimeoutMs ?? undefined,
|
|
2413
|
+
)
|
|
2414
|
+
const text = this._extractPromptMessagesText(result)
|
|
2415
|
+
if (!text) throw new Error('prompt returned no injectable text content')
|
|
2416
|
+
return text
|
|
2417
|
+
}
|
|
2418
|
+
|
|
2419
|
+
/**
|
|
2420
|
+
* #6845: emit the honesty marker for an expanded MCP prompt. The expansion is
|
|
2421
|
+
* SERVER-CONTROLLED (authored by the MCP server, not typed by the user) and
|
|
2422
|
+
* lands in the user role, so the marker is explicitly provenance-labeled and
|
|
2423
|
+
* carries the (bounded) injected text for audit. Structured on a `system`
|
|
2424
|
+
* message with `subtype: 'mcp_prompt_expansion'` + a `mcpPromptExpansion`
|
|
2425
|
+
* field — the same optional-field-on-an-existing-marker path #6768's
|
|
2426
|
+
* compact_boundary uses, so no new wire type is introduced. `content` carries
|
|
2427
|
+
* the same labeled+bounded text so generic renderers (mobile system bubble,
|
|
2428
|
+
* the System tab) stay honest even without the dedicated marker component.
|
|
2429
|
+
* A marker failure is logged and swallowed: surfacing the expansion must
|
|
2430
|
+
* never break delivery of the actual user turn.
|
|
2431
|
+
*/
|
|
2432
|
+
_emitMcpPromptExpansionMarker(match, expandedText) {
|
|
2433
|
+
try {
|
|
2434
|
+
const parsed = parseMcpToolName(match?.prefixedName) || {}
|
|
2435
|
+
const server = typeof parsed.serverName === 'string' ? parsed.serverName : ''
|
|
2436
|
+
const prompt = typeof parsed.toolName === 'string' ? parsed.toolName : ''
|
|
2437
|
+
const { text, truncated } = boundMcpPromptExpansionText(expandedText)
|
|
2438
|
+
const label = `Expanded /${match?.prefixedName ?? ''} (server-controlled MCP prompt)`
|
|
2439
|
+
this.emit('message', {
|
|
2440
|
+
type: 'system',
|
|
2441
|
+
subtype: 'mcp_prompt_expansion',
|
|
2442
|
+
content: `${label} →\n${text}`,
|
|
2443
|
+
mcpPromptExpansion: { server, prompt, text, truncated },
|
|
2444
|
+
timestamp: Date.now(),
|
|
2445
|
+
})
|
|
2446
|
+
} catch (err) {
|
|
2447
|
+
log.warn(`failed to emit MCP prompt expansion marker: ${err?.message || String(err)}`)
|
|
2448
|
+
}
|
|
2449
|
+
}
|
|
2450
|
+
|
|
2451
|
+
/**
|
|
2452
|
+
* Flatten an MCP `prompts/get` result's `messages[]` into a single string.
|
|
2453
|
+
* Handles the spec's `content` shapes: a bare string, a single
|
|
2454
|
+
* `{ type:'text', text }` object, or an array of content blocks. Non-text
|
|
2455
|
+
* blocks (image/resource) are skipped — chroxy injects prompts as a text
|
|
2456
|
+
* user turn.
|
|
2457
|
+
*/
|
|
2458
|
+
_extractPromptMessagesText(result) {
|
|
2459
|
+
const messages = Array.isArray(result?.messages) ? result.messages : []
|
|
2460
|
+
const parts = []
|
|
2461
|
+
for (const m of messages) {
|
|
2462
|
+
const c = m?.content
|
|
2463
|
+
if (typeof c === 'string') { parts.push(c); continue }
|
|
2464
|
+
if (Array.isArray(c)) {
|
|
2465
|
+
for (const block of c) if (typeof block?.text === 'string') parts.push(block.text)
|
|
2466
|
+
continue
|
|
2467
|
+
}
|
|
2468
|
+
if (c && typeof c === 'object' && typeof c.text === 'string') parts.push(c.text)
|
|
2469
|
+
}
|
|
2470
|
+
return parts.join('\n\n').trim()
|
|
2471
|
+
}
|
|
2472
|
+
|
|
1727
2473
|
/**
|
|
1728
2474
|
* In-process permission response — called by ws-permissions.js when the
|
|
1729
2475
|
* user taps Approve/Deny on the phone or dashboard. Forwards to
|
|
1730
2476
|
* PermissionManager which resolves the pending Promise in
|
|
1731
2477
|
* handlePermission() above.
|
|
1732
2478
|
*/
|
|
1733
|
-
respondToPermission(requestId, decision, editedInput) {
|
|
2479
|
+
respondToPermission(requestId, decision, editedInput, reason) {
|
|
1734
2480
|
// #5056: if this requestId belongs to a Task subagent (its pending
|
|
1735
2481
|
// entry lives in the CHILD's PermissionManager, not ours), forward
|
|
1736
2482
|
// the decision to that child. ws-permissions only ever calls the
|
|
@@ -1747,9 +2493,10 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1747
2493
|
// here too is idempotent and closes the lifetime tightly.
|
|
1748
2494
|
this._subagentPermissionRouting.delete(requestId)
|
|
1749
2495
|
// #6543: forward the operator's per-hunk editedInput to the child too.
|
|
1750
|
-
|
|
2496
|
+
// #6773: the deny `reason` forwards to the child as well.
|
|
2497
|
+
return child.respondToPermission(requestId, decision, editedInput, reason)
|
|
1751
2498
|
}
|
|
1752
|
-
return this._permissions.respondToPermission(requestId, decision, editedInput)
|
|
2499
|
+
return this._permissions.respondToPermission(requestId, decision, editedInput, reason)
|
|
1753
2500
|
}
|
|
1754
2501
|
|
|
1755
2502
|
/**
|
|
@@ -1770,6 +2517,33 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1770
2517
|
}
|
|
1771
2518
|
}
|
|
1772
2519
|
|
|
2520
|
+
/** Current session-scoped permission rules (#3072 parity with SdkSession). */
|
|
2521
|
+
getPermissionRules() {
|
|
2522
|
+
if (typeof this._permissions.getRules === 'function') {
|
|
2523
|
+
return this._permissions.getRules()
|
|
2524
|
+
}
|
|
2525
|
+
return []
|
|
2526
|
+
}
|
|
2527
|
+
|
|
2528
|
+
/**
|
|
2529
|
+
* #6771 — durable (project-scoped) permission rules applied to this session.
|
|
2530
|
+
*/
|
|
2531
|
+
getPersistentPermissionRules() {
|
|
2532
|
+
if (typeof this._permissions.getPersistentRules === 'function') {
|
|
2533
|
+
return this._permissions.getPersistentRules()
|
|
2534
|
+
}
|
|
2535
|
+
return []
|
|
2536
|
+
}
|
|
2537
|
+
|
|
2538
|
+
/**
|
|
2539
|
+
* #6771 — re-seed this session's in-memory durable rule set (no persist).
|
|
2540
|
+
*/
|
|
2541
|
+
setPersistentPermissionRules(rules) {
|
|
2542
|
+
if (typeof this._permissions.setPersistentRules === 'function') {
|
|
2543
|
+
this._permissions.setPersistentRules(rules)
|
|
2544
|
+
}
|
|
2545
|
+
}
|
|
2546
|
+
|
|
1773
2547
|
_emitTurnError(messageId, err, fallbackCode, partials) {
|
|
1774
2548
|
// #4057: SDK v0.81+ throws `APIUserAbortError` (not the generic
|
|
1775
2549
|
// `AbortError`) when an in-flight messages.stream sees its signal
|
|
@@ -1798,7 +2572,7 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1798
2572
|
messageId,
|
|
1799
2573
|
message: 'Interrupted by user',
|
|
1800
2574
|
code: 'ABORT',
|
|
1801
|
-
...(partials ? { usage: partials.usage, cost: partials.cost } : {}),
|
|
2575
|
+
...(partials ? { usage: partials.usage, cost: partials.cost, modelUsage: partials.modelUsage ?? null } : {}),
|
|
1802
2576
|
})
|
|
1803
2577
|
return
|
|
1804
2578
|
}
|
|
@@ -1808,7 +2582,7 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1808
2582
|
messageId,
|
|
1809
2583
|
message,
|
|
1810
2584
|
code,
|
|
1811
|
-
...(partials ? { usage: partials.usage, cost: partials.cost } : {}),
|
|
2585
|
+
...(partials ? { usage: partials.usage, cost: partials.cost, modelUsage: partials.modelUsage ?? null } : {}),
|
|
1812
2586
|
})
|
|
1813
2587
|
}
|
|
1814
2588
|
|
|
@@ -1977,6 +2751,8 @@ export class ClaudeByokSession extends BaseSession {
|
|
|
1977
2751
|
// active stream / outstanding permission count, but any external
|
|
1978
2752
|
// reference (test capture, future export) would keep them alive.
|
|
1979
2753
|
this._streamingIndexToToolUseId.clear()
|
|
2754
|
+
this._streamingIndexToThinkingId.clear()
|
|
2755
|
+
this._thinkingStartMs.clear()
|
|
1980
2756
|
this._pendingPermissionToolUseIds.clear()
|
|
1981
2757
|
// #5056: drop any outstanding subagent permission-routing pointers so
|
|
1982
2758
|
// the destroyed parent doesn't retain references to its children.
|