@chroxy/server 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,818 @@
1
+ /**
2
+ * Model, permission mode, and provider settings handlers.
3
+ *
4
+ * Handles: set_model, set_permission_mode, permission_response,
5
+ * query_permission_audit, list_providers, set_permission_rules
6
+ */
7
+ import { ALLOWED_MODEL_IDS, toShortModelId, isClaudeProvider } from '../models.js'
8
+ import {
9
+ ALLOWED_PERMISSION_MODE_IDS,
10
+ resolveSession,
11
+ resolveSessionOrError,
12
+ requireSessionMethod,
13
+ sendError,
14
+ sendSessionError,
15
+ buildSessionTokenMismatchPayload,
16
+ isSessionViewer,
17
+ } from '../handler-utils.js'
18
+ import { listProviders, getProvider } from '../providers.js'
19
+ import { isProviderModelUnrestricted } from '../config.js'
20
+ import { createLogger, loggerForSession, sessionLogger } from '../logger.js'
21
+ // Credential + skills handlers were split into sibling modules (audit P2-4);
22
+ // their maps are composed into settingsHandlers below.
23
+ import { credentialHandlers } from './credential-handlers.js'
24
+ import { skillsHandlers } from './skills-handlers.js'
25
+ import {
26
+ PER_SESSION_SETTINGS,
27
+ buildPerSessionSettingHandler,
28
+ } from '../per-session-settings.js'
29
+ import { createPermissionResolver, resolveOriginSessionId } from '../permission-resolver.js'
30
+ import { sanitizeToolInput, PULL_MAX_INPUT_CHARS } from '../redaction.js'
31
+ // #6605 — SINGLE source of truth for the rule-eligibility sets. These used to be
32
+ // a duplicate hard-coded copy here, which silently drifted from
33
+ // permission-manager's when codex's `apply_patch` (rule-eligible, like Write) and
34
+ // `shell` (never-auto-allow, like Bash) were added — so set_permission_rules
35
+ // validation and PermissionManager's enforcement could disagree. Import the
36
+ // exported sets so the two layers can never diverge again.
37
+ import { ELIGIBLE_TOOLS, NEVER_AUTO_ALLOW } from '../permission-manager.js'
38
+
39
+ const log = createLogger('ws')
40
+
41
+ /**
42
+ * Sentinel: the provider opted OUT of static model validation entirely
43
+ * (#5418 — ollama's `getAllowedModels()` returns null because valid models
44
+ * are whatever the local daemon has pulled; a static list would reject
45
+ * them all). Distinct from the legacy "no per-provider list" fallback,
46
+ * which routes to the global Claude allowlist and would wrongly reject
47
+ * every non-Claude id.
48
+ */
49
+ const PROVIDER_MODELS_UNRESTRICTED = Symbol('provider-models-unrestricted')
50
+
51
+ /**
52
+ * Resolve the allowed model IDs for a specific provider — #2946 / #5418.
53
+ *
54
+ * Providers opt in to per-provider validation by exposing a static
55
+ * `getAllowedModels()` returning an array of accepted IDs. Providers that
56
+ * don't have the method at all (docker-* wrappers and any pre-#2946
57
+ * embedder-registered class) fall back to the dynamic global
58
+ * `ALLOWED_MODEL_IDS`, which is fed by the Claude Agent SDK's supported-
59
+ * models list and is the historical source of truth for Claude sessions.
60
+ *
61
+ * Tri-state return:
62
+ * - `string[]` — provider opted in; the array is authoritative.
63
+ * - `PROVIDER_MODELS_UNRESTRICTED` — the method exists and returned a
64
+ * non-array (#5418 ollama): accept any non-empty model id verbatim.
65
+ * - `null` — no method / unknown provider / method threw: use the
66
+ * global allowlist (conservative legacy behaviour).
67
+ *
68
+ * @param {string|undefined} providerName - Session's registered provider name
69
+ * @returns {string[]|typeof PROVIDER_MODELS_UNRESTRICTED|null}
70
+ */
71
+ function getProviderAllowedModels(providerName, config) {
72
+ if (!providerName) return null
73
+ // #6378: an operator can opt a static-allowlist provider into unrestricted
74
+ // model validation via `config.providers.allowAnyModel` — treat it exactly
75
+ // like ollama (#5418) so an unlisted-but-API-valid id passes through and the
76
+ // upstream API validates, with no release. Checked before the class lookup so
77
+ // it applies regardless of what getAllowedModels() returns.
78
+ if (isProviderModelUnrestricted(config, providerName)) return PROVIDER_MODELS_UNRESTRICTED
79
+ let ProviderClass
80
+ try {
81
+ ProviderClass = getProvider(providerName)
82
+ } catch {
83
+ // Unknown provider — can't validate, defer to global list.
84
+ return null
85
+ }
86
+ if (typeof ProviderClass.getAllowedModels !== 'function') return null
87
+ try {
88
+ const list = ProviderClass.getAllowedModels()
89
+ if (Array.isArray(list)) return list
90
+ return PROVIDER_MODELS_UNRESTRICTED
91
+ } catch {
92
+ return null
93
+ }
94
+ }
95
+
96
+ function handleSetModel(ws, client, msg, ctx) {
97
+ if (typeof msg.model !== 'string') {
98
+ log.warn(`Rejected invalid model from ${client.id}: ${JSON.stringify(msg.model)}`)
99
+ sendError(ws, msg?.requestId, 'INVALID_MODEL', `Invalid or unsupported model: ${msg.model}`, undefined, ctx)
100
+ return
101
+ }
102
+
103
+ const modelSessionId = msg.sessionId || client.activeSessionId
104
+ const entry = resolveSession(ctx, msg, client)
105
+
106
+ // #5731 (T1): reject set_model on a provider that can't switch models, mirroring
107
+ // the permissionModeSwitch guard in handleSetPermissionMode below. Without this,
108
+ // a provider whose setModel is a no-op (e.g. claude-tui, modelSwitch:false) still
109
+ // updates BaseSession.model and broadcasts `model_changed` while the running
110
+ // session keeps its original model — so every client (incl. the ungated mobile
111
+ // picker) shows a switch that never happened.
112
+ if (entry && entry.provider) {
113
+ let ModelProviderClass
114
+ try {
115
+ ModelProviderClass = getProvider(entry.provider)
116
+ } catch {
117
+ // Unknown provider — allow through (fail open for forward-compat).
118
+ }
119
+ if (ModelProviderClass && ModelProviderClass.capabilities?.modelSwitch === false) {
120
+ ;sessionLogger(modelSessionId).warn(`Rejected set_model on ${entry.provider} session ${modelSessionId} from ${client.id}: provider does not support modelSwitch`)
121
+ sendError(
122
+ ws,
123
+ msg?.requestId,
124
+ 'CAPABILITY_NOT_SUPPORTED',
125
+ `The active provider '${entry.provider}' does not support model switching.`,
126
+ undefined,
127
+ ctx,
128
+ )
129
+ return
130
+ }
131
+ }
132
+
133
+ // Per-provider allowlist: the global ALLOWED_MODEL_IDS is Claude-only, so
134
+ // accepting any Claude model ID on a Gemini/Codex session and forwarding
135
+ // it to setModel() would respawn the CLI with an unknown `-m` arg and
136
+ // crash opaquely (see issue #2946). Consult the session's provider first.
137
+ if (entry) {
138
+ const providerAllowed = getProviderAllowedModels(entry.provider, ctx.services?.config)
139
+ if (providerAllowed === PROVIDER_MODELS_UNRESTRICTED) {
140
+ // #5418: the provider validates nothing statically (ollama — any
141
+ // locally pulled model id is valid; an unknown id surfaces as the
142
+ // backend's own error on the next message). Pass the id through
143
+ // verbatim after a minimal non-empty guard — without this branch the
144
+ // null fell through to the global Claude allowlist, which rejected
145
+ // every Ollama model and accepted Claude ids that 404 at the local
146
+ // daemon.
147
+ const model = msg.model.trim()
148
+ if (model.length === 0) {
149
+ log.warn(`Rejected empty model id on ${entry.provider} session ${modelSessionId} from ${client.id}`)
150
+ sendError(ws, msg?.requestId, 'INVALID_MODEL', `Invalid or unsupported model: ${msg.model}`, undefined, ctx)
151
+ return
152
+ }
153
+ ;sessionLogger(modelSessionId).info(`Model change from ${client.id} on session ${modelSessionId}: ${model}`)
154
+ // #5696: setModel() returns false when the session is busy (mid-turn) or
155
+ // the model is unchanged (no-op). Mirror the permission-mode guard
156
+ // (#3729) below — only broadcast model_changed when the change actually
157
+ // landed, else clients show a model the session never switched to.
158
+ if (!entry.session.setModel(model)) {
159
+ ;sessionLogger(modelSessionId).warn(`set_model rejected (session busy or no-op): requested ${model}`)
160
+ sendError(ws, msg?.requestId, 'MODEL_NOT_APPLIED', `Model change to '${model}' was not applied (session busy or already on that model).`, undefined, ctx)
161
+ return
162
+ }
163
+ ctx.transport.broadcastToSession(modelSessionId, { type: 'model_changed', model: toShortModelId(model) })
164
+ return
165
+ }
166
+ if (providerAllowed) {
167
+ if (!providerAllowed.includes(msg.model)) {
168
+ // #4828: session-scoped — modelSessionId identifies the affected
169
+ // session. Legacy single-session adapters may surface an empty
170
+ // sessionId, so fall back to the module-level `log` rather than
171
+ // throwing inside loggerForSession (matches the input-handlers
172
+ // pattern from #4823).
173
+ ;sessionLogger(modelSessionId).warn(`Rejected model '${msg.model}' on ${entry.provider} session ${modelSessionId} from ${client.id}`)
174
+ sendError(
175
+ ws,
176
+ msg?.requestId,
177
+ 'MODEL_NOT_SUPPORTED_BY_PROVIDER',
178
+ `Model '${msg.model}' is not supported by the active provider '${entry.provider}'. Supported models: ${providerAllowed.join(', ')}`,
179
+ undefined,
180
+ ctx,
181
+ )
182
+ return
183
+ }
184
+ // #4828: session-scoped (single-session fallback as above).
185
+ ;sessionLogger(modelSessionId).info(`Model change from ${client.id} on session ${modelSessionId}: ${msg.model}`)
186
+ // #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)
190
+ return
191
+ }
192
+ // Non-Claude providers use opaque model IDs (e.g. 'gemini-2.5-pro') —
193
+ // broadcast them verbatim. toShortModelId() is a Claude-specific
194
+ // alias collapse (claude-sonnet-4-6 → sonnet) and returns the input
195
+ // unchanged for non-Claude IDs, so applying it uniformly is safe.
196
+ ctx.transport.broadcastToSession(modelSessionId, { type: 'model_changed', model: toShortModelId(msg.model) })
197
+ return
198
+ }
199
+ // Fall through to the legacy global allowlist when the provider hasn't
200
+ // opted in (e.g. claude-sdk, claude-cli, docker-* inherit from it).
201
+ }
202
+
203
+ // #6201 (OCP) — the global ALLOWED_MODEL_IDS below is the Claude-only,
204
+ // SDK-fed allowlist. A KNOWN non-Claude provider reaches this fallthrough
205
+ // only when it declares no static getAllowedModels() (getProviderAllowedModels
206
+ // returned null above); letting it through would silently validate its model
207
+ // ids against Claude's allowlist — an open-for-extension gap a newly-added
208
+ // provider could trip purely by existing. Reject such a provider with a clear
209
+ // error instead. Claude-family providers (claudeFamily === true) and legacy
210
+ // single-session (entry === null) fall through unchanged; an UNKNOWN provider
211
+ // fails open, mirroring the modelSwitch capability guard above. No current
212
+ // provider hits this branch — every shipped non-Claude provider has
213
+ // getAllowedModels() (so it's handled above) and user-shell is modelSwitch:false
214
+ // (rejected earlier) — so this is a pure forward-compat guard.
215
+ if (entry && entry.provider) {
216
+ let ResolvedProviderClass = null
217
+ try {
218
+ ResolvedProviderClass = getProvider(entry.provider)
219
+ } catch {
220
+ // Unknown provider — can't classify; fail open to the legacy behaviour.
221
+ }
222
+ if (ResolvedProviderClass && !isClaudeProvider(entry.provider, ResolvedProviderClass)) {
223
+ ;sessionLogger(modelSessionId).warn(`Rejected set_model '${msg.model}' on ${entry.provider} session ${modelSessionId} from ${client.id}: provider declares no model allowlist and is not Claude-family`)
224
+ sendError(
225
+ ws,
226
+ msg?.requestId,
227
+ 'MODEL_NOT_SUPPORTED_BY_PROVIDER',
228
+ `The active provider '${entry.provider}' does not declare a model allowlist; cannot validate model '${msg.model}'.`,
229
+ undefined,
230
+ ctx,
231
+ )
232
+ return
233
+ }
234
+ }
235
+
236
+ if (ALLOWED_MODEL_IDS.has(msg.model)) {
237
+ if (entry) {
238
+ // #4828: session-scoped (single-session fallback).
239
+ ;sessionLogger(modelSessionId).info(`Model change from ${client.id} on session ${modelSessionId}: ${msg.model}`)
240
+ // #5696: only broadcast when setModel() reports the change landed.
241
+ if (!entry.session.setModel(msg.model)) {
242
+ ;sessionLogger(modelSessionId).warn(`set_model rejected (session busy or no-op): requested ${msg.model}`)
243
+ sendError(ws, msg?.requestId, 'MODEL_NOT_APPLIED', `Model change to '${msg.model}' was not applied (session busy or already on that model).`, undefined, ctx)
244
+ return
245
+ }
246
+ ctx.transport.broadcastToSession(modelSessionId, { type: 'model_changed', model: toShortModelId(msg.model) })
247
+ }
248
+ return
249
+ }
250
+
251
+ log.warn(`Rejected invalid model from ${client.id}: ${JSON.stringify(msg.model)}`)
252
+ sendError(ws, msg?.requestId, 'INVALID_MODEL', `Invalid or unsupported model: ${msg.model}`, undefined, ctx)
253
+ }
254
+
255
+ function handleSetPermissionMode(ws, client, msg, ctx) {
256
+ if (
257
+ typeof msg.mode === 'string' &&
258
+ ALLOWED_PERMISSION_MODE_IDS.has(msg.mode)
259
+ ) {
260
+ const permModeSessionId = msg.sessionId || client.activeSessionId
261
+ const entry = resolveSession(ctx, msg, client)
262
+ if (entry) {
263
+ // #2963 — capability gate: providers that don't support permission mode
264
+ // (Gemini, Codex) must be rejected here rather than silently accepting
265
+ // the change, which would let the UI show visual confirmation of a mode
266
+ // that has no effect on the session.
267
+ if (entry.provider) {
268
+ let ProviderClass
269
+ try {
270
+ ProviderClass = getProvider(entry.provider)
271
+ } catch {
272
+ // Unknown provider — allow through (fail open for forward-compat).
273
+ }
274
+ if (ProviderClass && ProviderClass.capabilities?.permissionModeSwitch === false) {
275
+ // #4828: session-scoped (single-session fallback).
276
+ ;sessionLogger(permModeSessionId).warn(`Rejected set_permission_mode on ${entry.provider} session ${permModeSessionId} from ${client.id}: provider does not support permissionModeSwitch`)
277
+ sendError(
278
+ ws,
279
+ msg?.requestId,
280
+ 'CAPABILITY_NOT_SUPPORTED',
281
+ `The active provider '${entry.provider}' does not support permission mode switching.`,
282
+ undefined,
283
+ ctx,
284
+ )
285
+ return
286
+ }
287
+ }
288
+
289
+ if (msg.mode === 'plan' && !entry.session.constructor.capabilities?.planMode) {
290
+ sendSessionError(ws, ctx, 'This provider does not support plan mode')
291
+ return
292
+ }
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
296
+ // 2026-04-11 audit (Adversary A5) flagged this as a step in
297
+ // the kill chain: an authenticated attacker sends
298
+ // `{mode:'auto', confirmed:true}` and trivially flips the
299
+ // session to unrestricted execution. Pre-audit, the only
300
+ // protection was a `confirmed:true` flag that a malicious
301
+ // client can just send directly — it requires no actual
302
+ // physical user confirmation.
303
+ //
304
+ // Two defense-in-depth gates close the attack:
305
+ //
306
+ // 1. Config opt-in: config.allowAutoPermissionMode must be
307
+ // explicitly set to true in the operator's config file.
308
+ // Default is false, so fresh installs reject auto mode
309
+ // entirely. The operator has to walk up to the dev machine
310
+ // and edit the config to enable it — out-of-band
311
+ // confirmation that no network-side flag can provide.
312
+ //
313
+ // 2. Bound-client rejection: clients that authenticated via a
314
+ // pairing-issued session token (client.boundSessionId set)
315
+ // are NEVER allowed to flip to auto mode, regardless of
316
+ // config. Pairing tokens are scoped to a specific session
317
+ // and should only be able to use existing permissions, not
318
+ // escalate. Only the primary API token can flip to auto.
319
+ if (msg.mode === 'auto') {
320
+ if (client.boundSessionId) {
321
+ // #4828: session-scoped to the bound session — that's the
322
+ // 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`)
324
+ sendError(ws, msg?.requestId, 'AUTO_MODE_FORBIDDEN_BOUND_CLIENT',
325
+ 'Pairing-issued session tokens cannot enable auto permission mode. Use the primary API token from a device with physical access to this machine.',
326
+ undefined, ctx)
327
+ return
328
+ }
329
+ if (ctx.services.config?.allowAutoPermissionMode !== true) {
330
+ // #4828: session-scoped (single-session fallback).
331
+ ;sessionLogger(permModeSessionId).warn(`Client ${client.id} attempted to flip to auto permission mode but allowAutoPermissionMode is not enabled in server config`)
332
+ sendError(ws, msg?.requestId, 'AUTO_MODE_DISABLED_BY_CONFIG',
333
+ 'Auto permission mode is disabled on this server. To enable, set allowAutoPermissionMode:true in the server config file (requires local filesystem access). Default is disabled for security.',
334
+ undefined, ctx)
335
+ return
336
+ }
337
+ }
338
+ if (msg.mode === 'auto' && !msg.confirmed) {
339
+ // #4828: session-scoped (single-session fallback).
340
+ ;sessionLogger(permModeSessionId).info(`Auto mode requested by ${client.id}, awaiting confirmation`)
341
+ // #5609: on providers where the auto-switch is destructive (CLI —
342
+ // _onPermissionModeChanged respawns the `claude -p` subprocess, the
343
+ // #3729 panic-button) AND a turn is currently in flight, name the
344
+ // consequence so the user isn't surprised by a dropped response. SDK
345
+ // and TUI apply the switch in-place and keep the turn running, so they
346
+ // keep the plain warning. The warning string is rendered verbatim by
347
+ // the mobile app's confirm Alert (SettingsBar.tsx).
348
+ const interruptsTurn = !!entry.session.constructor.capabilities?.interruptsTurnOnAutoSwitch
349
+ 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.'
352
+ ctx.transport.send(ws, {
353
+ type: 'confirm_permission_mode',
354
+ mode: 'auto',
355
+ warning,
356
+ })
357
+ } else {
358
+ const previousMode = entry.session.permissionMode || 'unknown'
359
+ // #4828: session-scoped (single-session fallback).
360
+ const _pmLog = sessionLogger(permModeSessionId)
361
+ if (msg.mode === 'auto') {
362
+ _pmLog.info(`Auto permission mode CONFIRMED by ${client.id} at ${new Date().toISOString()} (was: ${previousMode})`)
363
+ } else {
364
+ _pmLog.info(`Permission mode change from ${client.id} on session ${permModeSessionId}: ${previousMode} → ${msg.mode} at ${new Date().toISOString()}`)
365
+ }
366
+ // BaseSession exposes the mode on the public `permissionMode` field.
367
+ // The earlier `_permissionMode` read was a typo that always resolved
368
+ // to `undefined`, so the audit log silently fell back to 'approve'
369
+ // regardless of the real previous mode (Copilot review on PR #3730).
370
+ // Reuse `previousMode` from above (line 203) — same source of truth.
371
+ entry.session.setPermissionMode(msg.mode)
372
+ // #3729: setPermissionMode silently rejects mid-turn changes (and
373
+ // same-mode no-ops). Use the post-call value as ground truth — if
374
+ // the session is still on the previous mode, the call was rejected
375
+ // and we must not broadcast a misleading `permission_mode_changed`.
376
+ // Pre-fix the dashboard's optimistic update + this unconditional
377
+ // broadcast both confirmed an "auto" switch that never landed,
378
+ // leaving the user staring at fresh prompts in supposed bypass mode.
379
+ const actualMode = entry.session.permissionMode
380
+ if (actualMode !== msg.mode) {
381
+ // #4828: session-scoped (single-session fallback).
382
+ ;sessionLogger(permModeSessionId).warn(`set_permission_mode rejected (session busy or no-op): requested ${msg.mode}, still ${actualMode}`)
383
+ sendError(ws, msg?.requestId, 'PERMISSION_MODE_NOT_APPLIED',
384
+ `Permission mode change to '${msg.mode}' was not applied (session busy or already in that mode).`,
385
+ undefined, ctx)
386
+ return
387
+ }
388
+ if (ctx.permissions.permissionAudit) {
389
+ ctx.permissions.permissionAudit.logModeChange({
390
+ clientId: client.id,
391
+ sessionId: permModeSessionId,
392
+ previousMode,
393
+ newMode: msg.mode,
394
+ })
395
+ }
396
+ ctx.transport.broadcastToSession(permModeSessionId, { type: 'permission_mode_changed', mode: msg.mode })
397
+ }
398
+ }
399
+ } else {
400
+ log.warn(`Rejected invalid permission mode from ${client.id}: ${JSON.stringify(msg.mode)}`)
401
+ sendError(ws, msg?.requestId, 'INVALID_PERMISSION_MODE', `Invalid permission mode: ${msg.mode}`, undefined, ctx)
402
+ }
403
+ }
404
+
405
+ function handlePermissionResponse(ws, client, msg, ctx) {
406
+ const { requestId, decision } = msg
407
+ if (!requestId || !decision) return
408
+
409
+ // #5373: the binding check + SDK-vs-legacy dispatch + audit are delegated to
410
+ // the shared permission-resolver (also used by the HTTP handler in
411
+ // ws-permissions.js), so the binding rule lives in ONE place. Two things stay
412
+ // HERE because they have no HTTP analog / are transport-specific:
413
+ // - the WS-ONLY unbound-subscription guard (#4798, invariant G), which runs
414
+ // BEFORE the resolver, and
415
+ // - the elaborate binding-mismatch forensic log (#2832) + the per-transport
416
+ // error / permission_expired / permission_resolved messages.
417
+ //
418
+ // `mappedSessionId` is the raw mapping; `originSessionId` adds the WS-only
419
+ // legacy `client.activeSessionId` fallback. That fallback is passed to the
420
+ // resolver as `dispatchFallbackSessionId` (used ONLY to pick the dispatch
421
+ // session, NEVER for the binding check — invariant B / the #2806 residual).
422
+ // #6030: computed via resolveOriginSessionId (the SAME helper the resolver
423
+ // uses), so the session this handler authorizes against is byte-identical to
424
+ // the one the resolver dispatches to — closing the prior `||` (here) vs `??`
425
+ // (resolver) split that disagreed on empty-string / 0-ish mapped ids.
426
+ const mappedSessionId = ctx.permissions.permissionSessionMap.get(requestId)
427
+ const originSessionId = resolveOriginSessionId(mappedSessionId, client.activeSessionId)
428
+
429
+ // #4798 (audit P0 symmetry with #4788): for UNBOUND clients, require the
430
+ // originSessionId to match the client's active or subscribed sessions before
431
+ // routing the decision. Without this, an unbound dashboard tab could
432
+ // approve/deny a permission for any session by replaying a known requestId —
433
+ // arguably MORE dangerous than the question hijack vector (#4788) because
434
+ // permission decisions gate file writes / shell exec. Routes through
435
+ // isSessionViewer (#6030) — the SAME predicate _broadcastToSession uses to pick
436
+ // recipients (ws-broadcaster.js _matchesSession) — so "who may answer == who
437
+ // could receive" can never drift. Leaves the mapping intact so the legitimate
438
+ // subscribed client can still respond. WS-ONLY by design: a primary HTTP caller
439
+ // has full session authority (§3), so the HTTP path has no analog and must not
440
+ // inherit this restriction.
441
+ if (!client.boundSessionId && originSessionId) {
442
+ if (!isSessionViewer(client, originSessionId)) {
443
+ sessionLogger(originSessionId).warn(`[permission-response-reject] unbound client ${client.id} attempted to respond to ${requestId} (originSessionId=${originSessionId}, activeSessionId=${client.activeSessionId ?? 'none'}, subscribed=false) — dropped`)
444
+ return
445
+ }
446
+ }
447
+
448
+ const resolver = createPermissionResolver({
449
+ permissionSessionMap: ctx.permissions.permissionSessionMap,
450
+ pendingPermissions: ctx.permissions.pendingPermissions,
451
+ getSessionManager: () => ctx.sessions.sessionManager,
452
+ resolveLegacyPermission: (rid, dec) => ctx.permissions.permissions.resolvePermission(rid, dec),
453
+ getPermissionAudit: () => ctx.permissions.permissionAudit,
454
+ // #5704: route the map delete through the WsServer teardown so resolving a
455
+ // permission over WS also drops its permission-induced subscription refcount.
456
+ onRouteTeardown: ctx.permissions.unregisterPermissionRoute,
457
+ })
458
+ const result = resolver.resolve(requestId, decision, client.boundSessionId, {
459
+ clientId: client.id,
460
+ dispatchFallbackSessionId: client.activeSessionId,
461
+ // #6543 (feature B): the operator's per-hunk edits for an approve. The server
462
+ // whitelists which fields may be substituted (permission-manager.js
463
+ // mergeEditedInput) — a client can narrow the content but not redirect the
464
+ // path. Only present when the client reviewed + edited the proposed write.
465
+ editedInput: msg.editedInput,
466
+ })
467
+
468
+ if (result.kind === 'binding_mismatch') {
469
+ // Correlate with the [session-binding-create] log at the same requestId to
470
+ // recover the original creating client's bound session + createdAt (#2832).
471
+ const permData = (mappedSessionId && ctx.sessions.sessionManager)
472
+ ? ctx.sessions.sessionManager.getSession(mappedSessionId)?.session?._lastPermissionData?.get(requestId)
473
+ : ctx.permissions.pendingPermissions?.get(requestId)?.data
474
+ const createdAt = permData?.createdAt ?? null
475
+ const ageMs = createdAt ? Date.now() - createdAt : null
476
+ const clientConnectedAt = client.authTime ?? null
477
+ const likelyPostReconnect = Boolean(
478
+ (ageMs !== null && ageMs > 30_000) ||
479
+ (createdAt && clientConnectedAt && clientConnectedAt > createdAt)
480
+ )
481
+ // #4828: session-scoped to the bound session — the reject belongs to the
482
+ // OWNER of `boundSessionId`, not the mismatched mapped session.
483
+ loggerForSession('ws', result.boundSessionId).warn(`[session-binding-reject] permission_response rejected ${JSON.stringify({
484
+ requestId,
485
+ decision,
486
+ clientId: client.id,
487
+ activeSessionId: client.activeSessionId ?? null,
488
+ boundSessionId: client.boundSessionId ?? null,
489
+ mappedSessionId: mappedSessionId ?? null,
490
+ requestCreatedAt: createdAt,
491
+ clientConnectedAt,
492
+ requestAgeMs: ageMs,
493
+ likelyPostReconnect,
494
+ })}`)
495
+ // The resolver does NOT consume the map entry on a mismatch — the
496
+ // legitimate client can still respond. Issue #2912: payload shape matches
497
+ // every other SESSION_TOKEN_MISMATCH emit site.
498
+ ctx.transport.send(ws, {
499
+ type: 'error',
500
+ requestId: requestId ?? null,
501
+ ...buildSessionTokenMismatchPayload({
502
+ sessionManager: ctx.sessions.sessionManager,
503
+ boundSessionId: result.boundSessionId,
504
+ message: 'Not authorized to respond to this permission request',
505
+ }),
506
+ })
507
+ return
508
+ }
509
+
510
+ 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' })
512
+ return
513
+ }
514
+
515
+ // result.kind === 'resolved' — the resolver dispatched (sdk|legacy) + audited.
516
+ // #3048: SDK-session broadcasts go through the unified pipeline
517
+ // (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
+ )
525
+ }
526
+ }
527
+
528
+ function handleQueryPermissionAudit(ws, client, msg, ctx) {
529
+ if (ctx.permissions.permissionAudit) {
530
+ const entries = ctx.permissions.permissionAudit.query({
531
+ sessionId: msg.sessionId,
532
+ type: msg.auditType,
533
+ since: msg.since,
534
+ limit: msg.limit,
535
+ })
536
+ ctx.transport.send(ws, { type: 'permission_audit_result', entries })
537
+ } else {
538
+ ctx.transport.send(ws, { type: 'permission_audit_result', entries: [] })
539
+ }
540
+ }
541
+
542
+ function handleListProviders(ws, client, msg, ctx) {
543
+ ctx.transport.send(ws, { type: 'provider_list', providers: listProviders() })
544
+ }
545
+
546
+ const VALID_THINKING_LEVELS = new Set(['default', 'high', 'max'])
547
+
548
+ async function handleSetThinkingLevel(ws, client, msg, ctx) {
549
+ // #5731 T9: every rejection path echoes the client's requestId with a single
550
+ // THINKING_LEVEL_NOT_APPLIED code so the dashboard rolls back its optimistic
551
+ // dropdown update (mirrors set_model's MODEL_NOT_APPLIED and
552
+ // set_permission_mode's PERMISSION_MODE_NOT_APPLIED). The capability check is
553
+ // inlined (rather than routed through requireSessionMethod) so the
554
+ // unsupported-provider rejection carries the requestId + code too — otherwise
555
+ // a no-op on a provider without thinking-level control would leave the
556
+ // dropdown stuck on a level the session never entered. requestId is optional
557
+ // (older clients omit it); sendError tolerates null.
558
+ const requestId = msg?.requestId
559
+ const level = typeof msg.level === 'string' ? msg.level.trim() : ''
560
+ if (!VALID_THINKING_LEVELS.has(level)) {
561
+ sendError(ws, requestId, 'THINKING_LEVEL_NOT_APPLIED', `Invalid thinking level: ${level}`, undefined, ctx)
562
+ return
563
+ }
564
+
565
+ const sessionId = msg.sessionId || client.activeSessionId
566
+ const entry = resolveSession(ctx, msg, client)
567
+ if (!entry) {
568
+ sendError(ws, requestId, 'THINKING_LEVEL_NOT_APPLIED', 'No active session', undefined, ctx)
569
+ return
570
+ }
571
+
572
+ if (!entry.session || typeof entry.session.setThinkingLevel !== 'function') {
573
+ sendError(ws, requestId, 'THINKING_LEVEL_NOT_APPLIED', 'This provider does not support thinking level control', undefined, ctx)
574
+ return
575
+ }
576
+
577
+ try {
578
+ await entry.session.setThinkingLevel(level)
579
+ ctx.transport.broadcastToSession(sessionId, { type: 'thinking_level_changed', level })
580
+ } catch (err) {
581
+ sendError(ws, requestId, 'THINKING_LEVEL_NOT_APPLIED', `Failed to set thinking level: ${err.message}`, undefined, ctx)
582
+ }
583
+ }
584
+
585
+ /**
586
+ * #3639 — set the per-session promptEvaluatorSkipPattern. Mirrors the
587
+ * #3185 toggle handler: strict-typed payload validation, idempotent on
588
+ * unchanged input, broadcast on actual change, immediate persist (rather
589
+ * than the debounced schedulePersist) because pattern updates are operator
590
+ * actions and the synchronous flush prevents a crash inside the debounce
591
+ * window from silently losing the change.
592
+ *
593
+ * Empty string and `null` both clear the override — at that point
594
+ * `shouldSkipEvaluator` falls through to the server-wide
595
+ * `config.promptEvaluatorSkipPattern` (#3187) and the default skip rules.
596
+ *
597
+ * Validation: BaseSession.setPromptEvaluatorSkipPattern returns false for
598
+ * invalid regex sources. We surface that as a session_error with a clear
599
+ * message so the operator sees what was wrong instead of the change
600
+ * silently being dropped.
601
+ */
602
+ function handleSetPromptEvaluatorSkipPattern(ws, client, msg, ctx) {
603
+ // Accept string or null. Anything else is a malformed payload.
604
+ if (msg.value !== null && typeof msg.value !== 'string') {
605
+ sendSessionError(ws, ctx, 'set_prompt_evaluator_skip_pattern requires a string `value` (or null/empty to clear)')
606
+ return
607
+ }
608
+
609
+ const sessionId = msg.sessionId || client.activeSessionId
610
+ const entry = resolveSessionOrError(ws, ctx, msg, client)
611
+ if (!entry) return
612
+
613
+ if (!requireSessionMethod(ws, ctx, entry, 'setPromptEvaluatorSkipPattern', 'This provider does not support promptEvaluatorSkipPattern')) {
614
+ // Defensive — mirrors the parallel path in handleSetPromptEvaluator.
615
+ return
616
+ }
617
+
618
+ // Pre-validate non-empty strings here so we can distinguish a valid no-op
619
+ // (setter returns false because value matches current) from a rejected
620
+ // malformed regex (setter also returns false). Without this distinction
621
+ // the operator gets no feedback when their pattern is broken.
622
+ if (typeof msg.value === 'string' && msg.value.length > 0) {
623
+ try {
624
+ new RegExp(msg.value, 'i')
625
+ } catch (err) {
626
+ sendSessionError(ws, ctx, `Invalid pattern: ${err.message || 'malformed regex'}`)
627
+ return
628
+ }
629
+ }
630
+
631
+ const changed = entry.session.setPromptEvaluatorSkipPattern(msg.value)
632
+ if (!changed) {
633
+ // No-op (value already matches current) — no broadcast, no persist.
634
+ return
635
+ }
636
+
637
+ // The setter normalises empty string → null. Surface the stored value
638
+ // (not the raw payload) so subscribed clients see a stable shape.
639
+ const storedValue = entry.session.promptEvaluatorSkipPattern
640
+ ctx.transport.broadcastToSession(sessionId, {
641
+ type: 'prompt_evaluator_skip_pattern_changed',
642
+ sessionId,
643
+ value: storedValue,
644
+ })
645
+
646
+ // Immediate persist — same justification as handleSetPromptEvaluator:
647
+ // pattern updates are rare operator actions and the sync flush avoids
648
+ // losing the change to a crash inside the debounce window.
649
+ try {
650
+ ctx.sessions.sessionManager?.serializeState?.()
651
+ } catch (err) {
652
+ // #4828: session-scoped.
653
+ loggerForSession('ws', sessionId).warn(`Failed to persist promptEvaluatorSkipPattern for ${sessionId}: ${err?.message || err}`)
654
+ }
655
+ }
656
+
657
+ function handleSetPermissionRules(ws, client, msg, ctx) {
658
+ // Bound (pairing-issued) session tokens are scoped to USE existing
659
+ // permissions, never to escalate — the same principle that blocks them from
660
+ // flipping to auto mode in handleSetPermissionMode. Permission rules can
661
+ // auto-allow execution-capable tools (Write, Edit, …), so letting a bound
662
+ // (share-a-session) client set them is exactly that escalation. The gate is
663
+ // host-authority = an UNBOUND client (no boundSessionId — the primary token,
664
+ // 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`)
667
+ sendError(ws, msg?.requestId, 'PERMISSION_RULES_FORBIDDEN_BOUND_CLIENT',
668
+ 'Pairing-issued session tokens cannot modify permission rules. Use the primary API token from a device with physical access to this machine.',
669
+ undefined, ctx)
670
+ return
671
+ }
672
+
673
+ const rules = msg.rules
674
+
675
+ // Validate: must be an array
676
+ if (!Array.isArray(rules)) {
677
+ log.warn(`Rejected invalid permission rules from ${client.id}: not an array`)
678
+ sendSessionError(ws, ctx, 'rules must be an array')
679
+ return
680
+ }
681
+
682
+ // Validate each rule shape and eligibility
683
+ for (let i = 0; i < rules.length; i++) {
684
+ const rule = rules[i]
685
+ if (!rule || typeof rule !== 'object') {
686
+ sendSessionError(ws, ctx, `rules[${i}]: not an object`)
687
+ return
688
+ }
689
+ if (typeof rule.tool !== 'string' || !rule.tool.trim()) {
690
+ sendSessionError(ws, ctx, `rules[${i}]: missing tool name`)
691
+ return
692
+ }
693
+ if (rule.decision !== 'allow' && rule.decision !== 'deny') {
694
+ sendSessionError(ws, ctx, `rules[${i}]: decision must be 'allow' or 'deny'`)
695
+ return
696
+ }
697
+ if (NEVER_AUTO_ALLOW.has(rule.tool)) {
698
+ sendSessionError(ws, ctx, `rules[${i}]: tool '${rule.tool}' cannot be auto-allowed`)
699
+ return
700
+ }
701
+ if (!ELIGIBLE_TOOLS.has(rule.tool)) {
702
+ sendSessionError(ws, ctx, `rules[${i}]: tool '${rule.tool}' is not eligible for permission rules`)
703
+ return
704
+ }
705
+ }
706
+
707
+ const sessionId = msg.sessionId || client.activeSessionId
708
+ const entry = resolveSessionOrError(ws, ctx, msg, client)
709
+ if (!entry) return
710
+
711
+ if (!requireSessionMethod(ws, ctx, entry, 'setPermissionRules', 'This provider does not support permission rules')) {
712
+ return
713
+ }
714
+
715
+ entry.session.setPermissionRules(rules)
716
+
717
+ // Audit the whitelist change
718
+ if (ctx.permissions.permissionAudit) {
719
+ ctx.permissions.permissionAudit.logWhitelistChange({
720
+ clientId: client.id,
721
+ sessionId,
722
+ rules,
723
+ })
724
+ }
725
+
726
+ // Broadcast updated rules to all session clients
727
+ const currentRules = entry.session.getPermissionRules ? entry.session.getPermissionRules() : rules
728
+ ctx.transport.broadcastToSession(sessionId, { type: 'permission_rules_updated', rules: currentRules, sessionId })
729
+ // #4828: session-scoped.
730
+ loggerForSession('ws', sessionId).info(`Permission rules updated by ${client.id} on session ${sessionId}: ${rules.length} rule(s)`)
731
+ }
732
+
733
+ // #4664: assemble the per-session-setting WS handlers from the registry.
734
+ // Each setting's `requestType` (e.g. `'set_prompt_evaluator'`) is the
735
+ // message-type key the dispatcher looks up; the factory-built handler
736
+ // covers payload validation, session resolution, setter invocation,
737
+ // broadcast, and immediate persist with the same shape every existing
738
+ // hand-written handler used. Adding a new setting means appending one
739
+ // entry to PER_SESSION_SETTINGS — no new handler boilerplate.
740
+ const perSessionSettingHandlers = {}
741
+ for (const settingDef of PER_SESSION_SETTINGS) {
742
+ perSessionSettingHandlers[settingDef.requestType] = buildPerSessionSettingHandler(settingDef)
743
+ }
744
+
745
+ /**
746
+ * #6543 (IDE P3 feature B) — reply to a `get_permission_input` pull. The
747
+ * `permission_request` broadcast truncates `input` at ~10K (secret-safe), so a
748
+ * client building a per-hunk pre-write diff pulls the FULL (still secret-
749
+ * redacted) tool input by requestId.
750
+ *
751
+ * SECURITY — session-bound, read-only, redacted:
752
+ * 1. The requestId → session mapping (`permissionSessionMap`, populated for
753
+ * both the SDK and hook dispatch paths) locates the owning session.
754
+ * 2. Authorization is IDENTICAL to `permission_response`: a bound client must
755
+ * own that session; an unbound client must be a viewer of it
756
+ * (`isSessionViewer`). An unauthorized (or unknown) request gets
757
+ * `found:false` with NO input — it can never read another session's input.
758
+ * 3. The raw input (`session._pendingPermissions`, the back-compat accessor
759
+ * onto the session's PermissionManager) is re-run through `sanitizeToolInput`
760
+ * with the larger `PULL_MAX_INPUT_CHARS` cap — for the tool_input object the
761
+ * KEY-NAME + VALUE-SHAPE secret passes run on every value regardless of the
762
+ * cap, so a higher cap never weakens redaction, only the truncation point.
763
+ */
764
+ function handleGetPermissionInput(ws, client, msg, ctx) {
765
+ const requestId = msg.requestId
766
+ const send = (fields) => ctx.transport.send(ws, { type: 'permission_input', requestId, ...fields })
767
+ const notFound = (code, message) => send({ found: false, error: { code, message } })
768
+
769
+ const sessionId = ctx.permissions.permissionSessionMap.get(requestId)
770
+ if (!sessionId) return notFound('NOT_FOUND', 'No pending permission for that request.')
771
+
772
+ // Same authority gate as permission_response — a client may only read the
773
+ // input for a permission it could itself answer.
774
+ if (client.boundSessionId) {
775
+ if (client.boundSessionId !== sessionId) return notFound('NOT_FOUND', 'No pending permission for that request.')
776
+ } else if (!isSessionViewer(client, sessionId)) {
777
+ return notFound('NOT_FOUND', 'No pending permission for that request.')
778
+ }
779
+
780
+ const sess = ctx.sessions.sessionManager?.getSession?.(sessionId)?.session
781
+ const pending = sess?._pendingPermissions?.get(requestId)
782
+ if (!pending) return notFound('NOT_PENDING', 'That permission is no longer pending (resolved or expired).')
783
+
784
+ const tool = sess?._lastPermissionData?.get(requestId)?.tool
785
+ // #6551 — memoize the redacted pull on the pending entry so repeated pulls for
786
+ // the same requestId don't re-run the full redactDeep tree-walk + JSON.stringify
787
+ // per call. The pending entry is deleted at every resolve/timeout/abort site, so
788
+ // the memo auto-invalidates with it (no separate cache-invalidation wiring). The
789
+ // input is treated as immutable once pending, so the cached value stays correct.
790
+ if (pending._redactedPull === undefined) {
791
+ pending._redactedPull = sanitizeToolInput(pending.input, { maxChars: PULL_MAX_INPUT_CHARS })
792
+ }
793
+ return send({ found: true, tool, input: pending._redactedPull })
794
+ }
795
+
796
+ export const settingsHandlers = {
797
+ set_model: handleSetModel,
798
+ set_permission_mode: handleSetPermissionMode,
799
+ permission_response: handlePermissionResponse,
800
+ // #6543 (IDE P3 feature B): pull the full redacted tool input for a pre-write diff.
801
+ get_permission_input: handleGetPermissionInput,
802
+ query_permission_audit: handleQueryPermissionAudit,
803
+ list_providers: handleListProviders,
804
+ set_thinking_level: handleSetThinkingLevel,
805
+ set_permission_rules: handleSetPermissionRules,
806
+ // promptEvaluatorSkipPattern keeps its bespoke handler because the
807
+ // payload shape (string-or-null + pre-validation regex compile to
808
+ // surface a distinct error code) doesn't fit the boolean/string
809
+ // factory. The other three per-session settings come from the
810
+ // registry above.
811
+ set_prompt_evaluator_skip_pattern: handleSetPromptEvaluatorSkipPattern,
812
+ ...perSessionSettingHandlers,
813
+ // Skills + credential handlers split into sibling modules (audit P2-4).
814
+ ...skillsHandlers,
815
+ ...credentialHandlers,
816
+ }
817
+
818
+ export { ELIGIBLE_TOOLS, NEVER_AUTO_ALLOW }