@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,292 @@
1
+ /**
2
+ * Native Gemini API provider (`gemini-byok`) — talks directly to Google's
3
+ * Generative Language API (`v1beta` `streamGenerateContent?alt=sse`) using a
4
+ * user-supplied `GEMINI_API_KEY` (or `GOOGLE_API_KEY`). No `gemini` CLI binary,
5
+ * no OAuth, no `-y` auto-approve bypass — Chroxy IS the agent.
6
+ *
7
+ * Reuses `ClaudeByokSession`'s entire agent loop (streaming, built-in tools
8
+ * Read/Write/Edit/Bash/Glob/Grep, PermissionManager + permission-floor.js,
9
+ * MCP fleet, AGENTS.md project instruction projection, history rollback, cost
10
+ * calculation, thinking bubbles) by swapping the BYOK subclass seams and
11
+ * driving `createAnthropicGeminiShimClient` (`anthropic-gemini-shim.js` +
12
+ * `anthropic-gemini-translate.js`).
13
+ *
14
+ * Key differences from the CLI `gemini` provider (`gemini-session.js`):
15
+ * - Full multi-turn conversation continuity with rollback on Stop/error.
16
+ * - Full `PermissionManager` + `permission-floor.js` gating on every tool call.
17
+ * - Unrestricted model selection (`getAllowedModels() => null`) + live
18
+ * `/v1beta/models` catalog discovery so new / preview models (including
19
+ * Gemini 4 Neon) work immediately with real `inputTokenLimit` context windows.
20
+ * - Preserves Gemini `thoughtSignature` across multi-turn function calls and
21
+ * streams `thought: true` parts as live `thinking` bubbles.
22
+ * - Supports programmatic `thinkingLevel` forwarding (model-aware: `thinkingBudget`
23
+ * for Gemini 2.5, `thinkingLevel` for Gemini 3+/4+, omitted on legacy 1.5/2.0).
24
+ */
25
+
26
+ import { ClaudeByokSession } from './byok-session.js'
27
+ import { createAnthropicGeminiShimClient } from './anthropic-gemini-shim.js'
28
+ import { geminiThinkingRoster } from './anthropic-gemini-translate.js'
29
+ import { resolveGeminiApiKey } from './gemini-credentials.js'
30
+ import {
31
+ GEMINI_API_FALLBACK_MODELS,
32
+ GEMINI_PRICING_USD_PER_MTOK,
33
+ resolveGeminiApiBaseUrl,
34
+ refreshGeminiModels,
35
+ } from './gemini-models.js'
36
+ import { getRegistryForProvider } from './models.js'
37
+ import { BILLING_CLASSES } from './billing-class.js'
38
+ import { LEGACY_DEFAULT_THINKING_LEVEL } from '@chroxy/protocol'
39
+
40
+ const DEFAULT_GEMINI_API_MODEL = 'gemini-2.5-pro'
41
+ const GEMINI_DEPRECATED_SEED_IDS = Object.freeze(new Set())
42
+
43
+ export class GeminiByokSession extends ClaudeByokSession {
44
+ // NOT Claude-family — rides ClaudeByokSession's agent loop with its own
45
+ // Gemini model catalog and unrestricted model ids (`getAllowedModels() => null`).
46
+ static claudeFamily = false
47
+
48
+ // Explicit AgentConnectionRegistry API route isolation (`GEMINI_API_KEY`).
49
+ static agentConnectionRoutes = ['api']
50
+ static agentConnectionCredentialKey = 'GEMINI_API_KEY'
51
+
52
+ static get displayLabel() {
53
+ return 'Google Gemini (API key)'
54
+ }
55
+
56
+ static get dataDir() {
57
+ // Pure HTTPS to generativelanguage.googleapis.com — no local CLI dir.
58
+ return null
59
+ }
60
+
61
+ static get capabilities() {
62
+ return {
63
+ ...ClaudeByokSession.capabilities,
64
+ // The `set_thinking_level` gate takes its roster from each model's registry
65
+ // row (`getModelMetadata` below), so a model with no thinking control — and
66
+ // Gemini 1.5 / 2.0 — refuses every level rather than sending one the API
67
+ // would reject.
68
+ thinkingLevel: true,
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Connection readiness must use the SAME resolver, and so the same precedence,
74
+ * as a direct session: `GEMINI_API_KEY`, then `GOOGLE_API_KEY`, then the stored
75
+ * key and its legacy alias. The generic resolver knows only the one declared key
76
+ * name. Never returns or logs the key beyond `value`, which the registry only
77
+ * tests for presence.
78
+ *
79
+ * @returns {{ value: string|null, source: 'env' | 'store' | 'unset' }}
80
+ */
81
+ static resolveAgentConnectionCredential() {
82
+ const resolved = resolveGeminiApiKey()
83
+ if (!resolved.key) return { value: null, source: 'unset' }
84
+ return { value: resolved.key, source: resolved.source === 'env' ? 'env' : 'store' }
85
+ }
86
+
87
+ static get preflight() {
88
+ return {
89
+ label: 'Gemini API',
90
+ credentials: {
91
+ envVars: ['GEMINI_API_KEY', 'GOOGLE_API_KEY'],
92
+ hint: 'set GEMINI_API_KEY (or GOOGLE_API_KEY) or store GEMINI_API_KEY in ~/.chroxy/credentials.json (mode 0600)',
93
+ optional: false,
94
+ },
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Resolve runtime auth state for the dashboard and `chroxy doctor`.
100
+ *
101
+ * @param {NodeJS.ProcessEnv} env
102
+ * @param {{ cachedResolveCredentialFile?: Function }} helpers
103
+ */
104
+ static resolveAuth(env, helpers) {
105
+ const credSpec = this.preflight.credentials
106
+ const envVars = credSpec.envVars
107
+ const hint = credSpec.hint
108
+ const safeEnv = env && typeof env === 'object' ? env : {}
109
+ let matchedVar = null
110
+ let matchedVal = null
111
+ for (const v of envVars) {
112
+ if (typeof safeEnv[v] === 'string' && safeEnv[v].trim().length > 0) {
113
+ matchedVar = v
114
+ matchedVal = safeEnv[v].trim()
115
+ break
116
+ }
117
+ }
118
+ // Include the matched env var name in the cache key so switching between
119
+ // GEMINI_API_KEY and GOOGLE_API_KEY with the same key value never returns
120
+ // a stale `envVar` field.
121
+ const cacheKey = matchedVar ? `${matchedVar}:${matchedVal}` : undefined
122
+ const resolved = typeof helpers?.cachedResolveCredentialFile === 'function'
123
+ ? helpers.cachedResolveCredentialFile(
124
+ 'gemini-byok',
125
+ cacheKey,
126
+ () => resolveGeminiApiKey(safeEnv),
127
+ 'GEMINI_API_KEY / GOOGLE_API_KEY',
128
+ )
129
+ : resolveGeminiApiKey(safeEnv)
130
+
131
+ if (resolved?.key) {
132
+ const sourceLabel = resolved.source === 'env'
133
+ ? `${resolved.envVar || 'GEMINI_API_KEY'} set`
134
+ : resolved.source === 'store'
135
+ ? 'GEMINI_API_KEY in the credential store'
136
+ : 'legacy geminiApiKey in ~/.chroxy/credentials.json'
137
+ // `source` is the closed wire enum ('env' | 'oauth' | 'none'), where 'env'
138
+ // means "an API key" whichever way it was found. WHERE the key came from is
139
+ // said by `envVar` (null unless an env var supplied it) and `detail`.
140
+ return {
141
+ ready: true,
142
+ source: 'env',
143
+ envVar: resolved.source === 'env' ? (resolved.envVar || 'GEMINI_API_KEY') : null,
144
+ envVars,
145
+ hint: '',
146
+ detail: `Google Gemini API (${sourceLabel} — per-token billing)`,
147
+ billingClass: BILLING_CLASSES.API_KEY,
148
+ }
149
+ }
150
+ return {
151
+ ready: false,
152
+ source: 'none',
153
+ envVar: null,
154
+ envVars,
155
+ hint,
156
+ detail: `Google Gemini API (${resolved?.reason || hint})`,
157
+ billingClass: BILLING_CLASSES.API_KEY,
158
+ }
159
+ }
160
+
161
+ static getFallbackModels() {
162
+ return GEMINI_API_FALLBACK_MODELS
163
+ }
164
+
165
+ /**
166
+ * Deprecation roster for in-repo seed models (#7731 / #7788). Any seed id
167
+ * dropped by Google's live `/v1beta/models` catalog must be recorded here
168
+ * (or removed from `GEMINI_API_FALLBACK_MODELS`) so the seed cannot silently
169
+ * rot behind live discovery.
170
+ */
171
+ static get deprecatedSeedModelIds() {
172
+ return GEMINI_DEPRECATED_SEED_IDS
173
+ }
174
+
175
+ static getAllowedModels() {
176
+ // Unrestricted: any model id accepted by Google's Gemini API (including new
177
+ // or preview releases like Gemini 4 Neon) passes through verbatim.
178
+ return null
179
+ }
180
+
181
+ static getModelMetadata(modelId) {
182
+ if (typeof modelId !== 'string' || modelId.length === 0) return null
183
+ // The thinking roster is per model family and applies to a discovered id as
184
+ // much as a seeded one; absent (not empty) for a model with no thinking control.
185
+ const roster = geminiThinkingRoster(modelId)
186
+ const hit = GEMINI_API_FALLBACK_MODELS.find((m) => m.id === modelId || m.fullId === modelId)
187
+ if (hit) {
188
+ return {
189
+ id: hit.id,
190
+ label: hit.label,
191
+ fullId: hit.fullId,
192
+ contextWindow: hit.contextWindow,
193
+ ...(roster || {}),
194
+ }
195
+ }
196
+ // Never fabricate a context window for an unknown model id; live
197
+ // `/v1beta/models` discovery supplies the real `inputTokenLimit`.
198
+ return { id: modelId, label: modelId, fullId: modelId, contextWindow: null, ...(roster || {}) }
199
+ }
200
+
201
+ /**
202
+ * Dynamic model discovery hook — `ws-history` and `start()` invoke this
203
+ * (fire-and-forget) to populate the picker from `GET /v1beta/models`.
204
+ */
205
+ static refreshModels(opts) {
206
+ return refreshGeminiModels({ providerName: 'gemini-byok', ...opts })
207
+ }
208
+
209
+ constructor(opts = {}) {
210
+ // Spread-forward every BaseSession + BYOK opt and force `provider: 'gemini-byok'`.
211
+ super({ ...opts, provider: 'gemini-byok' })
212
+ this._thinkingLevel = typeof opts.thinkingLevel === 'string' && opts.thinkingLevel.length > 0
213
+ ? opts.thinkingLevel
214
+ : null
215
+ }
216
+
217
+ get thinkingLevel() {
218
+ return this._thinkingLevel
219
+ }
220
+
221
+ /**
222
+ * Set the active thinking level for subsequent turns (model-defined effort
223
+ * string, or `null` to let the model decide).
224
+ *
225
+ * @param {string|null} level
226
+ */
227
+ setThinkingLevel(level) {
228
+ // `default` is the roster's "model decides" entry: no override of our own.
229
+ this._thinkingLevel = typeof level === 'string' && level.length > 0 && level !== LEGACY_DEFAULT_THINKING_LEVEL
230
+ ? level
231
+ : null
232
+ }
233
+
234
+ /**
235
+ * Reset active `thinkingLevel` when switching models so a level configured
236
+ * for a thinking-capable model does not leak onto a non-thinking model.
237
+ */
238
+ _onModelChanged() {
239
+ if (this._thinkingLevel !== null) {
240
+ this._thinkingLevel = null
241
+ this.emit('thinking_level_changed', { level: null })
242
+ }
243
+ }
244
+
245
+ async start() {
246
+ await super.start()
247
+ if (!this._processReady || this._destroying) return
248
+ refreshGeminiModels({ providerName: 'gemini-byok' })
249
+ .then((models) => {
250
+ if (!this._destroying && Array.isArray(models) && models.length > 0) {
251
+ this.emit('models_updated', { models })
252
+ }
253
+ })
254
+ .catch(() => {})
255
+ }
256
+
257
+ // --- ClaudeByokSession seam overrides ---
258
+
259
+ get _defaultModel() {
260
+ const envDefault = process.env.CHROXY_GEMINI_DEFAULT_MODEL
261
+ if (typeof envDefault === 'string' && envDefault.trim().length > 0) {
262
+ return envDefault.trim()
263
+ }
264
+ return DEFAULT_GEMINI_API_MODEL
265
+ }
266
+
267
+ _resolveCredentials() {
268
+ return resolveGeminiApiKey()
269
+ }
270
+
271
+ _buildClient(apiKey) {
272
+ return createAnthropicGeminiShimClient({
273
+ baseURL: resolveGeminiApiBaseUrl(),
274
+ apiKey,
275
+ })
276
+ }
277
+
278
+ _buildStreamParams(params) {
279
+ if (!this._thinkingLevel) return params
280
+ return {
281
+ ...params,
282
+ thinking: { thinkingLevel: this._thinkingLevel },
283
+ }
284
+ }
285
+
286
+ _getPricing(model) {
287
+ if (typeof model !== 'string' || model.length === 0) return null
288
+ const fromOverlay = getRegistryForProvider(this._provider).getOverlayPricing(model)
289
+ if (fromOverlay) return fromOverlay
290
+ return GEMINI_PRICING_USD_PER_MTOK[model] || null
291
+ }
292
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Credential sourcing for the native Gemini API provider (`gemini-byok`).
3
+ *
4
+ * Resolution order:
5
+ * 1. env.GEMINI_API_KEY
6
+ * 2. env.GOOGLE_API_KEY
7
+ * 3. Canonical cipher-aware credential store (`credential-store.js`,
8
+ * `~/.chroxy/credentials.json` mode 0600, O_NOFOLLOW-hardened):
9
+ * - `GEMINI_API_KEY` via `resolveStoredCredentialWithMeta`
10
+ * - legacy camelCase `geminiApiKey` via `readStoredField`
11
+ *
12
+ * Respects a caller-supplied `env` without falling back to ambient `process.env`.
13
+ * Keys are never logged.
14
+ */
15
+
16
+ import { maskApiKey } from './byok-credentials.js'
17
+ import { resolveStoredCredentialWithMeta, readStoredField } from './credential-store.js'
18
+ import { configPath } from './config-dir.js'
19
+
20
+ function credentialsFilePath() {
21
+ return configPath('credentials.json')
22
+ }
23
+
24
+ /**
25
+ * Resolve the Gemini API key for a `gemini-byok` session.
26
+ *
27
+ * @param {NodeJS.ProcessEnv} [env]
28
+ * @returns {{ key: string, source: 'env' | 'store' | 'file', envVar?: string } | { key: null, source: 'none', reason: string }}
29
+ */
30
+ export function resolveGeminiApiKey(env = process.env) {
31
+ const safeEnv = env && typeof env === 'object' ? env : {}
32
+ for (const envVar of ['GEMINI_API_KEY', 'GOOGLE_API_KEY']) {
33
+ const val = safeEnv[envVar]
34
+ if (typeof val === 'string' && val.trim().length > 0) {
35
+ return { key: val.trim(), source: 'env', envVar }
36
+ }
37
+ }
38
+
39
+ // Canonical encryption-aware + O_NOFOLLOW credential store lookup.
40
+ const stored = resolveStoredCredentialWithMeta('GEMINI_API_KEY')
41
+ if (stored.value) {
42
+ return { key: stored.value, source: 'store' }
43
+ }
44
+ if (stored.error) {
45
+ return { key: null, source: 'none', reason: stored.error }
46
+ }
47
+
48
+ // Only inspect the legacy camelCase alias when the store read cleanly without
49
+ // finding `GEMINI_API_KEY`.
50
+ if (stored.fileExists) {
51
+ const legacy = readStoredField('geminiApiKey')
52
+ if (legacy.value) {
53
+ return { key: legacy.value, source: 'file' }
54
+ }
55
+ if (legacy.error) {
56
+ return { key: null, source: 'none', reason: legacy.error }
57
+ }
58
+ }
59
+
60
+ const credPath = credentialsFilePath()
61
+ const reason = !stored.fileExists
62
+ ? `GEMINI_API_KEY / GOOGLE_API_KEY not set and ${credPath} does not exist`
63
+ : `GEMINI_API_KEY / GOOGLE_API_KEY not set and no Gemini credential is stored in ${credPath}`
64
+ return { key: null, source: 'none', reason }
65
+ }
66
+
67
+ export { maskApiKey }
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Keeps the configured Gemini API key out of anything that leaves the provider
3
+ * (turn-error text, logs, model-discovery diagnostics).
4
+ *
5
+ * Two jobs, shared by the request shim and the model-discovery probe:
6
+ * 1. refuse a credential Node's header validation would reject, with a FIXED
7
+ * message (the runtime's own rejection quotes the whole header value);
8
+ * 2. remove the configured value from an error by exact match, then apply the
9
+ * shared pattern redaction on top.
10
+ */
11
+
12
+ import { redactBounded } from './redaction.js'
13
+
14
+ export const GEMINI_KEY_HEADER_UNSAFE_MESSAGE =
15
+ 'The Gemini API key contains characters that cannot be sent in a request header; re-enter it.'
16
+
17
+ const REDACTED = '[REDACTED]'
18
+ const ERROR_TEXT_MAX = 1000
19
+
20
+ // The same set Node's fetch accepts in a header value: HTAB, printable ASCII, and
21
+ // Latin-1 (0x80-0xFF). Anything else (CR, LF, NUL, other controls, DEL, code points
22
+ // above 0xFF) makes the request throw an exception that quotes the value.
23
+ const HEADER_VALUE_UNSAFE = /[^\t\x20-\x7e\x80-\xff]/
24
+
25
+ export const GEMINI_MALFORMED_JSON_MESSAGE = 'Gemini returned malformed JSON'
26
+
27
+ /**
28
+ * The key as fetch will send it: fetch trims leading and trailing HTTP whitespace
29
+ * (SP, HTAB, CR, LF) from a header value before validating it, so the key is
30
+ * normalized the same way once, and the normalized form is what is validated and sent.
31
+ */
32
+ export function normalizeGeminiKey(key) {
33
+ if (typeof key !== 'string') return key
34
+ // A linear scan from both ends: an anchored-alternation regex retries from every
35
+ // position of an interior whitespace run (quadratic).
36
+ const ws = (c) => c === 32 || c === 9 || c === 13 || c === 10
37
+ let start = 0
38
+ let end = key.length
39
+ while (start < end && ws(key.charCodeAt(start))) start++
40
+ while (end > start && ws(key.charCodeAt(end - 1))) end--
41
+ return start === 0 && end === key.length ? key : key.slice(start, end)
42
+ }
43
+
44
+ /** Longest key (after normalization) that is sent. Real keys are about 40 characters. */
45
+ export const GEMINI_KEY_MAX_LENGTH = 1024
46
+
47
+ export const GEMINI_KEY_TOO_LONG_MESSAGE =
48
+ 'The Gemini API key is longer than the supported maximum; re-enter it.'
49
+
50
+ export const GEMINI_DETAILS_WITHHELD_MESSAGE = 'Gemini request failed; details withheld'
51
+
52
+ /** Why `key` cannot be used, as an error code, or null when it can. */
53
+ export function geminiKeyProblem(key) {
54
+ const k = normalizeGeminiKey(key)
55
+ if (typeof k !== 'string' || k.length === 0 || HEADER_VALUE_UNSAFE.test(k)) return 'GEMINI_KEY_HEADER_UNSAFE'
56
+ if (k.length > GEMINI_KEY_MAX_LENGTH) return 'GEMINI_KEY_TOO_LONG'
57
+ return null
58
+ }
59
+
60
+ /** True when `key`, as normalized, can be sent: header-safe and within the length cap. */
61
+ export function isHeaderSafeGeminiKey(key) {
62
+ return geminiKeyProblem(key) === null
63
+ }
64
+
65
+ /**
66
+ * Replace a JSON parse diagnostic (Node quotes a clipped part of the malformed
67
+ * input in `SyntaxError.message`, which can be a key fragment) with a fixed message.
68
+ * Other errors pass through unchanged.
69
+ */
70
+ export function withoutParseDiagnostic(err) {
71
+ if (err?.name === 'SyntaxError') return new Error(GEMINI_MALFORMED_JSON_MESSAGE)
72
+ return err
73
+ }
74
+
75
+ /** Throw the fixed refusal when `key` is not header-safe. Never includes the value. */
76
+ export function assertHeaderSafeGeminiKey(key) {
77
+ const code = geminiKeyProblem(key)
78
+ if (code) {
79
+ const err = new Error(code === 'GEMINI_KEY_TOO_LONG' ? GEMINI_KEY_TOO_LONG_MESSAGE : GEMINI_KEY_HEADER_UNSAFE_MESSAGE)
80
+ err.code = code
81
+ throw err
82
+ }
83
+ }
84
+
85
+ const escapeRegex = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
86
+
87
+ // Percent escapes of the key are matched case-insensitively; its own literal
88
+ // characters stay case-sensitive.
89
+ function percentPattern(enc) {
90
+ return enc
91
+ .split(/(%[0-9a-fA-F]{2})/)
92
+ .map((part, i) => (i % 2 === 1
93
+ ? part.replace(/[a-fA-F]/g, (c) => `[${c.toLowerCase()}${c.toUpperCase()}]`)
94
+ : escapeRegex(part)))
95
+ .join('')
96
+ }
97
+
98
+ // Encoded forms are only worth matching for a key long enough to be distinctive.
99
+ const MIN_ENCODED_LENGTH = 8
100
+
101
+ /** Literal spellings of the key: raw, trimmed, and base64 / base64url of each. */
102
+ function literalForms(key) {
103
+ const forms = new Set()
104
+ for (const k of new Set([key, normalizeGeminiKey(key)])) {
105
+ if (k.length === 0) continue
106
+ forms.add(k)
107
+ for (const enc of ['utf8', 'latin1']) {
108
+ const b64 = Buffer.from(k, enc).toString('base64')
109
+ const url = Buffer.from(k, enc).toString('base64url')
110
+ for (const f of [b64, b64.replace(/=+$/, ''), url]) {
111
+ if (f.length >= MIN_ENCODED_LENGTH) forms.add(f)
112
+ }
113
+ }
114
+ }
115
+ return forms
116
+ }
117
+
118
+ function keyMatchers(key) {
119
+ if (typeof key !== 'string' || key.length === 0) return []
120
+ const literals = literalForms(key)
121
+ const patterns = new Map()
122
+ for (const k of new Set([key, normalizeGeminiKey(key)])) {
123
+ if (k.length === 0) continue
124
+ // A lone surrogate makes encodeURIComponent throw; the other forms still apply.
125
+ try {
126
+ const enc = encodeURIComponent(k)
127
+ if (enc !== k) patterns.set(enc, percentPattern(enc))
128
+ } catch { /* malformed UTF-16: skip the percent-encoded form */ }
129
+ const json = JSON.stringify(k).slice(1, -1)
130
+ if (json !== k && json.length > 0) literals.add(json)
131
+ }
132
+ return [
133
+ ...[...literals].map((l) => ({ len: l.length, apply: (t) => t.split(l).join(REDACTED) })),
134
+ ...[...patterns.entries()].map(([form, pat]) => {
135
+ const re = new RegExp(pat, 'g')
136
+ return { len: form.length, apply: (t) => t.replace(re, REDACTED) }
137
+ }),
138
+ ].sort((x, y) => y.len - x.len)
139
+ }
140
+
141
+ const percentDecodeOnce = (t) => t.replace(/(?:%[0-9a-fA-F]{2})+/g, (run) => {
142
+ try { return decodeURIComponent(run) } catch { return run }
143
+ })
144
+ const unicodeDecode = (t) => t.replace(/\\u([0-9a-fA-F]{4})/g, (_m, h) => String.fromCharCode(parseInt(h, 16)))
145
+ const plusToSpace = (t) => t.replace(/\+/g, ' ')
146
+
147
+ /**
148
+ * True when a decoded reading of `text` contains the key: one or two passes of
149
+ * percent-decoding (catches fully-encoded and double-encoded forms), literal \uXXXX
150
+ * escapes, and `+` read as a space (form encoding), alone and combined. Mapping a
151
+ * hit back to offsets in the original is error-prone, so a hit withholds the whole
152
+ * message instead.
153
+ */
154
+ function decodedCopiesHoldKey(text, key) {
155
+ const needles = [...literalForms(key)]
156
+ if (needles.length === 0) return false
157
+ const pass1 = percentDecodeOnce(text)
158
+ const pass2 = percentDecodeOnce(pass1)
159
+ const seen = new Set()
160
+ for (const base of [text, pass1, pass2]) {
161
+ for (const v of [base, unicodeDecode(base), plusToSpace(base), plusToSpace(unicodeDecode(base))]) {
162
+ if (v === text || seen.has(v)) continue
163
+ seen.add(v)
164
+ if (needles.some((n) => v.includes(n))) return true
165
+ }
166
+ }
167
+ return false
168
+ }
169
+
170
+ /**
171
+ * Remove every occurrence of the configured key (raw and fetch-normalized forms, plus
172
+ * its URL-encoded, JSON-escaped and base64 forms, percent escapes matched
173
+ * case-insensitively) from `text`, then withhold the whole message if a decoded
174
+ * reading of what is left still holds the key, then apply the shared pattern
175
+ * redaction. Exact removal runs BEFORE any clipping so a cut can never leave a key
176
+ * prefix. Fails closed: if anything here throws (a matcher too large to build, say),
177
+ * the result is fixed text, never the thrown message, which can quote the key.
178
+ *
179
+ * @param {unknown} text
180
+ * @param {string} key
181
+ * @param {number} [max]
182
+ */
183
+ export function scrubGeminiKey(text, key, max = ERROR_TEXT_MAX) {
184
+ try {
185
+ let s = typeof text === 'string' ? text : String(text ?? '')
186
+ for (const m of keyMatchers(key)) s = m.apply(s)
187
+ if (decodedCopiesHoldKey(s, key)) return GEMINI_DETAILS_WITHHELD_MESSAGE
188
+ return redactBounded(s, max)
189
+ } catch {
190
+ return GEMINI_DETAILS_WITHHELD_MESSAGE
191
+ }
192
+ }
193
+
194
+ function hasAbortOnCauseChain(err) {
195
+ for (let e = err, depth = 0; e && depth < 5; e = e.cause, depth++) {
196
+ if (e.name === 'AbortError') return true
197
+ }
198
+ return false
199
+ }
200
+
201
+ /**
202
+ * Return a fresh error equivalent to `err` with the key removed from every text
203
+ * field. Keeps name, HTTP status and code; drops the original (its message and
204
+ * stack could still hold the key). An abort stays recognisable as one.
205
+ */
206
+ export function sanitizeGeminiError(err, key) {
207
+ // Everything here, including reading `code` and `message` off the error, sits inside
208
+ // the guard: a getter that throws must not escape carrying key-derived text.
209
+ try {
210
+ // Our own refusals carry fixed text with no part of the key: pass them through as
211
+ // they are, so they stay legible even when scrubbing a very large key would fail.
212
+ const code = err?.code
213
+ const fixed = { GEMINI_KEY_HEADER_UNSAFE: GEMINI_KEY_HEADER_UNSAFE_MESSAGE, GEMINI_KEY_TOO_LONG: GEMINI_KEY_TOO_LONG_MESSAGE }[code]
214
+ if (fixed !== undefined && err.message === fixed) {
215
+ const out = new Error(fixed)
216
+ out.code = code
217
+ return out
218
+ }
219
+ return sanitizeGeminiErrorUnchecked(err, key)
220
+ } catch {
221
+ return new Error(GEMINI_DETAILS_WITHHELD_MESSAGE)
222
+ }
223
+ }
224
+
225
+ function sanitizeGeminiErrorUnchecked(err, key) {
226
+ const message = scrubGeminiKey(err?.message ?? err, key)
227
+ const out = new Error(message)
228
+ if (typeof err?.name === 'string' && err.name !== 'Error') out.name = scrubGeminiKey(err.name, key, 100)
229
+ if (Number.isInteger(err?.status)) out.status = err.status
230
+ if (typeof err?.code === 'string') out.code = scrubGeminiKey(err.code, key, 100)
231
+ else if (Number.isInteger(err?.code)) out.code = err.code
232
+ if (err?.error && typeof err.error === 'object') {
233
+ const e = err.error
234
+ out.error = {
235
+ code: Number.isInteger(e.code) ? e.code : undefined,
236
+ status: typeof e.status === 'string' ? scrubGeminiKey(e.status, key, 100) : undefined,
237
+ message: typeof e.message === 'string' ? scrubGeminiKey(e.message, key) : message,
238
+ }
239
+ }
240
+ if (hasAbortOnCauseChain(err) && out.name !== 'AbortError') {
241
+ const abort = new Error('The operation was aborted')
242
+ abort.name = 'AbortError'
243
+ out.cause = abort
244
+ }
245
+ return out
246
+ }