@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
@@ -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,18 +26,22 @@ 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'
20
- import { createLogger, loggerForSession, sessionLogger } from '../logger.js'
31
+ import { getProviderPermissionModeSupport } from '../permission-mode-support.js'
32
+ import { createLogger, loggableValue, loggerForSession, sessionLogger } from '../logger.js'
33
+ import { isBoundClient } from '../environments/authority.js'
34
+ import { isPrincipalClient, refusePrincipalHandler, sendPrincipalRefusal } from '../principal-policy.js'
21
35
  // Credential + skills handlers were split into sibling modules (audit P2-4);
22
36
  // their maps are composed into settingsHandlers below.
23
37
  import { credentialHandlers } from './credential-handlers.js'
24
38
  import { skillsHandlers } from './skills-handlers.js'
39
+ import { folderTrustHandlers } from './folder-trust-handlers.js'
25
40
  import {
26
41
  PER_SESSION_SETTINGS,
27
42
  buildPerSessionSettingHandler,
28
43
  } from '../per-session-settings.js'
29
- import { createPermissionResolver, resolveOriginSessionId } from '../permission-resolver.js'
44
+ import { createPermissionResolver, resolveOriginSessionId, buildLegacyResolvedBroadcast } from '../permission-resolver.js'
30
45
  import { sanitizeToolInput, PULL_MAX_INPUT_CHARS } from '../redaction.js'
31
46
  // #6605 — SINGLE source of truth for the rule-eligibility sets. These used to be
32
47
  // a duplicate hard-coded copy here, which silently drifted from
@@ -65,6 +80,19 @@ const PROVIDER_MODELS_UNRESTRICTED = Symbol('provider-models-unrestricted')
65
80
  * - `null` — no method / unknown provider / method threw: use the
66
81
  * global allowlist (conservative legacy behaviour).
67
82
  *
83
+ * A provider may move between the first two states at RUNTIME. `codex`
84
+ * (#7727) and the `anthropicCompatible` / `openaiCompatible` entries with
85
+ * live discovery return an array once their catalog is in hand and a
86
+ * non-array before that, so nothing here may cache the answer or assume a
87
+ * provider is permanently restricted.
88
+ *
89
+ * NOTE for anyone adding a provider: an EMPTY array is not "unrestricted"
90
+ * here. It is truthy, so it takes the allowlist branch below and
91
+ * `[].includes(model)` rejects every id — a total lockout, and one that
92
+ * `session-manager.js`'s copy of this gate does NOT reproduce (it guards on
93
+ * `length > 0` and skips validation instead). A provider with nothing to
94
+ * assert must return a NON-ARRAY, never `[]` (#7727).
95
+ *
68
96
  * @param {string|undefined} providerName - Session's registered provider name
69
97
  * @returns {string[]|typeof PROVIDER_MODELS_UNRESTRICTED|null}
70
98
  */
@@ -164,13 +192,34 @@ function handleSetModel(ws, client, msg, ctx) {
164
192
  return
165
193
  }
166
194
  if (providerAllowed) {
167
- if (!providerAllowed.includes(msg.model)) {
195
+ // #9139: the picker offers a models.json overlay row under its short id
196
+ // (`id`) while the allowlist holds TARGETS (`fullId`). Resolve an
197
+ // off-list id through this provider's roster and accept it only when the
198
+ // row's target is on the list; everything downstream (setModel, the
199
+ // broadcast) then speaks the target, which is also what the endpoint
200
+ // must receive — it would 404 an alias.
201
+ let requested = msg.model
202
+ if (!providerAllowed.includes(requested)) {
203
+ let row = null
204
+ try {
205
+ row = getRosterModelRow(entry.provider, requested)
206
+ } catch (err) {
207
+ // Roster unavailable: cannot resolve an alias, so refuse below —
208
+ // but leave a trace (#9153) so a broken lookup is not silent.
209
+ log.warn(`set_model roster lookup failed for provider '${entry.provider}' model ${loggableValue(msg.model)}: ${loggableValue(String(err?.message || err))}`)
210
+ }
211
+ // The re-check below is what refuses a target that is off the list.
212
+ if (row && typeof row.fullId === 'string') {
213
+ requested = row.fullId
214
+ }
215
+ }
216
+ if (!providerAllowed.includes(requested)) {
168
217
  // #4828: session-scoped — modelSessionId identifies the affected
169
218
  // session. Legacy single-session adapters may surface an empty
170
219
  // sessionId, so fall back to the module-level `log` rather than
171
220
  // throwing inside loggerForSession (matches the input-handlers
172
221
  // pattern from #4823).
173
- ;sessionLogger(modelSessionId).warn(`Rejected model '${msg.model}' on ${entry.provider} session ${modelSessionId} from ${client.id}`)
222
+ ;sessionLogger(modelSessionId).warn(`Rejected model ${loggableValue(msg.model)} on ${entry.provider} session ${modelSessionId} from ${client.id}`)
174
223
  sendError(
175
224
  ws,
176
225
  msg?.requestId,
@@ -182,18 +231,18 @@ function handleSetModel(ws, client, msg, ctx) {
182
231
  return
183
232
  }
184
233
  // #4828: session-scoped (single-session fallback as above).
185
- ;sessionLogger(modelSessionId).info(`Model change from ${client.id} on session ${modelSessionId}: ${msg.model}`)
234
+ ;sessionLogger(modelSessionId).info(`Model change from ${client.id} on session ${modelSessionId}: ${requested}`)
186
235
  // #5696: only broadcast when setModel() reports the change landed.
187
- if (!entry.session.setModel(msg.model)) {
188
- ;sessionLogger(modelSessionId).warn(`set_model rejected (session busy or no-op): requested ${msg.model}`)
189
- sendError(ws, msg?.requestId, 'MODEL_NOT_APPLIED', `Model change to '${msg.model}' was not applied (session busy or already on that model).`, undefined, ctx)
236
+ if (!entry.session.setModel(requested)) {
237
+ ;sessionLogger(modelSessionId).warn(`set_model rejected (session busy or no-op): requested ${requested}`)
238
+ sendError(ws, msg?.requestId, 'MODEL_NOT_APPLIED', `Model change to '${requested}' was not applied (session busy or already on that model).`, undefined, ctx)
190
239
  return
191
240
  }
192
241
  // Non-Claude providers use opaque model IDs (e.g. 'gemini-2.5-pro') —
193
242
  // broadcast them verbatim. toShortModelId() is a Claude-specific
194
243
  // alias collapse (claude-sonnet-4-6 → sonnet) and returns the input
195
244
  // unchanged for non-Claude IDs, so applying it uniformly is safe.
196
- ctx.transport.broadcastToSession(modelSessionId, { type: 'model_changed', model: toShortModelId(msg.model) })
245
+ ctx.transport.broadcastToSession(modelSessionId, { type: 'model_changed', model: toShortModelId(requested) })
197
246
  return
198
247
  }
199
248
  // Fall through to the legacy global allowlist when the provider hasn't
@@ -290,9 +339,25 @@ function handleSetPermissionMode(ws, client, msg, ctx) {
290
339
  sendSessionError(ws, ctx, 'This provider does not support plan mode')
291
340
  return
292
341
  }
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
342
+ // #7825 — reject unsupported adapter/mode combinations before the Auto
343
+ // config/confirmation flow. BaseSession repeats this guard for direct
344
+ // callers; this wire gate supplies a precise error instead of a generic
345
+ // post-setter no-op.
346
+ const modeSupport = getProviderPermissionModeSupport(entry.session.constructor, msg.mode)
347
+ if (!modeSupport.supported) {
348
+ sendError(
349
+ ws,
350
+ msg?.requestId,
351
+ 'CAPABILITY_NOT_SUPPORTED',
352
+ `The active provider '${entry.provider || 'unknown'}' cannot use '${msg.mode}' because its adapter cannot guarantee protected-path prompts reach Chroxy's permission floor.`,
353
+ undefined,
354
+ ctx,
355
+ )
356
+ return
357
+ }
358
+ // Auto permission mode is a broad privilege escalation in
359
+ // the chroxy handler dispatch — ordinary tool calls auto-execute while
360
+ // the protected-path floor still forces a real decision. The
296
361
  // 2026-04-11 audit (Adversary A5) flagged this as a step in
297
362
  // the kill chain: an authenticated attacker sends
298
363
  // `{mode:'auto', confirmed:true}` and trivially flips the
@@ -317,10 +382,10 @@ function handleSetPermissionMode(ws, client, msg, ctx) {
317
382
  // and should only be able to use existing permissions, not
318
383
  // escalate. Only the primary API token can flip to auto.
319
384
  if (msg.mode === 'auto') {
320
- if (client.boundSessionId) {
385
+ if (isBoundClient(client)) {
321
386
  // #4828: session-scoped to the bound session — that's the
322
387
  // 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`)
388
+ sessionLogger(client.boundSessionId, 'ws').warn(`Client ${client.id} (bound to ${client.boundSessionId}) attempted to flip to auto permission mode — rejected`)
324
389
  sendError(ws, msg?.requestId, 'AUTO_MODE_FORBIDDEN_BOUND_CLIENT',
325
390
  'Pairing-issued session tokens cannot enable auto permission mode. Use the primary API token from a device with physical access to this machine.',
326
391
  undefined, ctx)
@@ -346,9 +411,12 @@ function handleSetPermissionMode(ws, client, msg, ctx) {
346
411
  // keep the plain warning. The warning string is rendered verbatim by
347
412
  // the mobile app's confirm Alert (SettingsBar.tsx).
348
413
  const interruptsTurn = !!entry.session.constructor.capabilities?.interruptsTurnOnAutoSwitch
414
+ const enforcementCopy = modeSupport.enforcement === 'chroxy'
415
+ ? 'Protected paths and secret reads still require a Chroxy prompt.'
416
+ : 'Protected-path and secret-read enforcement is not reported by this provider.'
349
417
  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.'
418
+ ? `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}`
419
+ : `Auto mode runs ordinary tools without asking. ${enforcementCopy}`
352
420
  ctx.transport.send(ws, {
353
421
  type: 'confirm_permission_mode',
354
422
  mode: 'auto',
@@ -403,8 +471,12 @@ function handleSetPermissionMode(ws, client, msg, ctx) {
403
471
  }
404
472
 
405
473
  function handlePermissionResponse(ws, client, msg, ctx) {
474
+ // Principal branch, FIRST: a principal may answer only through principalMaySee
475
+ // (deny only, S15) and never reaches the dev-preview consent check or the host path.
476
+ if (isPrincipalClient(client)) return refusePrincipalHandler(ws, client, msg, ctx, 'answer')
406
477
  const { requestId, decision } = msg
407
478
  if (!requestId || !decision) return
479
+ if (ctx.services?.devPreview?.respondToConsent(client, msg)) return
408
480
 
409
481
  // #5373: the binding check + SDK-vs-legacy dispatch + audit are delegated to
410
482
  // the shared permission-resolver (also used by the HTTP handler in
@@ -438,9 +510,20 @@ function handlePermissionResponse(ws, client, msg, ctx) {
438
510
  // subscribed client can still respond. WS-ONLY by design: a primary HTTP caller
439
511
  // has full session authority (§3), so the HTTP path has no analog and must not
440
512
  // inherit this restriction.
441
- if (!client.boundSessionId && originSessionId) {
513
+ if (!isBoundClient(client) && originSessionId) {
442
514
  if (!isSessionViewer(client, originSessionId)) {
443
515
  sessionLogger(originSessionId).warn(`[permission-response-reject] unbound client ${client.id} attempted to respond to ${requestId} (originSessionId=${originSessionId}, activeSessionId=${client.activeSessionId ?? 'none'}, subscribed=false) — dropped`)
516
+ // #7858: answer with the SAME correlated negative a never-registered id gets
517
+ // (the caller's OWN active session, never the request's), so the caller sees
518
+ // an outcome instead of waiting out a timeout, and cannot tell "exists in a
519
+ // session I don't view" from "does not exist". The decision was NOT routed
520
+ // and the mapping is untouched.
521
+ ctx.transport.send(ws, {
522
+ type: 'permission_expired',
523
+ requestId,
524
+ ...(typeof client.activeSessionId === 'string' && client.activeSessionId.length > 0 ? { sessionId: client.activeSessionId } : {}),
525
+ message: 'This permission request has expired or was already handled',
526
+ })
444
527
  return
445
528
  }
446
529
  }
@@ -467,6 +550,10 @@ function handlePermissionResponse(ws, client, msg, ctx) {
467
550
  // server bounds + redacts it (permission-manager.js buildDenyMessage) and
468
551
  // feeds it back to the agent as the denial message instead of 'User denied'.
469
552
  reason: msg.reason,
553
+ // #8517: the "Allow for Session" label. The resolver keeps it only beside an
554
+ // `allow`; it grants nothing (the session rule is the client's separate
555
+ // set_permission_rules) and only names the allow in the broadcast and journal.
556
+ scope: msg.scope,
470
557
  })
471
558
 
472
559
  if (result.kind === 'binding_mismatch') {
@@ -484,7 +571,7 @@ function handlePermissionResponse(ws, client, msg, ctx) {
484
571
  )
485
572
  // #4828: session-scoped to the bound session — the reject belongs to the
486
573
  // OWNER of `boundSessionId`, not the mismatched mapped session.
487
- loggerForSession('ws', result.boundSessionId).warn(`[session-binding-reject] permission_response rejected ${JSON.stringify({
574
+ sessionLogger(result.boundSessionId, 'ws').warn(`[session-binding-reject] permission_response rejected ${JSON.stringify({
488
575
  requestId,
489
576
  decision,
490
577
  clientId: client.id,
@@ -511,6 +598,14 @@ function handlePermissionResponse(ws, client, msg, ctx) {
511
598
  return
512
599
  }
513
600
 
601
+ if (result.kind === 'edit_refused') {
602
+ // #8446: the resolver denied the request (fail closed: nothing was written) and
603
+ // the answering client is told why. The other clients learn of the denial from
604
+ // the unified pipeline's permission_resolved.
605
+ sendError(ws, requestId, 'PERMISSION_EDIT_REFUSED', result.message, undefined, ctx)
606
+ return
607
+ }
608
+
514
609
  if (result.kind === 'expired' || result.kind === 'not_found') {
515
610
  // #7096: OMIT sessionId when it is not a real id. `originSessionId` resolves to
516
611
  // `client.activeSessionId`, which defaults to null (ws-server.js), so the
@@ -529,23 +624,23 @@ function handlePermissionResponse(ws, client, msg, ctx) {
529
624
  // result.kind === 'resolved' — the resolver dispatched (sdk|legacy) + audited.
530
625
  // #3048: SDK-session broadcasts go through the unified pipeline
531
626
  // (PermissionManager → SdkSession → SessionManager → EventNormalizer →
532
- // broadcast). Legacy non-SDK sessions (no PermissionManager) keep an inline
533
- // broadcast for the unmapped case only — mirrors the prior `!originSessionId`.
534
- if (!result.sessionId) {
535
- // #6590: broadcast to ALL clients INCLUDING the resolver (no `c.id !==
536
- // client.id` exclusion). The resolving client needs its own
537
- // `permission_resolved` to prune `permissionInputs[requestId]` (#6559) —
538
- // append-only otherwise, so on this legacy path the entry used to linger
539
- // until disconnect. Echoing to the resolver is SAFE to re-apply: the
540
- // `permissionInputs` prune is a guarded copy-delete, the notification
541
- // read-stamp only touches not-yet-acked rows, and re-marking the
542
- // already-answered prompt is functionally inert (its label reads from
543
- // `resolvedPermissions`, and the pending-count only checks that `answered`
544
- // is truthy — only `answeredAt` is refreshed to the server-confirmed time).
545
- // This also matches the SDK path, which broadcasts session events to every
546
- // subscriber without excluding the origin client.
547
- ctx.transport.broadcast({ type: 'permission_resolved', requestId, decision })
548
- }
627
+ // broadcast). Only a legacy (non-SDK) dispatch keeps an inline broadcast, and
628
+ // whether the frame may NAME a session is decided by `result.mapped` (the
629
+ // request's own mapping), never by `result.sessionId`: for an UNMAPPED prompt
630
+ // the resolver fills `sessionId` from `client.activeSessionId` (dispatch
631
+ // fallback), so keying on it dropped the frame whenever the answering client had
632
+ // an active session (#8359). Mirrors POST /permission-response (ws-permissions.js).
633
+ // #7858: the legacy announcement is built once in permission-resolver.js and
634
+ // shared with POST /permission-response. Mapped (#7976): a hook-routed prompt
635
+ // (claude-tui / claude-cli / claude-channel) has NO PermissionManager, so
636
+ // nothing else announces its resolution — without this every other client keeps
637
+ // a stale card and agent-control reports `uncertain`. Unmapped (#6590): echoed to
638
+ // the resolver too, which needs it to prune `permissionInputs[requestId]`
639
+ // (#6559); re-applying it is inert. The resolver's own frame is therefore the
640
+ // success confirmation for BOTH, correlated by requestId + decision.
641
+ const effectiveDecision = result.decision ?? decision
642
+ const legacyBroadcast = buildLegacyResolvedBroadcast(result, requestId, effectiveDecision)
643
+ if (legacyBroadcast) ctx.transport.broadcast(legacyBroadcast.frame, legacyBroadcast.filter)
549
644
 
550
645
  // #6771 — an `allowAlways` that resolved on an in-process session just
551
646
  // persisted a durable project rule (permission-manager.js). Broadcast the
@@ -553,7 +648,14 @@ function handlePermissionResponse(ws, client, msg, ctx) {
553
648
  // etc.) reflects the new standing grant without a reconnect. The manager
554
649
  // updated its in-memory persistent set synchronously during respondToPermission,
555
650
  // so getPersistentPermissionRules() already includes it.
556
- if (decision === 'allowAlways' && result.sessionId) {
651
+ //
652
+ // #8398: gated on `via === 'sdk'`, as POST /permission-response is. A legacy
653
+ // dispatch (an unmapped HTTP-held prompt, or a hook-routed one) has no
654
+ // PermissionManager or rule store behind it, so an `allowAlways` there persists
655
+ // nothing and the rules did not change. For an UNMAPPED prompt `result.sessionId`
656
+ // is also only the answerer's dispatch fallback (#8359), so the frame would be a
657
+ // wasted refresh of an unrelated session's unchanged rules.
658
+ if (effectiveDecision === 'allowAlways' && result.via === 'sdk' && result.sessionId) {
557
659
  const rulesEntry = ctx.sessions.sessionManager?.getSession?.(result.sessionId)
558
660
  const rulesSession = rulesEntry?.session
559
661
  if (rulesSession && typeof rulesSession.getPersistentPermissionRules === 'function') {
@@ -574,8 +676,8 @@ function handleQueryPermissionAudit(ws, client, msg, ctx) {
574
676
  // omit sessionId entirely and pull the GLOBAL cross-session audit log. Bound
575
677
  // clients must name their own boundSessionId explicitly; the global query is
576
678
  // host-authority (unbound / primary token) only.
577
- if (client.boundSessionId && msg.sessionId !== client.boundSessionId) {
578
- loggerForSession('ws', client.boundSessionId).warn(`Client ${client.id} (bound to ${client.boundSessionId}) attempted to query permission audit for ${msg.sessionId || 'ALL sessions'} — rejected`)
679
+ if (isBoundClient(client) && msg.sessionId !== client.boundSessionId) {
680
+ sessionLogger(client.boundSessionId, 'ws').warn(`Client ${client.id} (bound to ${client.boundSessionId}) attempted to query permission audit for ${msg.sessionId || 'ALL sessions'} — rejected`)
579
681
  sendError(ws, msg?.requestId, 'PERMISSION_AUDIT_FORBIDDEN_BOUND_CLIENT',
580
682
  "Pairing-issued session tokens can only query their own session's permission audit.",
581
683
  undefined, ctx)
@@ -596,10 +698,142 @@ function handleQueryPermissionAudit(ws, client, msg, ctx) {
596
698
  }
597
699
 
598
700
  function handleListProviders(ws, client, msg, ctx) {
599
- ctx.transport.send(ws, { type: 'provider_list', providers: listProviders() })
701
+ ctx.transport.send(ws, {
702
+ type: 'provider_list',
703
+ providers: listProviders({ agentConnections: ctx.services?.config?.agentConnections }),
704
+ // #8151 (C3) — this daemon's own resolved default (CLI > env > config file
705
+ // > DEFAULT_PROVIDER), so a client can override its baked-in
706
+ // DEFAULT_PROVIDER fallback with what actually works here —
707
+ // e.g. the Docker image's ENV CHROXY_PROVIDER=claude-sdk.
708
+ defaultProvider: resolveDaemonDefaultProvider(ctx.services?.config),
709
+ })
600
710
  }
601
711
 
602
- const VALID_THINKING_LEVELS = new Set(['default', 'high', 'max'])
712
+ /**
713
+ * #7730 — the AUTHORITATIVE per-model thinking-level gate.
714
+ *
715
+ * This replaces `VALID_THINKING_LEVELS`, a Set of the three Claude levels and
716
+ * one of six frozen copies of a vocabulary that was only ever true of the
717
+ * Claude family. Codex advertises `supportedReasoningEfforts` PER MODEL (the
718
+ * values differ per model and move with releases), so the question "is this a
719
+ * real level?" has no repo-wide answer — only "is this level offered by the
720
+ * model THIS session is running?", and this handler is the layer that can see
721
+ * both the session and its provider.
722
+ *
723
+ * #7784 — THE ROSTER AND THE PICKER NOW READ THE SAME ROW.
724
+ *
725
+ * The row comes from `getRosterModelRow(provider, modelId)`, which is the
726
+ * roster `available_models` carried to this client — `getRegistryForProvider`'s
727
+ * rows, matched on `fullId || id` exactly as the dashboard's picker matches
728
+ * them. It used to come from `ProviderClass.getModelMetadata(id)`, a SECOND
729
+ * source with its own refresh timing, and the two provably disagreed: after a
730
+ * codex `model/list` that answers with zero rows the catalog records the empty
731
+ * answer while nothing is broadcast for it, so the registry keeps serving the
732
+ * previously discovered rows — levels and all — while `getModelMetadata` for
733
+ * those same ids returns null. The picker offered the stale row's efforts and
734
+ * this gate refused every one of them.
735
+ *
736
+ * A row with no `reasoningLevels` at all — every Claude provider today — falls
737
+ * back to `LEGACY_THINKING_LEVELS`, so claude-sdk keeps accepting the Claude
738
+ * triple and mapping it to `maxThinkingTokens`. That fallback is the CLAUDE
739
+ * family's roster and nobody else's, so whether it applies is asked through
740
+ * `thinkingLevelLegacyFallbackApplies` — the same derivation `listProviders()`
741
+ * ships to clients as the `thinkingLevelLegacyFallback` capability, so the
742
+ * picker narrows with this gate instead of against it. On a provider where it
743
+ * does not apply the answer is an EMPTY roster (`source: 'none'`) and the caller
744
+ * refuses every level: handing a cannot-check the Claude three would let
745
+ * `default` (offered by NO codex model, and the picker's first option) ride out
746
+ * on `turn/start.effort` as if a model had advertised it — "could not check"
747
+ * reading as "nothing to check", cause #2 in docs/false-safety-guards.md. The
748
+ * reachability is not hypothetical: `CodexSession.getFallbackModels` seeds the
749
+ * registry from `CODEX_MODEL_METADATA`, whose six rows carry no
750
+ * `reasoningLevels` at all, and `_refreshModelCatalog()` is skipped permanently
751
+ * when the binary reports `supportsModelList === false`.
752
+ *
753
+ * `claudeFamily` prefers the registry class and falls back to the live
754
+ * session's own constructor, so a session whose `entry.provider` is missing or
755
+ * unregistered is still classified by the class that is actually running
756
+ * (`isClaudeProvider` treats a passed class's `static claudeFamily` as
757
+ * authoritative).
758
+ *
759
+ * EXPORTED for the parity guard (`tests/thinking-level-roster-parity.test.js`),
760
+ * which drives one roster row through this function and through the picker's
761
+ * own `thinkingLevelOptions` and compares the two sets in both directions.
762
+ *
763
+ * @returns {{levels: string[], defaultLevel: string, source: 'model'|'legacy'|'none', modelId: string|null, claudeFamily: boolean}}
764
+ */
765
+ export function resolveSessionThinkingLevels(entry) {
766
+ const session = entry?.session
767
+ // Same precedence as ws-history's `model_changed` replay and session-manager's
768
+ // session_info render: the operator's explicit override first, then the model
769
+ // the provider actually booted. Keeping the three in step is what stops the
770
+ // gate from validating against a model the session is not running.
771
+ const modelId = (typeof session?.model === 'string' && session.model.length > 0)
772
+ ? session.model
773
+ : ((typeof session?.bootedModel === 'string' && session.bootedModel.length > 0) ? session.bootedModel : null)
774
+
775
+ const providerName = (typeof entry?.provider === 'string' && entry.provider.length > 0) ? entry.provider : null
776
+
777
+ let ProviderClass = null
778
+ if (providerName) {
779
+ // TWO lookups, TWO try blocks, because they fail for different reasons and
780
+ // only one of them says anything about which FAMILY the session belongs to.
781
+ try {
782
+ ProviderClass = getProvider(providerName) || null
783
+ } catch (err) {
784
+ // The provider NAME did not resolve to a class. A cannot-check, and it is
785
+ // LOGGED rather than swallowed: without this line a deployment whose
786
+ // registry lookup is permanently broken is indistinguishable in every log
787
+ // from one that is working (docs/false-safety-guards.md #2).
788
+ log.warn(`Thinking-level provider lookup failed for provider '${providerName}': ${err?.message || err}`)
789
+ ProviderClass = null
790
+ }
791
+ }
792
+
793
+ // Preferred for BOTH questions below: the class the registry resolved, else
794
+ // the class actually running. `isClaudeProvider` treats a passed class as
795
+ // authoritative, so a session whose entry lost its provider string is still
796
+ // classified by what it is.
797
+ const resolvedClass = ProviderClass || entry?.session?.constructor || null
798
+
799
+ let row = null
800
+ try {
801
+ row = getRosterModelRow(providerName, modelId)
802
+ } catch (err) {
803
+ // The ROSTER is unavailable — and that is all. `ProviderClass` stays set on
804
+ // purpose: it really resolved, and isClaudeProvider treats a passed class as
805
+ // authoritative, so nulling it here would downgrade a Claude session to its
806
+ // live constructor and then to the name map because of a failure one call
807
+ // LATER. The roster falls back (row null); the FAMILY does not have to.
808
+ // Reachable because building a provider registry runs provider-class code
809
+ // (`getFallbackModels()`), which a throwing implementation turns into a
810
+ // cannot-check here.
811
+ log.warn(`Thinking-level roster lookup failed for provider '${providerName || 'none'}' model '${modelId}': ${err?.message || err}`)
812
+ row = null
813
+ }
814
+
815
+ // ONE question, asked once, through the derivation `listProviders()` also
816
+ // ships: "does the legacy triple stand in for a row that advertised nothing
817
+ // on this provider?" It is the Claude-family test, which is why the returned
818
+ // `claudeFamily` is the same value rather than a second call — two spellings
819
+ // of one fact are free to disagree, and this one is load-bearing on both
820
+ // sides of the wire.
821
+ const legacyFallback = thinkingLevelLegacyFallbackApplies(providerName, resolvedClass)
822
+ return {
823
+ ...resolveThinkingLevels(row, { legacyFallback }),
824
+ modelId,
825
+ claudeFamily: legacyFallback,
826
+ }
827
+ }
828
+
829
+ /**
830
+ * A provider's setter may reject with anything: null, undefined or a bare
831
+ * string. `err.message` on the first two would throw INSIDE the catch block and
832
+ * the client would never get its THINKING_LEVEL_NOT_APPLIED (#7786 review).
833
+ */
834
+ function thrownMessage(err) {
835
+ return getErrorMessage(err, typeof err === 'string' && err.length > 0 ? err : 'unknown error')
836
+ }
603
837
 
604
838
  async function handleSetThinkingLevel(ws, client, msg, ctx) {
605
839
  // #5731 T9: every rejection path echoes the client's requestId with a single
@@ -612,8 +846,21 @@ async function handleSetThinkingLevel(ws, client, msg, ctx) {
612
846
  // dropdown stuck on a level the session never entered. requestId is optional
613
847
  // (older clients omit it); sendError tolerates null.
614
848
  const requestId = msg?.requestId
849
+ // #7786 — an explicit `level: null` is the wire spelling of "clear the
850
+ // override" (back to the provider/model default). Exactly null: an absent key,
851
+ // '' and whitespace stay malformed and are refused by the form check below, so
852
+ // a client that merely forgot the field cannot un-pin a level by accident.
853
+ const clearing = msg.level === null
615
854
  const level = typeof msg.level === 'string' ? msg.level.trim() : ''
616
- if (!VALID_THINKING_LEVELS.has(level)) {
855
+ // #7730 — two questions, asked separately and in this order.
856
+ //
857
+ // FORM first, because it needs no session: the level is about to become a
858
+ // JSON-RPC param on a subprocess, so charset and length are checked with the
859
+ // same predicate the wire schema uses (1-32 chars of [A-Za-z0-9_-] — this is
860
+ // what refuses `../../etc` and a 200-char string). This says nothing about
861
+ // which levels exist; a syntactic guard that also carried the roster is what
862
+ // the six-site problem was made of.
863
+ if (!clearing && !isWellFormedThinkingLevel(level)) {
617
864
  sendError(ws, requestId, 'THINKING_LEVEL_NOT_APPLIED', `Invalid thinking level: ${level}`, undefined, ctx)
618
865
  return
619
866
  }
@@ -630,11 +877,74 @@ async function handleSetThinkingLevel(ws, client, msg, ctx) {
630
877
  return
631
878
  }
632
879
 
880
+ // A CLEAR names no level, so there is nothing to check against a roster — and
881
+ // it must work when the roster is empty (a pre-catalog codex session refuses
882
+ // every SET, yet an override recorded earlier still has to be undoable).
883
+ // Everything after this point is about validating a level being SET.
884
+ if (clearing) {
885
+ const previousLevel = entry.session.thinkingLevel || LEGACY_DEFAULT_THINKING_LEVEL
886
+ try {
887
+ await entry.session.setThinkingLevel(null)
888
+ const described = typeof entry.session.describeThinkingLevel === 'function' ? entry.session.describeThinkingLevel() : null
889
+ ;sessionLogger(sessionId).info(`Thinking level cleared by ${client.id} on session ${sessionId}: ${previousLevel} → provider default${described ? ` (${described})` : ''}`)
890
+ ctx.transport.broadcastToSession(sessionId, buildThinkingLevelChanged(entry.session) ?? { type: 'thinking_level_changed', level: LEGACY_DEFAULT_THINKING_LEVEL })
891
+ } catch (err) {
892
+ sendError(ws, requestId, 'THINKING_LEVEL_NOT_APPLIED', `Failed to clear thinking level: ${thrownMessage(err)}`, undefined, ctx)
893
+ }
894
+ return
895
+ }
896
+
897
+ // MEMBERSHIP second, and only here — this is the first point that knows both
898
+ // the session and the model it is running, which is the only scope in which
899
+ // the question has an answer (see resolveSessionThinkingLevels above).
900
+ const offered = resolveSessionThinkingLevels(entry)
901
+ // NO ROSTER AT ALL is its own rejection, before membership, and it carries a
902
+ // different message: "this model has advertised nothing" is not "you picked
903
+ // the wrong level", and an empty `Supported levels:` list reads as a bug.
904
+ //
905
+ // `source: 'none'` is reached only when the row advertised nothing AND this
906
+ // provider has no legacy fallback (#7784) — the pre-catalog codex state. The
907
+ // Claude path never reaches it (the fallback applies, so source is 'legacy'
908
+ // with the triple), and a codex row that DID advertise levels has source
909
+ // 'model'. Since #7784 the picker resolves from the SAME fact, so it offers
910
+ // nothing here rather than offering three levels this branch refuses; the
911
+ // branch stays because a client can send any level it likes, and an older
912
+ // client still offers the triple.
913
+ if (offered.levels.length === 0) {
914
+ ;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})`)
915
+ sendError(
916
+ ws,
917
+ requestId,
918
+ 'THINKING_LEVEL_NOT_APPLIED',
919
+ `Model '${offered.modelId || 'unknown'}' has not advertised its reasoning levels yet, so no level can be applied on ${entry.provider || 'this provider'}.`,
920
+ undefined,
921
+ ctx,
922
+ )
923
+ return
924
+ }
925
+ if (!offered.levels.includes(level)) {
926
+ ;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})`)
927
+ sendError(
928
+ ws,
929
+ requestId,
930
+ 'THINKING_LEVEL_NOT_APPLIED',
931
+ `Thinking level '${level}' is not offered by model '${offered.modelId || 'unknown'}'. Supported levels: ${offered.levels.join(', ')}`,
932
+ undefined,
933
+ ctx,
934
+ )
935
+ return
936
+ }
937
+
938
+ const previousLevel = entry.session.thinkingLevel || LEGACY_DEFAULT_THINKING_LEVEL
633
939
  try {
634
940
  await entry.session.setThinkingLevel(level)
635
- ctx.transport.broadcastToSession(sessionId, { type: 'thinking_level_changed', level })
941
+ // #8700: the line an operator checks before a send. A provider that can say
942
+ // what it will run (SdkSession) appends its model/requested/effective summary.
943
+ const described = typeof entry.session.describeThinkingLevel === 'function' ? entry.session.describeThinkingLevel() : null
944
+ ;sessionLogger(sessionId).info(`Thinking level change from ${client.id} on session ${sessionId}: ${previousLevel} → ${level}${described ? ` (${described})` : ''}`)
945
+ ctx.transport.broadcastToSession(sessionId, buildThinkingLevelChanged(entry.session) ?? { type: 'thinking_level_changed', level })
636
946
  } catch (err) {
637
- sendError(ws, requestId, 'THINKING_LEVEL_NOT_APPLIED', `Failed to set thinking level: ${err.message}`, undefined, ctx)
947
+ sendError(ws, requestId, 'THINKING_LEVEL_NOT_APPLIED', `Failed to set thinking level: ${thrownMessage(err)}`, undefined, ctx)
638
948
  }
639
949
  }
640
950
 
@@ -647,7 +957,7 @@ async function handleSetThinkingLevel(ws, client, msg, ctx) {
647
957
  * window from silently losing the change.
648
958
  *
649
959
  * Empty string and `null` both clear the override — at that point
650
- * `shouldSkipEvaluator` falls through to the server-wide
960
+ * `shouldSkipEvaluatorAsync` falls through to the server-wide
651
961
  * `config.promptEvaluatorSkipPattern` (#3187) and the default skip rules.
652
962
  *
653
963
  * Validation: BaseSession.setPromptEvaluatorSkipPattern returns false for
@@ -682,6 +992,10 @@ function handleSetPromptEvaluatorSkipPattern(ws, client, msg, ctx) {
682
992
  sendSessionError(ws, ctx, `Invalid pattern: ${err.message || 'malformed regex'}`)
683
993
  return
684
994
  }
995
+ if (!isSafeRegexSource(msg.value)) {
996
+ 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+)+`)')
997
+ return
998
+ }
685
999
  }
686
1000
 
687
1001
  const changed = entry.session.setPromptEvaluatorSkipPattern(msg.value)
@@ -711,6 +1025,12 @@ function handleSetPromptEvaluatorSkipPattern(ws, client, msg, ctx) {
711
1025
  }
712
1026
 
713
1027
  function handleSetPermissionRules(ws, client, msg, ctx) {
1028
+ // Independent principal gate: permission rules are never delegated to an
1029
+ // agent principal, whatever its binding.
1030
+ if (isPrincipalClient(client)) {
1031
+ sendPrincipalRefusal(ws, client, msg, ctx, 'handler')
1032
+ return
1033
+ }
714
1034
  // Bound (pairing-issued) session tokens are scoped to USE existing
715
1035
  // permissions, never to escalate — the same principle that blocks them from
716
1036
  // flipping to auto mode in handleSetPermissionMode. Permission rules can
@@ -718,8 +1038,8 @@ function handleSetPermissionRules(ws, client, msg, ctx) {
718
1038
  // (share-a-session) client set them is exactly that escalation. The gate is
719
1039
  // host-authority = an UNBOUND client (no boundSessionId — the primary token,
720
1040
  // or an unbound linking-mode pairing token), mirroring rejectCredentialWriteIfBound.
721
- if (client.boundSessionId) {
722
- loggerForSession('ws', client.boundSessionId).warn(`Client ${client.id} (bound to ${client.boundSessionId}) attempted to set permission rules — rejected`)
1041
+ if (isBoundClient(client)) {
1042
+ sessionLogger(client.boundSessionId, 'ws').warn(`Client ${client.id} (bound to ${client.boundSessionId}) attempted to set permission rules — rejected`)
723
1043
  sendError(ws, msg?.requestId, 'PERMISSION_RULES_FORBIDDEN_BOUND_CLIENT',
724
1044
  'Pairing-issued session tokens cannot modify permission rules. Use the primary API token from a device with physical access to this machine.',
725
1045
  undefined, ctx)
@@ -1057,7 +1377,7 @@ function handleGetPermissionInput(ws, client, msg, ctx) {
1057
1377
 
1058
1378
  // Same authority gate as permission_response — a client may only read the
1059
1379
  // input for a permission it could itself answer.
1060
- if (client.boundSessionId) {
1380
+ if (isBoundClient(client)) {
1061
1381
  if (client.boundSessionId !== sessionId) return notFound('NOT_FOUND', 'No pending permission for that request.')
1062
1382
  } else if (!isSessionViewer(client, sessionId)) {
1063
1383
  return notFound('NOT_FOUND', 'No pending permission for that request.')
@@ -1185,7 +1505,7 @@ async function handleAddMcpServer(ws, client, msg, ctx) {
1185
1505
  }
1186
1506
 
1187
1507
  try {
1188
- const result = await entry.session.addMcpServer(name, msg.config, scope)
1508
+ const result = await entry.session.addMcpServer(name, msg.config, scope, { isAuthorized: authorizedFor(ctx, client) })
1189
1509
  if (!result || result.ok !== true) {
1190
1510
  // #7001: a denied spawn-trust prompt is a distinct outcome from a failure —
1191
1511
  // nothing was written, and the client should say "you declined" rather than
@@ -1312,6 +1632,8 @@ export const settingsHandlers = {
1312
1632
  // Skills + credential handlers split into sibling modules (audit P2-4).
1313
1633
  ...skillsHandlers,
1314
1634
  ...credentialHandlers,
1635
+ // Per-folder trust for project settings (primary-only; see folder-trust-handlers.js).
1636
+ ...folderTrustHandlers,
1315
1637
  }
1316
1638
 
1317
1639
  export { ELIGIBLE_TOOLS, NEVER_AUTO_ALLOW }