@chroxy/server 0.11.0 → 0.11.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +206 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +958 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +304 -0
- package/src/agent-control/client.js +1645 -0
- package/src/agent-control/events.js +551 -0
- package/src/agent-control/local-connection.js +293 -0
- package/src/agent-control/mcp-server.js +547 -0
- package/src/anthropic-compatible-config.js +30 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1520 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +291 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +92 -7
- package/src/byok-mcp-config.js +633 -122
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +37 -23
- package/src/byok-session.js +707 -179
- package/src/byok-tool-executor.js +2742 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-setting-sources.js +74 -0
- package/src/claude-stream-parser.js +53 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +215 -88
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3563 -284
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-cmd.js +236 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/connection-state.js +54 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/pages-cmd.js +6 -4
- package/src/cli/pair-code-cmd.js +7 -6
- package/src/cli/pair-discord-cmd.js +7 -6
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +91 -40
- package/src/cli/server-cmd.js +54 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1250 -126
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1517 -81
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-error-text.js +114 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +450 -27
- package/src/config-dir-migration.js +449 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +306 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +78 -23
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +227 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +42 -39
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +28 -39
- package/src/credential-store.js +23 -19
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +170 -182
- package/src/device-preferences.js +2 -2
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +172 -3
- package/src/docker-session.js +294 -11
- package/src/doctor.js +781 -64
- package/src/durable-write.js +35 -0
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +101 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +186 -235
- package/src/folder-trust-wire.js +137 -0
- package/src/folder-trust-worker.js +17 -0
- package/src/folder-trust.js +1572 -0
- package/src/freshness/activity-meter.js +101 -0
- package/src/freshness/adapter.js +199 -0
- package/src/freshness/checks.js +239 -0
- package/src/freshness/config.js +98 -0
- package/src/freshness/core.js +185 -0
- package/src/freshness/derive.js +680 -0
- package/src/freshness/exchange.js +305 -0
- package/src/freshness/file-ledger.js +400 -0
- package/src/freshness/grade.js +81 -0
- package/src/freshness/hash.js +45 -0
- package/src/freshness/inbox.js +163 -0
- package/src/freshness/index.js +20 -0
- package/src/freshness/investigation.js +474 -0
- package/src/freshness/keys.js +177 -0
- package/src/freshness/ledger.js +122 -0
- package/src/freshness/outbox.js +131 -0
- package/src/freshness/policy.js +599 -0
- package/src/freshness/queue.js +843 -0
- package/src/freshness/read-errors.js +23 -0
- package/src/freshness/render.js +153 -0
- package/src/freshness/runtime.js +113 -0
- package/src/freshness/session-registry-adapter.js +161 -0
- package/src/freshness/state-file-adapter.js +167 -0
- package/src/freshness-runner/build-info.js +139 -0
- package/src/freshness-runner/cli.js +105 -0
- package/src/freshness-runner/run-tick.js +109 -0
- package/src/freshness-runner/stamp.js +57 -0
- package/src/freshness-sources/claude-transcript-adapter.js +211 -0
- package/src/freshness-sources/codex-transcript-adapter.js +33 -0
- package/src/freshness-sources/index.js +8 -0
- package/src/gemini-byok-session.js +292 -0
- package/src/gemini-credentials.js +67 -0
- package/src/gemini-key-safety.js +246 -0
- package/src/gemini-models.js +386 -0
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +540 -80
- package/src/handlers/checkpoint-handlers.js +47 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +57 -13
- package/src/handlers/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +714 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +92 -18
- package/src/handlers/session-handlers.js +551 -20
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +372 -50
- package/src/handlers/skills-handlers.js +20 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +112 -0
- package/src/http-routes.js +127 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +378 -91
- package/src/jsonl-subprocess-session.js +96 -9
- package/src/keychain.js +1 -1
- package/src/logger.js +166 -30
- package/src/mailbox-route.js +113 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +27 -4
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +64 -23
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +112 -36
- package/src/orchestration/permission-gate.js +17 -2
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +185 -43
- package/src/orphan-reaper.js +470 -0
- package/src/outgoing-policy.js +189 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1410 -43
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +737 -89
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +126 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +315 -47
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/principal-audit.js +189 -0
- package/src/principal-binding.js +25 -0
- package/src/principal-brakes.js +21 -0
- package/src/principal-effect.js +101 -0
- package/src/principal-journal.js +905 -0
- package/src/principal-kill-switch.js +183 -0
- package/src/principal-label.js +5 -0
- package/src/principal-pending-permissions.js +177 -0
- package/src/principal-policy.js +1094 -0
- package/src/principal-sessions-snapshot.js +208 -0
- package/src/principal-store.js +488 -0
- package/src/principal-subscriptions.js +283 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +209 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +531 -20
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +330 -26
- package/src/scheduler.js +368 -11
- package/src/sdk-session.js +2114 -188
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +17 -3
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +553 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +1099 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +4062 -312
- package/src/session-message-history.js +841 -16
- package/src/session-name-allocator.js +685 -0
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-token-store.js +17 -8
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +100 -29
- package/src/summarize-session.js +53 -4
- package/src/supervisor.js +22 -11
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +140 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +770 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +639 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +29 -0
- package/src/utils/bounded-regex.js +162 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +133 -37
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/pid-liveness.js +47 -0
- package/src/utils/preflight.js +360 -16
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +297 -16
- package/src/worktree-gc.js +202 -6
- package/src/ws-auth.js +163 -31
- package/src/ws-broadcaster.js +49 -5
- package/src/ws-client-manager.js +24 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +363 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +349 -39
- package/src/ws-handler-context.js +88 -2
- package/src/ws-history.js +1010 -175
- package/src/ws-message-handlers.js +25 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +885 -98
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
|
@@ -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
|
+
}
|