@chroxy/server 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- package/src/ws-server.js +2866 -0
|
@@ -0,0 +1,829 @@
|
|
|
1
|
+
import { EventEmitter } from 'events'
|
|
2
|
+
import { randomUUID } from 'crypto'
|
|
3
|
+
import { createLogger } from './logger.js'
|
|
4
|
+
// #6038: the SDK/TUI permission path broadcasts to clients too, so it must apply
|
|
5
|
+
// the same redaction as the hook path. Shared sanitizer + value redactor live in
|
|
6
|
+
// redaction.js (a leaf module — no import cycle / HTTP-handler weight).
|
|
7
|
+
import { sanitizeToolInput, redactValue } from './redaction.js'
|
|
8
|
+
|
|
9
|
+
const _fallbackLog = createLogger('permission-manager')
|
|
10
|
+
|
|
11
|
+
// Tools that acceptEdits mode auto-approves. `apply_patch` is codex's file-edit
|
|
12
|
+
// approval (item/fileChange/requestApproval, #6605) — the codex analogue of
|
|
13
|
+
// Write/Edit, so acceptEdits auto-approves codex edits too.
|
|
14
|
+
const ACCEPT_EDITS_TOOLS = new Set(['Read', 'Write', 'Edit', 'NotebookEdit', 'Glob', 'Grep', 'apply_patch'])
|
|
15
|
+
|
|
16
|
+
// Tools eligible for session-scoped auto-allow rules (`apply_patch` = codex edits).
|
|
17
|
+
export const ELIGIBLE_TOOLS = new Set(['Read', 'Write', 'Edit', 'NotebookEdit', 'Glob', 'Grep', 'apply_patch'])
|
|
18
|
+
|
|
19
|
+
// Tools that can never be auto-allowed by rules (too dangerous to whitelist).
|
|
20
|
+
// `shell` is codex's command-execution approval — the codex analogue of Bash, so
|
|
21
|
+
// arbitrary codex command execution can't be rule-whitelisted either (#6605).
|
|
22
|
+
export const NEVER_AUTO_ALLOW = new Set(['Bash', 'Task', 'WebFetch', 'WebSearch', 'shell'])
|
|
23
|
+
|
|
24
|
+
// Default permission timeout (5 minutes)
|
|
25
|
+
const DEFAULT_TIMEOUT_MS = 300_000
|
|
26
|
+
|
|
27
|
+
// #6448 — resource-limit caps (DoS hardening). A normal session sits far below
|
|
28
|
+
// all of these; they only bite under a flood of requests or a malicious tool
|
|
29
|
+
// input, where the alternative is unbounded memory/CPU growth.
|
|
30
|
+
const MAX_PENDING_PERMISSIONS = 1000 // concurrent pending requests (each holds map entries + a timer)
|
|
31
|
+
const MAX_SESSION_RULES = 100 // session-scoped auto-allow rules
|
|
32
|
+
const MAX_RAW_DESCRIPTION_LEN = 8192 // raw tool field length fed to redactValue (far above the 200-char shown window)
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* #6543 (IDE P3 feature B) — per-tool whitelist of the CONTENT field(s) a client
|
|
36
|
+
* may substitute via `editedInput` on an `allow` (the per-hunk pre-write review).
|
|
37
|
+
* ONLY these content fields can come from the client; the path/anchor fields
|
|
38
|
+
* (`file_path`, `old_string`, `command`, …) are always taken from the ORIGINAL
|
|
39
|
+
* input. So an operator can narrow/edit the shown content but can NEVER redirect
|
|
40
|
+
* where the write lands or what runs. A tool absent from this map ignores
|
|
41
|
+
* `editedInput` entirely (accept/reject-the-whole-tool). `old_string` is
|
|
42
|
+
* deliberately NOT editable — it is the Edit's match anchor, not shown content.
|
|
43
|
+
*/
|
|
44
|
+
const EDITABLE_INPUT_FIELDS = {
|
|
45
|
+
Write: ['content'],
|
|
46
|
+
Edit: ['new_string'],
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Merge a client's `editedInput` into the agent's original tool input under the
|
|
51
|
+
* strict {@link EDITABLE_INPUT_FIELDS} whitelist. Returns the original REFERENCE
|
|
52
|
+
* when there's no editedInput, it isn't a plain object, or the tool isn't
|
|
53
|
+
* editable; otherwise returns a shallow clone with only the whitelisted STRING
|
|
54
|
+
* fields substituted (a non-string edited value is skipped, so the clone equals
|
|
55
|
+
* the original by value). Never mutates the inputs. This is the load-bearing
|
|
56
|
+
* "narrow-only, no path redirect" control for feature B — keep it dumb + auditable.
|
|
57
|
+
*
|
|
58
|
+
* @param {object} originalInput the agent's proposed tool input
|
|
59
|
+
* @param {*} editedInput the client-supplied override (untrusted)
|
|
60
|
+
* @param {string} toolName the tool the permission is for
|
|
61
|
+
* @returns {object}
|
|
62
|
+
*/
|
|
63
|
+
export function mergeEditedInput(originalInput, editedInput, toolName) {
|
|
64
|
+
if (!editedInput || typeof editedInput !== 'object' || Array.isArray(editedInput)) return originalInput
|
|
65
|
+
const allowed = EDITABLE_INPUT_FIELDS[toolName]
|
|
66
|
+
if (!allowed) return originalInput
|
|
67
|
+
const merged = { ...originalInput }
|
|
68
|
+
for (const field of allowed) {
|
|
69
|
+
if (Object.prototype.hasOwnProperty.call(editedInput, field) && typeof editedInput[field] === 'string') {
|
|
70
|
+
merged[field] = editedInput[field]
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return merged
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Manages in-process permission requests for SDK-style sessions.
|
|
78
|
+
*
|
|
79
|
+
* Handles the lifecycle of permission prompts:
|
|
80
|
+
* - Creating permission requests with unique IDs
|
|
81
|
+
* - Emitting permission_request events for the UI
|
|
82
|
+
* - Resolving/denying requests via respondToPermission()
|
|
83
|
+
* - Auto-denying on timeout or abort signal
|
|
84
|
+
* - Tracking last permission data for reconnect re-send
|
|
85
|
+
* - AskUserQuestion routing and handling
|
|
86
|
+
*
|
|
87
|
+
* Events emitted:
|
|
88
|
+
* permission_request { requestId, tool, description, input, remainingMs, createdAt }
|
|
89
|
+
* user_question { toolUseId, questions }
|
|
90
|
+
*/
|
|
91
|
+
export class PermissionManager extends EventEmitter {
|
|
92
|
+
constructor({ timeoutMs, log, maxPendingPermissions } = {}) {
|
|
93
|
+
super()
|
|
94
|
+
this._timeoutMs = timeoutMs || DEFAULT_TIMEOUT_MS
|
|
95
|
+
this._log = log || console
|
|
96
|
+
// #6448 — bound on concurrent pending permissions; injectable so the cap is
|
|
97
|
+
// testable without minting 1000 real requests.
|
|
98
|
+
this._maxPendingPermissions = maxPendingPermissions || MAX_PENDING_PERMISSIONS
|
|
99
|
+
|
|
100
|
+
this._pendingPermissions = new Map() // requestId -> { resolve, input }
|
|
101
|
+
this._permissionTimers = new Map() // requestId -> timer
|
|
102
|
+
this._permissionCounter = 0
|
|
103
|
+
// Per-instance (per-session) nonce so requestIds are globally unique
|
|
104
|
+
// across sessions. Without it the id was `perm-${counter}-${ms}` with a
|
|
105
|
+
// counter that restarts at 0 every session — two sessions could mint the
|
|
106
|
+
// same id (same counter + same millisecond), and the parent-level
|
|
107
|
+
// subagent routing table (byok-session.js) would then alias a parent's
|
|
108
|
+
// own pending id against a child's (#5121). The counter is retained for
|
|
109
|
+
// human-readable ordering in logs; global uniqueness comes from the
|
|
110
|
+
// nonce. The id is opaque to all consumers — nothing parses its shape.
|
|
111
|
+
// Full 128-bit UUID (dashes stripped so the nonce stays a single id
|
|
112
|
+
// segment) — 32 bits would be birthday-bound vulnerable at scale.
|
|
113
|
+
this._idNonce = randomUUID().replace(/-/g, '')
|
|
114
|
+
this._lastPermissionData = new Map() // requestId -> emitted permission_request payload
|
|
115
|
+
|
|
116
|
+
// Session-scoped permission rules
|
|
117
|
+
this._sessionRules = [] // [{ tool, decision }]
|
|
118
|
+
|
|
119
|
+
// AskUserQuestion handling
|
|
120
|
+
this._pendingUserAnswer = null // { resolve, input, toolUseId } when waiting for user answer
|
|
121
|
+
this._questionTimer = null
|
|
122
|
+
this._waitingForAnswer = false
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Set session-scoped permission rules.
|
|
127
|
+
* Each rule must have a `tool` in ELIGIBLE_TOOLS and a `decision` of 'allow' or 'deny'.
|
|
128
|
+
* Rules for NEVER_AUTO_ALLOW tools are rejected with an error.
|
|
129
|
+
*
|
|
130
|
+
* @param {Array<{tool: string, decision: string}>} rules
|
|
131
|
+
* @throws {Error} if any rule is invalid
|
|
132
|
+
*/
|
|
133
|
+
setRules(rules) {
|
|
134
|
+
if (!Array.isArray(rules)) {
|
|
135
|
+
throw new Error('rules must be an array')
|
|
136
|
+
}
|
|
137
|
+
// #6448 — bound the session rules array (it is matched on every tool call).
|
|
138
|
+
if (rules.length > MAX_SESSION_RULES) {
|
|
139
|
+
throw new Error(`too many rules (max ${MAX_SESSION_RULES})`)
|
|
140
|
+
}
|
|
141
|
+
for (const rule of rules) {
|
|
142
|
+
if (!rule || typeof rule.tool !== 'string') {
|
|
143
|
+
throw new Error('each rule must have a tool string')
|
|
144
|
+
}
|
|
145
|
+
if (rule.decision !== 'allow' && rule.decision !== 'deny') {
|
|
146
|
+
throw new Error(`rule decision must be 'allow' or 'deny', got '${rule.decision}'`)
|
|
147
|
+
}
|
|
148
|
+
if (NEVER_AUTO_ALLOW.has(rule.tool)) {
|
|
149
|
+
throw new Error(`${rule.tool} is in NEVER_AUTO_ALLOW and cannot be auto-allowed`)
|
|
150
|
+
}
|
|
151
|
+
if (!ELIGIBLE_TOOLS.has(rule.tool)) {
|
|
152
|
+
throw new Error(`${rule.tool} is not in ELIGIBLE_TOOLS`)
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
this._sessionRules = rules.slice()
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Return a copy of the current session rules.
|
|
160
|
+
*
|
|
161
|
+
* @returns {Array<{tool: string, decision: string}>}
|
|
162
|
+
*/
|
|
163
|
+
getRules() {
|
|
164
|
+
return this._sessionRules.slice()
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Clear all session-scoped permission rules.
|
|
169
|
+
*/
|
|
170
|
+
clearRules() {
|
|
171
|
+
this._sessionRules = []
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Check whether a toolName matches a session rule.
|
|
176
|
+
*
|
|
177
|
+
* @param {string} toolName
|
|
178
|
+
* @returns {'allow'|'deny'|null} null if no rule matches
|
|
179
|
+
*/
|
|
180
|
+
_matchesRule(toolName) {
|
|
181
|
+
for (const rule of this._sessionRules) {
|
|
182
|
+
if (rule.tool === toolName) {
|
|
183
|
+
return rule.decision
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return null
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Handle a permission check from the SDK canUseTool callback.
|
|
191
|
+
*
|
|
192
|
+
* For AskUserQuestion: emits user_question and waits for respondToQuestion().
|
|
193
|
+
* For session rules: auto-resolves without prompting.
|
|
194
|
+
* For acceptEdits mode: auto-approves file operation tools.
|
|
195
|
+
* For all other tools: emits permission_request and waits for respondToPermission().
|
|
196
|
+
*
|
|
197
|
+
* @param {string} toolName - The tool requesting permission
|
|
198
|
+
* @param {Object} input - The tool input
|
|
199
|
+
* @param {AbortSignal|null} signal - Abort signal for cancellation
|
|
200
|
+
* @param {string} permissionMode - Current permission mode
|
|
201
|
+
* @param {PermissionUpdate[]} [suggestions] - Suggestions from the SDK
|
|
202
|
+
* canUseTool callback options — the pre-built permission rules to
|
|
203
|
+
* echo back via `updatedPermissions` when the user picks "allow
|
|
204
|
+
* always". Per the Agent SDK 'Always allow' flow, these are the
|
|
205
|
+
* correct shape of rule to persist for this tool in this session.
|
|
206
|
+
* @returns {Promise<{behavior: string, updatedInput?: Object, message?: string, updatedPermissions?: Array}>}
|
|
207
|
+
*/
|
|
208
|
+
handlePermission(toolName, input, signal, permissionMode, suggestions = undefined) {
|
|
209
|
+
if (toolName === 'AskUserQuestion') {
|
|
210
|
+
return this._handleAskUserQuestion(input, signal)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// 'auto' (= SDK bypassPermissions) short-circuit: approve every tool
|
|
214
|
+
// call without consulting rules or emitting a prompt. SdkSession also
|
|
215
|
+
// skips canUseTool registration when starting a turn in auto mode, but
|
|
216
|
+
// a turn that started in another mode keeps its callback alive for the
|
|
217
|
+
// whole turn — without this guard, flipping to auto mid-turn (#3729)
|
|
218
|
+
// still emits prompts because session rules and the prompt path run
|
|
219
|
+
// before any mode check.
|
|
220
|
+
if (permissionMode === 'auto') {
|
|
221
|
+
return Promise.resolve({ behavior: 'allow', updatedInput: input || {} })
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Session rules: check before acceptEdits and the prompt path
|
|
225
|
+
const ruleDecision = this._matchesRule(toolName)
|
|
226
|
+
if (ruleDecision !== null) {
|
|
227
|
+
this._logInfo(`Permission rule matched for ${toolName}: ${ruleDecision}`)
|
|
228
|
+
if (ruleDecision === 'allow') {
|
|
229
|
+
return Promise.resolve({ behavior: 'allow', updatedInput: input || {} })
|
|
230
|
+
}
|
|
231
|
+
return Promise.resolve({ behavior: 'deny', message: 'Denied by session rule' })
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// acceptEdits: auto-approve file operations, prompt for everything else
|
|
235
|
+
if (permissionMode === 'acceptEdits' && ACCEPT_EDITS_TOOLS.has(toolName)) {
|
|
236
|
+
return Promise.resolve({ behavior: 'allow', updatedInput: input || {} })
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
return new Promise((resolve) => {
|
|
240
|
+
const requestId = `perm-${this._idNonce}-${++this._permissionCounter}-${Date.now()}`
|
|
241
|
+
// #6448 — bound concurrent pending permissions (each holds entries in
|
|
242
|
+
// _pendingPermissions / _permissionTimers / _lastPermissionData plus a
|
|
243
|
+
// live timer). A normal session has 1-2 pending; this only trips under a
|
|
244
|
+
// flood, where the incoming request is auto-denied rather than letting
|
|
245
|
+
// those grow unbounded. The per-request timeout (below) sweeps stuck old
|
|
246
|
+
// entries, so the cap + timeout together bound memory.
|
|
247
|
+
if (this._pendingPermissions.size >= this._maxPendingPermissions) {
|
|
248
|
+
this._logInfo(`Pending-permission cap (${this._maxPendingPermissions}) reached — auto-denying ${requestId}`)
|
|
249
|
+
resolve({ behavior: 'deny', message: 'Too many pending permission requests' })
|
|
250
|
+
return
|
|
251
|
+
}
|
|
252
|
+
this._pendingPermissions.set(requestId, {
|
|
253
|
+
resolve,
|
|
254
|
+
input: input || {},
|
|
255
|
+
// Stashed for the allowAlways branch of respondToPermission so
|
|
256
|
+
// we can echo them back as updatedPermissions per the SDK
|
|
257
|
+
// 'Always allow' flow.
|
|
258
|
+
suggestions: Array.isArray(suggestions) ? suggestions : [],
|
|
259
|
+
})
|
|
260
|
+
|
|
261
|
+
const toolInput = input || {}
|
|
262
|
+
const rawDescription = toolInput.description
|
|
263
|
+
|| toolInput.command
|
|
264
|
+
|| toolInput.file_path
|
|
265
|
+
|| toolInput.pattern
|
|
266
|
+
|| toolInput.query
|
|
267
|
+
|| (Object.keys(toolInput).length > 0 ? JSON.stringify(toolInput) : toolName)
|
|
268
|
+
// #6038/#6048/#6049: build the broadcast description by REDACTING the full
|
|
269
|
+
// string first, THEN truncating — truncating first (the old order) could
|
|
270
|
+
// leave a secret straddling the cap as a sub-floor partial prefix that the
|
|
271
|
+
// pattern scan misses. String() coerces a non-string field so a malformed
|
|
272
|
+
// tool input can't crash the emit path (.replace on a non-string throws).
|
|
273
|
+
// #6448 — cap the raw string BEFORE redaction so a malicious multi-MB tool
|
|
274
|
+
// field can't make redactValue scan the whole thing (CPU DoS). The 8KB cap
|
|
275
|
+
// is far above the 200-char shown window below, so it can never split a
|
|
276
|
+
// SHOWN secret — the #6038 redact-then-truncate guarantee holds for
|
|
277
|
+
// everything the client sees (anything past 8KB is sliced away regardless).
|
|
278
|
+
const description = redactValue(String(rawDescription).slice(0, MAX_RAW_DESCRIPTION_LEN)).slice(0, 200)
|
|
279
|
+
|
|
280
|
+
this._logInfo(`Permission request ${requestId}: ${toolName}`)
|
|
281
|
+
|
|
282
|
+
// #6038: redact before broadcast. The raw input/description are kept for
|
|
283
|
+
// execution via the _pendingPermissions entry above; this payload is
|
|
284
|
+
// broadcast/display only, so a secret in a value (or the stringified
|
|
285
|
+
// fallback description) must not reach subscribed clients.
|
|
286
|
+
const permPayload = {
|
|
287
|
+
requestId,
|
|
288
|
+
tool: toolName,
|
|
289
|
+
description,
|
|
290
|
+
input: sanitizeToolInput(toolInput),
|
|
291
|
+
remainingMs: this._timeoutMs,
|
|
292
|
+
createdAt: Date.now(),
|
|
293
|
+
}
|
|
294
|
+
this._lastPermissionData.set(requestId, permPayload)
|
|
295
|
+
this.emit('permission_request', permPayload)
|
|
296
|
+
|
|
297
|
+
// Auto-deny on abort signal (user interrupted)
|
|
298
|
+
if (signal) {
|
|
299
|
+
signal.addEventListener('abort', () => {
|
|
300
|
+
if (this._pendingPermissions.has(requestId)) {
|
|
301
|
+
this._pendingPermissions.delete(requestId)
|
|
302
|
+
this._lastPermissionData.delete(requestId)
|
|
303
|
+
this._clearPermissionTimer(requestId)
|
|
304
|
+
resolve({ behavior: 'deny', message: 'Request cancelled' })
|
|
305
|
+
this.emit('permission_resolved', { requestId, decision: 'deny', reason: 'aborted' })
|
|
306
|
+
}
|
|
307
|
+
}, { once: true })
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// Auto-deny after timeout if no response
|
|
311
|
+
const timer = setTimeout(() => {
|
|
312
|
+
this._permissionTimers.delete(requestId)
|
|
313
|
+
if (this._pendingPermissions.has(requestId)) {
|
|
314
|
+
this._logInfo(`Permission ${requestId} timed out, auto-denying`)
|
|
315
|
+
this._pendingPermissions.delete(requestId)
|
|
316
|
+
this._lastPermissionData.delete(requestId)
|
|
317
|
+
resolve({ behavior: 'deny', message: 'Permission timed out' })
|
|
318
|
+
this.emit('permission_resolved', { requestId, decision: 'deny', reason: 'timeout' })
|
|
319
|
+
}
|
|
320
|
+
}, this._timeoutMs)
|
|
321
|
+
this._permissionTimers.set(requestId, timer)
|
|
322
|
+
})
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Handle AskUserQuestion via canUseTool.
|
|
327
|
+
* Emits user_question and waits for respondToQuestion() to deliver the
|
|
328
|
+
* user's answer, then resolves with structured updatedInput.
|
|
329
|
+
*/
|
|
330
|
+
_handleAskUserQuestion(input, signal) {
|
|
331
|
+
return new Promise((resolve) => {
|
|
332
|
+
const questionInput = input || {}
|
|
333
|
+
this._waitingForAnswer = true
|
|
334
|
+
const toolUseId = `ask-${this._idNonce}-${++this._permissionCounter}-${Date.now()}`
|
|
335
|
+
// #3975: stash toolUseId on the pending entry so clearAll() can
|
|
336
|
+
// emit it on the cleared-variant permission_resolved. Without
|
|
337
|
+
// toolUseId the sdk-session re-emit gate at sdk-session.js:281
|
|
338
|
+
// drops the event and the unified pipeline never prunes the
|
|
339
|
+
// questionSessionMap entry — small leak (~80 bytes) per
|
|
340
|
+
// message-completion-while-question-pending event, bounded only by
|
|
341
|
+
// session_destroyed cleanup.
|
|
342
|
+
this._pendingUserAnswer = { resolve, input: questionInput, toolUseId }
|
|
343
|
+
this._logInfo(`AskUserQuestion detected (${toolUseId})`)
|
|
344
|
+
|
|
345
|
+
this.emit('user_question', {
|
|
346
|
+
toolUseId,
|
|
347
|
+
questions: questionInput.questions,
|
|
348
|
+
})
|
|
349
|
+
|
|
350
|
+
// Auto-deny on abort signal
|
|
351
|
+
if (signal) {
|
|
352
|
+
signal.addEventListener('abort', () => {
|
|
353
|
+
if (this._pendingUserAnswer) {
|
|
354
|
+
this._clearQuestionTimer()
|
|
355
|
+
this._pendingUserAnswer = null
|
|
356
|
+
this._waitingForAnswer = false
|
|
357
|
+
resolve({ behavior: 'deny', message: 'Cancelled' })
|
|
358
|
+
this.emit('permission_resolved', { toolUseId, reason: 'aborted' })
|
|
359
|
+
}
|
|
360
|
+
}, { once: true })
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// Auto-deny after timeout if no response
|
|
364
|
+
this._questionTimer = setTimeout(() => {
|
|
365
|
+
this._questionTimer = null
|
|
366
|
+
if (this._pendingUserAnswer) {
|
|
367
|
+
this._logInfo(`Question ${toolUseId} timed out, auto-denying`)
|
|
368
|
+
this._pendingUserAnswer = null
|
|
369
|
+
this._waitingForAnswer = false
|
|
370
|
+
resolve({ behavior: 'deny', message: 'Question timed out' })
|
|
371
|
+
this.emit('permission_resolved', { toolUseId, reason: 'timeout' })
|
|
372
|
+
}
|
|
373
|
+
}, this._timeoutMs)
|
|
374
|
+
})
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Resolve a pending permission request.
|
|
379
|
+
*
|
|
380
|
+
* @param {string} requestId - The permission request ID
|
|
381
|
+
* @param {string} decision - 'allow', 'deny', or 'allowAlways'
|
|
382
|
+
* @returns {boolean} true if a pending permission was found and resolved,
|
|
383
|
+
* false if the requestId was unknown (already resolved or expired).
|
|
384
|
+
*/
|
|
385
|
+
respondToPermission(requestId, decision, editedInput) {
|
|
386
|
+
const pending = this._pendingPermissions.get(requestId)
|
|
387
|
+
if (!pending) {
|
|
388
|
+
this._logWarn(`No pending permission for ${requestId}`)
|
|
389
|
+
return false
|
|
390
|
+
}
|
|
391
|
+
// #6543: capture the tool name BEFORE deleting the last-permission data, so
|
|
392
|
+
// the editedInput whitelist knows which content field(s) are substitutable.
|
|
393
|
+
const toolName = this._lastPermissionData.get(requestId)?.tool
|
|
394
|
+
this._pendingPermissions.delete(requestId)
|
|
395
|
+
this._lastPermissionData.delete(requestId)
|
|
396
|
+
this._clearPermissionTimer(requestId)
|
|
397
|
+
|
|
398
|
+
this._logInfo(`Permission ${requestId} resolved: ${decision}`)
|
|
399
|
+
|
|
400
|
+
// Emit before resolve() so listeners see the pending-count drop
|
|
401
|
+
// before any follow-on work runs synchronously.
|
|
402
|
+
this.emit('permission_resolved', { requestId, decision, reason: 'user' })
|
|
403
|
+
|
|
404
|
+
// #6543 (feature B): on an approve, an operator who reviewed the proposed
|
|
405
|
+
// Write/Edit per-hunk may substitute the CONTENT (never the path — see
|
|
406
|
+
// mergeEditedInput). Ignored on deny. The merged input flows to the agent's
|
|
407
|
+
// tool executor as `updatedInput`, which still path-confines the write.
|
|
408
|
+
const approvedInput = mergeEditedInput(pending.input, editedInput, toolName)
|
|
409
|
+
|
|
410
|
+
if (decision === 'allow') {
|
|
411
|
+
pending.resolve({ behavior: 'allow', updatedInput: approvedInput })
|
|
412
|
+
} else if (decision === 'allowAlways') {
|
|
413
|
+
// Per the Agent SDK type contract (PermissionResult in
|
|
414
|
+
// @anthropic-ai/claude-agent-sdk coreTypes.d.ts), behavior is
|
|
415
|
+
// strictly 'allow' | 'deny' — there is NO 'allowAlways' variant.
|
|
416
|
+
// The "always allow" flow works by returning behavior='allow'
|
|
417
|
+
// AND attaching a list of permission rules to persist via
|
|
418
|
+
// updatedPermissions (which the SDK sources from the `suggestions`
|
|
419
|
+
// field of the canUseTool callback options, stashed on pending
|
|
420
|
+
// at capture time).
|
|
421
|
+
//
|
|
422
|
+
// Pre-audit, we passed behavior:'allowAlways' directly to the SDK
|
|
423
|
+
// callback, which the SDK silently coerced (or dropped) — the
|
|
424
|
+
// user-facing "Allow Always" button effectively did nothing more
|
|
425
|
+
// than a plain "Allow", and no persistent rule was added. Found
|
|
426
|
+
// by Skeptic in the 2026-04-11 production readiness audit.
|
|
427
|
+
const result = {
|
|
428
|
+
behavior: 'allow',
|
|
429
|
+
updatedInput: approvedInput,
|
|
430
|
+
}
|
|
431
|
+
if (pending.suggestions && pending.suggestions.length > 0) {
|
|
432
|
+
result.updatedPermissions = pending.suggestions
|
|
433
|
+
}
|
|
434
|
+
pending.resolve(result)
|
|
435
|
+
} else {
|
|
436
|
+
pending.resolve({ behavior: 'deny', message: 'User denied' })
|
|
437
|
+
}
|
|
438
|
+
return true
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Send a response to an AskUserQuestion prompt.
|
|
443
|
+
*
|
|
444
|
+
* @param {string} text - The user's text answer
|
|
445
|
+
* @param {Object} [answersMap] - Per-question answers map
|
|
446
|
+
*/
|
|
447
|
+
respondToQuestion(text, answersMap) {
|
|
448
|
+
if (!this._pendingUserAnswer) return
|
|
449
|
+
this._clearQuestionTimer()
|
|
450
|
+
// #3988: include toolUseId on the answered emit for symmetry with the
|
|
451
|
+
// other 3 question-variant emit sites (aborted/timeout/cleared). The
|
|
452
|
+
// 'auto' path applies only to requestId-based prompts —
|
|
453
|
+
// autoAllowPending() leaves AskUserQuestion entries untouched — so
|
|
454
|
+
// there is no auto-variant question emit to mirror.
|
|
455
|
+
//
|
|
456
|
+
// The user-response handler at packages/server/src/handlers/input-handlers.js:451
|
|
457
|
+
// already prunes questionSessionMap eagerly before calling this method,
|
|
458
|
+
// so the unified-pipeline cleanup is redundant on the happy path — but
|
|
459
|
+
// the sdk-session re-emit gate at sdk-session.js:281 keys on
|
|
460
|
+
// (data.requestId || data.toolUseId), and any future internal path
|
|
461
|
+
// (or refactor that drops the eager delete) would silently leak. Read
|
|
462
|
+
// toolUseId BEFORE the null-out below, mirroring the clearAll #3975
|
|
463
|
+
// pattern.
|
|
464
|
+
const { resolve, input, toolUseId } = this._pendingUserAnswer
|
|
465
|
+
this._pendingUserAnswer = null
|
|
466
|
+
this._waitingForAnswer = false
|
|
467
|
+
|
|
468
|
+
this._logInfo(`Question response received: "${text.slice(0, 60)}"`)
|
|
469
|
+
|
|
470
|
+
// Emit before resolve() so listeners (e.g. the SdkSession
|
|
471
|
+
// inactivity-timer resumer, #2831) see the state flip before any
|
|
472
|
+
// downstream synchronous work runs.
|
|
473
|
+
this.emit('permission_resolved', { toolUseId, reason: 'answered' })
|
|
474
|
+
|
|
475
|
+
// Build structured answers map: SDK expects { [questionText]: selectedLabel }.
|
|
476
|
+
// Per @anthropic-ai/claude-agent-sdk sdk-tools.d.ts (AskUserQuestionOutput.answers,
|
|
477
|
+
// ~line 2696) the contract is explicit: each value is a plain string,
|
|
478
|
+
// and multi-select answers are comma-separated. So this layer
|
|
479
|
+
// normalizes the dashboard's wire shape (native string | string[] post-
|
|
480
|
+
// #4731, or legacy JSON-stringified arrays from #4604 Chunk B
|
|
481
|
+
// dashboards) into that canonical string-per-question shape before
|
|
482
|
+
// resolving the canUseTool Promise — otherwise the model would receive
|
|
483
|
+
// raw JSON literals like '["A","B"]' as the user's answer text (#4731).
|
|
484
|
+
const answers = {}
|
|
485
|
+
const questions = input.questions || []
|
|
486
|
+
const questionKeys = new Set(questions.map(q => q.question))
|
|
487
|
+
if (answersMap && typeof answersMap === 'object' && Object.keys(answersMap).length > 0) {
|
|
488
|
+
// Per-question answers provided by the client — only copy known question keys
|
|
489
|
+
for (const key of Object.keys(answersMap)) {
|
|
490
|
+
if (questionKeys.has(key)) {
|
|
491
|
+
answers[key] = normalizeAnswerValue(answersMap[key])
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
} else if (questions.length > 0) {
|
|
495
|
+
// Fallback: single answer mapped to all questions
|
|
496
|
+
for (const q of questions) {
|
|
497
|
+
answers[q.question] = text
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
resolve({
|
|
502
|
+
behavior: 'allow',
|
|
503
|
+
updatedInput: {
|
|
504
|
+
questions,
|
|
505
|
+
answers,
|
|
506
|
+
},
|
|
507
|
+
})
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* Clear a permission timeout timer by request ID.
|
|
512
|
+
*/
|
|
513
|
+
_clearPermissionTimer(requestId) {
|
|
514
|
+
const timer = this._permissionTimers.get(requestId)
|
|
515
|
+
if (timer) {
|
|
516
|
+
clearTimeout(timer)
|
|
517
|
+
this._permissionTimers.delete(requestId)
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* Clear the AskUserQuestion timeout timer.
|
|
523
|
+
*/
|
|
524
|
+
_clearQuestionTimer() {
|
|
525
|
+
if (this._questionTimer) {
|
|
526
|
+
clearTimeout(this._questionTimer)
|
|
527
|
+
this._questionTimer = null
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* Auto-allow every outstanding permission request. Called when the
|
|
533
|
+
* session switches into auto/bypass mode (#3729) — the user has just
|
|
534
|
+
* declared "approve everything", so any prompt still on screen should
|
|
535
|
+
* resolve as if they had clicked Allow rather than sit there until
|
|
536
|
+
* timeout. Pending AskUserQuestion prompts are NOT touched: those are
|
|
537
|
+
* solicited user input, not permission gates.
|
|
538
|
+
*
|
|
539
|
+
* #4462: MCP trust prompts (requestMcpTrust) are also exempt — their
|
|
540
|
+
* allow path PERSISTS the binary to ~/.chroxy/mcp-trust.json forever
|
|
541
|
+
* via byok-mcp-fleet's recordTrust call. A panic-button bypass is "I
|
|
542
|
+
* trust everything for this turn" semantics, NOT "trust this MCP
|
|
543
|
+
* binary forever." Treating mcp_spawn under auto as deny re-prompts
|
|
544
|
+
* the user next start — they can explicitly approve then, when the
|
|
545
|
+
* decision is in front of them.
|
|
546
|
+
*/
|
|
547
|
+
autoAllowPending() {
|
|
548
|
+
if (this._pendingPermissions.size === 0) return
|
|
549
|
+
const pendingIds = Array.from(this._pendingPermissions.keys())
|
|
550
|
+
let allowed = 0
|
|
551
|
+
let deniedMcpTrust = 0
|
|
552
|
+
for (const requestId of pendingIds) {
|
|
553
|
+
const pending = this._pendingPermissions.get(requestId)
|
|
554
|
+
if (!pending) continue
|
|
555
|
+
this._pendingPermissions.delete(requestId)
|
|
556
|
+
this._lastPermissionData.delete(requestId)
|
|
557
|
+
this._clearPermissionTimer(requestId)
|
|
558
|
+
if (pending.mcpTrust === true) {
|
|
559
|
+
// Don't silently persist trust on bypass. Deny — the MCP server
|
|
560
|
+
// won't spawn for this session, but no on-disk trust entry is
|
|
561
|
+
// written, and the user re-prompts next start.
|
|
562
|
+
pending.resolve({
|
|
563
|
+
behavior: 'deny',
|
|
564
|
+
message: 'MCP trust not persisted via auto-mode bypass; approve explicitly to trust this server',
|
|
565
|
+
})
|
|
566
|
+
this.emit('permission_resolved', { requestId, decision: 'deny', reason: 'auto_mode_mcp_trust_bypass' })
|
|
567
|
+
deniedMcpTrust += 1
|
|
568
|
+
continue
|
|
569
|
+
}
|
|
570
|
+
pending.resolve({ behavior: 'allow', updatedInput: pending.input })
|
|
571
|
+
this.emit('permission_resolved', { requestId, decision: 'allow', reason: 'auto_mode' })
|
|
572
|
+
allowed += 1
|
|
573
|
+
}
|
|
574
|
+
if (deniedMcpTrust > 0) {
|
|
575
|
+
this._logInfo(
|
|
576
|
+
`Auto-allowed ${allowed} pending permission(s) and denied ${deniedMcpTrust} MCP trust prompt(s) on auto mode switch (trust not persisted via bypass — #4462)`,
|
|
577
|
+
)
|
|
578
|
+
} else {
|
|
579
|
+
this._logInfo(`Auto-allowed ${allowed} pending permission(s) on auto mode switch`)
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* Auto-deny all pending permissions and questions. Called on message
|
|
585
|
+
* completion or session destruction.
|
|
586
|
+
*/
|
|
587
|
+
clearAll() {
|
|
588
|
+
// Collect requestIds first so we can emit permission_resolved AFTER
|
|
589
|
+
// the maps are cleared — the SdkSession timeout-pause listener decrements
|
|
590
|
+
// its counter on each event and should see a consistent final state.
|
|
591
|
+
const pendingIds = Array.from(this._pendingPermissions.keys())
|
|
592
|
+
// #3975: capture the pending-answer entry (not just a boolean) so we
|
|
593
|
+
// can include its toolUseId on the cleared emit. Without toolUseId the
|
|
594
|
+
// sdk-session re-emit gate drops the event and questionSessionMap
|
|
595
|
+
// leaks. Reading toolUseId BEFORE the null-out below avoids races
|
|
596
|
+
// with any synchronous listeners on the resolve.
|
|
597
|
+
const clearedUserAnswer = this._pendingUserAnswer
|
|
598
|
+
|
|
599
|
+
// Auto-deny pending permissions and clear timers
|
|
600
|
+
for (const [requestId, pending] of this._pendingPermissions) {
|
|
601
|
+
this._clearPermissionTimer(requestId)
|
|
602
|
+
pending.resolve({ behavior: 'deny', message: 'Message completed' })
|
|
603
|
+
}
|
|
604
|
+
this._pendingPermissions.clear()
|
|
605
|
+
this._lastPermissionData.clear()
|
|
606
|
+
|
|
607
|
+
// #6027: belt-and-braces — the loop above only clears timers for entries
|
|
608
|
+
// still in _pendingPermissions. A permission timer whose requestId has
|
|
609
|
+
// already left that map would otherwise survive destroy() and keep the
|
|
610
|
+
// suite alive without --test-force-exit. Drop any stragglers.
|
|
611
|
+
for (const timer of this._permissionTimers.values()) clearTimeout(timer)
|
|
612
|
+
this._permissionTimers.clear()
|
|
613
|
+
|
|
614
|
+
// Auto-deny pending user answer
|
|
615
|
+
this._clearQuestionTimer()
|
|
616
|
+
if (this._pendingUserAnswer) {
|
|
617
|
+
this._pendingUserAnswer.resolve({ behavior: 'deny', message: 'Message completed' })
|
|
618
|
+
this._pendingUserAnswer = null
|
|
619
|
+
}
|
|
620
|
+
this._waitingForAnswer = false
|
|
621
|
+
|
|
622
|
+
// Emit resolved events so listeners reset any paused state (#2831).
|
|
623
|
+
for (const requestId of pendingIds) {
|
|
624
|
+
this.emit('permission_resolved', { requestId, decision: 'deny', reason: 'cleared' })
|
|
625
|
+
}
|
|
626
|
+
if (clearedUserAnswer) {
|
|
627
|
+
// #3975: toolUseId is required for the EventNormalizer to prune
|
|
628
|
+
// questionSessionMap on the cleared path. The SdkSession
|
|
629
|
+
// timeout-pause listener (#2831) ignores fields it doesn't know
|
|
630
|
+
// about, so the extra toolUseId is harmless there.
|
|
631
|
+
this.emit('permission_resolved', { toolUseId: clearedUserAnswer.toolUseId, reason: 'cleared' })
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/**
|
|
636
|
+
* #4457: trust gate for spawning an MCP server child. Reuses the
|
|
637
|
+
* existing _pendingPermissions machinery so the dashboard / mobile
|
|
638
|
+
* permission UIs render this with zero changes — they receive a
|
|
639
|
+
* standard `permission_request` event and call `respondToPermission`
|
|
640
|
+
* with allow/deny.
|
|
641
|
+
*
|
|
642
|
+
* Behavior:
|
|
643
|
+
* - On allow (or allowAlways): resolves to true; caller persists trust.
|
|
644
|
+
* - On deny: resolves to false; caller marks the client DEAD.
|
|
645
|
+
* - On timeout (default permissionTimeout): treated as deny.
|
|
646
|
+
*
|
|
647
|
+
* @param {{ name: string, command: string, args?: string[], envKeys?: string[] }} server
|
|
648
|
+
* @returns {Promise<boolean>}
|
|
649
|
+
*/
|
|
650
|
+
requestMcpTrust(server) {
|
|
651
|
+
return new Promise((resolve) => {
|
|
652
|
+
const requestId = `mcp-trust-${this._idNonce}-${++this._permissionCounter}-${Date.now()}`
|
|
653
|
+
const argv0 = Array.isArray(server.args) && server.args.length > 0 ? server.args[0] : ''
|
|
654
|
+
const input = {
|
|
655
|
+
mcpServer: {
|
|
656
|
+
name: server.name,
|
|
657
|
+
command: server.command,
|
|
658
|
+
args: Array.isArray(server.args) ? [...server.args] : [],
|
|
659
|
+
envKeys: Array.isArray(server.envKeys) ? [...server.envKeys] : [],
|
|
660
|
+
},
|
|
661
|
+
}
|
|
662
|
+
const description = `Spawn MCP server "${server.name}" running ${server.command}${argv0 ? ' ' + argv0 : ''}`
|
|
663
|
+
|
|
664
|
+
// Wrap pending entry so respondToPermission's standard mapping
|
|
665
|
+
// ({behavior:'allow'} or {behavior:'deny'}) translates to a boolean
|
|
666
|
+
// for the caller. updatedInput / suggestions are unused on the trust
|
|
667
|
+
// path — we only care about allow-vs-deny.
|
|
668
|
+
//
|
|
669
|
+
// #4462: mark this entry as an MCP-trust prompt so autoAllowPending
|
|
670
|
+
// can treat it differently. Auto-allow is the "panic button"
|
|
671
|
+
// bypass — it's the right call for one-shot Read/Bash/Edit prompts
|
|
672
|
+
// (the user just declared "approve everything") but the WRONG call
|
|
673
|
+
// for MCP trust, which persists forever via recordTrust on allow.
|
|
674
|
+
// The persistence semantics turn a bypass into a "trust this binary
|
|
675
|
+
// forever" decision the user never explicitly made. We tag the
|
|
676
|
+
// entry and have autoAllowPending deny it instead.
|
|
677
|
+
this._pendingPermissions.set(requestId, {
|
|
678
|
+
resolve: (result) => resolve(result?.behavior === 'allow'),
|
|
679
|
+
input,
|
|
680
|
+
suggestions: [],
|
|
681
|
+
mcpTrust: true,
|
|
682
|
+
})
|
|
683
|
+
|
|
684
|
+
this._logInfo(`MCP trust request ${requestId}: ${server.name}`)
|
|
685
|
+
|
|
686
|
+
// #6038: redact before broadcast (description embeds server.command/argv0;
|
|
687
|
+
// input carries args/envKeys). Raw values for execution live on the
|
|
688
|
+
// _pendingPermissions entry above.
|
|
689
|
+
const permPayload = {
|
|
690
|
+
requestId,
|
|
691
|
+
tool: 'mcp_spawn',
|
|
692
|
+
description: redactValue(String(description)).slice(0, 200),
|
|
693
|
+
input: sanitizeToolInput(input),
|
|
694
|
+
remainingMs: this._timeoutMs,
|
|
695
|
+
createdAt: Date.now(),
|
|
696
|
+
}
|
|
697
|
+
this._lastPermissionData.set(requestId, permPayload)
|
|
698
|
+
this.emit('permission_request', permPayload)
|
|
699
|
+
|
|
700
|
+
const timer = setTimeout(() => {
|
|
701
|
+
this._permissionTimers.delete(requestId)
|
|
702
|
+
if (this._pendingPermissions.has(requestId)) {
|
|
703
|
+
this._logInfo(`MCP trust ${requestId} timed out, auto-denying`)
|
|
704
|
+
this._pendingPermissions.delete(requestId)
|
|
705
|
+
this._lastPermissionData.delete(requestId)
|
|
706
|
+
resolve(false)
|
|
707
|
+
this.emit('permission_resolved', { requestId, decision: 'deny', reason: 'timeout' })
|
|
708
|
+
}
|
|
709
|
+
}, this._timeoutMs)
|
|
710
|
+
this._permissionTimers.set(requestId, timer)
|
|
711
|
+
})
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/**
|
|
715
|
+
* Clean up all resources.
|
|
716
|
+
*/
|
|
717
|
+
destroy() {
|
|
718
|
+
this.clearAll()
|
|
719
|
+
this.removeAllListeners()
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** @private */
|
|
723
|
+
_logInfo(msg) {
|
|
724
|
+
if (this._log.info) {
|
|
725
|
+
this._log.info(msg)
|
|
726
|
+
} else {
|
|
727
|
+
_fallbackLog.info(msg)
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/** @private */
|
|
732
|
+
_logWarn(msg) {
|
|
733
|
+
if (this._log.warn) {
|
|
734
|
+
this._log.warn(msg)
|
|
735
|
+
} else {
|
|
736
|
+
_fallbackLog.warn(msg)
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/**
|
|
742
|
+
* #4731 — coerce a dashboard-supplied per-question answer value into the
|
|
743
|
+
* SDK's canonical string shape. The SDK's `AskUserQuestionOutput.answers`
|
|
744
|
+
* (see `@anthropic-ai/claude-agent-sdk/sdk-tools.d.ts:2696`) types every
|
|
745
|
+
* value as a plain string with multi-select answers comma-separated.
|
|
746
|
+
*
|
|
747
|
+
* Accepted inputs:
|
|
748
|
+
* - Array of labels (post-#4731 wire shape from updated dashboards) →
|
|
749
|
+
* joined as `"A, B, C"`.
|
|
750
|
+
* - JSON-stringified array (`'["A","B"]'` — the legacy #4604 Chunk B
|
|
751
|
+
* dashboard JSON.stringifies multi-select arrays to fit the original
|
|
752
|
+
* `Record<string,string>` schema) → parsed then joined.
|
|
753
|
+
* - Plain string (single-select, freeform, or model-side "Other"
|
|
754
|
+
* sentinel) → passed through unchanged.
|
|
755
|
+
*
|
|
756
|
+
* Anything else (null, undefined, object, number) coerces to the empty
|
|
757
|
+
* string — the SDK then receives a null-equivalent answer and the model
|
|
758
|
+
* surfaces "no preference" semantics, which is safer than throwing and
|
|
759
|
+
* stalling the canUseTool Promise.
|
|
760
|
+
*/
|
|
761
|
+
function normalizeAnswerValue(value) {
|
|
762
|
+
if (Array.isArray(value)) {
|
|
763
|
+
return value.map((v) => String(v ?? '')).join(', ')
|
|
764
|
+
}
|
|
765
|
+
if (typeof value === 'string') {
|
|
766
|
+
// Detect the legacy JSON-stringified-array shape. Bare strings (e.g.
|
|
767
|
+
// `"Red"`) never look like JSON arrays, so this gate is tight enough
|
|
768
|
+
// that no plain-string answer is accidentally parsed. The try/catch
|
|
769
|
+
// means a string that merely starts with `[` but isn't valid JSON
|
|
770
|
+
// (e.g. someone literally answered `"[note]"`) falls through to the
|
|
771
|
+
// pass-through return below — no data loss.
|
|
772
|
+
if (value.length >= 2 && value.startsWith('[') && value.endsWith(']')) {
|
|
773
|
+
try {
|
|
774
|
+
const parsed = JSON.parse(value)
|
|
775
|
+
if (Array.isArray(parsed)) {
|
|
776
|
+
return parsed.map((v) => String(v ?? '')).join(', ')
|
|
777
|
+
}
|
|
778
|
+
} catch {
|
|
779
|
+
// not JSON — fall through
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
return value
|
|
783
|
+
}
|
|
784
|
+
return ''
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/**
|
|
788
|
+
* Wire a PermissionManager's three events to a session's own EventEmitter and
|
|
789
|
+
* install the back-compat accessors (`_pendingPermissions` / `_lastPermissionData`,
|
|
790
|
+
* read by ws-permissions.js + settings-handlers.js). Extracted from the two
|
|
791
|
+
* in-process providers (SdkSession, ByokSession) that each hand-rolled the same
|
|
792
|
+
* wiring (audit P2-9); Docker variants inherit from these.
|
|
793
|
+
*
|
|
794
|
+
* The only real asymmetry is SdkSession's inactivity-timer pause/resume around a
|
|
795
|
+
* pending permission (#2831) — passed as optional `onRequest` (fired on both
|
|
796
|
+
* permission_request and user_question, before the re-emit) and `onResolved`
|
|
797
|
+
* (fired on every permission_resolved, before the requestId/toolUseId re-emit
|
|
798
|
+
* guard). ByokSession passes neither.
|
|
799
|
+
*
|
|
800
|
+
* @param {import('events').EventEmitter} session the session to re-emit on
|
|
801
|
+
* @param {PermissionManager} permissions
|
|
802
|
+
* @param {{ onRequest?: () => void, onResolved?: () => void }} [hooks]
|
|
803
|
+
*/
|
|
804
|
+
export function wirePermissionManager(session, permissions, { onRequest, onResolved } = {}) {
|
|
805
|
+
permissions.on('permission_request', (data) => {
|
|
806
|
+
if (onRequest) onRequest()
|
|
807
|
+
session.emit('permission_request', data)
|
|
808
|
+
})
|
|
809
|
+
permissions.on('user_question', (data) => {
|
|
810
|
+
if (onRequest) onRequest()
|
|
811
|
+
session.emit('user_question', data)
|
|
812
|
+
})
|
|
813
|
+
permissions.on('permission_resolved', (data) => {
|
|
814
|
+
if (onResolved) onResolved()
|
|
815
|
+
// #3048: re-emit so the unified pipeline (SessionManager → ws-forwarding →
|
|
816
|
+
// EventNormalizer → broadcast) fans the resolution out to every client.
|
|
817
|
+
// #3736: AskUserQuestion resolutions carry `toolUseId` instead of
|
|
818
|
+
// `requestId` — re-emit both shapes so the EventNormalizer can prune the
|
|
819
|
+
// questionSessionMap entry (pre-fix this branch was dropped and the map
|
|
820
|
+
// leaked one entry per timeout/abort/clear). The permission-audit listener
|
|
821
|
+
// in ws-server.js gates on `data.requestId` and ignores the question variant.
|
|
822
|
+
if (data && (data.requestId || data.toolUseId)) {
|
|
823
|
+
session.emit('permission_resolved', data)
|
|
824
|
+
}
|
|
825
|
+
})
|
|
826
|
+
// Backward-compatible accessors used by ws-permissions.js + settings-handlers.js.
|
|
827
|
+
session._pendingPermissions = permissions._pendingPermissions
|
|
828
|
+
session._lastPermissionData = permissions._lastPermissionData
|
|
829
|
+
}
|