@chroxy/server 0.10.0 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  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-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -4,7 +4,18 @@
4
4
  * Handles: set_model, set_permission_mode, permission_response,
5
5
  * query_permission_audit, list_providers, set_permission_rules
6
6
  */
7
- import { ALLOWED_MODEL_IDS, toShortModelId, isClaudeProvider } from '../models.js'
7
+ import { isSafeRegexSource } from '../utils/safe-regex.js'
8
+ import { getErrorMessage } from '../utils/error-message.js'
9
+ import { authorizedFor } from '../connection-authority.js'
10
+ import { isWellFormedThinkingLevel, resolveThinkingLevels, LEGACY_DEFAULT_THINKING_LEVEL } from '@chroxy/protocol'
11
+ import { buildThinkingLevelChanged } from '../thinking-level-wire.js'
12
+ import {
13
+ ALLOWED_MODEL_IDS,
14
+ toShortModelId,
15
+ isClaudeProvider,
16
+ getRosterModelRow,
17
+ thinkingLevelLegacyFallbackApplies,
18
+ } from '../models.js'
8
19
  import {
9
20
  ALLOWED_PERMISSION_MODE_IDS,
10
21
  resolveSession,
@@ -15,9 +26,11 @@ import {
15
26
  buildSessionTokenMismatchPayload,
16
27
  isSessionViewer,
17
28
  } from '../handler-utils.js'
18
- import { listProviders, getProvider } from '../providers.js'
29
+ import { listProviders, getProvider, resolveDaemonDefaultProvider } from '../providers.js'
19
30
  import { isProviderModelUnrestricted } from '../config.js'
31
+ import { getProviderPermissionModeSupport } from '../permission-mode-support.js'
20
32
  import { createLogger, loggerForSession, sessionLogger } from '../logger.js'
33
+ import { isBoundClient } from '../environments/authority.js'
21
34
  // Credential + skills handlers were split into sibling modules (audit P2-4);
22
35
  // their maps are composed into settingsHandlers below.
23
36
  import { credentialHandlers } from './credential-handlers.js'
@@ -26,7 +39,7 @@ import {
26
39
  PER_SESSION_SETTINGS,
27
40
  buildPerSessionSettingHandler,
28
41
  } from '../per-session-settings.js'
29
- import { createPermissionResolver, resolveOriginSessionId } from '../permission-resolver.js'
42
+ import { createPermissionResolver, resolveOriginSessionId, buildLegacyResolvedBroadcast } from '../permission-resolver.js'
30
43
  import { sanitizeToolInput, PULL_MAX_INPUT_CHARS } from '../redaction.js'
31
44
  // #6605 — SINGLE source of truth for the rule-eligibility sets. These used to be
32
45
  // a duplicate hard-coded copy here, which silently drifted from
@@ -65,6 +78,19 @@ const PROVIDER_MODELS_UNRESTRICTED = Symbol('provider-models-unrestricted')
65
78
  * - `null` — no method / unknown provider / method threw: use the
66
79
  * global allowlist (conservative legacy behaviour).
67
80
  *
81
+ * A provider may move between the first two states at RUNTIME. `codex`
82
+ * (#7727) and the `anthropicCompatible` / `openaiCompatible` entries with
83
+ * live discovery return an array once their catalog is in hand and a
84
+ * non-array before that, so nothing here may cache the answer or assume a
85
+ * provider is permanently restricted.
86
+ *
87
+ * NOTE for anyone adding a provider: an EMPTY array is not "unrestricted"
88
+ * here. It is truthy, so it takes the allowlist branch below and
89
+ * `[].includes(model)` rejects every id — a total lockout, and one that
90
+ * `session-manager.js`'s copy of this gate does NOT reproduce (it guards on
91
+ * `length > 0` and skips validation instead). A provider with nothing to
92
+ * assert must return a NON-ARRAY, never `[]` (#7727).
93
+ *
68
94
  * @param {string|undefined} providerName - Session's registered provider name
69
95
  * @returns {string[]|typeof PROVIDER_MODELS_UNRESTRICTED|null}
70
96
  */
@@ -290,9 +316,25 @@ function handleSetPermissionMode(ws, client, msg, ctx) {
290
316
  sendSessionError(ws, ctx, 'This provider does not support plan mode')
291
317
  return
292
318
  }
293
- // Auto permission mode is the ultimate privilege escalation in
294
- // the chroxy handler dispatch — it disables all permission
295
- // checks, so every subsequent tool call auto-executes. The
319
+ // #7825 — reject unsupported adapter/mode combinations before the Auto
320
+ // config/confirmation flow. BaseSession repeats this guard for direct
321
+ // callers; this wire gate supplies a precise error instead of a generic
322
+ // post-setter no-op.
323
+ const modeSupport = getProviderPermissionModeSupport(entry.session.constructor, msg.mode)
324
+ if (!modeSupport.supported) {
325
+ sendError(
326
+ ws,
327
+ msg?.requestId,
328
+ 'CAPABILITY_NOT_SUPPORTED',
329
+ `The active provider '${entry.provider || 'unknown'}' cannot use '${msg.mode}' because its adapter cannot guarantee protected-path prompts reach Chroxy's permission floor.`,
330
+ undefined,
331
+ ctx,
332
+ )
333
+ return
334
+ }
335
+ // Auto permission mode is a broad privilege escalation in
336
+ // the chroxy handler dispatch — ordinary tool calls auto-execute while
337
+ // the protected-path floor still forces a real decision. The
296
338
  // 2026-04-11 audit (Adversary A5) flagged this as a step in
297
339
  // the kill chain: an authenticated attacker sends
298
340
  // `{mode:'auto', confirmed:true}` and trivially flips the
@@ -317,10 +359,10 @@ function handleSetPermissionMode(ws, client, msg, ctx) {
317
359
  // and should only be able to use existing permissions, not
318
360
  // escalate. Only the primary API token can flip to auto.
319
361
  if (msg.mode === 'auto') {
320
- if (client.boundSessionId) {
362
+ if (isBoundClient(client)) {
321
363
  // #4828: session-scoped to the bound session — that's the
322
364
  // session the rejection belongs to.
323
- loggerForSession('ws', client.boundSessionId).warn(`Client ${client.id} (bound to ${client.boundSessionId}) attempted to flip to auto permission mode — rejected`)
365
+ sessionLogger(client.boundSessionId, 'ws').warn(`Client ${client.id} (bound to ${client.boundSessionId}) attempted to flip to auto permission mode — rejected`)
324
366
  sendError(ws, msg?.requestId, 'AUTO_MODE_FORBIDDEN_BOUND_CLIENT',
325
367
  'Pairing-issued session tokens cannot enable auto permission mode. Use the primary API token from a device with physical access to this machine.',
326
368
  undefined, ctx)
@@ -346,9 +388,12 @@ function handleSetPermissionMode(ws, client, msg, ctx) {
346
388
  // keep the plain warning. The warning string is rendered verbatim by
347
389
  // the mobile app's confirm Alert (SettingsBar.tsx).
348
390
  const interruptsTurn = !!entry.session.constructor.capabilities?.interruptsTurnOnAutoSwitch
391
+ const enforcementCopy = modeSupport.enforcement === 'chroxy'
392
+ ? 'Protected paths and secret reads still require a Chroxy prompt.'
393
+ : 'Protected-path and secret-read enforcement is not reported by this provider.'
349
394
  const warning = interruptsTurn && entry.session._isBusy
350
- ? 'This session is mid-response. Switching to Auto will INTERRUPT the running turn and restart the session — the in-flight response will be dropped. Tools will then run without asking for permission.'
351
- : 'Auto mode bypasses all permission checks. Claude will execute tools without asking.'
395
+ ? `This session is mid-response. Switching to Auto will INTERRUPT the running turn and restart the session — the in-flight response will be dropped. Ordinary tools will then run without asking; ${enforcementCopy}`
396
+ : `Auto mode runs ordinary tools without asking. ${enforcementCopy}`
352
397
  ctx.transport.send(ws, {
353
398
  type: 'confirm_permission_mode',
354
399
  mode: 'auto',
@@ -405,6 +450,7 @@ function handleSetPermissionMode(ws, client, msg, ctx) {
405
450
  function handlePermissionResponse(ws, client, msg, ctx) {
406
451
  const { requestId, decision } = msg
407
452
  if (!requestId || !decision) return
453
+ if (ctx.services?.devPreview?.respondToConsent(client, msg)) return
408
454
 
409
455
  // #5373: the binding check + SDK-vs-legacy dispatch + audit are delegated to
410
456
  // the shared permission-resolver (also used by the HTTP handler in
@@ -438,9 +484,20 @@ function handlePermissionResponse(ws, client, msg, ctx) {
438
484
  // subscribed client can still respond. WS-ONLY by design: a primary HTTP caller
439
485
  // has full session authority (§3), so the HTTP path has no analog and must not
440
486
  // inherit this restriction.
441
- if (!client.boundSessionId && originSessionId) {
487
+ if (!isBoundClient(client) && originSessionId) {
442
488
  if (!isSessionViewer(client, originSessionId)) {
443
489
  sessionLogger(originSessionId).warn(`[permission-response-reject] unbound client ${client.id} attempted to respond to ${requestId} (originSessionId=${originSessionId}, activeSessionId=${client.activeSessionId ?? 'none'}, subscribed=false) — dropped`)
490
+ // #7858: answer with the SAME correlated negative a never-registered id gets
491
+ // (the caller's OWN active session, never the request's), so the caller sees
492
+ // an outcome instead of waiting out a timeout, and cannot tell "exists in a
493
+ // session I don't view" from "does not exist". The decision was NOT routed
494
+ // and the mapping is untouched.
495
+ ctx.transport.send(ws, {
496
+ type: 'permission_expired',
497
+ requestId,
498
+ ...(typeof client.activeSessionId === 'string' && client.activeSessionId.length > 0 ? { sessionId: client.activeSessionId } : {}),
499
+ message: 'This permission request has expired or was already handled',
500
+ })
444
501
  return
445
502
  }
446
503
  }
@@ -463,6 +520,14 @@ function handlePermissionResponse(ws, client, msg, ctx) {
463
520
  // mergeEditedInput) — a client can narrow the content but not redirect the
464
521
  // path. Only present when the client reviewed + edited the proposed write.
465
522
  editedInput: msg.editedInput,
523
+ // #6773: the operator's free-text deny reason. Used only on a `deny` — the
524
+ // server bounds + redacts it (permission-manager.js buildDenyMessage) and
525
+ // feeds it back to the agent as the denial message instead of 'User denied'.
526
+ reason: msg.reason,
527
+ // #8517: the "Allow for Session" label. The resolver keeps it only beside an
528
+ // `allow`; it grants nothing (the session rule is the client's separate
529
+ // set_permission_rules) and only names the allow in the broadcast and journal.
530
+ scope: msg.scope,
466
531
  })
467
532
 
468
533
  if (result.kind === 'binding_mismatch') {
@@ -480,7 +545,7 @@ function handlePermissionResponse(ws, client, msg, ctx) {
480
545
  )
481
546
  // #4828: session-scoped to the bound session — the reject belongs to the
482
547
  // OWNER of `boundSessionId`, not the mismatched mapped session.
483
- loggerForSession('ws', result.boundSessionId).warn(`[session-binding-reject] permission_response rejected ${JSON.stringify({
548
+ sessionLogger(result.boundSessionId, 'ws').warn(`[session-binding-reject] permission_response rejected ${JSON.stringify({
484
549
  requestId,
485
550
  decision,
486
551
  clientId: client.id,
@@ -507,25 +572,92 @@ function handlePermissionResponse(ws, client, msg, ctx) {
507
572
  return
508
573
  }
509
574
 
575
+ if (result.kind === 'edit_refused') {
576
+ // #8446: the resolver denied the request (fail closed: nothing was written) and
577
+ // the answering client is told why. The other clients learn of the denial from
578
+ // the unified pipeline's permission_resolved.
579
+ sendError(ws, requestId, 'PERMISSION_EDIT_REFUSED', result.message, undefined, ctx)
580
+ return
581
+ }
582
+
510
583
  if (result.kind === 'expired' || result.kind === 'not_found') {
511
- ctx.transport.send(ws, { type: 'permission_expired', requestId, sessionId: originSessionId, message: 'This permission request has expired or was already handled' })
584
+ // #7096: OMIT sessionId when it is not a real id. `originSessionId` resolves to
585
+ // `client.activeSessionId`, which defaults to null (ws-server.js), so the
586
+ // expired/not_found branch could stamp null — and the wire field is
587
+ // `z.string().optional()`, where undefined is legal and null is not. This is the
588
+ // SECOND producer of this frame; the normalizer's mapping is the other.
589
+ ctx.transport.send(ws, {
590
+ type: 'permission_expired',
591
+ requestId,
592
+ ...(typeof originSessionId === 'string' && originSessionId.length > 0 ? { sessionId: originSessionId } : {}),
593
+ message: 'This permission request has expired or was already handled',
594
+ })
512
595
  return
513
596
  }
514
597
 
515
598
  // result.kind === 'resolved' — the resolver dispatched (sdk|legacy) + audited.
516
599
  // #3048: SDK-session broadcasts go through the unified pipeline
517
600
  // (PermissionManager → SdkSession → SessionManager → EventNormalizer →
518
- // broadcast). Legacy non-SDK sessions (no PermissionManager) keep an inline
519
- // broadcast for the unmapped case only — mirrors the prior `!originSessionId`.
520
- if (!result.sessionId) {
521
- ctx.transport.broadcast(
522
- { type: 'permission_resolved', requestId, decision },
523
- (c) => c.id !== client.id
524
- )
601
+ // broadcast). Only a legacy (non-SDK) dispatch keeps an inline broadcast, and
602
+ // whether the frame may NAME a session is decided by `result.mapped` (the
603
+ // request's own mapping), never by `result.sessionId`: for an UNMAPPED prompt
604
+ // the resolver fills `sessionId` from `client.activeSessionId` (dispatch
605
+ // fallback), so keying on it dropped the frame whenever the answering client had
606
+ // an active session (#8359). Mirrors POST /permission-response (ws-permissions.js).
607
+ // #7858: the legacy announcement is built once in permission-resolver.js and
608
+ // shared with POST /permission-response. Mapped (#7976): a hook-routed prompt
609
+ // (claude-tui / claude-cli / claude-channel) has NO PermissionManager, so
610
+ // nothing else announces its resolution — without this every other client keeps
611
+ // a stale card and agent-control reports `uncertain`. Unmapped (#6590): echoed to
612
+ // the resolver too, which needs it to prune `permissionInputs[requestId]`
613
+ // (#6559); re-applying it is inert. The resolver's own frame is therefore the
614
+ // success confirmation for BOTH, correlated by requestId + decision.
615
+ const effectiveDecision = result.decision ?? decision
616
+ const legacyBroadcast = buildLegacyResolvedBroadcast(result, requestId, effectiveDecision)
617
+ if (legacyBroadcast) ctx.transport.broadcast(legacyBroadcast.frame, legacyBroadcast.filter)
618
+
619
+ // #6771 — an `allowAlways` that resolved on an in-process session just
620
+ // persisted a durable project rule (permission-manager.js). Broadcast the
621
+ // updated rule sets so every client's rules surface (mobile SessionRules,
622
+ // etc.) reflects the new standing grant without a reconnect. The manager
623
+ // updated its in-memory persistent set synchronously during respondToPermission,
624
+ // so getPersistentPermissionRules() already includes it.
625
+ //
626
+ // #8398: gated on `via === 'sdk'`, as POST /permission-response is. A legacy
627
+ // dispatch (an unmapped HTTP-held prompt, or a hook-routed one) has no
628
+ // PermissionManager or rule store behind it, so an `allowAlways` there persists
629
+ // nothing and the rules did not change. For an UNMAPPED prompt `result.sessionId`
630
+ // is also only the answerer's dispatch fallback (#8359), so the frame would be a
631
+ // wasted refresh of an unrelated session's unchanged rules.
632
+ if (effectiveDecision === 'allowAlways' && result.via === 'sdk' && result.sessionId) {
633
+ const rulesEntry = ctx.sessions.sessionManager?.getSession?.(result.sessionId)
634
+ const rulesSession = rulesEntry?.session
635
+ if (rulesSession && typeof rulesSession.getPersistentPermissionRules === 'function') {
636
+ ctx.transport.broadcastToSession(result.sessionId, {
637
+ type: 'permission_rules_updated',
638
+ sessionId: result.sessionId,
639
+ rules: typeof rulesSession.getPermissionRules === 'function' ? rulesSession.getPermissionRules() : [],
640
+ persistentRules: rulesSession.getPersistentPermissionRules(),
641
+ })
642
+ }
525
643
  }
526
644
  }
527
645
 
528
646
  function handleQueryPermissionAudit(ws, client, msg, ctx) {
647
+ // #6837 — same authority principle as the adjacent handleGetPermissionInput: a
648
+ // pairing-bound (share-a-session) token is scoped to ITS OWN session. Without
649
+ // this gate a bound client could read another session's decision history, or
650
+ // omit sessionId entirely and pull the GLOBAL cross-session audit log. Bound
651
+ // clients must name their own boundSessionId explicitly; the global query is
652
+ // host-authority (unbound / primary token) only.
653
+ if (isBoundClient(client) && msg.sessionId !== client.boundSessionId) {
654
+ sessionLogger(client.boundSessionId, 'ws').warn(`Client ${client.id} (bound to ${client.boundSessionId}) attempted to query permission audit for ${msg.sessionId || 'ALL sessions'} — rejected`)
655
+ sendError(ws, msg?.requestId, 'PERMISSION_AUDIT_FORBIDDEN_BOUND_CLIENT',
656
+ "Pairing-issued session tokens can only query their own session's permission audit.",
657
+ undefined, ctx)
658
+ return
659
+ }
660
+
529
661
  if (ctx.permissions.permissionAudit) {
530
662
  const entries = ctx.permissions.permissionAudit.query({
531
663
  sessionId: msg.sessionId,
@@ -540,10 +672,142 @@ function handleQueryPermissionAudit(ws, client, msg, ctx) {
540
672
  }
541
673
 
542
674
  function handleListProviders(ws, client, msg, ctx) {
543
- ctx.transport.send(ws, { type: 'provider_list', providers: listProviders() })
675
+ ctx.transport.send(ws, {
676
+ type: 'provider_list',
677
+ providers: listProviders({ agentConnections: ctx.services?.config?.agentConnections }),
678
+ // #8151 (C3) — this daemon's own resolved default (CLI > env > config file
679
+ // > DEFAULT_PROVIDER), so a client can override its baked-in
680
+ // DEFAULT_PROVIDER fallback with what actually works here —
681
+ // e.g. the Docker image's ENV CHROXY_PROVIDER=claude-sdk.
682
+ defaultProvider: resolveDaemonDefaultProvider(ctx.services?.config),
683
+ })
684
+ }
685
+
686
+ /**
687
+ * #7730 — the AUTHORITATIVE per-model thinking-level gate.
688
+ *
689
+ * This replaces `VALID_THINKING_LEVELS`, a Set of the three Claude levels and
690
+ * one of six frozen copies of a vocabulary that was only ever true of the
691
+ * Claude family. Codex advertises `supportedReasoningEfforts` PER MODEL (the
692
+ * values differ per model and move with releases), so the question "is this a
693
+ * real level?" has no repo-wide answer — only "is this level offered by the
694
+ * model THIS session is running?", and this handler is the layer that can see
695
+ * both the session and its provider.
696
+ *
697
+ * #7784 — THE ROSTER AND THE PICKER NOW READ THE SAME ROW.
698
+ *
699
+ * The row comes from `getRosterModelRow(provider, modelId)`, which is the
700
+ * roster `available_models` carried to this client — `getRegistryForProvider`'s
701
+ * rows, matched on `fullId || id` exactly as the dashboard's picker matches
702
+ * them. It used to come from `ProviderClass.getModelMetadata(id)`, a SECOND
703
+ * source with its own refresh timing, and the two provably disagreed: after a
704
+ * codex `model/list` that answers with zero rows the catalog records the empty
705
+ * answer while nothing is broadcast for it, so the registry keeps serving the
706
+ * previously discovered rows — levels and all — while `getModelMetadata` for
707
+ * those same ids returns null. The picker offered the stale row's efforts and
708
+ * this gate refused every one of them.
709
+ *
710
+ * A row with no `reasoningLevels` at all — every Claude provider today — falls
711
+ * back to `LEGACY_THINKING_LEVELS`, so claude-sdk keeps accepting the Claude
712
+ * triple and mapping it to `maxThinkingTokens`. That fallback is the CLAUDE
713
+ * family's roster and nobody else's, so whether it applies is asked through
714
+ * `thinkingLevelLegacyFallbackApplies` — the same derivation `listProviders()`
715
+ * ships to clients as the `thinkingLevelLegacyFallback` capability, so the
716
+ * picker narrows with this gate instead of against it. On a provider where it
717
+ * does not apply the answer is an EMPTY roster (`source: 'none'`) and the caller
718
+ * refuses every level: handing a cannot-check the Claude three would let
719
+ * `default` (offered by NO codex model, and the picker's first option) ride out
720
+ * on `turn/start.effort` as if a model had advertised it — "could not check"
721
+ * reading as "nothing to check", cause #2 in docs/false-safety-guards.md. The
722
+ * reachability is not hypothetical: `CodexSession.getFallbackModels` seeds the
723
+ * registry from `CODEX_MODEL_METADATA`, whose six rows carry no
724
+ * `reasoningLevels` at all, and `_refreshModelCatalog()` is skipped permanently
725
+ * when the binary reports `supportsModelList === false`.
726
+ *
727
+ * `claudeFamily` prefers the registry class and falls back to the live
728
+ * session's own constructor, so a session whose `entry.provider` is missing or
729
+ * unregistered is still classified by the class that is actually running
730
+ * (`isClaudeProvider` treats a passed class's `static claudeFamily` as
731
+ * authoritative).
732
+ *
733
+ * EXPORTED for the parity guard (`tests/thinking-level-roster-parity.test.js`),
734
+ * which drives one roster row through this function and through the picker's
735
+ * own `thinkingLevelOptions` and compares the two sets in both directions.
736
+ *
737
+ * @returns {{levels: string[], defaultLevel: string, source: 'model'|'legacy'|'none', modelId: string|null, claudeFamily: boolean}}
738
+ */
739
+ export function resolveSessionThinkingLevels(entry) {
740
+ const session = entry?.session
741
+ // Same precedence as ws-history's `model_changed` replay and session-manager's
742
+ // session_info render: the operator's explicit override first, then the model
743
+ // the provider actually booted. Keeping the three in step is what stops the
744
+ // gate from validating against a model the session is not running.
745
+ const modelId = (typeof session?.model === 'string' && session.model.length > 0)
746
+ ? session.model
747
+ : ((typeof session?.bootedModel === 'string' && session.bootedModel.length > 0) ? session.bootedModel : null)
748
+
749
+ const providerName = (typeof entry?.provider === 'string' && entry.provider.length > 0) ? entry.provider : null
750
+
751
+ let ProviderClass = null
752
+ if (providerName) {
753
+ // TWO lookups, TWO try blocks, because they fail for different reasons and
754
+ // only one of them says anything about which FAMILY the session belongs to.
755
+ try {
756
+ ProviderClass = getProvider(providerName) || null
757
+ } catch (err) {
758
+ // The provider NAME did not resolve to a class. A cannot-check, and it is
759
+ // LOGGED rather than swallowed: without this line a deployment whose
760
+ // registry lookup is permanently broken is indistinguishable in every log
761
+ // from one that is working (docs/false-safety-guards.md #2).
762
+ log.warn(`Thinking-level provider lookup failed for provider '${providerName}': ${err?.message || err}`)
763
+ ProviderClass = null
764
+ }
765
+ }
766
+
767
+ // Preferred for BOTH questions below: the class the registry resolved, else
768
+ // the class actually running. `isClaudeProvider` treats a passed class as
769
+ // authoritative, so a session whose entry lost its provider string is still
770
+ // classified by what it is.
771
+ const resolvedClass = ProviderClass || entry?.session?.constructor || null
772
+
773
+ let row = null
774
+ try {
775
+ row = getRosterModelRow(providerName, modelId)
776
+ } catch (err) {
777
+ // The ROSTER is unavailable — and that is all. `ProviderClass` stays set on
778
+ // purpose: it really resolved, and isClaudeProvider treats a passed class as
779
+ // authoritative, so nulling it here would downgrade a Claude session to its
780
+ // live constructor and then to the name map because of a failure one call
781
+ // LATER. The roster falls back (row null); the FAMILY does not have to.
782
+ // Reachable because building a provider registry runs provider-class code
783
+ // (`getFallbackModels()`), which a throwing implementation turns into a
784
+ // cannot-check here.
785
+ log.warn(`Thinking-level roster lookup failed for provider '${providerName || 'none'}' model '${modelId}': ${err?.message || err}`)
786
+ row = null
787
+ }
788
+
789
+ // ONE question, asked once, through the derivation `listProviders()` also
790
+ // ships: "does the legacy triple stand in for a row that advertised nothing
791
+ // on this provider?" It is the Claude-family test, which is why the returned
792
+ // `claudeFamily` is the same value rather than a second call — two spellings
793
+ // of one fact are free to disagree, and this one is load-bearing on both
794
+ // sides of the wire.
795
+ const legacyFallback = thinkingLevelLegacyFallbackApplies(providerName, resolvedClass)
796
+ return {
797
+ ...resolveThinkingLevels(row, { legacyFallback }),
798
+ modelId,
799
+ claudeFamily: legacyFallback,
800
+ }
544
801
  }
545
802
 
546
- const VALID_THINKING_LEVELS = new Set(['default', 'high', 'max'])
803
+ /**
804
+ * A provider's setter may reject with anything: null, undefined or a bare
805
+ * string. `err.message` on the first two would throw INSIDE the catch block and
806
+ * the client would never get its THINKING_LEVEL_NOT_APPLIED (#7786 review).
807
+ */
808
+ function thrownMessage(err) {
809
+ return getErrorMessage(err, typeof err === 'string' && err.length > 0 ? err : 'unknown error')
810
+ }
547
811
 
548
812
  async function handleSetThinkingLevel(ws, client, msg, ctx) {
549
813
  // #5731 T9: every rejection path echoes the client's requestId with a single
@@ -556,8 +820,21 @@ async function handleSetThinkingLevel(ws, client, msg, ctx) {
556
820
  // dropdown stuck on a level the session never entered. requestId is optional
557
821
  // (older clients omit it); sendError tolerates null.
558
822
  const requestId = msg?.requestId
823
+ // #7786 — an explicit `level: null` is the wire spelling of "clear the
824
+ // override" (back to the provider/model default). Exactly null: an absent key,
825
+ // '' and whitespace stay malformed and are refused by the form check below, so
826
+ // a client that merely forgot the field cannot un-pin a level by accident.
827
+ const clearing = msg.level === null
559
828
  const level = typeof msg.level === 'string' ? msg.level.trim() : ''
560
- if (!VALID_THINKING_LEVELS.has(level)) {
829
+ // #7730 — two questions, asked separately and in this order.
830
+ //
831
+ // FORM first, because it needs no session: the level is about to become a
832
+ // JSON-RPC param on a subprocess, so charset and length are checked with the
833
+ // same predicate the wire schema uses (1-32 chars of [A-Za-z0-9_-] — this is
834
+ // what refuses `../../etc` and a 200-char string). This says nothing about
835
+ // which levels exist; a syntactic guard that also carried the roster is what
836
+ // the six-site problem was made of.
837
+ if (!clearing && !isWellFormedThinkingLevel(level)) {
561
838
  sendError(ws, requestId, 'THINKING_LEVEL_NOT_APPLIED', `Invalid thinking level: ${level}`, undefined, ctx)
562
839
  return
563
840
  }
@@ -574,11 +851,74 @@ async function handleSetThinkingLevel(ws, client, msg, ctx) {
574
851
  return
575
852
  }
576
853
 
854
+ // A CLEAR names no level, so there is nothing to check against a roster — and
855
+ // it must work when the roster is empty (a pre-catalog codex session refuses
856
+ // every SET, yet an override recorded earlier still has to be undoable).
857
+ // Everything after this point is about validating a level being SET.
858
+ if (clearing) {
859
+ const previousLevel = entry.session.thinkingLevel || LEGACY_DEFAULT_THINKING_LEVEL
860
+ try {
861
+ await entry.session.setThinkingLevel(null)
862
+ const described = typeof entry.session.describeThinkingLevel === 'function' ? entry.session.describeThinkingLevel() : null
863
+ ;sessionLogger(sessionId).info(`Thinking level cleared by ${client.id} on session ${sessionId}: ${previousLevel} → provider default${described ? ` (${described})` : ''}`)
864
+ ctx.transport.broadcastToSession(sessionId, buildThinkingLevelChanged(entry.session) ?? { type: 'thinking_level_changed', level: LEGACY_DEFAULT_THINKING_LEVEL })
865
+ } catch (err) {
866
+ sendError(ws, requestId, 'THINKING_LEVEL_NOT_APPLIED', `Failed to clear thinking level: ${thrownMessage(err)}`, undefined, ctx)
867
+ }
868
+ return
869
+ }
870
+
871
+ // MEMBERSHIP second, and only here — this is the first point that knows both
872
+ // the session and the model it is running, which is the only scope in which
873
+ // the question has an answer (see resolveSessionThinkingLevels above).
874
+ const offered = resolveSessionThinkingLevels(entry)
875
+ // NO ROSTER AT ALL is its own rejection, before membership, and it carries a
876
+ // different message: "this model has advertised nothing" is not "you picked
877
+ // the wrong level", and an empty `Supported levels:` list reads as a bug.
878
+ //
879
+ // `source: 'none'` is reached only when the row advertised nothing AND this
880
+ // provider has no legacy fallback (#7784) — the pre-catalog codex state. The
881
+ // Claude path never reaches it (the fallback applies, so source is 'legacy'
882
+ // with the triple), and a codex row that DID advertise levels has source
883
+ // 'model'. Since #7784 the picker resolves from the SAME fact, so it offers
884
+ // nothing here rather than offering three levels this branch refuses; the
885
+ // branch stays because a client can send any level it likes, and an older
886
+ // client still offers the triple.
887
+ if (offered.levels.length === 0) {
888
+ ;sessionLogger(sessionId).warn(`Rejected thinking level '${level}' on ${entry.provider || 'unknown-provider'} session ${sessionId} from ${client.id}: model ${offered.modelId || 'unknown'} has advertised no reasoning levels, and the legacy roster is Claude-only (source=${offered.source})`)
889
+ sendError(
890
+ ws,
891
+ requestId,
892
+ 'THINKING_LEVEL_NOT_APPLIED',
893
+ `Model '${offered.modelId || 'unknown'}' has not advertised its reasoning levels yet, so no level can be applied on ${entry.provider || 'this provider'}.`,
894
+ undefined,
895
+ ctx,
896
+ )
897
+ return
898
+ }
899
+ if (!offered.levels.includes(level)) {
900
+ ;sessionLogger(sessionId).warn(`Rejected thinking level '${level}' on ${entry.provider || 'unknown-provider'} session ${sessionId} from ${client.id}: model ${offered.modelId || 'unknown'} offers ${offered.levels.join(', ')} (${offered.source})`)
901
+ sendError(
902
+ ws,
903
+ requestId,
904
+ 'THINKING_LEVEL_NOT_APPLIED',
905
+ `Thinking level '${level}' is not offered by model '${offered.modelId || 'unknown'}'. Supported levels: ${offered.levels.join(', ')}`,
906
+ undefined,
907
+ ctx,
908
+ )
909
+ return
910
+ }
911
+
912
+ const previousLevel = entry.session.thinkingLevel || LEGACY_DEFAULT_THINKING_LEVEL
577
913
  try {
578
914
  await entry.session.setThinkingLevel(level)
579
- ctx.transport.broadcastToSession(sessionId, { type: 'thinking_level_changed', level })
915
+ // #8700: the line an operator checks before a send. A provider that can say
916
+ // what it will run (SdkSession) appends its model/requested/effective summary.
917
+ const described = typeof entry.session.describeThinkingLevel === 'function' ? entry.session.describeThinkingLevel() : null
918
+ ;sessionLogger(sessionId).info(`Thinking level change from ${client.id} on session ${sessionId}: ${previousLevel} → ${level}${described ? ` (${described})` : ''}`)
919
+ ctx.transport.broadcastToSession(sessionId, buildThinkingLevelChanged(entry.session) ?? { type: 'thinking_level_changed', level })
580
920
  } catch (err) {
581
- sendError(ws, requestId, 'THINKING_LEVEL_NOT_APPLIED', `Failed to set thinking level: ${err.message}`, undefined, ctx)
921
+ sendError(ws, requestId, 'THINKING_LEVEL_NOT_APPLIED', `Failed to set thinking level: ${thrownMessage(err)}`, undefined, ctx)
582
922
  }
583
923
  }
584
924
 
@@ -591,7 +931,7 @@ async function handleSetThinkingLevel(ws, client, msg, ctx) {
591
931
  * window from silently losing the change.
592
932
  *
593
933
  * Empty string and `null` both clear the override — at that point
594
- * `shouldSkipEvaluator` falls through to the server-wide
934
+ * `shouldSkipEvaluatorAsync` falls through to the server-wide
595
935
  * `config.promptEvaluatorSkipPattern` (#3187) and the default skip rules.
596
936
  *
597
937
  * Validation: BaseSession.setPromptEvaluatorSkipPattern returns false for
@@ -626,6 +966,10 @@ function handleSetPromptEvaluatorSkipPattern(ws, client, msg, ctx) {
626
966
  sendSessionError(ws, ctx, `Invalid pattern: ${err.message || 'malformed regex'}`)
627
967
  return
628
968
  }
969
+ if (!isSafeRegexSource(msg.value)) {
970
+ sendSessionError(ws, ctx, 'Pattern not accepted: over 200 characters, uses a backreference, or repeats a group that begins with an unbounded repeat (such as `(a+)+`)')
971
+ return
972
+ }
629
973
  }
630
974
 
631
975
  const changed = entry.session.setPromptEvaluatorSkipPattern(msg.value)
@@ -662,8 +1006,8 @@ function handleSetPermissionRules(ws, client, msg, ctx) {
662
1006
  // (share-a-session) client set them is exactly that escalation. The gate is
663
1007
  // host-authority = an UNBOUND client (no boundSessionId — the primary token,
664
1008
  // or an unbound linking-mode pairing token), mirroring rejectCredentialWriteIfBound.
665
- if (client.boundSessionId) {
666
- loggerForSession('ws', client.boundSessionId).warn(`Client ${client.id} (bound to ${client.boundSessionId}) attempted to set permission rules — rejected`)
1009
+ if (isBoundClient(client)) {
1010
+ sessionLogger(client.boundSessionId, 'ws').warn(`Client ${client.id} (bound to ${client.boundSessionId}) attempted to set permission rules — rejected`)
667
1011
  sendError(ws, msg?.requestId, 'PERMISSION_RULES_FORBIDDEN_BOUND_CLIENT',
668
1012
  'Pairing-issued session tokens cannot modify permission rules. Use the primary API token from a device with physical access to this machine.',
669
1013
  undefined, ctx)
@@ -702,17 +1046,102 @@ function handleSetPermissionRules(ws, client, msg, ctx) {
702
1046
  sendSessionError(ws, ctx, `rules[${i}]: tool '${rule.tool}' is not eligible for permission rules`)
703
1047
  return
704
1048
  }
1049
+ // #6803 — optional path/glob scope: a non-empty string when present.
1050
+ if (rule.path !== undefined && (typeof rule.path !== 'string' || !rule.path.trim())) {
1051
+ sendSessionError(ws, ctx, `rules[${i}]: path scope must be a non-empty string`)
1052
+ return
1053
+ }
1054
+ }
1055
+
1056
+ // #6771 — optional durable (project-scoped) rule set. When present, it FULLY
1057
+ // REPLACES the persisted rules for this session's project cwd — the client
1058
+ // "manage / remove persistent rule" path (send the reduced list to drop one).
1059
+ // Validated with the same eligibility floor as session rules.
1060
+ const projectRules = msg.projectRules
1061
+ if (projectRules !== undefined) {
1062
+ if (!Array.isArray(projectRules)) {
1063
+ sendSessionError(ws, ctx, 'projectRules must be an array')
1064
+ return
1065
+ }
1066
+ for (let i = 0; i < projectRules.length; i++) {
1067
+ const rule = projectRules[i]
1068
+ if (!rule || typeof rule !== 'object') {
1069
+ sendSessionError(ws, ctx, `projectRules[${i}]: not an object`)
1070
+ return
1071
+ }
1072
+ if (typeof rule.tool !== 'string' || !rule.tool.trim()) {
1073
+ sendSessionError(ws, ctx, `projectRules[${i}]: missing tool name`)
1074
+ return
1075
+ }
1076
+ if (rule.decision !== 'allow' && rule.decision !== 'deny') {
1077
+ sendSessionError(ws, ctx, `projectRules[${i}]: decision must be 'allow' or 'deny'`)
1078
+ return
1079
+ }
1080
+ if (rule.decision === 'allow' && NEVER_AUTO_ALLOW.has(rule.tool)) {
1081
+ sendSessionError(ws, ctx, `projectRules[${i}]: tool '${rule.tool}' cannot be auto-allowed`)
1082
+ return
1083
+ }
1084
+ if (rule.decision === 'allow' && !ELIGIBLE_TOOLS.has(rule.tool)) {
1085
+ sendSessionError(ws, ctx, `projectRules[${i}]: tool '${rule.tool}' is not eligible for permission rules`)
1086
+ return
1087
+ }
1088
+ // #6803 — optional path/glob scope: a non-empty string when present.
1089
+ if (rule.path !== undefined && (typeof rule.path !== 'string' || !rule.path.trim())) {
1090
+ sendSessionError(ws, ctx, `projectRules[${i}]: path scope must be a non-empty string`)
1091
+ return
1092
+ }
1093
+ }
705
1094
  }
706
1095
 
707
1096
  const sessionId = msg.sessionId || client.activeSessionId
708
1097
  const entry = resolveSessionOrError(ws, ctx, msg, client)
709
1098
  if (!entry) return
710
1099
 
711
- if (!requireSessionMethod(ws, ctx, entry, 'setPermissionRules', 'This provider does not support permission rules')) {
712
- return
1100
+ // #6829 — the two halves have DIFFERENT capability gates. Session rules need
1101
+ // the session-rule setter (`setPermissionRules` — absent on codex by design,
1102
+ // so it keeps advertising sessionRules:false). Durable project rules need only
1103
+ // the persistent re-seed setter (`setPersistentPermissionRules` — which codex
1104
+ // HAS since #6829). Gating the whole handler on `setPermissionRules` made the
1105
+ // projectRules remove/clear path dead on codex: durable rules could be CREATED
1106
+ // (allowAlways resolves inside the PermissionManager, no handler involved) but
1107
+ // never removed from any client.
1108
+ const supportsSessionRules = typeof entry.session?.setPermissionRules === 'function'
1109
+
1110
+ if (projectRules === undefined) {
1111
+ // Session-rules-only request — unchanged legacy gate: providers without the
1112
+ // session-rule setter (codex, cli, tui, gemini) are rejected.
1113
+ if (!requireSessionMethod(ws, ctx, entry, 'setPermissionRules', 'This provider does not support permission rules')) {
1114
+ return
1115
+ }
1116
+ } else {
1117
+ // projectRules present — the durable half needs the persistent setter (all
1118
+ // in-process-permission providers: sdk / byok / codex). Providers with no
1119
+ // PermissionManager at all stay rejected, as before.
1120
+ if (!requireSessionMethod(ws, ctx, entry, 'setPersistentPermissionRules', 'This provider does not support persistent permission rules')) {
1121
+ return
1122
+ }
1123
+ // A NON-EMPTY session-rule set aimed at a provider without the session-rule
1124
+ // setter must fail loudly, not be silently dropped. The rules:[] echo the
1125
+ // clients send alongside a project-rule removal is a no-op and passes.
1126
+ if (!supportsSessionRules && rules.length > 0) {
1127
+ sendSessionError(ws, ctx, 'This provider does not support session permission rules')
1128
+ return
1129
+ }
713
1130
  }
714
1131
 
715
- entry.session.setPermissionRules(rules)
1132
+ if (supportsSessionRules) {
1133
+ entry.session.setPermissionRules(rules)
1134
+ }
1135
+
1136
+ // #6771 — apply the durable project-rule replacement (if any) to the store,
1137
+ // then re-seed THIS session's in-memory persistent set so it takes effect
1138
+ // immediately. The store is keyed by the session's cwd. (The persistent-setter
1139
+ // gate above already guaranteed the method exists on this path.)
1140
+ const ruleStore = ctx.sessions.sessionManager?.permissionRuleStore
1141
+ if (projectRules !== undefined && ruleStore && typeof ruleStore.setRules === 'function') {
1142
+ const stored = ruleStore.setRules(entry.session.cwd, projectRules)
1143
+ entry.session.setPersistentPermissionRules(stored)
1144
+ }
716
1145
 
717
1146
  // Audit the whitelist change
718
1147
  if (ctx.permissions.permissionAudit) {
@@ -723,11 +1152,156 @@ function handleSetPermissionRules(ws, client, msg, ctx) {
723
1152
  })
724
1153
  }
725
1154
 
726
- // Broadcast updated rules to all session clients
1155
+ // Broadcast updated rules to all session clients. #6771 — include the durable
1156
+ // persistentRules so the rules surfaces show session AND project grants.
727
1157
  const currentRules = entry.session.getPermissionRules ? entry.session.getPermissionRules() : rules
728
- ctx.transport.broadcastToSession(sessionId, { type: 'permission_rules_updated', rules: currentRules, sessionId })
1158
+ const persistentRules = typeof entry.session.getPersistentPermissionRules === 'function'
1159
+ ? entry.session.getPersistentPermissionRules()
1160
+ : []
1161
+ ctx.transport.broadcastToSession(sessionId, { type: 'permission_rules_updated', rules: currentRules, persistentRules, sessionId })
729
1162
  // #4828: session-scoped.
730
- loggerForSession('ws', sessionId).info(`Permission rules updated by ${client.id} on session ${sessionId}: ${rules.length} rule(s)`)
1163
+ loggerForSession('ws', sessionId).info(`Permission rules updated by ${client.id} on session ${sessionId}: ${rules.length} session rule(s)${projectRules !== undefined ? `, ${projectRules.length} project rule(s)` : ''}`)
1164
+ }
1165
+
1166
+ /**
1167
+ * #6824 — enable/disable an already-configured MCP server for the active
1168
+ * session (runtime toggle, not add/remove). Only the BYOK lane runs an
1169
+ * in-daemon MCP fleet that can be parked/unparked, so this rejects other
1170
+ * providers with a capability error the client uses to keep its toggle hidden.
1171
+ *
1172
+ * AUTH: routed through `resolveSession`, which enforces session-token
1173
+ * binding — a pairing-bound client may only act on ITS OWN session; a bound
1174
+ * token naming a different session resolves to no entry and is rejected. This
1175
+ * is the own-session gate, not the host-authority (unbound-only) gate that
1176
+ * `set_permission_rules` uses: enabling a server can never ADD an untrusted
1177
+ * one (the fleet re-runs the trust gate on unpark) and disabling only REDUCES
1178
+ * capability, so neither direction is the privilege escalation that rule-
1179
+ * setting is. Every rejection — validation, session resolution, capability,
1180
+ * unknown server — echoes `requestId` (when supplied) with a stable code
1181
+ * (MCP_SERVER_NOT_APPLIED / MCP_SERVER_TOGGLE_UNSUPPORTED /
1182
+ * MCP_SERVER_NOT_FOUND), the same echo discipline as the set_model /
1183
+ * set_permission_mode / set_thinking_level NOT_APPLIED family.
1184
+ *
1185
+ * On success the session re-emits `mcp_servers` (broadcast to every subscriber
1186
+ * → multi-device consistency), so this handler does not send its own ack — the
1187
+ * updated list IS the confirmation.
1188
+ */
1189
+ async function handleSetMcpServerEnabled(ws, client, msg, ctx) {
1190
+ const requestId = msg?.requestId
1191
+ const server = typeof msg?.server === 'string' ? msg.server.trim() : ''
1192
+ if (!server) {
1193
+ sendError(ws, requestId, 'MCP_SERVER_NOT_APPLIED', 'set_mcp_server_enabled requires a non-empty `server` name', undefined, ctx)
1194
+ return
1195
+ }
1196
+ if (typeof msg?.enabled !== 'boolean') {
1197
+ sendError(ws, requestId, 'MCP_SERVER_NOT_APPLIED', 'set_mcp_server_enabled requires a boolean `enabled`', undefined, ctx)
1198
+ return
1199
+ }
1200
+
1201
+ const sessionId = msg?.sessionId || client?.activeSessionId
1202
+ // Session resolution failures (no active session, or a bound token naming a
1203
+ // DIFFERENT session — resolveSession enforces the binding) echo requestId +
1204
+ // the stable NOT_APPLIED code, mirroring handleSetThinkingLevel, rather than
1205
+ // resolveSessionOrError's code-less session_error, so the doc-block contract
1206
+ // ("every rejection echoes requestId with a stable code") holds on ALL paths.
1207
+ const entry = resolveSession(ctx, msg, client)
1208
+ if (!entry) {
1209
+ sendError(ws, requestId, 'MCP_SERVER_NOT_APPLIED', 'No active session', undefined, ctx)
1210
+ return
1211
+ }
1212
+
1213
+ // Capability gate — only providers that expose `setMcpServerEnabled` (the
1214
+ // BYOK lane) can toggle. Others ride the claude binary's own MCP config.
1215
+ if (!entry.session || typeof entry.session.setMcpServerEnabled !== 'function') {
1216
+ sendError(ws, requestId, 'MCP_SERVER_TOGGLE_UNSUPPORTED',
1217
+ 'This provider does not support enabling/disabling MCP servers (its MCP config is managed by the underlying CLI).',
1218
+ undefined, ctx)
1219
+ return
1220
+ }
1221
+
1222
+ try {
1223
+ const result = await entry.session.setMcpServerEnabled(server, msg.enabled)
1224
+ if (!result || result.found === false) {
1225
+ sendError(ws, requestId, 'MCP_SERVER_NOT_FOUND', `No configured MCP server named '${server}' for this session.`, undefined, ctx)
1226
+ return
1227
+ }
1228
+ // The session re-emits `mcp_servers` on a real change (forwarded to all
1229
+ // subscribers). Persist immediately so a crash inside the debounce window
1230
+ // can't lose the parked-set change — same discipline as the permission-rule
1231
+ // and per-session-setting handlers.
1232
+ if (result.changed) {
1233
+ try {
1234
+ ctx.sessions.sessionManager?.serializeState?.()
1235
+ } catch (err) {
1236
+ loggerForSession('ws', sessionId).warn(`Failed to persist disabledMcpServers for ${sessionId}: ${err?.message || err}`)
1237
+ }
1238
+ }
1239
+ loggerForSession('ws', sessionId).info(`MCP server '${server}' ${msg.enabled ? 'enabled' : 'disabled'} by ${client.id} on session ${sessionId} (changed=${result.changed})`)
1240
+ } catch (err) {
1241
+ sendError(ws, requestId, 'MCP_SERVER_NOT_APPLIED', `Failed to ${msg.enabled ? 'enable' : 'disable'} MCP server '${server}': ${err?.message || String(err)}`, undefined, ctx)
1242
+ }
1243
+ }
1244
+
1245
+ /**
1246
+ * #6822 — submit a pasted OAuth authorization code for a remote MCP server that
1247
+ * reported `oauth-required`. The daemon redeems the code (holding the PKCE
1248
+ * verifier + state server-side), persists the tokens encrypted at rest, and
1249
+ * reconnects the server authenticated. Only the BYOK lane runs an in-daemon MCP
1250
+ * fleet, so this rejects other providers with a capability error.
1251
+ *
1252
+ * AUTH: identical own-session gate as `set_mcp_server_enabled` (routed through
1253
+ * `resolveSession`, which enforces session-token binding). Redeeming a code can
1254
+ * only authorize the server the user is already trying to connect — it never
1255
+ * escalates. Every rejection echoes `requestId` (when supplied) with a stable
1256
+ * code (MCP_AUTH_NOT_APPLIED / MCP_AUTH_UNSUPPORTED / MCP_AUTH_NOT_FOUND /
1257
+ * MCP_AUTH_FAILED). On success the session re-emits `mcp_servers` (the new
1258
+ * status IS the confirmation) — no separate ack. The `code` and any token are
1259
+ * NEVER logged.
1260
+ */
1261
+ async function handleSubmitMcpAuthCode(ws, client, msg, ctx) {
1262
+ const requestId = msg?.requestId
1263
+ const server = typeof msg?.server === 'string' ? msg.server.trim() : ''
1264
+ const code = typeof msg?.code === 'string' ? msg.code.trim() : ''
1265
+ if (!server) {
1266
+ sendError(ws, requestId, 'MCP_AUTH_NOT_APPLIED', 'submit_mcp_auth_code requires a non-empty `server` name', undefined, ctx)
1267
+ return
1268
+ }
1269
+ if (!code) {
1270
+ sendError(ws, requestId, 'MCP_AUTH_NOT_APPLIED', 'submit_mcp_auth_code requires a non-empty `code`', undefined, ctx)
1271
+ return
1272
+ }
1273
+
1274
+ const sessionId = msg?.sessionId || client?.activeSessionId
1275
+ const entry = resolveSession(ctx, msg, client)
1276
+ if (!entry) {
1277
+ sendError(ws, requestId, 'MCP_AUTH_NOT_APPLIED', 'No active session', undefined, ctx)
1278
+ return
1279
+ }
1280
+
1281
+ if (!entry.session || typeof entry.session.submitMcpAuthCode !== 'function') {
1282
+ sendError(ws, requestId, 'MCP_AUTH_UNSUPPORTED',
1283
+ 'This provider does not support MCP OAuth authorization (its MCP config is managed by the underlying CLI).',
1284
+ undefined, ctx)
1285
+ return
1286
+ }
1287
+
1288
+ try {
1289
+ const result = await entry.session.submitMcpAuthCode(server, code)
1290
+ if (!result || result.found === false) {
1291
+ sendError(ws, requestId, 'MCP_AUTH_NOT_FOUND', `No configured MCP server named '${server}' awaiting authorization for this session.`, undefined, ctx)
1292
+ return
1293
+ }
1294
+ if (result.ok === false) {
1295
+ // Value-free reason — redemption failed (wrong/expired code, AS error).
1296
+ sendError(ws, requestId, 'MCP_AUTH_FAILED', result.error || `Authorization for MCP server '${server}' failed.`, undefined, ctx)
1297
+ return
1298
+ }
1299
+ // Success: the session re-emitted `mcp_servers` (status now connected or,
1300
+ // if the server still rejects, oauth-required again). Never log the code.
1301
+ loggerForSession('ws', sessionId).info(`MCP server '${server}' authorization completed by ${client.id} on session ${sessionId} (status=${result.status || 'unknown'})`)
1302
+ } catch (err) {
1303
+ sendError(ws, requestId, 'MCP_AUTH_FAILED', `Authorization for MCP server '${server}' failed: ${err?.message || String(err)}`, undefined, ctx)
1304
+ }
731
1305
  }
732
1306
 
733
1307
  // #4664: assemble the per-session-setting WS handlers from the registry.
@@ -771,7 +1345,7 @@ function handleGetPermissionInput(ws, client, msg, ctx) {
771
1345
 
772
1346
  // Same authority gate as permission_response — a client may only read the
773
1347
  // input for a permission it could itself answer.
774
- if (client.boundSessionId) {
1348
+ if (isBoundClient(client)) {
775
1349
  if (client.boundSessionId !== sessionId) return notFound('NOT_FOUND', 'No pending permission for that request.')
776
1350
  } else if (!isSessionViewer(client, sessionId)) {
777
1351
  return notFound('NOT_FOUND', 'No pending permission for that request.')
@@ -793,6 +1367,210 @@ function handleGetPermissionInput(ws, client, msg, ctx) {
793
1367
  return send({ found: true, tool, input: pending._redactedPull })
794
1368
  }
795
1369
 
1370
+ /**
1371
+ * #6974 — MCP config-MUTATION gate: require the STRICT PRIMARY token class
1372
+ * (`client.isPrimaryToken === true`) before any validation or write.
1373
+ *
1374
+ * Why strict-primary rather than the "any unbound client" host-authority bar the
1375
+ * credential-write (#5155) / permission-rule / file-git (#6541) gates use: those
1376
+ * gates reject only `client.boundSessionId`, which leaves the unbound
1377
+ * linking-mode pairing token — an ordinary paired phone — with full authority. A
1378
+ * configured MCP server is a command this daemon SPAWNS, so an add is arbitrary
1379
+ * host code execution, which is the same escalation class as creating a
1380
+ * `user-shell` session, `terminal_input`, `revoke_token` and
1381
+ * `orchestration_run_start` — every one of which checks strict
1382
+ * `client.isPrimaryToken === true` (docs/security/bearer-token-authority.md,
1383
+ * "The WS primary-token gate"). #6974's first cut rejected only bound tokens
1384
+ * while its own error message told the user to "use the primary API token from a
1385
+ * device with physical access": the message was right and the gate was one tier
1386
+ * too weak (#7001 review).
1387
+ *
1388
+ * REMOVE carries the same gate. It only reduces capability, but it still mutates
1389
+ * a host-owned file, and a non-primary client able to delete servers could
1390
+ * silently strip a session's tooling out from under its owner.
1391
+ *
1392
+ * There is no shared cross-surface helper to import: each surface defines its own
1393
+ * local reject helper so the error CODE names the surface that refused
1394
+ * (`rejectMutationIfBound` in file-handlers.js, `rejectCredentialWriteIfBound` in
1395
+ * credential-handlers.js, `guardAction` in orchestration-handlers.js). This
1396
+ * follows that convention exactly — strict `!== true` comparison, an `op`
1397
+ * parameter for the log line, and a surface-specific code.
1398
+ *
1399
+ * Logging uses `sessionLogger` (not `loggerForSession`) because a non-primary
1400
+ * client is frequently UNBOUND — `loggerForSession` throws on an absent sessionId,
1401
+ * which would turn a rejection into a 500-shaped throw.
1402
+ *
1403
+ * @returns {boolean} true if the caller was rejected (handler must return).
1404
+ */
1405
+ function rejectMcpConfigWriteUnlessPrimary(ws, client, msg, ctx, op) {
1406
+ if (client?.isPrimaryToken === true) return false
1407
+ // A non-primary client attempting a host-level config write is a potential
1408
+ // privilege-escalation signal — log it (with the client id + binding) so it
1409
+ // surfaces in triage, the same discipline as token-handlers.js.
1410
+ sessionLogger(client?.boundSessionId).warn(
1411
+ `Client ${client?.id}${client?.boundSessionId ? ` (bound to ${client.boundSessionId})` : ' (unbound, non-primary)'} attempted ${op} — rejected (MCP config writes require the primary token)`,
1412
+ )
1413
+ sendError(
1414
+ ws,
1415
+ msg?.requestId,
1416
+ 'MCP_CONFIG_FORBIDDEN_NON_PRIMARY_CLIENT',
1417
+ 'Pairing-issued tokens cannot add or remove MCP servers — a configured MCP server is a command this machine will run. Use the primary API token from a device with physical access to this machine.',
1418
+ undefined,
1419
+ ctx,
1420
+ )
1421
+ return true
1422
+ }
1423
+
1424
+ /**
1425
+ * #6974 — add a brand-new MCP server, persisting it to the user's MCP config.
1426
+ *
1427
+ * AUTH: two gates, in this order. (1) strict-primary — anything that is not the
1428
+ * primary token class is refused up front by
1429
+ * `rejectMcpConfigWriteUnlessPrimary`, BEFORE any validation, session resolve,
1430
+ * config read or payload logging, so a non-primary client's payload never
1431
+ * reaches the config file. (2) own-session — `resolveSession` still enforces
1432
+ * session-token binding for the primary client's target session.
1433
+ *
1434
+ * Only the BYOK lane runs an in-daemon MCP fleet it can mutate, so other
1435
+ * providers reject with `MCP_CONFIG_UNSUPPORTED` (their MCP config is managed by
1436
+ * the underlying CLI). Every rejection echoes `requestId` with a stable code
1437
+ * (MCP_CONFIG_FORBIDDEN_NON_PRIMARY_CLIENT / MCP_SERVER_ADD_NOT_APPLIED /
1438
+ * MCP_CONFIG_UNSUPPORTED / MCP_SERVER_EXISTS / MCP_SERVER_ADD_TRUST_DENIED), the
1439
+ * same echo discipline as the #6824 toggle family.
1440
+ *
1441
+ * The user's spawn-trust decision is taken BEFORE the config is written (#7001),
1442
+ * so a denied add leaves no entry behind; the denial surfaces as
1443
+ * `MCP_SERVER_ADD_TRUST_DENIED` rather than a generic failure.
1444
+ *
1445
+ * On success the session re-emits `mcp_servers` to every subscriber — that
1446
+ * broadcast IS the ack, so this handler sends nothing on the happy path.
1447
+ */
1448
+ async function handleAddMcpServer(ws, client, msg, ctx) {
1449
+ if (rejectMcpConfigWriteUnlessPrimary(ws, client, msg, ctx, 'add_mcp_server')) return
1450
+ const requestId = msg?.requestId
1451
+ const name = typeof msg?.name === 'string' ? msg.name.trim() : ''
1452
+ if (!name) {
1453
+ sendError(ws, requestId, 'MCP_SERVER_ADD_NOT_APPLIED', 'add_mcp_server requires a non-empty `name`', undefined, ctx)
1454
+ return
1455
+ }
1456
+ if (!msg?.config || typeof msg.config !== 'object' || Array.isArray(msg.config)) {
1457
+ sendError(ws, requestId, 'MCP_SERVER_ADD_NOT_APPLIED', 'add_mcp_server requires a `config` object', undefined, ctx)
1458
+ return
1459
+ }
1460
+ const scope = msg?.scope === 'project' ? 'project' : 'user'
1461
+
1462
+ const sessionId = msg?.sessionId || client?.activeSessionId
1463
+ const entry = resolveSession(ctx, msg, client)
1464
+ if (!entry) {
1465
+ sendError(ws, requestId, 'MCP_SERVER_ADD_NOT_APPLIED', 'No active session', undefined, ctx)
1466
+ return
1467
+ }
1468
+ if (!entry.session || typeof entry.session.addMcpServer !== 'function') {
1469
+ sendError(ws, requestId, 'MCP_CONFIG_UNSUPPORTED',
1470
+ 'This provider does not support adding MCP servers (its MCP config is managed by the underlying CLI).',
1471
+ undefined, ctx)
1472
+ return
1473
+ }
1474
+
1475
+ try {
1476
+ const result = await entry.session.addMcpServer(name, msg.config, scope, { isAuthorized: authorizedFor(ctx, client) })
1477
+ if (!result || result.ok !== true) {
1478
+ // #7001: a denied spawn-trust prompt is a distinct outcome from a failure —
1479
+ // nothing was written, and the client should say "you declined" rather than
1480
+ // "the add failed".
1481
+ const code = result?.code === 'EXISTS'
1482
+ ? 'MCP_SERVER_EXISTS'
1483
+ : result?.code === 'TRUST_DENIED'
1484
+ ? 'MCP_SERVER_ADD_TRUST_DENIED'
1485
+ : 'MCP_SERVER_ADD_NOT_APPLIED'
1486
+ sendError(ws, requestId, code, result?.error || `Failed to add MCP server '${name}'.`, undefined, ctx)
1487
+ return
1488
+ }
1489
+ // Log the NAME and scope only — never the command, args, env, url or headers
1490
+ // (they routinely carry tokens and local paths).
1491
+ //
1492
+ // sessionLogger, not loggerForSession: `sessionId` is undefined whenever the
1493
+ // request carried no sessionId and the client has no activeSessionId (the
1494
+ // single-session cliSession adapter still resolves an entry for a null sid),
1495
+ // and loggerForSession THROWS on an absent sessionId — inside this try/catch
1496
+ // that turned a SUCCESSFUL mutation into an MCP_SERVER_ADD_NOT_APPLIED
1497
+ // rejection (#7001 review).
1498
+ sessionLogger(sessionId).info(
1499
+ `MCP server '${name}' added in ${scope} scope by ${client.id} on session ${sessionId} (status=${result.status})`,
1500
+ )
1501
+ // #7002: a group/world-readable MCP config that just received env/headers.
1502
+ // Operator-visible warning only — the message names the file and its mode and
1503
+ // never echoes a secret value, and the add itself succeeded, so this must not
1504
+ // turn into an error frame.
1505
+ if (result.warning) sessionLogger(sessionId).warn(`MCP config permissions: ${result.warning}`)
1506
+ } catch (err) {
1507
+ sendError(ws, requestId, 'MCP_SERVER_ADD_NOT_APPLIED',
1508
+ `Failed to add MCP server '${name}': ${err?.message || String(err)}`, undefined, ctx)
1509
+ }
1510
+ }
1511
+
1512
+ /**
1513
+ * #6974 — permanently remove a configured MCP server from the user's MCP config.
1514
+ *
1515
+ * Same two-gate AUTH as `handleAddMcpServer` (strict-primary first, then
1516
+ * own-session), same capability gate, same requestId echo discipline. A name
1517
+ * absent from the REQUESTED scope yields `MCP_SERVER_NOT_FOUND` and no write —
1518
+ * a remove never silently jumps scope to find something to delete.
1519
+ */
1520
+ async function handleRemoveMcpServer(ws, client, msg, ctx) {
1521
+ if (rejectMcpConfigWriteUnlessPrimary(ws, client, msg, ctx, 'remove_mcp_server')) return
1522
+ const requestId = msg?.requestId
1523
+ const name = typeof msg?.name === 'string' ? msg.name.trim() : ''
1524
+ if (!name) {
1525
+ sendError(ws, requestId, 'MCP_SERVER_REMOVE_NOT_APPLIED', 'remove_mcp_server requires a non-empty `name`', undefined, ctx)
1526
+ return
1527
+ }
1528
+ const scope = msg?.scope === 'project' ? 'project' : 'user'
1529
+
1530
+ const sessionId = msg?.sessionId || client?.activeSessionId
1531
+ const entry = resolveSession(ctx, msg, client)
1532
+ if (!entry) {
1533
+ sendError(ws, requestId, 'MCP_SERVER_REMOVE_NOT_APPLIED', 'No active session', undefined, ctx)
1534
+ return
1535
+ }
1536
+ if (!entry.session || typeof entry.session.removeMcpServer !== 'function') {
1537
+ sendError(ws, requestId, 'MCP_CONFIG_UNSUPPORTED',
1538
+ 'This provider does not support removing MCP servers (its MCP config is managed by the underlying CLI).',
1539
+ undefined, ctx)
1540
+ return
1541
+ }
1542
+
1543
+ try {
1544
+ const result = await entry.session.removeMcpServer(name, scope)
1545
+ if (!result || result.ok !== true) {
1546
+ sendError(ws, requestId, 'MCP_SERVER_REMOVE_NOT_APPLIED',
1547
+ result?.error || `Failed to remove MCP server '${name}'.`, undefined, ctx)
1548
+ return
1549
+ }
1550
+ if (result.found === false) {
1551
+ sendError(ws, requestId, 'MCP_SERVER_NOT_FOUND',
1552
+ `No MCP server named '${name}' in ${scope} scope.`, undefined, ctx)
1553
+ return
1554
+ }
1555
+ // The parked-set may have lost an entry (a disabled server that was removed),
1556
+ // so flush session state immediately rather than waiting on the debounce —
1557
+ // same discipline as the #6824 toggle handler.
1558
+ try {
1559
+ ctx.sessions.sessionManager?.serializeState?.()
1560
+ } catch (err) {
1561
+ sessionLogger(sessionId).warn(`Failed to persist session state after MCP remove on ${sessionId}: ${err?.message || err}`)
1562
+ }
1563
+ // sessionLogger, not loggerForSession — see the note in handleAddMcpServer:
1564
+ // an absent sessionId made a successful remove report as REMOVE_NOT_APPLIED.
1565
+ sessionLogger(sessionId).info(
1566
+ `MCP server '${name}' removed from ${scope} scope by ${client.id} on session ${sessionId}`,
1567
+ )
1568
+ } catch (err) {
1569
+ sendError(ws, requestId, 'MCP_SERVER_REMOVE_NOT_APPLIED',
1570
+ `Failed to remove MCP server '${name}': ${err?.message || String(err)}`, undefined, ctx)
1571
+ }
1572
+ }
1573
+
796
1574
  export const settingsHandlers = {
797
1575
  set_model: handleSetModel,
798
1576
  set_permission_mode: handleSetPermissionMode,
@@ -803,6 +1581,15 @@ export const settingsHandlers = {
803
1581
  list_providers: handleListProviders,
804
1582
  set_thinking_level: handleSetThinkingLevel,
805
1583
  set_permission_rules: handleSetPermissionRules,
1584
+ // #6824: per-server MCP enable/disable (BYOK lane; capability-gated).
1585
+ set_mcp_server_enabled: handleSetMcpServerEnabled,
1586
+ // #6822: submit a pasted OAuth authorization code (BYOK lane; capability-gated).
1587
+ submit_mcp_auth_code: handleSubmitMcpAuthCode,
1588
+ // #6974: MCP config MUTATION — add/remove a server (BYOK lane;
1589
+ // capability-gated AND strict-primary gated: anything that is not the primary
1590
+ // token class is refused, since a configured server is host code execution).
1591
+ add_mcp_server: handleAddMcpServer,
1592
+ remove_mcp_server: handleRemoveMcpServer,
806
1593
  // promptEvaluatorSkipPattern keeps its bespoke handler because the
807
1594
  // payload shape (string-or-null + pre-validation regex compile to
808
1595
  // surface a distinct error code) doesn't fit the boolean/string