@chroxy/server 0.11.0 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +69 -5
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -1,7 +1,11 @@
1
1
  import { EventEmitter } from 'events'
2
2
  import { randomUUID } from 'crypto'
3
3
  import { resolve, relative, sep, isAbsolute } from 'node:path'
4
+ import { realpathSync } from 'node:fs'
5
+ import { resolveTargetComponentwiseSync } from './utils/componentwise-resolver.js'
6
+ import { isPathWithin } from './utils/path-containment.js'
4
7
  import { createLogger } from './logger.js'
8
+ import { globPatternEscapeReason } from './built-in-tools/tool-transforms.js'
5
9
  // #7004: the protected-path / secret-read FLOOR lives in permission-floor.js — a
6
10
  // leaf module — because BOTH permission pipelines must apply the identical floor:
7
11
  // this in-process path, and the HOOK-routed path (claude-tui/cli-session decide
@@ -14,12 +18,15 @@ import {
14
18
  isProtectedPathTarget,
15
19
  isSecretReadTarget,
16
20
  PROTECTED_PATH_INPUT_FIELDS,
21
+ collectChangeTargets,
22
+ effectiveSearchRoot,
17
23
  } from './permission-floor.js'
18
24
  // #6038: the SDK/TUI permission path broadcasts to clients too, so it must apply
19
25
  // the same redaction as the hook path. Shared sanitizer + value redactor live in
20
26
  // redaction.js (a leaf module — no import cycle / HTTP-handler weight).
21
- import { sanitizeToolInput, redactValue } from './redaction.js'
22
- import { redactMcpUrl, resolveTrustAddress } from './byok-mcp-config.js'
27
+ import { sanitizeToolInput, redactValue, describeByNamedField, describeToolInput, describeComposedText } from './redaction.js'
28
+ import { redactMcpUrl, resolveTrustAddress, MCP_SERVER_SOURCE_VALUES } from './byok-mcp-config.js'
29
+ import { DROPPED_HUNKS_KEY, KEPT_HUNKS_KEY, EditedInputRefusedError, isHunkReviewedTool, narrowByDroppedHunks, assertClientTextAllowed } from './edited-input.js'
23
30
  // #6842 review (Copilot) — audit entries must carry the store's NORMALIZED
24
31
  // project key, not the raw session cwd, or a relative / `..`-laden cwd
25
32
  // produces entries that never correlate with the persisted rule they audit.
@@ -28,13 +35,18 @@ import { redactMcpUrl, resolveTrustAddress } from './byok-mcp-config.js'
28
35
  // inside function bodies (call time), never at module evaluation, and
29
36
  // normalizeProjectKey is a hoisted function declaration.
30
37
  import { normalizeProjectKey } from './permission-rule-store.js'
38
+ import { permissionScope } from './permission-scope.js'
31
39
 
32
40
  const _fallbackLog = createLogger('permission-manager')
33
41
 
34
42
  // Tools that acceptEdits mode auto-approves. `apply_patch` is codex's file-edit
35
43
  // approval (item/fileChange/requestApproval, #6605) — the codex analogue of
36
44
  // Write/Edit, so acceptEdits auto-approves codex edits too.
37
- const ACCEPT_EDITS_TOOLS = new Set(['Read', 'Write', 'Edit', 'NotebookEdit', 'Glob', 'Grep', 'apply_patch'])
45
+ // Exported so the classification can be PINNED by tests: it is the strongest of
46
+ // the three read-only premises behind #7295 (ELIGIBLE_TOOLS needs a user to
47
+ // create a rule; this one is automatic in acceptEdits mode), and it was the only
48
+ // one a test could not assert.
49
+ export const ACCEPT_EDITS_TOOLS = new Set(['Read', 'Write', 'Edit', 'NotebookEdit', 'Glob', 'Grep', 'apply_patch'])
38
50
 
39
51
  // Tools eligible for session-scoped auto-allow rules (`apply_patch` = codex edits).
40
52
  export const ELIGIBLE_TOOLS = new Set(['Read', 'Write', 'Edit', 'NotebookEdit', 'Glob', 'Grep', 'apply_patch'])
@@ -46,7 +58,138 @@ export const ELIGIBLE_TOOLS = new Set(['Read', 'Write', 'Edit', 'NotebookEdit',
46
58
  // filesystem/network scope must always prompt, never be silently rule-whitelisted.
47
59
  // `mcp_elicitation` is a codex MCP connector eliciting the user (#6635, e.g. a
48
60
  // GitHub connector write approval) — a connector action must always prompt too.
49
- export const NEVER_AUTO_ALLOW = new Set(['Bash', 'Task', 'WebFetch', 'WebSearch', 'shell', 'request_permissions', 'mcp_elicitation'])
61
+ // `Agent` is what Claude Code calls the sub-delegation tool today; `Task` is the
62
+ // older spelling and both are live, because chroxy runs against whatever
63
+ // `claude` the user has installed (#7340). Not exploitable on its own — a rule
64
+ // also has to clear `ELIGIBLE_TOOLS`, which neither name is in — but a denylist
65
+ // that names only the retired spelling is a guard whose comment describes a
66
+ // stronger check than its code performs.
67
+ export const NEVER_AUTO_ALLOW = new Set(['Bash', 'Task', 'Agent', 'WebFetch', 'WebSearch', 'shell', 'request_permissions', 'mcp_elicitation'])
68
+
69
+ // #7973 — tools an EXTERNAL PLANNER (agent-control's `chroxy_respond_permission`,
70
+ // packages/server/src/agent-control/client.js) may never approve with `allow`,
71
+ // WHATEVER the protected-path floor's `floored` verdict says about the request
72
+ // — these are high-authority independent of any path field:
73
+ // - `mcp_spawn` (#4462): an `allow` PERSISTS a permanent "trust this binary"
74
+ // grant to disk (byok-mcp-fleet's recordTrust). `autoAllowPending()` below
75
+ // already refuses to fold this into a bypass-mode sweep, via the
76
+ // `pending.mcpTrust` flag it sets on the pending entry — a per-REQUEST
77
+ // runtime marker, not a tool-name membership check. `mcp_spawn` was never
78
+ // added to NEVER_AUTO_ALLOW above because that set gates PERSISTED
79
+ // permission RULES, a mechanism `requestMcpTrust` never consults in the
80
+ // first place (it skips `_matchesRule` entirely).
81
+ // - `request_permissions` (codex's sandbox-scope escalation prompt) is
82
+ // already in NEVER_AUTO_ALLOW, so a persisted "always allow" RULE for it
83
+ // is rejected. This set additionally covers the ONE-SHOT external-planner
84
+ // `allow` path in agent-control, which NEVER_AUTO_ALLOW does not govern.
85
+ //
86
+ // FIXED (#7975, was FINDING #7973): `autoAllowPending()` below now consults
87
+ // this EXACT set (by tool name, via `_lastPermissionData`) so a pending
88
+ // `request_permissions` prompt — which carries neither `protectedTarget` nor
89
+ // `mcpTrust` — is left genuinely pending for a human rather than silently
90
+ // folded into a bypass-mode sweep. `mcp_spawn`'s own `pending.mcpTrust`
91
+ // handling (explicit deny, never silently allowed) is unchanged; the new
92
+ // check only ever widens which tools autoAllowPending refuses to auto-allow,
93
+ // checked after the mcpTrust branch so it never intercepts mcp_spawn's
94
+ // existing behavior.
95
+ //
96
+ // Exported so agent-control/client.js AND autoAllowPending() below both
97
+ // consult this EXACT Set (identity, not an equal-valued copy) rather than
98
+ // hand-rolling independent, driftable copies of "which tools are too
99
+ // high-authority for an unattended approver to ever say yes to."
100
+ export const NOT_DELEGABLE_TOOLS = new Set(['mcp_spawn', 'request_permissions', 'dev_preview'])
101
+
102
+ // #7973 — tools that execute an arbitrary, caller-supplied command/shell
103
+ // string. The protected-path floor (`isFlooredTarget`, permission-floor.js)
104
+ // inspects PATH-carrying input fields only — it is fundamentally unable to
105
+ // see a command string, so `floored: false` on one of these tools means "no
106
+ // path field looked protected," not "this command is safe" (`cat .env` is an
107
+ // ordinary, unfloored Bash invocation). Names are sourced from what each
108
+ // provider actually hands `handlePermission` or `POST /permission` — never
109
+ // guessed:
110
+ // - `Bash` — Claude Code (the Agent SDK's bundled binary for sdk-session.js,
111
+ // and the installed CLI behind the hook-routed claude-cli / claude-tui /
112
+ // claude-channel providers) and BYOK's built-in tool executor
113
+ // (byok-tool-executor.js, which dispatches by exact, case-sensitive name).
114
+ // - `PowerShell` — Claude Code's Windows shell tool, and the ONLY shell tool
115
+ // on a Windows host without Git Bash. Permission-checked with Bash's rules.
116
+ // - `Monitor` — Claude Code's background-script tool: its input is a bash
117
+ // `command`, permission-checked by the same function as Bash.
118
+ // - `shell` — codex's app-server driver (codex-app-server-session.js).
119
+ // Gemini sessions (gemini-session.js) declare `permissions: false` and never
120
+ // call `handlePermission` at all; ACP-backed providers (acp-session.js) deny
121
+ // every permission request outright without reaching this module either.
122
+ // This is a DENYLIST beside a tool roster that grows with every Claude Code
123
+ // release (PowerShell and Monitor were missed when it was first written) — a
124
+ // new command-executing tool is approvable until its name is added here.
125
+ //
126
+ // Exported for the same reason as NOT_DELEGABLE_TOOLS above — one shared Set,
127
+ // imported (not copied) by agent-control/client.js.
128
+ export const COMMAND_TOOLS = new Set(['Bash', 'shell', 'PowerShell', 'Monitor'])
129
+
130
+ // #7975 (S3, final security review of #7854) — the ALLOWLIST of tools an
131
+ // EXTERNAL PLANNER's `chroxy_respond_permission` may ever send `allow` for
132
+ // (before the #7973 command-tool opt-in on top): exactly the tools whose
133
+ // inputs the protected-path floor (`isFlooredTarget`, permission-floor.js)
134
+ // FULLY inspects — meaning every field of that tool's real input which
135
+ // selects the file(s) it reads or writes is one of PROTECTED_PATH_INPUT_FIELDS
136
+ // (`file_path`/`path`/`notebook_path`) or, for codex `apply_patch`, its
137
+ // `changes[]` member paths. `floored: false` is only a MEANINGFUL "nothing
138
+ // protected here" signal when that condition holds for EVERY field — not
139
+ // merely when the floor recognizes *some* field on the tool.
140
+ //
141
+ // Read/Write/Edit/NotebookEdit/apply_patch satisfy it: the one field the
142
+ // floor inspects (`file_path`/`notebook_path`/`changes[].path`) is exactly the
143
+ // field that determines what gets read or written.
144
+ //
145
+ // #7975-followup (adversarial review of 71e78ba38) — `Grep` and `Glob` do
146
+ // NOT satisfy it and are deliberately EXCLUDED, even though both are in
147
+ // {@link ACCEPT_EDITS_TOOLS} and both DO carry a `path` field the floor
148
+ // inspects. Each also carries a SECOND, file-selecting field the floor never
149
+ // looks at: `Grep`'s `glob` (byok-tools.js) and `Glob`'s `pattern`. A caller
150
+ // can leave `path` pointed at a wholly benign directory and use that second
151
+ // field to select a secret file directly — `isFlooredTarget` sees only the
152
+ // benign `path` and reports `floored: false`, exactly the vacuous-`false`
153
+ // failure mode #7975 was written to close, just moved one field over. Grep is
154
+ // the sharper case because it returns the matched file's CONTENT: measured
155
+ // against ripgrep 15.2.0, `rg --glob=.env -e <pattern> -- <benign-dir>`
156
+ // matches `.env` even WITHOUT `--hidden` — an explicit `--glob` overrides the
157
+ // default hidden-file/`.gitignore` skip that would otherwise protect a
158
+ // dotfile. So `Grep({ path: '<cwd>', glob: '.env', pattern: '.' })` returned
159
+ // live secret bytes while `floored` read `false`.
160
+ //
161
+ // #7978 closed that one shape: the floor now inspects Grep's `glob` and floors
162
+ // a glob that can select a secret (permission-floor.js, "Grep's FILE-SELECTING
163
+ // `glob` field"). Grep STAYS excluded, because the floor still cannot see the
164
+ // other half: a Grep with NO glob reads every file under `path` that the ignore
165
+ // rules let through, and a committed (non-gitignored) secret is one of them.
166
+ // `floored: false` on a Grep therefore still means "the path is not a secret",
167
+ // never "nothing this call reads is a secret". `Glob` shares the same
168
+ // blind field but can only ever return a matched PATH NAME (see its
169
+ // `input_schema` and description in byok-tools.js — "Returns sorted file
170
+ // paths"), never file bytes, so it cannot leak secret VALUES; it is excluded
171
+ // anyway for consistency with "meaningful for every allowlisted tool" and
172
+ // because listing files (unlike reading their content) is already the
173
+ // existing, deliberate design of the read floor itself (`isSecretReadTarget`
174
+ // floors a config-dir READ only when the target is a specific secret FILE,
175
+ // not merely because a directory containing one is being enumerated). See
176
+ // `tests/agent-control/permission-policy.test.js` for the bypass proof
177
+ // (a real `path`-benign / `glob`-malicious Grep input against
178
+ // `isFlooredTarget`) and `tests/built-in-tools/tool-transforms.js`'s own doc
179
+ // comment on `buildGrepCommand`, which already flagged this exact tension for
180
+ // the acceptEdits/rule-engine surface before agent-control existed.
181
+ //
182
+ // Deliberately NOT the same object as {@link ACCEPT_EDITS_TOOLS} (no more
183
+ // identity reuse): aliasing the planner's allowlist to the acceptEdits set
184
+ // meant any FUTURE widening of acceptEdits (adding a tool there because it is
185
+ // fine for a human clicking "accept edits" to auto-approve) would silently
186
+ // widen what an unattended external planner may also approve — a different,
187
+ // stronger bar. This Set is its own literal, a strict SUBSET of
188
+ // ACCEPT_EDITS_TOOLS, pinned by a behavioral test against permission-floor.js
189
+ // (not by comparing two hand-authored lists) that fails if a tool whose real
190
+ // input schema carries an uninspected file-selecting field (`glob`/`pattern`)
191
+ // is ever added back.
192
+ export const FLOOR_ALLOWLISTED_TOOLS = new Set(['Read', 'Write', 'Edit', 'NotebookEdit', 'apply_patch'])
50
193
 
51
194
  // #7004 — back-compat re-exports. The floor moved to permission-floor.js (the
52
195
  // single source both pipelines import); these names were exported from here since
@@ -61,7 +204,6 @@ const DEFAULT_TIMEOUT_MS = 300_000
61
204
  // input, where the alternative is unbounded memory/CPU growth.
62
205
  const MAX_PENDING_PERMISSIONS = 1000 // concurrent pending requests (each holds map entries + a timer)
63
206
  const MAX_SESSION_RULES = 100 // session-scoped auto-allow rules
64
- const MAX_RAW_DESCRIPTION_LEN = 8192 // raw tool field length fed to redactValue (far above the 200-char shown window)
65
207
 
66
208
  /**
67
209
  * #6543 (IDE P3 feature B) / #6773 — per-tool whitelist of the field(s) a client
@@ -110,22 +252,47 @@ const MAX_DENY_REASON_LEN = 2000
110
252
  * the original by value). Never mutates the inputs. This is the load-bearing
111
253
  * "narrow-only, no path redirect" control for feature B — keep it dumb + auditable.
112
254
  *
255
+ * #8446 — what reaches the tool executor is built from `originalInput`, the RAW
256
+ * input held here, never from content the client saw. The client reviewed a
257
+ * REDACTED copy, so text it builds carries `[REDACTED]` where a secret was:
258
+ * - a Write/Edit whose `editedInput` has a `droppedHunks` key (an empty list
259
+ * included) is rebuilt here from the raw input and those ranges (see
260
+ * edited-input.js); any text the client also sent for that field is ignored;
261
+ * - any other whitelisted text (an older client's content, a Bash command) is
262
+ * refused when redaction changed the copy it was drawn from, whatever the text
263
+ * contains.
264
+ * Anything that goes wrong while doing this is a refusal, never a throw of another
265
+ * kind: the caller answers a refusal by denying the request.
266
+ *
113
267
  * @param {object} originalInput the agent's proposed tool input
114
268
  * @param {*} editedInput the client-supplied override (untrusted)
115
269
  * @param {string} toolName the tool the permission is for
116
270
  * @returns {object}
271
+ * @throws {EditedInputRefusedError} the edit cannot be applied safely; nothing has
272
+ * been changed
117
273
  */
118
274
  export function mergeEditedInput(originalInput, editedInput, toolName) {
119
275
  if (!editedInput || typeof editedInput !== 'object' || Array.isArray(editedInput)) return originalInput
120
276
  const allowed = EDITABLE_INPUT_FIELDS[toolName]
121
277
  if (!allowed) return originalInput
122
- const merged = { ...originalInput }
123
- for (const field of allowed) {
124
- if (Object.prototype.hasOwnProperty.call(editedInput, field) && typeof editedInput[field] === 'string') {
125
- merged[field] = editedInput[field]
278
+ try {
279
+ const merged = { ...originalInput }
280
+ // The key being present puts the field in hunk mode, an empty list included.
281
+ const hunkMode = isHunkReviewedTool(toolName)
282
+ && Object.prototype.hasOwnProperty.call(editedInput, DROPPED_HUNKS_KEY)
283
+ if (hunkMode) merged[allowed[0]] = narrowByDroppedHunks(originalInput, toolName, editedInput[DROPPED_HUNKS_KEY], editedInput[KEPT_HUNKS_KEY])
284
+ for (const field of allowed) {
285
+ if (hunkMode && field === allowed[0]) continue
286
+ if (Object.prototype.hasOwnProperty.call(editedInput, field) && typeof editedInput[field] === 'string') {
287
+ assertClientTextAllowed(originalInput, toolName, field)
288
+ merged[field] = editedInput[field]
289
+ }
126
290
  }
291
+ return merged
292
+ } catch (err) {
293
+ if (err instanceof EditedInputRefusedError) throw err
294
+ throw new EditedInputRefusedError('This edit could not be applied, so the request was denied.')
127
295
  }
128
- return merged
129
296
  }
130
297
 
131
298
  /**
@@ -151,26 +318,78 @@ export function buildDenyMessage(reason) {
151
318
 
152
319
 
153
320
  /**
154
- * #6803 — collect every concrete target path a tool input names: the flat
155
- * {@link PROTECTED_PATH_INPUT_FIELDS} plus `changes[]` member paths (codex
156
- * apply_patch). Used by the rule-scope test so a path-scoped rule can confirm
157
- * ALL of a tool call's targets fall inside its scope. Returns [] for a
158
- * command-shaped / path-less input.
321
+ * Tools whose single path-carrying input field a scoped rule reads. Glob and
322
+ * Grep are handled separately: they search from an effective root.
323
+ */
324
+ const SCOPED_RULE_PATH_FIELD = {
325
+ Read: 'file_path',
326
+ Write: 'file_path',
327
+ Edit: 'file_path',
328
+ MultiEdit: 'file_path',
329
+ NotebookEdit: 'notebook_path',
330
+ }
331
+
332
+ /** Does a Glob pattern select files outside its search root? */
333
+ function _globPatternLeavesRoot(pattern) {
334
+ if (typeof pattern !== 'string') return false
335
+ // The whitespace rule only concerns how a container splits a pattern; a space
336
+ // does not make a pattern leave its root. An unquoted space starts a new word,
337
+ // so judge each word by turning whitespace into a comma: that is both a
338
+ // word-start anchor and a segment delimiter for the other rules.
339
+ const reason = globPatternEscapeReason(pattern.replace(/\s/g, ','))
340
+ return reason !== null || isAbsolute(pattern) || /^[/\\]/.test(pattern)
341
+ }
342
+
343
+ /** A path starting with `~` may be expanded to a home directory, so it names no fixed target. */
344
+ function _startsWithHomeMarker(value) {
345
+ return /^~/.test(value)
346
+ }
347
+
348
+ /**
349
+ * #6803 — collect every concrete target path a tool call names, for the
350
+ * rule-scope test. Tool-aware: Read/Write/Edit use `file_path`, NotebookEdit uses
351
+ * `notebook_path`, Glob/Grep search from their effective root (`path`, else the
352
+ * session cwd; a Glob pattern that is absolute, climbs with `..` or expands
353
+ * through `~` or braces to such a path selects files outside it), and
354
+ * `apply_patch` uses every `changes` path and rename destination plus the
355
+ * approval's top-level `file_path` (the root the approval grants writes under),
356
+ * requiring a complete change list. Other fields are ignored.
357
+ *
358
+ * Returns null when the call names no usable target set: a command-shaped tool,
359
+ * a malformed or incomplete patch, a missing path, a `~`-prefixed path, or a
360
+ * Glob pattern that leaves its root. A rule that grants (allow) does not match
361
+ * such a call; a rule that refuses (deny) does.
362
+ * @param {string} toolName
159
363
  * @param {object} input
160
- * @returns {string[]}
364
+ * @returns {string[]|null}
161
365
  */
162
- function collectTargetPaths(input) {
163
- if (!input || typeof input !== 'object') return []
164
- const out = []
165
- for (const field of PROTECTED_PATH_INPUT_FIELDS) {
166
- if (typeof input[field] === 'string' && input[field].length > 0) out.push(input[field])
167
- }
168
- if (Array.isArray(input.changes)) {
169
- for (const change of input.changes) {
170
- if (change && typeof change.path === 'string' && change.path.length > 0) out.push(change.path)
366
+ function collectTargetPaths(toolName, input) {
367
+ const targets = _collectTargets(toolName, input)
368
+ if (targets === null || targets.length === 0) return null
369
+ return targets.some(_startsWithHomeMarker) ? null : targets
370
+ }
371
+
372
+ function _collectTargets(toolName, input) {
373
+ if (!input || typeof input !== 'object') return null
374
+ if (toolName === 'apply_patch') {
375
+ const { complete, paths } = collectChangeTargets(input.changes)
376
+ if (!complete) return null
377
+ const root = input.file_path
378
+ if (root !== undefined && root !== null) {
379
+ if (typeof root !== 'string') return null
380
+ if (root.length > 0) paths.push(root)
171
381
  }
382
+ return paths
172
383
  }
173
- return out
384
+ if (toolName === 'Glob' || toolName === 'Grep') {
385
+ if (toolName === 'Glob' && _globPatternLeavesRoot(input.pattern)) return null
386
+ const root = effectiveSearchRoot(input)
387
+ return root === null ? null : [root]
388
+ }
389
+ const field = SCOPED_RULE_PATH_FIELD[toolName]
390
+ if (field === undefined) return null
391
+ const value = input[field]
392
+ return typeof value === 'string' && value.length > 0 ? [value] : null
174
393
  }
175
394
 
176
395
  // #6803 — a scope string is a GLOB (vs a plain directory prefix) when it carries
@@ -224,6 +443,11 @@ function globToRegExp(glob) {
224
443
  * @returns {boolean}
225
444
  */
226
445
  function pathWithinScope(target, scope, base) {
446
+ return lexicallyWithinScope(target, scope, base) && realLocationWithinScope(target, scope, base)
447
+ }
448
+
449
+ /** The path-text half of {@link pathWithinScope}: resolve()/relative() only. */
450
+ function lexicallyWithinScope(target, scope, base) {
227
451
  const resolvedTarget = resolve(base, target)
228
452
  if (_scopeHasGlobMagic(scope)) {
229
453
  // PR #6873 review — a glob scope must NEVER reach ABOVE the session cwd:
@@ -242,6 +466,40 @@ function pathWithinScope(target, scope, base) {
242
466
  return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith('..' + sep))
243
467
  }
244
468
 
469
+ /**
470
+ * The filesystem half of {@link pathWithinScope}: a path-scoped rule matches
471
+ * only when the target's real location is inside the scope, as the permission
472
+ * floor already does. The base is resolved with realpath, the target and a
473
+ * plain scope are walked component by component (symlinks followed, a missing
474
+ * tail applied lexically), then compared. A glob scope also requires the real
475
+ * location to be under the real base and to satisfy the glob on its path
476
+ * relative to the real base. Any resolution error means no match.
477
+ */
478
+ function realLocationWithinScope(target, scope, base, onError = false) {
479
+ try {
480
+ const realBase = realpathSync(base)
481
+ const realTarget = resolveTargetComponentwiseSync(realBase, target)
482
+ if (_scopeHasGlobMagic(scope)) {
483
+ if (!isPathWithin(realTarget, realBase)) return false
484
+ // The directory named before the first wildcard may itself be a link, so
485
+ // resolve it and match the glob against the target's path below it, as
486
+ // if the target were reached through the prefix's written spelling.
487
+ const head = scope.slice(0, scope.search(/[*?]/))
488
+ const prefix = head.slice(0, Math.max(head.lastIndexOf('/'), 0))
489
+ const written = relative(base, resolve(base, prefix)).split(sep).join('/')
490
+ const realPrefix = resolveTargetComponentwiseSync(realBase, prefix === '' ? '.' : prefix)
491
+ if (!isPathWithin(realTarget, realPrefix)) return false
492
+ const below = relative(realPrefix, realTarget).split(sep).join('/')
493
+ const through = written === '' ? below : below === '' ? written : `${written}/${below}`
494
+ return globToRegExp(scope).test(through)
495
+ }
496
+ const realScope = resolveTargetComponentwiseSync(realBase, scope)
497
+ return isPathWithin(realTarget, realScope)
498
+ } catch {
499
+ return onError
500
+ }
501
+ }
502
+
245
503
  /**
246
504
  * #6803 — normalize a rule to the stored shape `{ tool, decision }`, carrying an
247
505
  * optional `path` scope ONLY when it is a non-empty string. Keeping `path` off
@@ -256,6 +514,19 @@ function normalizeStoredRule(rule) {
256
514
  return out
257
515
  }
258
516
 
517
+ /**
518
+ * #8430: a prompt or question the user's Stop resolved carries the provider's id
519
+ * for the tool call, so the session can mark that tool row stopped. Only for a
520
+ * `stopped` resolution: a Deny, a timeout or a rule decision made in the same
521
+ * window must keep its own row. The event normalizer picks its wire fields, so this never
522
+ * reaches a client.
523
+ */
524
+ function stoppedToolUseField(reason, toolUseId) {
525
+ return reason === 'stopped' && typeof toolUseId === 'string' && toolUseId.length > 0
526
+ ? { sourceToolUseId: toolUseId }
527
+ : {}
528
+ }
529
+
259
530
  /**
260
531
  * Manages in-process permission requests for SDK-style sessions.
261
532
  *
@@ -306,6 +577,11 @@ export class PermissionManager extends EventEmitter {
306
577
  this._pendingPermissions = new Map() // requestId -> { resolve, input }
307
578
  this._permissionTimers = new Map() // requestId -> timer
308
579
  this._permissionCounter = 0
580
+ // #8430: the user pressed Stop on the turn that is running. Turn-scoped, set
581
+ // by `markUserStopInFlight()` and cleared by `clearUserStopInFlight()` at turn
582
+ // end. The abort listener reads it, so a prompt raised AFTER the Stop but
583
+ // before the provider's abort lands is a Stop's too.
584
+ this._userStopInFlight = false
309
585
  // Per-instance (per-session) nonce so requestIds are globally unique
310
586
  // across sessions. Without it the id was `perm-${counter}-${ms}` with a
311
587
  // counter that restarts at 0 every session — two sessions could mint the
@@ -429,21 +705,28 @@ export class PermissionManager extends EventEmitter {
429
705
 
430
706
  /**
431
707
  * #6803 — does this rule's optional `path` SCOPE admit `input`? An UNSCOPED
432
- * rule (no `path`) matches every input, exactly as before. A SCOPED rule
433
- * matches only when the input names at least one concrete target path AND
434
- * EVERY target falls within the scope (resolved against the session cwd) — so
435
- * a scoped `allow` never auto-approves an out-of-scope target, and an input
436
- * with no path (a command-shaped tool, or a bare `Read` with no file) never
437
- * matches a scoped rule and falls through to a prompt.
708
+ * rule (no `path`) matches every input, exactly as before. For a SCOPED rule:
709
+ * an allow rule matches only when the input names at least one target and
710
+ * EVERY target is within the scope (resolved against the session cwd); a deny
711
+ * rule matches when ANY target is within the scope, or when the targets cannot
712
+ * be determined. So a scoped `allow` never auto-approves an out-of-scope
713
+ * target, and an input with no path never matches a scoped allow and falls
714
+ * through to a prompt.
438
715
  * @param {{tool: string, decision: string, path?: string}} rule
439
716
  * @param {object} [input]
440
717
  * @returns {boolean}
441
718
  */
442
719
  _ruleScopeMatches(rule, input) {
443
720
  if (typeof rule.path !== 'string' || rule.path.length === 0) return true
444
- const targets = collectTargetPaths(input)
445
- if (targets.length === 0) return false
721
+ const targets = collectTargetPaths(rule.tool, input)
446
722
  const base = this._cwd || process.cwd()
723
+ if (rule.decision === 'deny') {
724
+ // A refusal matches when ANY target is inside the scope by its path text or
725
+ // by its real location, and when the targets cannot be determined.
726
+ if (targets === null) return true
727
+ return targets.some((t) => lexicallyWithinScope(t, rule.path, base) || realLocationWithinScope(t, rule.path, base, true))
728
+ }
729
+ if (targets === null) return false
447
730
  return targets.every((t) => pathWithinScope(t, rule.path, base))
448
731
  }
449
732
 
@@ -558,11 +841,15 @@ export class PermissionManager extends EventEmitter {
558
841
  * echo back via `updatedPermissions` when the user picks "allow
559
842
  * always". Per the Agent SDK 'Always allow' flow, these are the
560
843
  * correct shape of rule to persist for this tool in this session.
844
+ * @param {string} [sourceToolUseId] - #8336: the PROVIDER's id for this
845
+ * tool call (the SDK's `toolUseID`, BYOK's `block.id`) -- the id its
846
+ * `tool_start` is recorded under. Only AskUserQuestion reads it.
561
847
  * @returns {Promise<{behavior: string, updatedInput?: Object, message?: string, updatedPermissions?: Array}>}
562
848
  */
563
- handlePermission(toolName, input, signal, permissionMode, suggestions = undefined) {
849
+ handlePermission(toolName, input, signal, permissionMode, suggestions = undefined, sourceToolUseId = undefined) {
850
+ if (toolName === 'dev_preview') return Promise.resolve({ behavior: 'deny', message: 'Preview publication requires a client-bound explicit consent request' })
564
851
  if (toolName === 'AskUserQuestion') {
565
- return this._handleAskUserQuestion(input, signal)
852
+ return this._handleAskUserQuestion(input, signal, sourceToolUseId)
566
853
  }
567
854
 
568
855
  // #6794 — protected-path floor. A path-carrying tool aimed at a protected
@@ -592,7 +879,16 @@ export class PermissionManager extends EventEmitter {
592
879
  // still emits prompts because session rules and the prompt path run
593
880
  // before any mode check. #6794: the floor takes precedence — a protected
594
881
  // target still prompts even under auto.
595
- if (permissionMode === 'auto' && !protectedTarget) {
882
+ //
883
+ // #8619: so does NOT_DELEGABLE_TOOLS — the one list of tools an unattended
884
+ // approver may never say yes to (#7975). A codex sandbox-scope escalation
885
+ // (`request_permissions`) carries no path field, so the floor cannot see
886
+ // it, yet a turn-scoped grant would switch off the only floor codex has
887
+ // (`apply_patch` → `changes[].path`) for the rest of the turn. Now that
888
+ // codex Auto keeps `approvalPolicy: 'on-request'`, this is the first path
889
+ // on which such a request can reach the short-circuit; it falls through to
890
+ // the prompt, exactly as `autoAllowPending` leaves a pending one pending.
891
+ if (permissionMode === 'auto' && !protectedTarget && !NOT_DELEGABLE_TOOLS.has(toolName)) {
596
892
  return Promise.resolve({ behavior: 'allow', updatedInput: input || {} })
597
893
  }
598
894
 
@@ -636,7 +932,14 @@ export class PermissionManager extends EventEmitter {
636
932
  }
637
933
  this._pendingPermissions.set(requestId, {
638
934
  resolve,
935
+ // #8363: the provider's id for this tool call, so `hasPendingForToolUse`
936
+ // can say whether its prompt is STILL waiting (not merely was asked).
937
+ toolUseId: sourceToolUseId,
639
938
  input: input || {},
939
+ // Preserve the single floor verdict made above. A later mode switch
940
+ // may drain ordinary prompts, but it must not turn an already pending
941
+ // protected-path prompt into an implicit approval.
942
+ protectedTarget,
640
943
  // Stashed for the allowAlways branch of respondToPermission so
641
944
  // we can echo them back as updatedPermissions per the SDK
642
945
  // 'Always allow' flow.
@@ -644,23 +947,12 @@ export class PermissionManager extends EventEmitter {
644
947
  })
645
948
 
646
949
  const toolInput = input || {}
647
- const rawDescription = toolInput.description
648
- || toolInput.command
649
- || toolInput.file_path
650
- || toolInput.pattern
651
- || toolInput.query
652
- || (Object.keys(toolInput).length > 0 ? JSON.stringify(toolInput) : toolName)
653
- // #6038/#6048/#6049: build the broadcast description by REDACTING the full
654
- // string first, THEN truncating — truncating first (the old order) could
655
- // leave a secret straddling the cap as a sub-floor partial prefix that the
656
- // pattern scan misses. String() coerces a non-string field so a malformed
657
- // tool input can't crash the emit path (.replace on a non-string throws).
658
- // #6448 — cap the raw string BEFORE redaction so a malicious multi-MB tool
659
- // field can't make redactValue scan the whole thing (CPU DoS). The 8KB cap
660
- // is far above the 200-char shown window below, so it can never split a
661
- // SHOWN secret — the #6038 redact-then-truncate guarantee holds for
662
- // everything the client sees (anything past 8KB is sliced away regardless).
663
- const description = redactValue(String(rawDescription).slice(0, MAX_RAW_DESCRIPTION_LEN)).slice(0, 200)
950
+ // #6038/#6048/#6049/#8384: the broadcast description is built by
951
+ // `describeToolInput`, the one place a description is derived from a tool
952
+ // input: redaction (of the identifying field, or of the SANITIZED input
953
+ // when none exists) always runs before the 200-char clip. The raw input is
954
+ // never serialized into it.
955
+ const description = describeToolInput(toolInput, toolName).slice(0, 200)
664
956
 
665
957
  this._logInfo(`Permission request ${requestId}: ${toolName}`)
666
958
 
@@ -668,6 +960,12 @@ export class PermissionManager extends EventEmitter {
668
960
  // execution via the _pendingPermissions entry above; this payload is
669
961
  // broadcast/display only, so a secret in a value (or the stringified
670
962
  // fallback description) must not reach subscribed clients.
963
+ // #7968: carry the floor verdict computed above so an external consumer
964
+ // of permission_request (e.g. the agent-control MCP, #7854) can tell a
965
+ // floored prompt apart from an ordinary one. Stashed on _lastPermissionData
966
+ // too, so both the resend path (resendPendingPermissions) and this
967
+ // broadcast agree — one computation, replayed verbatim.
968
+ const recordDescription = describeByNamedField(toolInput)
671
969
  const permPayload = {
672
970
  requestId,
673
971
  tool: toolName,
@@ -675,19 +973,40 @@ export class PermissionManager extends EventEmitter {
675
973
  input: sanitizeToolInput(toolInput),
676
974
  remainingMs: this._timeoutMs,
677
975
  createdAt: Date.now(),
976
+ floored: protectedTarget,
977
+ explicitConsent: false,
978
+ nonDelegable: NOT_DELEGABLE_TOOLS.has(toolName),
979
+ // #8348: the identifying field of the RAW input, redacted, for the
980
+ // session's permission transcript. Not on the wire (the request builder
981
+ // picks its fields), and read from the raw input because the broadcast
982
+ // copy of a large input no longer has the field.
983
+ ...(recordDescription !== undefined ? { recordDescription } : {}),
678
984
  }
679
985
  this._lastPermissionData.set(requestId, permPayload)
680
986
  this.emit('permission_request', permPayload)
681
987
 
682
- // Auto-deny on abort signal (user interrupted)
988
+ // Auto-deny on abort signal. WHY the signal aborted is not on the signal --
989
+ // a user Stop and a failed turn (a dead app-server, a stalled stream) abort
990
+ // the same controller -- so the user's Stop entry point sets the turn's
991
+ // "user Stop in flight" flag (`markUserStopInFlight`, #8374/#8430) and this
992
+ // reads it when the abort lands: `stopped` for a Stop, `aborted` for
993
+ // everything else. The flag, not a mark on each prompt, so a prompt raised
994
+ // in the window between the Stop and the abort is covered too.
683
995
  if (signal) {
684
996
  signal.addEventListener('abort', () => {
685
- if (this._pendingPermissions.has(requestId)) {
997
+ const pending = this._pendingPermissions.get(requestId)
998
+ if (pending) {
999
+ const reason = this._userStopInFlight ? 'stopped' : 'aborted'
686
1000
  this._pendingPermissions.delete(requestId)
687
1001
  this._lastPermissionData.delete(requestId)
688
1002
  this._clearPermissionTimer(requestId)
689
1003
  resolve({ behavior: 'deny', message: 'Request cancelled' })
690
- this.emit('permission_resolved', { requestId, decision: 'deny', reason: 'aborted' })
1004
+ this.emit('permission_resolved', {
1005
+ requestId,
1006
+ decision: 'deny',
1007
+ reason,
1008
+ ...stoppedToolUseField(reason, pending.toolUseId),
1009
+ })
691
1010
  }
692
1011
  }, { once: true })
693
1012
  }
@@ -707,14 +1026,71 @@ export class PermissionManager extends EventEmitter {
707
1026
  })
708
1027
  }
709
1028
 
1029
+ /**
1030
+ * #8374/#8430: the user pressed Stop. Record that for the rest of the turn, so
1031
+ * the abort that follows resolves every open prompt -- including one raised
1032
+ * between this call and the abort -- with `reason: 'stopped'` instead of
1033
+ * `'aborted'`.
1034
+ *
1035
+ * Called only from the user's Stop entry point (the `interrupt` message
1036
+ * handler), never from `interrupt()` itself: the scheduler and teardown call
1037
+ * that too, and a turn failed by a stalled stream or a dead app-server aborts
1038
+ * the same controller. Those are not Stops.
1039
+ *
1040
+ * Ends with the turn (`clearUserStopInFlight`, called from the session's turn
1041
+ * teardown), so a later turn's failure is not mislabelled.
1042
+ */
1043
+ markUserStopInFlight() {
1044
+ this._userStopInFlight = true
1045
+ }
1046
+
1047
+ /** #8430: the turn is over; a Stop pressed during it must not label the next. */
1048
+ clearUserStopInFlight() {
1049
+ this._userStopInFlight = false
1050
+ }
1051
+
1052
+ /** #8430: has the user pressed Stop on the turn that is running? */
1053
+ isUserStopInFlight() {
1054
+ return this._userStopInFlight
1055
+ }
1056
+
1057
+ /** #8430: is any permission prompt or question waiting for a decision right now? */
1058
+ hasPendingPrompt() {
1059
+ return this._pendingPermissions.size > 0 || this._pendingUserAnswer != null
1060
+ }
1061
+
710
1062
  /**
711
1063
  * Handle AskUserQuestion via canUseTool.
712
1064
  * Emits user_question and waits for respondToQuestion() to deliver the
713
1065
  * user's answer, then resolves with structured updatedInput.
714
1066
  */
715
- _handleAskUserQuestion(input, signal) {
1067
+ /**
1068
+ * #8363: is a permission prompt (or AskUserQuestion) for this PROVIDER tool-use
1069
+ * id still waiting for a decision? Reads the live pending state, which a
1070
+ * response clears synchronously -- unlike a promise continuation, which runs a
1071
+ * microtask later.
1072
+ * @param {string} toolUseId
1073
+ * @returns {boolean}
1074
+ */
1075
+ hasPendingForToolUse(toolUseId) {
1076
+ if (typeof toolUseId !== 'string' || toolUseId.length === 0) return false
1077
+ if (this._pendingUserAnswer?.sourceToolUseId === toolUseId) return true
1078
+ for (const entry of this._pendingPermissions.values()) {
1079
+ if (entry.toolUseId === toolUseId) return true
1080
+ }
1081
+ return false
1082
+ }
1083
+
1084
+ _handleAskUserQuestion(input, signal, sourceToolUseId = undefined) {
716
1085
  return new Promise((resolve) => {
717
1086
  const questionInput = input || {}
1087
+ // #8470: this manager holds ONE pending question. A second one arriving
1088
+ // while the first is still open used to overwrite the slot, so the first
1089
+ // `canUseTool` promise never settled (the tool call hung until the turn
1090
+ // ended), its timer kept running against the NEW question, and its card
1091
+ // read pending on every client. End it as a deny, tell the clients, and
1092
+ // only then take the slot.
1093
+ this._supersedePendingQuestion()
718
1094
  this._waitingForAnswer = true
719
1095
  const toolUseId = `ask-${this._idNonce}-${++this._permissionCounter}-${Date.now()}`
720
1096
  // #3975: stash toolUseId on the pending entry so clearAll() can
@@ -724,23 +1100,48 @@ export class PermissionManager extends EventEmitter {
724
1100
  // questionSessionMap entry — small leak (~80 bytes) per
725
1101
  // message-completion-while-question-pending event, bounded only by
726
1102
  // session_destroyed cleanup.
727
- this._pendingUserAnswer = { resolve, input: questionInput, toolUseId }
1103
+ const entry = { resolve, input: questionInput, toolUseId, sourceToolUseId }
1104
+ this._pendingUserAnswer = entry
728
1105
  this._logInfo(`AskUserQuestion detected (${toolUseId})`)
1106
+ // #8336: without the provider's id, the restore-time sweep cannot tell
1107
+ // which `tool_start` this question belongs to, so a restart mid-question
1108
+ // will leave it looking like any other replayed question ("(resolved)").
1109
+ // Both providers that reach here (SDK, BYOK) are meant to supply it. Say so
1110
+ // once, with the id the question WAS recorded under, and carry on.
1111
+ if (typeof sourceToolUseId !== 'string' || sourceToolUseId.length === 0) {
1112
+ this._logWarn(
1113
+ `AskUserQuestion ${toolUseId} has no provider tool-use id; a restart while it is pending cannot mark it interrupted (#8336)`,
1114
+ )
1115
+ }
729
1116
 
1117
+ // #8336: `toolUseId` here is chroxy's own `ask-...` id (what the answer
1118
+ // routes on), which is NOT the id the provider recorded the
1119
+ // AskUserQuestion `tool_start` under. Carry the provider's id alongside
1120
+ // it so the restore-time sweep can tell which question a swept tool start
1121
+ // belongs to. Never on the live wire: the event normalizer picks
1122
+ // `toolUseId` and `questions` only.
730
1123
  this.emit('user_question', {
731
1124
  toolUseId,
732
1125
  questions: questionInput.questions,
1126
+ ...(typeof sourceToolUseId === 'string' && sourceToolUseId.length > 0
1127
+ ? { sourceToolUseId }
1128
+ : {}),
733
1129
  })
734
1130
 
735
1131
  // Auto-deny on abort signal
736
1132
  if (signal) {
737
1133
  signal.addEventListener('abort', () => {
738
- if (this._pendingUserAnswer) {
1134
+ // #8470: identity, not "something is pending". A superseded question's
1135
+ // listener stays on the (shared) turn signal; without this it would
1136
+ // cancel the question that replaced it.
1137
+ if (this._pendingUserAnswer === entry) {
1138
+ // #8430: same cause attribution as a permission prompt's abort.
1139
+ const reason = this._userStopInFlight ? 'stopped' : 'aborted'
739
1140
  this._clearQuestionTimer()
740
1141
  this._pendingUserAnswer = null
741
1142
  this._waitingForAnswer = false
742
1143
  resolve({ behavior: 'deny', message: 'Cancelled' })
743
- this.emit('permission_resolved', { toolUseId, reason: 'aborted' })
1144
+ this.emit('permission_resolved', { toolUseId, reason, ...stoppedToolUseField(reason, sourceToolUseId) })
744
1145
  }
745
1146
  }, { once: true })
746
1147
  }
@@ -759,6 +1160,24 @@ export class PermissionManager extends EventEmitter {
759
1160
  })
760
1161
  }
761
1162
 
1163
+ /**
1164
+ * #8470: end the pending AskUserQuestion, if any, because a newer one is about
1165
+ * to replace it. Resolves its `canUseTool` promise as a deny (the tool call
1166
+ * ends and the agent hears why), stops its timer, and emits the question
1167
+ * variant of `permission_resolved` with `reason: 'superseded'` so the clients
1168
+ * stop showing it as waiting. Not an answer: nothing is recorded as answered.
1169
+ */
1170
+ _supersedePendingQuestion() {
1171
+ const superseded = this._pendingUserAnswer
1172
+ if (!superseded) return
1173
+ this._clearQuestionTimer()
1174
+ this._pendingUserAnswer = null
1175
+ this._waitingForAnswer = false
1176
+ this._logInfo(`Question ${superseded.toolUseId} superseded by a newer question`)
1177
+ superseded.resolve({ behavior: 'deny', message: 'Superseded by a newer question' })
1178
+ this.emit('permission_resolved', { toolUseId: superseded.toolUseId, decision: 'deny', reason: 'superseded' })
1179
+ }
1180
+
762
1181
  /**
763
1182
  * Resolve a pending permission request.
764
1183
  *
@@ -768,18 +1187,31 @@ export class PermissionManager extends EventEmitter {
768
1187
  * {@link EDITABLE_INPUT_FIELDS} whitelist on an approve (ignored on deny).
769
1188
  * @param {string} [reason] - #6773 operator-supplied free-text deny reason;
770
1189
  * used only on a `deny` to replace the fixed 'User denied' agent message.
1190
+ * @param {string} [scope] - #8517 `session` when the user chose "Allow for
1191
+ * Session" (the decision is then `allow`). A LABEL for the permission_resolved
1192
+ * event and the journal: it changes nothing about how the request is resolved,
1193
+ * and is dropped unless it rides beside `allow` (permission-scope.js).
771
1194
  * @returns {boolean} true if a pending permission was found and resolved,
772
1195
  * false if the requestId was unknown (already resolved or expired).
773
1196
  */
774
- respondToPermission(requestId, decision, editedInput, reason) {
1197
+ respondToPermission(requestId, decision, editedInput, reason, scope) {
775
1198
  const pending = this._pendingPermissions.get(requestId)
776
1199
  if (!pending) {
777
1200
  this._logWarn(`No pending permission for ${requestId}`)
778
1201
  return false
779
1202
  }
1203
+ // Explicit consent has its own client-bound response route. Generic
1204
+ // responders, durable grants and edited inputs cannot approve it.
1205
+ if (pending.explicitConsent === true && decision !== 'deny') return false
780
1206
  // #6543: capture the tool name BEFORE deleting the last-permission data, so
781
1207
  // the editedInput whitelist knows which content field(s) are substitutable.
782
1208
  const toolName = this._lastPermissionData.get(requestId)?.tool
1209
+ // #8446: build the approved input BEFORE touching any state. A refused edit
1210
+ // throws EditedInputRefusedError with the request still pending, so the caller
1211
+ // (permission-resolver.js) can answer it; ignored on a deny.
1212
+ const approvedInput = (decision === 'allow' || decision === 'allowAlways')
1213
+ ? mergeEditedInput(pending.input, editedInput, toolName)
1214
+ : pending.input
783
1215
  this._pendingPermissions.delete(requestId)
784
1216
  this._lastPermissionData.delete(requestId)
785
1217
  this._clearPermissionTimer(requestId)
@@ -788,13 +1220,14 @@ export class PermissionManager extends EventEmitter {
788
1220
 
789
1221
  // Emit before resolve() so listeners see the pending-count drop
790
1222
  // before any follow-on work runs synchronously.
791
- this.emit('permission_resolved', { requestId, decision, reason: 'user' })
1223
+ const resolvedScope = permissionScope(decision, scope)
1224
+ this.emit('permission_resolved', { requestId, decision, reason: 'user', ...(resolvedScope ? { scope: resolvedScope } : {}) })
792
1225
 
793
1226
  // #6543 (feature B): on an approve, an operator who reviewed the proposed
794
- // Write/Edit per-hunk may substitute the CONTENT (never the path — see
795
- // mergeEditedInput). Ignored on deny. The merged input flows to the agent's
796
- // tool executor as `updatedInput`, which still path-confines the write.
797
- const approvedInput = mergeEditedInput(pending.input, editedInput, toolName)
1227
+ // Write/Edit per-hunk may narrow the CONTENT (never the path — see
1228
+ // mergeEditedInput, built above from the RAW input, #8446). The merged input
1229
+ // flows to the agent's tool executor as `updatedInput`, which still
1230
+ // path-confines the write.
798
1231
 
799
1232
  if (decision === 'allow') {
800
1233
  pending.resolve({ behavior: 'allow', updatedInput: approvedInput })
@@ -851,9 +1284,26 @@ export class PermissionManager extends EventEmitter {
851
1284
  *
852
1285
  * @param {string} text - The user's text answer
853
1286
  * @param {Object} [answersMap] - Per-question answers map
1287
+ * @param {string} [toolUseId] - #8460: the chroxy question id the answer was
1288
+ * given for (the `ask-...` id on the `user_question` frame). When supplied and
1289
+ * it is not the pending question's, the answer is for a different question
1290
+ * (a retry, a second client, a reconnect re-send landing after the first
1291
+ * question was answered or timed out), so it is dropped rather than resolved
1292
+ * against whichever question happens to be pending now. Absent, the answer
1293
+ * goes to the pending question as before. `typeof === 'string'`, not
1294
+ * truthiness: an empty id is still an id, and still not this question's.
1295
+ * @returns {boolean|undefined} `false` only when the answer was refused for a
1296
+ * mismatching `toolUseId` (the pending question is untouched, nothing reached
1297
+ * the agent). `undefined` otherwise, including "nothing was pending".
854
1298
  */
855
- respondToQuestion(text, answersMap) {
1299
+ respondToQuestion(text, answersMap, toolUseId = undefined) {
856
1300
  if (!this._pendingUserAnswer) return
1301
+ if (typeof toolUseId === 'string' && toolUseId !== this._pendingUserAnswer.toolUseId) {
1302
+ this._logWarn(
1303
+ `Question response dropped: answer is for ${JSON.stringify(toolUseId)} but the pending question is ${JSON.stringify(this._pendingUserAnswer.toolUseId)}`,
1304
+ )
1305
+ return false
1306
+ }
857
1307
  this._clearQuestionTimer()
858
1308
  // #3988: include toolUseId on the answered emit for symmetry with the
859
1309
  // other 3 question-variant emit sites (aborted/timeout/cleared). The
@@ -869,7 +1319,7 @@ export class PermissionManager extends EventEmitter {
869
1319
  // (or refactor that drops the eager delete) would silently leak. Read
870
1320
  // toolUseId BEFORE the null-out below, mirroring the clearAll #3975
871
1321
  // pattern.
872
- const { resolve, input, toolUseId } = this._pendingUserAnswer
1322
+ const { resolve, input, toolUseId: pendingToolUseId } = this._pendingUserAnswer
873
1323
  this._pendingUserAnswer = null
874
1324
  this._waitingForAnswer = false
875
1325
 
@@ -878,7 +1328,7 @@ export class PermissionManager extends EventEmitter {
878
1328
  // Emit before resolve() so listeners (e.g. the SdkSession
879
1329
  // inactivity-timer resumer, #2831) see the state flip before any
880
1330
  // downstream synchronous work runs.
881
- this.emit('permission_resolved', { toolUseId, reason: 'answered' })
1331
+ this.emit('permission_resolved', { toolUseId: pendingToolUseId, reason: 'answered' })
882
1332
 
883
1333
  // Build structured answers map: SDK expects { [questionText]: selectedLabel }.
884
1334
  // Per @anthropic-ai/claude-agent-sdk sdk-tools.d.ts (AskUserQuestionOutput.answers,
@@ -915,6 +1365,31 @@ export class PermissionManager extends EventEmitter {
915
1365
  })
916
1366
  }
917
1367
 
1368
+ /**
1369
+ * #7457 -- the AskUserQuestion this manager is still blocked on, if any.
1370
+ *
1371
+ * A read-through of `_pendingUserAnswer`, which IS the blocked `canUseTool`
1372
+ * resolver: every path that resolves the promise nulls it in the same
1373
+ * statement block (`respondToQuestion`, the abort listener, the question
1374
+ * timer, `clearAll`), so this can never report a question the turn is no
1375
+ * longer waiting on. There is no second record to leak.
1376
+ *
1377
+ * `autoAllowPending()` is deliberately NOT one of those paths (#3729/#4462):
1378
+ * solicited user input is not a permission gate, so a mode switch to
1379
+ * auto/bypass leaves the resolver blocked -- and therefore leaves the
1380
+ * question correctly pending here.
1381
+ *
1382
+ * Shaped as an array because the other two providers hold a MAP of them, and
1383
+ * `ws-history.resendPendingQuestions` reads one shape from every provider.
1384
+ *
1385
+ * @returns {{ toolUseId: string, questions: object[] }[]}
1386
+ */
1387
+ getPendingQuestions() {
1388
+ const pending = this._pendingUserAnswer
1389
+ if (!pending) return []
1390
+ return [{ toolUseId: pending.toolUseId, questions: pending.input?.questions ?? [] }]
1391
+ }
1392
+
918
1393
  /**
919
1394
  * Clear a permission timeout timer by request ID.
920
1395
  */
@@ -937,12 +1412,13 @@ export class PermissionManager extends EventEmitter {
937
1412
  }
938
1413
 
939
1414
  /**
940
- * Auto-allow every outstanding permission request. Called when the
1415
+ * Auto-allow every ordinary outstanding permission request. Called when the
941
1416
  * session switches into auto/bypass mode (#3729) — the user has just
942
- * declared "approve everything", so any prompt still on screen should
1417
+ * enabled broad auto-approval, so an ordinary prompt still on screen should
943
1418
  * resolve as if they had clicked Allow rather than sit there until
944
1419
  * timeout. Pending AskUserQuestion prompts are NOT touched: those are
945
- * solicited user input, not permission gates.
1420
+ * solicited user input, not permission gates. Protected-path prompts also
1421
+ * remain pending because Auto is still subject to the permission floor.
946
1422
  *
947
1423
  * #4462: MCP trust prompts (requestMcpTrust) are also exempt — their
948
1424
  * allow path PERSISTS the binary to ~/.chroxy/mcp-trust.json forever
@@ -951,19 +1427,51 @@ export class PermissionManager extends EventEmitter {
951
1427
  * binary forever." Treating mcp_spawn under auto as deny re-prompts
952
1428
  * the user next start — they can explicitly approve then, when the
953
1429
  * decision is in front of them.
1430
+ *
1431
+ * #7975: a pending `request_permissions` prompt (codex's sandbox-scope
1432
+ * escalation) carries neither `protectedTarget` nor `mcpTrust` — before
1433
+ * this fix it fell straight through to the default allow branch below, so
1434
+ * a session that flipped into auto/bypass mode mid-turn silently granted a
1435
+ * sandbox-scope escalation the user never explicitly approved. This is now
1436
+ * checked by TOOL NAME against {@link NOT_DELEGABLE_TOOLS} — the exact same
1437
+ * Set agent-control's `respondPermission` gate uses, so the daemon's "never
1438
+ * approve without a human" list has one source of truth, not two that can
1439
+ * drift — via the tool name stashed on `_lastPermissionData` (the pending
1440
+ * entry itself carries no tool field). It is left GENUINELY PENDING, the
1441
+ * same treatment as a protected-path prompt: the original `permission_request`
1442
+ * broadcast already reached any connected client when the prompt was first
1443
+ * emitted, and `resendPendingPermissions` (ws-permissions.js) replays it to
1444
+ * a reconnecting client for as long as it stays in `_pendingPermissions` —
1445
+ * nothing here removes it from either map, so it is neither silently
1446
+ * granted nor silently dropped. `mcp_spawn` is ALSO in NOT_DELEGABLE_TOOLS,
1447
+ * but this check is placed AFTER the `mcpTrust` branch below (which fires
1448
+ * for every mcp_spawn entry) so mcp_spawn's existing explicit-deny handling
1449
+ * is unchanged — this only widens what happens to `request_permissions`.
1450
+ *
1451
+ * #7975-followup: the tool-name lookup FAILS CLOSED — a pending entry with
1452
+ * no recoverable `_lastPermissionData` (which every current call site sets
1453
+ * in lockstep with `_pendingPermissions`, so this is a belt-and-braces
1454
+ * default, not a reachable path today) is preserved genuinely pending, same
1455
+ * as a known not-delegable tool, rather than silently allowed.
954
1456
  */
955
1457
  autoAllowPending() {
956
1458
  if (this._pendingPermissions.size === 0) return
957
1459
  const pendingIds = Array.from(this._pendingPermissions.keys())
958
1460
  let allowed = 0
959
1461
  let deniedMcpTrust = 0
1462
+ let preservedProtected = 0
1463
+ let preservedNotDelegable = 0
960
1464
  for (const requestId of pendingIds) {
961
1465
  const pending = this._pendingPermissions.get(requestId)
962
1466
  if (!pending) continue
963
- this._pendingPermissions.delete(requestId)
964
- this._lastPermissionData.delete(requestId)
965
- this._clearPermissionTimer(requestId)
1467
+ if (pending.protectedTarget === true) {
1468
+ preservedProtected += 1
1469
+ continue
1470
+ }
966
1471
  if (pending.mcpTrust === true) {
1472
+ this._pendingPermissions.delete(requestId)
1473
+ this._lastPermissionData.delete(requestId)
1474
+ this._clearPermissionTimer(requestId)
967
1475
  // Don't silently persist trust on bypass. Deny — the MCP server
968
1476
  // won't spawn for this session, but no on-disk trust entry is
969
1477
  // written, and the user re-prompts next start.
@@ -975,13 +1483,37 @@ export class PermissionManager extends EventEmitter {
975
1483
  deniedMcpTrust += 1
976
1484
  continue
977
1485
  }
1486
+ // #7975 — same NOT_DELEGABLE_TOOLS set agent-control's respondPermission
1487
+ // gate consults, checked by the tool name stashed alongside this
1488
+ // requestId (the pending entry itself has no tool field). Left pending,
1489
+ // never deleted — see the doc comment above.
1490
+ //
1491
+ // #7975-followup — every current call site sets `_lastPermissionData`
1492
+ // in the SAME synchronous step as `_pendingPermissions` (handlePermission
1493
+ // and requestMcpTrust both do this, and nothing else in this module ever
1494
+ // mutates either map), so `lastData` below is not expected to be missing
1495
+ // in practice. But `NOT_DELEGABLE_TOOLS.has(undefined)` is `false` — if
1496
+ // that invariant were ever violated by a future change, an entry with no
1497
+ // recoverable tool name would silently fall through to the ALLOW branch
1498
+ // below, which is exactly the bug this fix exists to close, just for an
1499
+ // unknown tool instead of a known one. Fail closed instead: treat a
1500
+ // missing lookup the same as a not-delegable tool (leave it genuinely
1501
+ // pending for a human) rather than assume it is safe to allow.
1502
+ const lastData = this._lastPermissionData.get(requestId)
1503
+ if (pending.explicitConsent === true || !lastData || NOT_DELEGABLE_TOOLS.has(lastData.tool)) {
1504
+ preservedNotDelegable += 1
1505
+ continue
1506
+ }
1507
+ this._pendingPermissions.delete(requestId)
1508
+ this._lastPermissionData.delete(requestId)
1509
+ this._clearPermissionTimer(requestId)
978
1510
  pending.resolve({ behavior: 'allow', updatedInput: pending.input })
979
1511
  this.emit('permission_resolved', { requestId, decision: 'allow', reason: 'auto_mode' })
980
1512
  allowed += 1
981
1513
  }
982
- if (deniedMcpTrust > 0) {
1514
+ if (deniedMcpTrust > 0 || preservedProtected > 0 || preservedNotDelegable > 0) {
983
1515
  this._logInfo(
984
- `Auto-allowed ${allowed} pending permission(s) and denied ${deniedMcpTrust} MCP trust prompt(s) on auto mode switch (trust not persisted via bypass — #4462)`,
1516
+ `Auto-allowed ${allowed} pending permission(s), denied ${deniedMcpTrust} MCP trust prompt(s), preserved ${preservedProtected} protected-path prompt(s), and preserved ${preservedNotDelegable} not-delegable prompt(s) on auto mode switch`,
985
1517
  )
986
1518
  } else {
987
1519
  this._logInfo(`Auto-allowed ${allowed} pending permission(s) on auto mode switch`)
@@ -992,11 +1524,20 @@ export class PermissionManager extends EventEmitter {
992
1524
  * Auto-deny all pending permissions and questions. Called on message
993
1525
  * completion or session destruction.
994
1526
  */
995
- clearAll() {
1527
+ clearAll({ userStop = this._userStopInFlight } = {}) {
1528
+ // #8430: why the prompts are being drained. On a live claude-sdk Stop this is
1529
+ // the path that resolves them (the generator throws AbortError and the turn
1530
+ // ends through the session's teardown; the abort listener never ran first), so
1531
+ // a user Stop in flight must be read HERE. `userStop` lets a caller that has
1532
+ // already cleared the flag in its own teardown pass the value it captured.
1533
+ const requestReason = userStop === true ? 'stopped' : 'cleared'
996
1534
  // Collect requestIds first so we can emit permission_resolved AFTER
997
1535
  // the maps are cleared — the SdkSession timeout-pause listener decrements
998
1536
  // its counter on each event and should see a consistent final state.
999
1537
  const pendingIds = Array.from(this._pendingPermissions.keys())
1538
+ // #8430: the provider's tool-use id of each, for a `stopped` resolution.
1539
+ const pendingToolUseIds = new Map()
1540
+ for (const [requestId, pending] of this._pendingPermissions) pendingToolUseIds.set(requestId, pending.toolUseId)
1000
1541
  // #3975: capture the pending-answer entry (not just a boolean) so we
1001
1542
  // can include its toolUseId on the cleared emit. Without toolUseId the
1002
1543
  // sdk-session re-emit gate drops the event and questionSessionMap
@@ -1029,17 +1570,69 @@ export class PermissionManager extends EventEmitter {
1029
1570
 
1030
1571
  // Emit resolved events so listeners reset any paused state (#2831).
1031
1572
  for (const requestId of pendingIds) {
1032
- this.emit('permission_resolved', { requestId, decision: 'deny', reason: 'cleared' })
1573
+ this.emit('permission_resolved', {
1574
+ requestId,
1575
+ decision: 'deny',
1576
+ reason: requestReason,
1577
+ ...stoppedToolUseField(requestReason, pendingToolUseIds.get(requestId)),
1578
+ })
1033
1579
  }
1034
1580
  if (clearedUserAnswer) {
1035
1581
  // #3975: toolUseId is required for the EventNormalizer to prune
1036
1582
  // questionSessionMap on the cleared path. The SdkSession
1037
1583
  // timeout-pause listener (#2831) ignores fields it doesn't know
1038
1584
  // about, so the extra toolUseId is harmless there.
1039
- this.emit('permission_resolved', { toolUseId: clearedUserAnswer.toolUseId, reason: 'cleared' })
1585
+ this.emit('permission_resolved', {
1586
+ toolUseId: clearedUserAnswer.toolUseId,
1587
+ reason: requestReason,
1588
+ ...stoppedToolUseField(requestReason, clearedUserAnswer.sourceToolUseId),
1589
+ })
1040
1590
  }
1041
1591
  }
1042
1592
 
1593
+ /** Request one-time human consent without mode, rule or durable-grant shortcuts. */
1594
+ requestExplicitConsent({ requestId, clientId, tool, input, description, signal }) {
1595
+ if (!requestId || !clientId || !NOT_DELEGABLE_TOOLS.has(tool)) throw new Error('Invalid explicit consent request')
1596
+ if (signal?.aborted || this._pendingPermissions.has(requestId)) return Promise.resolve(false)
1597
+ return new Promise((resolve) => {
1598
+ const finish = (allowed, reason) => {
1599
+ if (!this._pendingPermissions.has(requestId)) return
1600
+ this._pendingPermissions.delete(requestId)
1601
+ this._lastPermissionData.delete(requestId)
1602
+ this._clearPermissionTimer(requestId)
1603
+ signal?.removeEventListener('abort', abort)
1604
+ this.emit('permission_resolved', { requestId, decision: allowed ? 'allow' : 'deny', reason })
1605
+ resolve(allowed)
1606
+ }
1607
+ const abort = () => finish(false, 'cancelled')
1608
+ const payload = {
1609
+ requestId, tool, input: sanitizeToolInput(input), description: describeComposedText(description),
1610
+ remainingMs: this._timeoutMs, createdAt: Date.now(), floored: true,
1611
+ explicitConsent: true, nonDelegable: true,
1612
+ }
1613
+ this._pendingPermissions.set(requestId, {
1614
+ input, suggestions: [], explicitConsent: true, clientId,
1615
+ finish,
1616
+ resolve: result => {
1617
+ signal?.removeEventListener('abort', abort)
1618
+ resolve(result?.behavior === 'allow')
1619
+ },
1620
+ })
1621
+ this._lastPermissionData.set(requestId, payload)
1622
+ signal?.addEventListener('abort', abort, { once: true })
1623
+ this._permissionTimers.set(requestId, setTimeout(() => finish(false, 'timeout'), this._timeoutMs))
1624
+ this.emit('permission_request', payload)
1625
+ })
1626
+ }
1627
+
1628
+ respondToExplicitConsent(requestId, decision, { clientId, editedInput, scope } = {}) {
1629
+ const pending = this._pendingPermissions.get(requestId)
1630
+ if (pending?.explicitConsent !== true || pending.clientId !== clientId) return false
1631
+ if (!['allow', 'deny'].includes(decision) || editedInput !== undefined || scope !== undefined) return false
1632
+ pending.finish(decision === 'allow', 'user')
1633
+ return true
1634
+ }
1635
+
1043
1636
  /**
1044
1637
  * #4457: trust gate for spawning an MCP server child. Reuses the
1045
1638
  * existing _pendingPermissions machinery so the dashboard / mobile
@@ -1057,12 +1650,24 @@ export class PermissionManager extends EventEmitter {
1057
1650
  * credential-stripped (via redactMcpUrl) before it reaches the description
1058
1651
  * or the broadcast input; header VALUES are never passed in.
1059
1652
  *
1060
- * @param {{ name: string, command?: string, args?: string[], envKeys?: string[], url?: string, headerKeys?: string[] }} server
1653
+ * #7939: `server.source` (an `MCP_SERVER_SOURCE` value — see
1654
+ * byok-mcp-config.js) names WHICH config scope this spawn config came from.
1655
+ * It is validated against the closed `MCP_SERVER_SOURCE_VALUES` roster and
1656
+ * only forwarded into the prompt payload when it matches — an absent or
1657
+ * unrecognized value is silently DROPPED (never passed through as-is),
1658
+ * consistent with never sending free-form text where a closed enum belongs.
1659
+ * A caller that predates #7939 (or a cfg built without going through
1660
+ * discovery/add) simply omits it, and the prompt shows no source, which is
1661
+ * the same "no source" the client already has to handle for every other
1662
+ * field it treats as optional.
1663
+ *
1664
+ * @param {{ name: string, command?: string, args?: string[], envKeys?: string[], url?: string, headerKeys?: string[], source?: string }} server
1061
1665
  * @returns {Promise<boolean>}
1062
1666
  */
1063
1667
  async requestMcpTrust(server) {
1064
1668
  const isRemote = typeof server.url === 'string' && server.url.length > 0
1065
1669
  const safeUrl = isRemote ? redactMcpUrl(server.url) : ''
1670
+ const source = MCP_SERVER_SOURCE_VALUES.includes(server.source) ? server.source : undefined
1066
1671
  // #6834 — for a REMOTE server, best-effort-resolve the host BEFORE we build
1067
1672
  // the prompt so the consent string can show when a "remote" URL actually
1068
1673
  // points at a loopback / private / internal address (owner decision:
@@ -1096,12 +1701,18 @@ export class PermissionManager extends EventEmitter {
1096
1701
  display: resolved.display,
1097
1702
  }
1098
1703
  : null,
1704
+ // #7939: OMITTED (not null) when absent/unrecognized, matching
1705
+ // every other optional field on this payload — a client that
1706
+ // doesn't know the field yet just doesn't see the key.
1707
+ ...(source ? { source } : {}),
1099
1708
  }
1100
1709
  : {
1101
1710
  name: server.name,
1102
1711
  command: server.command,
1103
1712
  args: Array.isArray(server.args) ? [...server.args] : [],
1104
1713
  envKeys: Array.isArray(server.envKeys) ? [...server.envKeys] : [],
1714
+ // #7939: see the remote branch's comment above.
1715
+ ...(source ? { source } : {}),
1105
1716
  },
1106
1717
  }
1107
1718
  const description = isRemote
@@ -1133,13 +1744,24 @@ export class PermissionManager extends EventEmitter {
1133
1744
  // #6038: redact before broadcast (description embeds server.command/argv0;
1134
1745
  // input carries args/envKeys). Raw values for execution live on the
1135
1746
  // _pendingPermissions entry above.
1747
+ // #7968: mcp_spawn carries no PROTECTED_PATH_INPUT_FIELDS (its input is
1748
+ // `{ mcpServer: {...} }`, not a bare file_path/path/notebook_path), so
1749
+ // isFlooredTarget is always false here — computed rather than hardcoded
1750
+ // so this stays correct if that ever changes.
1751
+ const shownDescription = describeComposedText(description)
1136
1752
  const permPayload = {
1137
1753
  requestId,
1138
1754
  tool: 'mcp_spawn',
1139
- description: redactValue(String(description)).slice(0, 200),
1755
+ description: shownDescription,
1140
1756
  input: sanitizeToolInput(input),
1141
1757
  remainingMs: this._timeoutMs,
1142
1758
  createdAt: Date.now(),
1759
+ floored: isFlooredTarget('mcp_spawn', input, this._cwd),
1760
+ explicitConsent: false,
1761
+ nonDelegable: true,
1762
+ // #8348: for the permission transcript (see handlePermission). The
1763
+ // shown description is already redacted and clipped.
1764
+ recordDescription: shownDescription,
1143
1765
  }
1144
1766
  this._lastPermissionData.set(requestId, permPayload)
1145
1767
  this.emit('permission_request', permPayload)
@@ -1273,6 +1895,13 @@ export function wirePermissionManager(session, permissions, { onRequest, onResol
1273
1895
  // Backward-compatible accessors used by ws-permissions.js + settings-handlers.js.
1274
1896
  session._pendingPermissions = permissions._pendingPermissions
1275
1897
  session._lastPermissionData = permissions._lastPermissionData
1898
+ // #7457 -- delegate the still-blocked AskUserQuestion set, read after every
1899
+ // history replay by `ws-history.resendPendingQuestions`. Installed HERE, once,
1900
+ // rather than as three identical overrides on SdkSession / ByokSession /
1901
+ // CodexAppServerSession: those are exactly the hand-copied parallel wirings
1902
+ // audit P2-9 folded into this function, and the third copy is always the one
1903
+ // that gets forgotten. Shadows BaseSession's empty default as an own property.
1904
+ session.getPendingQuestions = () => permissions.getPendingQuestions()
1276
1905
  // #6830 (PR #6842 review) — public delegate so the WsServer can wire its
1277
1906
  // PermissionAuditLog straight into this manager's persisted-rule audit path
1278
1907
  // (ws-server.js _attachPermissionAuditSink) without reaching into privates.