@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,444 @@
1
+ /**
2
+ * Thin network glue for the native Gemini API provider (`gemini-byok`).
3
+ *
4
+ * Mirrors `anthropic-openai-shim.js`: exposes the minimal Anthropic-SDK-shaped
5
+ * client surface `{ messages: { stream(params, opts) } }` that `ClaudeByokSession`
6
+ * drives, backed by Google's native `v1beta` `streamGenerateContent?alt=sse`
7
+ * endpoint over Node 22's built-in `fetch` (zero extra npm dependencies).
8
+ *
9
+ * Auth rides in the `x-goog-api-key` header — NEVER in the URL query string —
10
+ * so the key cannot leak into logs, proxies, or error messages.
11
+ *
12
+ * All request/response shape translation lives in `anthropic-gemini-translate.js`.
13
+ */
14
+
15
+ import { anthropicRequestToGemini, createGeminiStreamTranslator } from './anthropic-gemini-translate.js'
16
+ import { assertHeaderSafeGeminiKey, normalizeGeminiKey, sanitizeGeminiError, scrubGeminiKey, withoutParseDiagnostic } from './gemini-key-safety.js'
17
+
18
+ export const DEFAULT_GEMINI_API_BASE_URL = 'https://generativelanguage.googleapis.com/v1beta'
19
+
20
+ /**
21
+ * Strip a leading `models/` prefix if present so callers can pass either
22
+ * `gemini-2.5-pro` or `models/gemini-2.5-pro`.
23
+ *
24
+ * @param {string} model
25
+ * @returns {string}
26
+ */
27
+ export function normalizeGeminiModelPathId(model) {
28
+ if (typeof model !== 'string') return ''
29
+ return model.trim().replace(/^models\//, '')
30
+ }
31
+
32
+ const GEMINI_LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
33
+
34
+ /**
35
+ * Validate and normalize a Gemini API base URL. Rejects non-http(s) schemes,
36
+ * embedded credentials (`user:pass@`), and query strings/fragments so an env
37
+ * override cannot smuggle secrets or redirect to arbitrary schemes. Plain `http:`
38
+ * is accepted for loopback hosts only.
39
+ *
40
+ * @param {string} [baseURL]
41
+ * @returns {string}
42
+ */
43
+ export function normalizeGeminiBaseUrl(baseURL) {
44
+ const raw = typeof baseURL === 'string' && baseURL.trim().length > 0
45
+ ? baseURL.trim()
46
+ : DEFAULT_GEMINI_API_BASE_URL
47
+ let parsed
48
+ try {
49
+ parsed = new URL(raw)
50
+ } catch {
51
+ throw new Error('Invalid Gemini API base URL')
52
+ }
53
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
54
+ throw new Error(`Invalid Gemini API base URL scheme: ${parsed.protocol}`)
55
+ }
56
+ // The API key travels in a header: plain http is allowed only to this machine.
57
+ if (parsed.protocol === 'http:' && !GEMINI_LOOPBACK_HOSTS.has(parsed.hostname.toLowerCase())) {
58
+ throw new Error('Gemini API base URL must use https unless it points at a loopback host (localhost, 127.0.0.1 or [::1])')
59
+ }
60
+ if (parsed.username || parsed.password) {
61
+ throw new Error('Gemini API base URL must not contain embedded credentials')
62
+ }
63
+ if (parsed.search || parsed.hash || raw.includes('?') || raw.includes('#')) {
64
+ throw new Error('Gemini API base URL must not contain a query string or fragment')
65
+ }
66
+ return raw.replace(/\/+$/, '')
67
+ }
68
+
69
+ /**
70
+ * Build the streaming endpoint URL for a Gemini model.
71
+ *
72
+ * @param {string} baseURL
73
+ * @param {string} model
74
+ * @returns {string}
75
+ */
76
+ export function buildGeminiStreamUrl(baseURL, model) {
77
+ const root = normalizeGeminiBaseUrl(baseURL)
78
+ const modelId = normalizeGeminiModelPathId(model)
79
+ if (!modelId) {
80
+ throw new Error('Gemini API request requires a non-empty model id')
81
+ }
82
+ return `${root}/models/${encodeURIComponent(modelId)}:streamGenerateContent?alt=sse`
83
+ }
84
+
85
+ // Stream bounds. A real Gemini event is a few KB (a long answer chunk, at most a
86
+ // few hundred KB with a large tool argument or inline image); these are far above
87
+ // that and far below anything that threatens the daemon's memory. Each is checked
88
+ // BEFORE the bytes are concatenated or parsed.
89
+ export const GEMINI_STREAM_LIMITS = Object.freeze({
90
+ // One SSE line (UTF-16 code units). An upstream that never sends a newline would
91
+ // otherwise grow the pending buffer without bound.
92
+ maxLineChars: 1024 * 1024,
93
+ // All `data:` lines of one event, before the blank-line delimiter (UTF-16 code
94
+ // units). Bounds an upstream that sends `data:` lines but never ends the event.
95
+ maxEventChars: 4 * 1024 * 1024,
96
+ // Raw bytes of the whole response. Generous for the longest legitimate answer.
97
+ maxTotalBytes: 32 * 1024 * 1024,
98
+ // Bytes read of a non-2xx body: only a short diagnostic is built from it.
99
+ maxErrorBodyBytes: 64 * 1024,
100
+ })
101
+
102
+ // No bytes for this long ends the turn. Gemini can think for a while before the
103
+ // first token, but not for two minutes without sending anything.
104
+ export const GEMINI_STREAM_IDLE_TIMEOUT_MS = 120_000
105
+
106
+ export const GEMINI_STREAM_TOO_LARGE = 'GEMINI_STREAM_TOO_LARGE'
107
+ export const GEMINI_STREAM_STALLED = 'GEMINI_STREAM_STALLED'
108
+
109
+ function streamError(code, message) {
110
+ const err = new Error(message)
111
+ err.code = code
112
+ return err
113
+ }
114
+
115
+ const tooLarge = (what) => streamError(GEMINI_STREAM_TOO_LARGE, `Gemini response stream exceeded the ${what} size limit`)
116
+ const stalled = () => streamError(GEMINI_STREAM_STALLED, 'Gemini stream stalled: no data was received within the idle limit')
117
+
118
+ /**
119
+ * Race `promise` against an idle deadline. The timer is cleared on every exit
120
+ * path; on expiry `onStall` runs (it aborts the request) and the race rejects.
121
+ */
122
+ function withIdleDeadline(promise, idleMs, onStall) {
123
+ let timer
124
+ const deadline = new Promise((_resolve, reject) => {
125
+ timer = setTimeout(() => {
126
+ // Reject BEFORE aborting: with a real fetch the abort errors the body stream
127
+ // synchronously, and that AbortError must not win the race (it would read as a
128
+ // user Stop). The stall flag in the caller backs this up.
129
+ reject(stalled())
130
+ onStall()
131
+ }, idleMs)
132
+ })
133
+ return Promise.race([promise, deadline]).finally(() => clearTimeout(timer))
134
+ }
135
+
136
+ /**
137
+ * Uniform chunk reader over a web `ReadableStream` (getReader) or any async
138
+ * iterable of chunks. `cancel()` never waits on a read that is still pending.
139
+ */
140
+ function openChunkReader(body) {
141
+ if (typeof body?.getReader === 'function') {
142
+ const reader = body.getReader()
143
+ return {
144
+ next: () => reader.read(),
145
+ cancel: async () => { try { await reader.cancel() } catch { /* already closed */ } },
146
+ }
147
+ }
148
+ const it = body[Symbol.asyncIterator]()
149
+ return {
150
+ next: () => it.next(),
151
+ cancel: async () => {
152
+ if (typeof body.cancel === 'function') {
153
+ await body.cancel().catch(() => {})
154
+ } else if (typeof it.return === 'function') {
155
+ // Queued behind a pending read on a generator: never awaited.
156
+ Promise.resolve(it.return()).catch(() => {})
157
+ }
158
+ },
159
+ }
160
+ }
161
+
162
+ const chunkBytes = (chunk) => (typeof chunk === 'string' ? Buffer.byteLength(chunk) : (chunk?.byteLength ?? 0))
163
+
164
+ /**
165
+ * Parse a `ReadableStream<Uint8Array>` (or async iterable of chunks) carrying
166
+ * Server-Sent Events into JSON-parsed `data:` payloads.
167
+ *
168
+ * Follows the SSE spec: strips at most ONE leading space after `data:`,
169
+ * checks `signal?.aborted`, and cancels the underlying stream in `finally`
170
+ * on abort or early exit so connections do not leak.
171
+ *
172
+ * Bounded: see GEMINI_STREAM_LIMITS (checked before concatenation / parsing) and
173
+ * the idle deadline. The line scan is linear: only the new chunk is searched for
174
+ * a newline, never the accumulated buffer.
175
+ */
176
+ async function* readSseJsonEvents(body, signal, { limits = GEMINI_STREAM_LIMITS, idleMs = GEMINI_STREAM_IDLE_TIMEOUT_MS, onStall = () => {} } = {}) {
177
+ const decoder = new TextDecoder()
178
+ const reader = openChunkReader(body)
179
+ let pending = '' // the incomplete trailing line
180
+ let dataLines = []
181
+ let dataChars = 0
182
+ let totalBytes = 0
183
+
184
+ function flushEvent() {
185
+ if (dataLines.length === 0) return null
186
+ const raw = dataLines.join('\n').trim()
187
+ dataLines = []
188
+ dataChars = 0
189
+ if (!raw || raw === '[DONE]') return null
190
+ try {
191
+ return JSON.parse(raw)
192
+ } catch (err) {
193
+ throw withoutParseDiagnostic(err)
194
+ }
195
+ }
196
+
197
+ // Handle one complete line (terminator already removed); returns a parsed event or null.
198
+ function processLine(line) {
199
+ if (line.length > limits.maxLineChars) throw tooLarge('line')
200
+ if (line === '') return flushEvent()
201
+ if (line.startsWith('data:')) {
202
+ // SSE spec: remove a single leading U+0020 SPACE after `data:`, if present.
203
+ const value = line.startsWith('data: ') ? line.slice(6) : line.slice(5)
204
+ dataChars += value.length + 1
205
+ if (dataChars > limits.maxEventChars) throw tooLarge('event')
206
+ dataLines.push(value)
207
+ }
208
+ return null
209
+ }
210
+
211
+ try {
212
+ for (;;) {
213
+ const { done, value: chunk } = await withIdleDeadline(reader.next(), idleMs, onStall)
214
+ if (done) break
215
+ if (signal?.aborted) {
216
+ const abortErr = new Error('The operation was aborted')
217
+ abortErr.name = 'AbortError'
218
+ throw abortErr
219
+ }
220
+ totalBytes += chunkBytes(chunk)
221
+ if (totalBytes > limits.maxTotalBytes) throw tooLarge('response')
222
+ const text = typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true })
223
+
224
+ let pos = 0
225
+ for (;;) {
226
+ const nl = text.indexOf('\n', pos)
227
+ if (nl === -1) {
228
+ if (pending.length + (text.length - pos) > limits.maxLineChars) throw tooLarge('line')
229
+ pending += text.slice(pos)
230
+ break
231
+ }
232
+ // +1: a trailing CR is part of the terminator, not of the line.
233
+ if (pending.length + (nl - pos) > limits.maxLineChars + 1) throw tooLarge('line')
234
+ let line = pending + text.slice(pos, nl)
235
+ pending = ''
236
+ if (line.endsWith('\r')) line = line.slice(0, -1)
237
+ const parsed = processLine(line)
238
+ if (parsed !== null) yield parsed
239
+ pos = nl + 1
240
+ }
241
+ }
242
+
243
+ pending += decoder.decode()
244
+ if (pending.length > limits.maxLineChars) throw tooLarge('line')
245
+ if (pending.endsWith('\r')) pending = pending.slice(0, -1)
246
+ if (pending.length > 0) processLine(pending)
247
+ const trailing = flushEvent()
248
+ if (trailing !== null) yield trailing
249
+ } finally {
250
+ await reader.cancel()
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Read at most `maxErrorBodyBytes` of a non-2xx body as text. The rest is never
256
+ * read: the stream is cancelled once the cap is reached (the body is only used to
257
+ * build a short diagnostic).
258
+ */
259
+ async function readBoundedErrorText(res, { limits, idleMs, onStall }) {
260
+ const max = limits.maxErrorBodyBytes
261
+ if (res?.body && (typeof res.body.getReader === 'function' || typeof res.body[Symbol.asyncIterator] === 'function')) {
262
+ const reader = openChunkReader(res.body)
263
+ const parts = []
264
+ let size = 0
265
+ try {
266
+ while (size < max) {
267
+ const { done, value } = await withIdleDeadline(reader.next(), idleMs, onStall)
268
+ if (done) break
269
+ const bytes = typeof value === 'string' ? Buffer.from(value) : value
270
+ const room = max - size
271
+ parts.push(bytes.byteLength > room ? bytes.subarray(0, room) : bytes)
272
+ size += Math.min(bytes.byteLength, room)
273
+ }
274
+ } finally {
275
+ await reader.cancel()
276
+ }
277
+ return new TextDecoder().decode(Buffer.concat(parts))
278
+ }
279
+ if (typeof res?.text === 'function') {
280
+ return String(await res.text()).slice(0, max)
281
+ }
282
+ return ''
283
+ }
284
+
285
+ /**
286
+ * Build a structured upstream error from a mid-stream Gemini `{ error }` frame.
287
+ */
288
+ function buildMidStreamGeminiError(errorObj, apiKey) {
289
+ const rawMsg = typeof errorObj?.message === 'string' && errorObj.message.length > 0
290
+ ? errorObj.message
291
+ : 'Gemini stream error'
292
+ const safeMsg = scrubGeminiKey(rawMsg, apiKey, 300)
293
+ const code = Number.isInteger(errorObj?.code) ? errorObj.code : null
294
+ const err = new Error(code ? `Gemini API error (HTTP ${code}): ${safeMsg}` : `Gemini API error: ${safeMsg}`)
295
+ if (code) err.status = code
296
+ err.error = {
297
+ code: code ?? undefined,
298
+ status: typeof errorObj?.status === 'string' ? errorObj.status : undefined,
299
+ message: safeMsg,
300
+ }
301
+ return err
302
+ }
303
+
304
+ /**
305
+ * Extract a concise, redacted error message from a non-2xx Gemini API response.
306
+ */
307
+ async function buildGeminiHttpError(res, apiKey, readOpts) {
308
+ let detail = ''
309
+ try {
310
+ const text = await readBoundedErrorText(res, readOpts)
311
+ if (text) {
312
+ try {
313
+ const parsed = JSON.parse(text)
314
+ const msg = parsed?.error?.message || parsed?.[0]?.error?.message
315
+ if (typeof msg === 'string' && msg.length > 0) detail = msg
316
+ } catch {
317
+ detail = text
318
+ }
319
+ }
320
+ } catch {
321
+ // Ignore body read failures; status code alone is still actionable.
322
+ }
323
+ const safeDetail = detail ? scrubGeminiKey(detail, apiKey, 300) : ''
324
+ const status = res?.status ?? 'unknown'
325
+ const err = new Error(safeDetail ? `Gemini API error (HTTP ${status}): ${safeDetail}` : `Gemini API error (HTTP ${status})`)
326
+ err.status = res?.status
327
+ return err
328
+ }
329
+
330
+ /**
331
+ * Build a minimal Anthropic-SDK-shaped client backed by the native Gemini API.
332
+ *
333
+ * @param {{ baseURL?: string, apiKey: string, fetchFn?: typeof fetch, streamIdleTimeoutMs?: number, streamLimits?: Partial<typeof GEMINI_STREAM_LIMITS> }} cfg
334
+ * @returns {{ messages: { stream: (params: object, opts?: { signal?: AbortSignal }) => object } }}
335
+ */
336
+ export function createAnthropicGeminiShimClient({ baseURL = DEFAULT_GEMINI_API_BASE_URL, apiKey, fetchFn = fetch, streamIdleTimeoutMs = GEMINI_STREAM_IDLE_TIMEOUT_MS, streamLimits = {} }) {
337
+ const limits = { ...GEMINI_STREAM_LIMITS, ...streamLimits }
338
+ return {
339
+ messages: {
340
+ stream(params = {}, opts = {}) {
341
+ return createGeminiShimStream({ baseURL, apiKey, fetchFn, idleMs: streamIdleTimeoutMs, limits }, params, opts)
342
+ },
343
+ },
344
+ }
345
+ }
346
+
347
+ function createGeminiShimStream(cfg, params, opts) {
348
+ const userSignal = opts?.signal
349
+ // The request is also aborted by our own idle deadline, so fetch gets a signal that
350
+ // follows either; `signal` (the user's Stop) keeps its own meaning everywhere else.
351
+ const stallController = new AbortController()
352
+ const signal = userSignal
353
+ const requestSignal = userSignal ? AbortSignal.any([userSignal, stallController.signal]) : stallController.signal
354
+ let didStall = false
355
+ const onStall = () => {
356
+ didStall = true
357
+ stallController.abort()
358
+ }
359
+ const model = normalizeGeminiModelPathId(params?.model || '')
360
+ let finalMessage = null
361
+ let streamError = null
362
+
363
+ async function* iterate() {
364
+ try {
365
+ // Refuse a header-unsafe credential before any request: the runtime's own
366
+ // rejection would quote the whole value.
367
+ assertHeaderSafeGeminiKey(cfg.apiKey)
368
+ const url = buildGeminiStreamUrl(cfg.baseURL, params?.model)
369
+ const body = anthropicRequestToGemini(params)
370
+ // The alias map travels with this request: calls come back under the
371
+ // original tool names without any shared state.
372
+ const translator = createGeminiStreamTranslator({ model, toolNameMap: body.toolNameAliases })
373
+
374
+ const res = await withIdleDeadline(Promise.resolve(cfg.fetchFn(url, {
375
+ method: 'POST',
376
+ // A misconfigured endpoint fails loudly; the key header is never replayed to a redirect target.
377
+ redirect: 'error',
378
+ signal: requestSignal,
379
+ headers: {
380
+ 'content-type': 'application/json',
381
+ 'accept': 'text/event-stream',
382
+ 'x-goog-api-key': normalizeGeminiKey(cfg.apiKey),
383
+ },
384
+ body: JSON.stringify(body),
385
+ })), cfg.idleMs, onStall)
386
+
387
+ if (!res?.ok) {
388
+ throw await buildGeminiHttpError(res, cfg.apiKey, { limits: cfg.limits, idleMs: cfg.idleMs, onStall })
389
+ }
390
+
391
+ let sawCandidate = false
392
+ let blockReason = null
393
+
394
+ if (res.body) {
395
+ for await (const chunk of readSseJsonEvents(res.body, signal, { limits: cfg.limits, idleMs: cfg.idleMs, onStall })) {
396
+ if (chunk?.error && typeof chunk.error === 'object') {
397
+ throw buildMidStreamGeminiError(chunk.error, cfg.apiKey)
398
+ }
399
+ if (Array.isArray(chunk?.candidates) && chunk.candidates.length > 0) {
400
+ sawCandidate = true
401
+ }
402
+ if (typeof chunk?.promptFeedback?.blockReason === 'string' && chunk.promptFeedback.blockReason.length > 0) {
403
+ blockReason = chunk.promptFeedback.blockReason
404
+ }
405
+ for (const event of translator.push(chunk)) yield event
406
+ }
407
+ }
408
+
409
+ if (!sawCandidate && blockReason) {
410
+ const err = new Error(`Gemini prompt blocked (${scrubGeminiKey(blockReason, cfg.apiKey, 100)})`)
411
+ err.status = 400
412
+ err.error = { code: 400, status: blockReason, message: err.message }
413
+ throw err
414
+ }
415
+
416
+ const { events, finalMessage: assembled } = translator.finish()
417
+ finalMessage = assembled
418
+ for (const event of events) yield event
419
+ } catch (err) {
420
+ // Our own idle abort can surface as the request's AbortError (the body stream is
421
+ // errored by the abort). It was a stall, not a Stop, unless the user also aborted.
422
+ if (didStall && !userSignal?.aborted) err = stalled()
423
+ // Every error leaving the shim has the configured key removed by value.
424
+ streamError = sanitizeGeminiError(err, cfg.apiKey)
425
+ throw streamError
426
+ }
427
+ }
428
+
429
+ const iterable = iterate()
430
+
431
+ return {
432
+ [Symbol.asyncIterator]() {
433
+ return iterable
434
+ },
435
+ async finalMessage() {
436
+ if (streamError) throw streamError
437
+ if (finalMessage === null) {
438
+ for await (const _event of iterable) { /* drain */ }
439
+ }
440
+ if (streamError) throw streamError
441
+ return finalMessage
442
+ },
443
+ }
444
+ }