@chroxy/server 0.11.10 → 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 (153) hide show
  1. package/CONFIG.md +4 -2
  2. package/package.json +3 -3
  3. package/src/acp-session.js +5 -1
  4. package/src/agent-connections.js +12 -1
  5. package/src/agent-control/client.js +29 -0
  6. package/src/agent-control/events.js +8 -4
  7. package/src/agent-control/local-connection.js +34 -16
  8. package/src/agent-control/mcp-server.js +2 -0
  9. package/src/anthropic-compatible-config.js +1 -0
  10. package/src/anthropic-gemini-shim.js +444 -0
  11. package/src/anthropic-gemini-translate.js +1030 -0
  12. package/src/base-session.js +319 -2
  13. package/src/bound-client-policy.js +12 -0
  14. package/src/byok-mcp-config.js +9 -5
  15. package/src/byok-mcp-trust.js +34 -20
  16. package/src/byok-session.js +62 -9
  17. package/src/byok-tool-executor.js +81 -1
  18. package/src/claude-setting-sources.js +74 -0
  19. package/src/claude-tui/pty-driver.js +5 -1
  20. package/src/claude-tui/usage-limit.js +2 -2
  21. package/src/claude-tui-session.js +57 -4
  22. package/src/cli/agent-cmd.js +236 -0
  23. package/src/cli/connection-state.js +54 -0
  24. package/src/cli/freshness-cmd.js +53 -0
  25. package/src/cli/pages-cmd.js +6 -4
  26. package/src/cli/pair-code-cmd.js +7 -6
  27. package/src/cli/pair-discord-cmd.js +7 -6
  28. package/src/cli/schedule-cmd.js +25 -3
  29. package/src/cli/server-cmd.js +6 -0
  30. package/src/cli/shell-cmd.js +7 -4
  31. package/src/cli/status-cmd.js +19 -5
  32. package/src/cli-session.js +190 -11
  33. package/src/cli.js +4 -0
  34. package/src/codex-app-server-session.js +78 -17
  35. package/src/codex-error-text.js +114 -0
  36. package/src/config-dir-migration.js +11 -6
  37. package/src/config.js +23 -3
  38. package/src/connection-info.js +73 -14
  39. package/src/continuations.js +153 -40
  40. package/src/conversation-scanner.js +2 -21
  41. package/src/conversation-search.js +4 -17
  42. package/src/dev-preview.js +2 -1
  43. package/src/docker-session.js +10 -1
  44. package/src/doctor.js +14 -3
  45. package/src/durable-write.js +35 -0
  46. package/src/environments/authority.js +7 -1
  47. package/src/event-normalizer.js +35 -2
  48. package/src/folder-trust-wire.js +137 -0
  49. package/src/folder-trust-worker.js +17 -0
  50. package/src/folder-trust.js +1572 -0
  51. package/src/freshness/activity-meter.js +101 -0
  52. package/src/freshness/adapter.js +199 -0
  53. package/src/freshness/checks.js +239 -0
  54. package/src/freshness/config.js +98 -0
  55. package/src/freshness/core.js +185 -0
  56. package/src/freshness/derive.js +680 -0
  57. package/src/freshness/exchange.js +305 -0
  58. package/src/freshness/file-ledger.js +400 -0
  59. package/src/freshness/grade.js +81 -0
  60. package/src/freshness/hash.js +45 -0
  61. package/src/freshness/inbox.js +163 -0
  62. package/src/freshness/index.js +20 -0
  63. package/src/freshness/investigation.js +474 -0
  64. package/src/freshness/keys.js +177 -0
  65. package/src/freshness/ledger.js +122 -0
  66. package/src/freshness/outbox.js +131 -0
  67. package/src/freshness/policy.js +599 -0
  68. package/src/freshness/queue.js +843 -0
  69. package/src/freshness/read-errors.js +23 -0
  70. package/src/freshness/render.js +153 -0
  71. package/src/freshness/runtime.js +113 -0
  72. package/src/freshness/session-registry-adapter.js +161 -0
  73. package/src/freshness/state-file-adapter.js +167 -0
  74. package/src/freshness-runner/build-info.js +139 -0
  75. package/src/freshness-runner/cli.js +105 -0
  76. package/src/freshness-runner/run-tick.js +109 -0
  77. package/src/freshness-runner/stamp.js +57 -0
  78. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  79. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  80. package/src/freshness-sources/index.js +8 -0
  81. package/src/gemini-byok-session.js +292 -0
  82. package/src/gemini-credentials.js +67 -0
  83. package/src/gemini-key-safety.js +246 -0
  84. package/src/gemini-models.js +386 -0
  85. package/src/handler-utils.js +6 -13
  86. package/src/handlers/checkpoint-handlers.js +8 -0
  87. package/src/handlers/folder-trust-handlers.js +90 -0
  88. package/src/handlers/input-handlers.js +40 -11
  89. package/src/handlers/principal-admin-handlers.js +229 -0
  90. package/src/handlers/principal-handlers.js +262 -0
  91. package/src/handlers/scheduler-handlers.js +4 -4
  92. package/src/handlers/session-handlers.js +10 -1
  93. package/src/handlers/settings-handlers.js +42 -8
  94. package/src/handlers/skills-handlers.js +7 -0
  95. package/src/history-page.js +8 -0
  96. package/src/jsonl-reader.js +90 -10
  97. package/src/jsonl-subprocess-session.js +4 -1
  98. package/src/logger.js +105 -15
  99. package/src/mailbox-route.js +102 -0
  100. package/src/notification-prefs.js +15 -0
  101. package/src/orchestration/orchestration-manager.js +38 -9
  102. package/src/orchestration/permission-gate.js +4 -1
  103. package/src/orchestration/run-record.js +11 -0
  104. package/src/orchestration/turn-driver.js +151 -33
  105. package/src/orphan-reaper.js +77 -20
  106. package/src/outgoing-policy.js +10 -4
  107. package/src/permission-floor.js +54 -2
  108. package/src/permission-manager.js +32 -13
  109. package/src/permission-resolved-by.js +89 -0
  110. package/src/permission-resolver.js +7 -3
  111. package/src/platform.js +156 -4
  112. package/src/principal-audit.js +189 -0
  113. package/src/principal-binding.js +25 -0
  114. package/src/principal-brakes.js +21 -0
  115. package/src/principal-effect.js +101 -0
  116. package/src/principal-journal.js +905 -0
  117. package/src/principal-kill-switch.js +183 -0
  118. package/src/principal-label.js +5 -0
  119. package/src/principal-pending-permissions.js +177 -0
  120. package/src/principal-policy.js +1094 -0
  121. package/src/principal-sessions-snapshot.js +208 -0
  122. package/src/principal-store.js +488 -0
  123. package/src/principal-subscriptions.js +283 -0
  124. package/src/providers.js +2 -0
  125. package/src/redaction.js +181 -22
  126. package/src/scheduled-task-store.js +12 -0
  127. package/src/scheduler.js +304 -17
  128. package/src/sdk-session.js +60 -7
  129. package/src/server-cli/push-notification-handler.js +6 -1
  130. package/src/server-cli.js +30 -1
  131. package/src/session-ci-watcher.js +210 -37
  132. package/src/session-manager.js +590 -19
  133. package/src/session-message-history.js +121 -2
  134. package/src/session-name-allocator.js +685 -0
  135. package/src/statusline.js +78 -19
  136. package/src/summarize-session.js +2 -0
  137. package/src/turn-outcome.js +5 -2
  138. package/src/utils/argv-safety.js +29 -0
  139. package/src/utils/binary-package-manifest.js +57 -15
  140. package/src/utils/bounded-regex-worker.js +4 -0
  141. package/src/utils/bounded-regex.js +16 -7
  142. package/src/utils/pid-liveness.js +47 -0
  143. package/src/web-task-manager.js +45 -4
  144. package/src/worktree-gc.js +195 -4
  145. package/src/ws-auth.js +103 -19
  146. package/src/ws-broadcaster.js +39 -7
  147. package/src/ws-client-manager.js +8 -0
  148. package/src/ws-file-ops/browser.js +35 -3
  149. package/src/ws-forwarding.js +23 -3
  150. package/src/ws-handler-context.js +18 -0
  151. package/src/ws-history.js +79 -12
  152. package/src/ws-message-handlers.js +10 -2
  153. package/src/ws-server.js +253 -13
@@ -0,0 +1,386 @@
1
+ /**
2
+ * Gemini API model catalog, pricing table, base URL resolution, and live
3
+ * `GET /v1beta/models` discovery for `gemini-byok`.
4
+ *
5
+ * Design constraints (mirroring `ollama-tags.js` and `model-discovery.js`):
6
+ * - ADVISORY discovery, UNRESTRICTED validation on `gemini-byok`: Google
7
+ * ships new / preview models (e.g. Gemini 4 Neon) faster than static tables
8
+ * update. `GeminiByokSession.getAllowedModels()` returns `null` so any
9
+ * model id works immediately; `/v1beta/models` populates the picker with
10
+ * the live catalog and real `inputTokenLimit` context windows.
11
+ * - NEVER FABRICATE context windows or pricing: unknown models report
12
+ * `contextWindow: null` (unless returned by `/v1beta/models`) and `null`
13
+ * pricing (unless overridden in `~/.chroxy/models.json`).
14
+ * - GRACEFUL FAILURE & NO RETRY STORM: bounded timeout, debug-level failure
15
+ * logging, 5-minute TTL cache (not latched when unauthenticated), and
16
+ * single-flight dedupe.
17
+ */
18
+
19
+ import { getRegistryForProvider } from './models.js'
20
+ import { createLogger } from './logger.js'
21
+ import { DEFAULT_GEMINI_API_BASE_URL, normalizeGeminiBaseUrl } from './anthropic-gemini-shim.js'
22
+ import { geminiThinkingRoster } from './anthropic-gemini-translate.js'
23
+ import { resolveGeminiApiKey } from './gemini-credentials.js'
24
+ import { isHeaderSafeGeminiKey, normalizeGeminiKey, scrubGeminiKey, withoutParseDiagnostic } from './gemini-key-safety.js'
25
+
26
+ const log = createLogger('gemini-models')
27
+
28
+ export const GEMINI_MODELS_TIMEOUT_MS = 4000
29
+ export const GEMINI_MODELS_CACHE_TTL_MS = 5 * 60_000
30
+ const MAX_MODEL_PAGES = 5
31
+
32
+ // One `GET /models` answer is upstream-controlled and is parsed and PERSISTED, so
33
+ // every dimension of it is bounded before the catalog is built. A real page of 200
34
+ // models is a few hundred KB; these are far above that.
35
+ export const GEMINI_MODELS_LIMITS = Object.freeze({
36
+ // Raw bytes of ONE page, checked as it is read (the reader is cancelled at the cap).
37
+ maxResponseBytes: 2 * 1024 * 1024,
38
+ // Rows retained across all pages.
39
+ maxRows: 500,
40
+ // Characters of a model id, a label and a page token. A row over the id cap is
41
+ // dropped; a label over its cap falls back to the id; a page token over its cap
42
+ // ends pagination.
43
+ maxIdChars: 256,
44
+ maxLabelChars: 256,
45
+ maxPageTokenChars: 256,
46
+ })
47
+
48
+ const MODELS_TOO_LARGE = 'GEMINI_MODELS_TOO_LARGE'
49
+ const MODELS_NO_BODY = 'GEMINI_MODELS_NO_BODY'
50
+
51
+ function modelsError(code, message) {
52
+ const err = new Error(message)
53
+ err.code = code
54
+ return err
55
+ }
56
+
57
+ /**
58
+ * Read one JSON page through a reader with a byte cap, then cancel it. The cap is
59
+ * checked on each chunk BEFORE it is kept, so an oversize page is never held or
60
+ * parsed. A response with no readable body is refused rather than read unbounded.
61
+ */
62
+ async function readBoundedModelsJson(res, maxBytes) {
63
+ const body = res?.body
64
+ if (!body || typeof body.getReader !== 'function') {
65
+ throw modelsError(MODELS_NO_BODY, 'Gemini models response has no readable body')
66
+ }
67
+ const reader = body.getReader()
68
+ const parts = []
69
+ let size = 0
70
+ try {
71
+ for (;;) {
72
+ const { done, value } = await reader.read()
73
+ if (done) break
74
+ size += value?.byteLength ?? 0
75
+ if (size > maxBytes) throw modelsError(MODELS_TOO_LARGE, 'Gemini models response exceeded the size limit')
76
+ parts.push(value)
77
+ }
78
+ } finally {
79
+ try { await reader.cancel() } catch { /* already closed */ }
80
+ }
81
+ try {
82
+ return JSON.parse(new TextDecoder().decode(Buffer.concat(parts)))
83
+ } catch (err) {
84
+ throw withoutParseDiagnostic(err)
85
+ }
86
+ }
87
+
88
+ // Curated seed catalog used before live `/v1beta/models` discovery completes
89
+ // (or when offline / unauthenticated). Google's `/v1beta/models` exposes only a
90
+ // boolean `thinking` flag, not a per-model list of effort levels, so each row's
91
+ // `reasoningLevels` comes from `geminiThinkingRoster` (per model FAMILY, in the
92
+ // translator that turns a level into a request) — for the seed here and, through
93
+ // `GeminiByokSession.getModelMetadata`, for every discovered row. The
94
+ // `set_thinking_level` gate reads the row, so a row without it offers nothing.
95
+ const seedRow = (id, label, contextWindow) => Object.freeze({
96
+ id,
97
+ label,
98
+ fullId: id,
99
+ contextWindow,
100
+ ...(geminiThinkingRoster(id) || {}),
101
+ })
102
+
103
+ export const GEMINI_API_FALLBACK_MODELS = Object.freeze([
104
+ seedRow('gemini-2.5-pro', 'Gemini 2.5 Pro', 1_048_576),
105
+ seedRow('gemini-2.5-flash', 'Gemini 2.5 Flash', 1_048_576),
106
+ seedRow('gemini-2.0-flash', 'Gemini 2.0 Flash', 1_048_576),
107
+ ])
108
+
109
+ // Published Gemini API pricing (USD per MTok) for known GA models.
110
+ // Unknown / preview models (including Gemini 4 Neon until rates are finalized)
111
+ // resolve to `null` (honest unknown cost) unless overridden via
112
+ // `~/.chroxy/models.json` (`provider: "gemini-byok"`).
113
+ export const GEMINI_PRICING_USD_PER_MTOK = Object.freeze({
114
+ 'gemini-2.5-pro': Object.freeze({
115
+ input: 1.25,
116
+ output: 10.0,
117
+ cacheRead: 0.31,
118
+ cacheWrite: 0,
119
+ longContext: Object.freeze({
120
+ thresholdInputTokens: 200_000,
121
+ input: 2.50,
122
+ output: 15.0,
123
+ cacheRead: 0.625,
124
+ cacheWrite: 0,
125
+ }),
126
+ }),
127
+ 'gemini-2.5-flash': Object.freeze({
128
+ input: 0.30,
129
+ output: 2.50,
130
+ cacheRead: 0.03,
131
+ cacheWrite: 0,
132
+ }),
133
+ 'gemini-2.0-flash': Object.freeze({
134
+ input: 0.10,
135
+ output: 0.40,
136
+ cacheRead: 0.025,
137
+ cacheWrite: 0,
138
+ }),
139
+ })
140
+
141
+ /**
142
+ * Resolve and validate the Gemini API base URL.
143
+ *
144
+ * Resolution order:
145
+ * 1. CHROXY_GEMINI_BASE_URL
146
+ * 2. GEMINI_API_BASE_URL
147
+ * 3. https://generativelanguage.googleapis.com/v1beta
148
+ *
149
+ * @param {NodeJS.ProcessEnv} [env]
150
+ * @returns {string}
151
+ */
152
+ export function resolveGeminiApiBaseUrl(env = process.env) {
153
+ for (const key of ['CHROXY_GEMINI_BASE_URL', 'GEMINI_API_BASE_URL']) {
154
+ if (typeof env[key] === 'string' && env[key].trim().length > 0) {
155
+ return normalizeGeminiBaseUrl(env[key])
156
+ }
157
+ }
158
+ return DEFAULT_GEMINI_API_BASE_URL
159
+ }
160
+
161
+ /**
162
+ * Build the `GET /v1beta/models` URL from a resolved base URL, with optional
163
+ * pagination token.
164
+ *
165
+ * @param {string} baseUrl
166
+ * @param {string|null} [pageToken]
167
+ * @returns {string}
168
+ */
169
+ export function buildGeminiModelsUrl(baseUrl, pageToken = null) {
170
+ const root = normalizeGeminiBaseUrl(baseUrl)
171
+ const qs = pageToken
172
+ ? `pageSize=200&pageToken=${encodeURIComponent(pageToken)}`
173
+ : 'pageSize=200'
174
+ return `${root}/models?${qs}`
175
+ }
176
+
177
+ /**
178
+ * Parse a Google Generative Language `GET /v1beta/models` response body into
179
+ * normalized Chroxy model rows.
180
+ *
181
+ * Filters to models that support `generateContent` (excluding embedding,
182
+ * imagen, aqa, and tts-only entries that cannot serve chat turns).
183
+ *
184
+ * @param {*} body
185
+ * @returns {Array<{id:string, label:string, fullId:string, contextWindow:number|null}>|null}
186
+ */
187
+ export function parseGeminiModelsResponse(body, { maxRows = GEMINI_MODELS_LIMITS.maxRows, alreadySeen = null } = {}) {
188
+ const list = Array.isArray(body?.models) ? body.models : null
189
+ if (!list) return null
190
+
191
+ const seen = new Set()
192
+ const models = []
193
+ for (const m of list) {
194
+ if (models.length >= maxRows) break
195
+ if (!m || typeof m !== 'object') continue
196
+ const methods = Array.isArray(m.supportedGenerationMethods) ? m.supportedGenerationMethods : null
197
+ if (methods && !methods.includes('generateContent')) continue
198
+
199
+ const rawName = typeof m.name === 'string' ? m.name.trim() : ''
200
+ const id = rawName.replace(/^models\//, '')
201
+ // An id an earlier page already supplied is not a new row and costs none of this page's allowance.
202
+ if (!id || id.length > GEMINI_MODELS_LIMITS.maxIdChars || seen.has(id) || alreadySeen?.has(id)) continue
203
+ seen.add(id)
204
+
205
+ const displayName = typeof m.displayName === 'string' ? m.displayName.trim() : ''
206
+ const label = displayName.length > 0 && displayName.length <= GEMINI_MODELS_LIMITS.maxLabelChars
207
+ ? displayName
208
+ : id
209
+ const contextWindow = Number.isInteger(m.inputTokenLimit) && m.inputTokenLimit > 0
210
+ ? m.inputTokenLimit
211
+ : null
212
+
213
+ models.push({ id, label, fullId: id, contextWindow })
214
+ }
215
+
216
+ return models.length > 0 ? models : null
217
+ }
218
+
219
+ /**
220
+ * Fetch the live Gemini model list via `GET /v1beta/models` (following up to
221
+ * `MAX_MODEL_PAGES` pagination pages) using the `x-goog-api-key` header.
222
+ * Returns normalized rows or `null` on any failure.
223
+ */
224
+ export async function fetchGeminiModels({
225
+ apiKey,
226
+ baseUrl,
227
+ env = process.env,
228
+ fetchFn = fetch,
229
+ timeoutMs = GEMINI_MODELS_TIMEOUT_MS,
230
+ } = {}) {
231
+ const key = typeof apiKey === 'string' && apiKey.length > 0
232
+ ? apiKey
233
+ : resolveGeminiApiKey(env).key
234
+ if (!key) return null
235
+ if (!isHeaderSafeGeminiKey(key)) {
236
+ log.debug('gemini models probe skipped: API key is not usable (header-unsafe or too long)')
237
+ return null
238
+ }
239
+
240
+ let resolvedBase
241
+ try {
242
+ resolvedBase = baseUrl ? normalizeGeminiBaseUrl(baseUrl) : resolveGeminiApiBaseUrl(env)
243
+ } catch (err) {
244
+ log.debug(`gemini models probe skipped: ${err?.message || err}`)
245
+ return null
246
+ }
247
+
248
+ const controller = new AbortController()
249
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
250
+ try {
251
+ const seen = new Set()
252
+ const combined = []
253
+ let pageToken = null
254
+
255
+ for (let page = 0; page < MAX_MODEL_PAGES; page++) {
256
+ const url = buildGeminiModelsUrl(resolvedBase, pageToken)
257
+ const res = await fetchFn(url, {
258
+ method: 'GET',
259
+ // A misconfigured endpoint fails loudly; the key header is never replayed to a redirect target.
260
+ redirect: 'error',
261
+ signal: controller.signal,
262
+ headers: {
263
+ accept: 'application/json',
264
+ 'x-goog-api-key': normalizeGeminiKey(key),
265
+ },
266
+ })
267
+ if (!res?.ok) {
268
+ log.debug(`gemini models probe answered HTTP ${res?.status ?? 'no response'}`)
269
+ return combined.length > 0 ? combined : null
270
+ }
271
+ const body = await readBoundedModelsJson(res, GEMINI_MODELS_LIMITS.maxResponseBytes)
272
+ const parsed = parseGeminiModelsResponse(body, { maxRows: GEMINI_MODELS_LIMITS.maxRows - combined.length, alreadySeen: seen })
273
+ if (parsed) {
274
+ for (const m of parsed) {
275
+ if (seen.has(m.id)) continue
276
+ seen.add(m.id)
277
+ combined.push(m)
278
+ }
279
+ }
280
+ const next = typeof body?.nextPageToken === 'string' && body.nextPageToken.trim().length > 0
281
+ && body.nextPageToken.trim().length <= GEMINI_MODELS_LIMITS.maxPageTokenChars
282
+ ? body.nextPageToken.trim()
283
+ : null
284
+ if (!next || next === pageToken || combined.length >= GEMINI_MODELS_LIMITS.maxRows) break
285
+ pageToken = next
286
+ }
287
+
288
+ return combined.length > 0 ? combined : null
289
+ } catch (err) {
290
+ log.debug(`gemini models probe failed (${err?.name === 'AbortError' ? `timeout after ${timeoutMs}ms` : scrubGeminiKey(err?.message || err, key)})`)
291
+ return null
292
+ } finally {
293
+ clearTimeout(timer)
294
+ }
295
+ }
296
+
297
+ // Per-provider TTL cache + single-flight dedupe (keyed by providerName so
298
+ // `gemini-byok` and any other caller stay isolated).
299
+ const _slots = new Map()
300
+
301
+ function slotFor(providerName) {
302
+ let slot = _slots.get(providerName)
303
+ if (!slot) {
304
+ slot = { lastProbeAt: -Infinity, inflight: null, lastAppliedKey: null }
305
+ _slots.set(providerName, slot)
306
+ }
307
+ return slot
308
+ }
309
+
310
+ /**
311
+ * Refresh the `gemini-byok` (or specified provider) models registry from
312
+ * Google's `/v1beta/models` endpoint.
313
+ *
314
+ * Returns the updated model list when the registry changed, or `null` when
315
+ * unchanged, TTL-cached, unauthenticated, or unreachable. Does NOT latch the
316
+ * 5-minute negative cache when no API key is configured, so saving a key in
317
+ * Settings enables immediate discovery on the next probe. Never throws.
318
+ */
319
+ export async function refreshGeminiModels({
320
+ providerName = 'gemini-byok',
321
+ apiKey,
322
+ baseUrl,
323
+ env = process.env,
324
+ fetchFn = fetch,
325
+ timeoutMs = GEMINI_MODELS_TIMEOUT_MS,
326
+ force = false,
327
+ now = Date.now,
328
+ } = {}) {
329
+ const key = typeof apiKey === 'string' && apiKey.length > 0
330
+ ? apiKey
331
+ : resolveGeminiApiKey(env).key
332
+ if (!key) return null
333
+
334
+ const slot = slotFor(providerName)
335
+ if (slot.inflight) return slot.inflight
336
+ if (!force && now() - slot.lastProbeAt < GEMINI_MODELS_CACHE_TTL_MS) {
337
+ return null
338
+ }
339
+
340
+ const run = (async () => {
341
+ try {
342
+ const discovered = await fetchGeminiModels({ apiKey: key, baseUrl, env, fetchFn, timeoutMs })
343
+ slot.lastProbeAt = now()
344
+ if (!discovered || discovered.length === 0) return null
345
+
346
+ const appliedKey = discovered
347
+ .map((m) => `${m.id}:${m.label}:${m.contextWindow ?? ''}`)
348
+ .join('|')
349
+ if (appliedKey === slot.lastAppliedKey) return null
350
+
351
+ const registry = getRegistryForProvider(providerName)
352
+ registry.updateModels(
353
+ discovered.map((m) => ({
354
+ value: m.id,
355
+ displayName: m.label,
356
+ contextWindow: m.contextWindow,
357
+ })),
358
+ )
359
+ if (typeof registry.saveCache === 'function') {
360
+ try { registry.saveCache() } catch { /* best-effort cache persist */ }
361
+ }
362
+ slot.lastAppliedKey = appliedKey
363
+ return registry.getModels()
364
+ } catch (err) {
365
+ // Fixed text plus at most a safe status or code: the message can hold anything.
366
+ const safe = Number.isInteger(err?.status)
367
+ ? ` (HTTP ${err.status})`
368
+ : (typeof err?.code === 'string' && /^[A-Z0-9_]{1,64}$/.test(err.code) ? ` (${err.code})` : '')
369
+ log.debug(`refreshGeminiModels(${providerName}) failed; details withheld${safe}`)
370
+ slot.lastProbeAt = now()
371
+ return null
372
+ } finally {
373
+ slot.inflight = null
374
+ }
375
+ })()
376
+
377
+ slot.inflight = run
378
+ return run
379
+ }
380
+
381
+ /**
382
+ * Test-only hook: reset the discovery TTL cache.
383
+ */
384
+ export function _resetGeminiModelsCacheForTest() {
385
+ _slots.clear()
386
+ }
@@ -16,6 +16,7 @@ import { resolveClaudeConfigDirOverride } from './utils/claude-config-dir.js'
16
16
  import { canonicalName, segmentName } from './permission-floor.js'
17
17
  import { getProviderPermissionModeSupport } from './permission-mode-support.js'
18
18
  import { isBoundClient, isBoundToOtherSession } from './environments/authority.js'
19
+ import { publicBoundSessionId } from './principal-binding.js'
19
20
 
20
21
  const log = createLogger('handler-utils')
21
22
 
@@ -882,17 +883,6 @@ export function validateCwdWithinHome(cwd) {
882
883
  // Exported for tests
883
884
  export { FORBIDDEN_HOME_SUBDIRS }
884
885
 
885
- /**
886
- * Check whether a connected WS client declared a specific capability during auth.
887
- *
888
- * @param {WebSocket} ws - The WebSocket connection object
889
- * @param {string} capability - The capability string to check
890
- * @returns {boolean} true if the client declared the capability, false otherwise
891
- */
892
- export function clientHasCapability(ws, capability) {
893
- return ws.clientCapabilities?.has(capability) ?? false
894
- }
895
-
896
886
  /** Broadcast client_focus_changed to other clients when a client's active session changes */
897
887
  export function broadcastFocusChanged(client, sessionId, ctx) {
898
888
  ctx.transport.broadcast(
@@ -909,7 +899,9 @@ export function broadcastFocusChanged(client, sessionId, ctx) {
909
899
  export function autoSubscribeOtherClients(sessionId, excludeWs, ctx) {
910
900
  for (const [clientWs, c] of ctx.transport.clients) {
911
901
  if (c.authenticated && clientWs !== excludeWs) {
912
- // A client bound to another session is never subscribed to a new one.
902
+ // A client bound to another session is never subscribed to a new one. This also skips an
903
+ // agent principal (sentinel binding): deliberate and fail-closed in S2, pinned by
904
+ // tests/principal-dispatch-wiring.test.js; S3 changes it on purpose.
913
905
  if (isBoundToOtherSession(c, sessionId)) continue
914
906
  // #5563: route through the index-maintaining helper so the
915
907
  // sessionId→clients reverse index stays in sync. Falls back to a bare
@@ -1149,7 +1141,8 @@ export function buildSessionTokenMismatchPayload({
1149
1141
  boundSessionId = null,
1150
1142
  message = SESSION_TOKEN_MISMATCH_DEFAULT_MESSAGE,
1151
1143
  } = {}) {
1152
- const normalisedBoundId = typeof boundSessionId === 'string' && boundSessionId ? boundSessionId : null
1144
+ // #9116: a principal's sentinel binding is never serialized: it reads as no binding.
1145
+ const normalisedBoundId = publicBoundSessionId(boundSessionId)
1153
1146
  let boundSessionName = null
1154
1147
  if (normalisedBoundId && sessionManager && typeof sessionManager.getSession === 'function') {
1155
1148
  const entry = sessionManager.getSession(normalisedBoundId)
@@ -187,6 +187,14 @@ async function handleRestoreCheckpoint(ws, client, msg, ctx) {
187
187
  // checkpoint WITHOUT touching the working tree.
188
188
  let checkpoint
189
189
  if (restoreFiles) {
190
+ // #9242: a person is about to rewrite this session's working tree. Claim it for
191
+ // them BEFORE the first await (the restore waits on a directory lock and async
192
+ // git): a scheduled fire that becomes due meanwhile must not drive it, and a
193
+ // task must not own or later adopt it. Both link forms, one entry point.
194
+ // Only once the (synchronous) checks above have passed and the connection is
195
+ // still authorized: a refused or unauthorized restore must not cost the task its
196
+ // session. The restore re-asserts the same authority itself (isAuthorized below).
197
+ if (stillAuthorized(authorizedFor(ctx, client))) ctx.sessions.sessionManager?.releaseScheduledTaskLink?.(sid)
190
198
  checkpoint = await ctx.services.checkpointManager.restoreCheckpoint(sid, msg.checkpointId, { isAuthorized: authorizedFor(ctx, client) })
191
199
  } else {
192
200
  checkpoint = ctx.services.checkpointManager.getCheckpoint(sid, msg.checkpointId)
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Handlers: trust_folder, untrust_folder.
3
+ *
4
+ * Trusting a folder lets its project settings (MCP servers, hooks, status line,
5
+ * agents, skills, commands) run, so it is PRIMARY-ONLY: the primary API token,
6
+ * on a connection that is not bound to a session and carries no agent principal
7
+ * (the bar `add_mcp_server` holds, plus the unbound requirement). Everyone else
8
+ * gets a typed error before the session is looked up.
9
+ *
10
+ * The folder is ALWAYS the cwd in the server's record of `sessionId`. The
11
+ * message carries no path; a `cwd` or `path` field on it is ignored.
12
+ */
13
+
14
+ import { sendError } from '../handler-utils.js'
15
+ import { isBoundClient } from '../environments/authority.js'
16
+ import { sessionLogger } from '../logger.js'
17
+ import { trustFolder, untrustFolder, getFolderTrustStatusForReply } from '../folder-trust.js'
18
+ import { broadcastFolderTrustState } from '../folder-trust-wire.js'
19
+
20
+ /** @returns {boolean} true when the caller was refused (the handler must return). */
21
+ export function rejectFolderTrustUnlessPrimary(ws, client, msg, ctx, op) {
22
+ if (client?.isPrimaryToken === true && !isBoundClient(client)) return false
23
+ sessionLogger(client?.boundSessionId).warn(
24
+ `Client ${client?.id} attempted ${op} — rejected (folder trust needs the primary token on an unbound connection)`,
25
+ )
26
+ sendError(
27
+ ws,
28
+ msg?.requestId,
29
+ 'FOLDER_TRUST_FORBIDDEN',
30
+ 'Only the primary API token, on a connection not bound to a session, can change which folders are trusted.',
31
+ sessionTag(msg),
32
+ ctx,
33
+ )
34
+ return true
35
+ }
36
+
37
+ const sessionTag = (msg) => (typeof msg?.sessionId === 'string' && msg.sessionId.length <= 256 ? { sessionId: msg.sessionId } : undefined)
38
+
39
+ function makeHandler(op, apply, logVerb) {
40
+ return async function handleFolderTrust(ws, client, msg, ctx) {
41
+ if (rejectFolderTrustUnlessPrimary(ws, client, msg, ctx, op)) return
42
+ const requestId = msg?.requestId
43
+ const sessionId = typeof msg?.sessionId === 'string' ? msg.sessionId : ''
44
+ const entry = sessionId ? ctx.sessions?.sessionManager?.getSession(sessionId) : null
45
+ const cwd = entry?.cwd ?? entry?.session?.cwd
46
+ if (!entry || typeof cwd !== 'string' || cwd === '') {
47
+ sendError(ws, requestId, 'FOLDER_TRUST_NOT_APPLIED', `${op} needs a known session`, sessionTag(msg), ctx)
48
+ return
49
+ }
50
+ let result
51
+ try {
52
+ result = await apply(cwd, msg)
53
+ } catch (err) {
54
+ sessionLogger(sessionId).warn(`${op} failed for ${cwd}: ${err?.message || err}`)
55
+ // Report the state the folder is really in now, and tell every session of it.
56
+ const current = await getFolderTrustStatusForReply(cwd)
57
+ ctx.transport.send(ws, {
58
+ type: 'folder_trust_result',
59
+ sessionId,
60
+ ok: false,
61
+ status: current.status,
62
+ error: 'The trust change could not be saved',
63
+ ...(requestId ? { requestId } : {}),
64
+ })
65
+ await broadcastFolderTrustState(ctx, current.realPath)
66
+ return
67
+ }
68
+ if (result.ok) {
69
+ // The path is logged; the summary (commands, args) is not.
70
+ sessionLogger(sessionId).info(`Folder ${result.realPath} ${logVerb} by ${client.id} (session ${sessionId})`)
71
+ ctx.transport.send(ws, {
72
+ type: 'folder_trust_result',
73
+ sessionId,
74
+ ok: true,
75
+ status: result.status,
76
+ ...(requestId ? { requestId } : {}),
77
+ })
78
+ } else {
79
+ sessionLogger(sessionId).warn(`${op} refused for ${result.realPath ?? cwd}: ${result.code}`)
80
+ sendError(ws, requestId, result.code || 'FOLDER_TRUST_NOT_APPLIED', result.error || 'The trust change was not applied', { sessionId }, ctx)
81
+ }
82
+ if (result.realPath) await broadcastFolderTrustState(ctx, result.realPath)
83
+ }
84
+ }
85
+
86
+ export const folderTrustHandlers = {
87
+ // The digest is the one the owner reviewed: trustFolder rescans and refuses if it moved.
88
+ trust_folder: makeHandler('trust_folder', (cwd, msg) => trustFolder(cwd, msg?.digest), 'trusted'),
89
+ untrust_folder: makeHandler('untrust_folder', (cwd) => untrustFolder(cwd), 'no longer trusted'),
90
+ }
@@ -12,6 +12,7 @@ import { validateAttachments, resolveFileRefAttachments, resolveSession, sendErr
12
12
  import { evaluateDraft as defaultEvaluateDraft, shouldSkipEvaluator, shouldSkipEvaluatorAsync } from '../prompt-evaluator.js'
13
13
  import { PushManager } from '../push.js'
14
14
  import { isBoundClient } from '../environments/authority.js'
15
+ import { isPrincipalClient, refusePrincipalHandler, sendPrincipalRefusal } from '../principal-policy.js'
15
16
  import { createLogger, sessionLogger } from '../logger.js'
16
17
  import { answerDigest } from '../question-route-map.js'
17
18
  import { INPUT_CONTEXT_CAPABILITIES, InputContextError, prepareInputContext } from '../input-context.js'
@@ -319,6 +320,10 @@ function buildInputConflictError(sessionId, clientMessageId, message = INPUT_CON
319
320
  }
320
321
 
321
322
  async function handleInput(ws, client, msg, ctx) {
323
+ // An agent principal never falls into the host path below: its target is
324
+ // resolved from an EXPLICIT sessionId through principalMaySee (no activeSessionId
325
+ // fallback) and the branch always returns (contract §3.1 item 6).
326
+ if (isPrincipalClient(client)) return refusePrincipalHandler(ws, client, msg, ctx, 'steer')
322
327
  const text = msg.data
323
328
  let attachments = Array.isArray(msg.attachments) ? msg.attachments : undefined
324
329
  const targetSessionId = msg.sessionId || client.activeSessionId
@@ -378,17 +383,6 @@ async function handleInput(ws, client, msg, ctx) {
378
383
  return
379
384
  }
380
385
 
381
- // #8301: a person just typed into this session. Record the INTENT here, at
382
- // receipt: synchronously, before any await or dispatch, and whether or not the
383
- // input is later rejected, queued or deduped. It must not wait for admission
384
- // (`recordUserInput` runs at admission for correlated input, which a provider
385
- // may reach only after awaiting its transport): input sent BEFORE a Stop could
386
- // otherwise be admitted after it and silently undo it. An empty send is not
387
- // intent.
388
- if ((typeof text === 'string' && text.trim().length > 0) || attachments?.length) {
389
- ctx.sessions.sessionManager?.recordUserIntent?.(targetSessionId)
390
- }
391
-
392
386
  // Only negotiated clients receive the new acknowledgement/dedup behavior.
393
387
  // An explicit context envelope also opts in by construction. This keeps the
394
388
  // observable plain-input behavior unchanged for deployed older clients.
@@ -523,6 +517,9 @@ async function handleInput(ws, client, msg, ctx) {
523
517
  }
524
518
 
525
519
  if (ctx.sessions.sessionManager.isBudgetPaused(targetSessionId)) {
520
+ // A budget-paused rejection is still a person typing (#8301): the reservation
521
+ // site below is never reached, so record the intent here.
522
+ ctx.sessions.sessionManager?.recordUserIntent?.(targetSessionId)
526
523
  sendSessionError(ws, ctx, 'Session is paused — cost budget exceeded. Use "Resume Budget" to continue.')
527
524
  if (supportsInputAck) {
528
525
  sendInputRejectionAck(ws, ctx, targetSessionId, msg, 'budget_paused', 'The input was not dispatched because the session budget is paused.')
@@ -598,6 +595,16 @@ async function handleInput(ws, client, msg, ctx) {
598
595
  }
599
596
  const inputRecord = reservation.record
600
597
 
598
+ // #8301 / #8329: a person just typed into this session. Record the INTENT here,
599
+ // once the input is a NEW one (the empty-input return and the duplicate /
600
+ // payload_mismatch / expired / capacity rejections above have already run), so a
601
+ // client's retransmit of input sent before a Stop cannot undo that Stop. Nothing
602
+ // between receipt and this line awaits, so it still lands before any dispatch or
603
+ // admission wait: input sent BEFORE a Stop cannot be admitted after it and
604
+ // silently undo it. A context-only send counts. A budget-paused rejection
605
+ // records at its own return above.
606
+ ctx.sessions.sessionManager?.recordUserIntent?.(targetSessionId)
607
+
601
608
  // #3666 — hoist the per-session evaluator-await lock check above the
602
609
  // routing logic so trivial-skip-path messages also reject during an
603
610
  // in-flight evaluator round-trip. Without this, a fast trivial draft
@@ -1072,6 +1079,8 @@ async function handleInput(ws, client, msg, ctx) {
1072
1079
  }
1073
1080
 
1074
1081
  function handleInterrupt(ws, client, msg, ctx) {
1082
+ // Principal branch: explicit sessionId through principalMaySee, never the host path.
1083
+ if (isPrincipalClient(client)) return refusePrincipalHandler(ws, client, msg, ctx, 'drive')
1075
1084
  const interruptSessionId = msg.sessionId || client.activeSessionId
1076
1085
  const entry = resolveSession(ctx, msg, client)
1077
1086
  if (entry) {
@@ -1081,6 +1090,8 @@ function handleInterrupt(ws, client, msg, ctx) {
1081
1090
  // #8374/#8430: record that the USER stopped this turn, before the abort
1082
1091
  // resolves any open prompt (a failed turn aborts the same controller).
1083
1092
  entry.session.markUserStopInFlight?.()
1093
+ // #9241: and for the stop-before-reply marker, which is separate on purpose.
1094
+ entry.session.markStopRequested?.()
1084
1095
  entry.session.interrupt()
1085
1096
  return
1086
1097
  }
@@ -1363,6 +1374,12 @@ function handleNotificationPrefsGet(ws, client, msg, ctx) {
1363
1374
  }
1364
1375
 
1365
1376
  function handleNotificationPrefsSet(ws, client, msg, ctx) {
1377
+ // Host-wide notification routing is never delegated to an agent principal. This
1378
+ // handler carries no other client-authority check (S2 adds the principal one).
1379
+ if (isPrincipalClient(client)) {
1380
+ sendPrincipalRefusal(ws, client, msg, ctx, 'handler')
1381
+ return
1382
+ }
1366
1383
  if (!ctx.services.pushManager) {
1367
1384
  sendError(ws, msg?.requestId, 'NOT_AVAILABLE', 'notification prefs unavailable (no push manager)', undefined, ctx)
1368
1385
  return
@@ -1534,6 +1551,10 @@ function handleUserQuestionResponse(ws, client, msg, ctx) {
1534
1551
 
1535
1552
  const entry = ctx.sessions.sessionManager.getSession(questionSessionId)
1536
1553
  if (entry && typeof entry.session.respondToQuestion === 'function' && typeof msg.answer === 'string') {
1554
+ // #9242: a person answering a session's question is taking part in its
1555
+ // conversation: a scheduled task stops owning the session, exactly as when they
1556
+ // type. Before delivery, so the turn their answer resumes is already theirs.
1557
+ ctx.sessions.sessionManager?.recordUserIntent?.(questionSessionId)
1537
1558
  // #4604: log the incoming response shape so a multi-question form
1538
1559
  // wedge is correlatable from chroxy.log alone (toolUseId + map-key
1539
1560
  // count distinguishes the SDK's per-question form from the TUI's
@@ -1616,6 +1637,14 @@ function handleUserQuestionResponse(ws, client, msg, ctx) {
1616
1637
  // Only claude-tui sessions expose writeTerminalInput; other providers have no PTY,
1617
1638
  // so the keystroke is silently dropped for them.
1618
1639
  function handleTerminalInput(ws, client, msg, ctx) {
1640
+ // Raw keystrokes into a PTY are never delegated to an agent principal. The
1641
+ // user-shell check below applies to user-shell sessions only, so this refusal is
1642
+ // unconditional and first (a principal reaches a PTY only through the fenced
1643
+ // sendMessage path of the input contract).
1644
+ if (isPrincipalClient(client)) {
1645
+ sendPrincipalRefusal(ws, client, msg, ctx, 'handler')
1646
+ return
1647
+ }
1619
1648
  const sid = msg.sessionId || client.activeSessionId
1620
1649
  const entry = resolveSession(ctx, msg, client)
1621
1650
  if (!entry) {