@chroxy/server 0.11.0 → 0.11.11

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