diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000000000000000000000000000000000000..26489836eb5116edbfb70357d888a110d8288f67
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,28 @@
+.git
+.github
+.claude
+.agents
+.codex
+.cursor
+.trellis
+.wrangler
+node_modules
+dist
+dist-coverage
+coverage
+release-assets
+reports
+tests
+docs
+*.log
+.env
+.env.*
+!.env.example
+.dev.vars
+.dev.vars.*
+!.dev.vars.example
+README*
+LICENSE
+compose.yaml
+worker-configuration.d.ts
+AGENTS.md
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000000000000000000000000000000000000..2f9024baebde631af66c0ccecdd3c00232f18fdc
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,49 @@
+# Normalize text files to LF in both the repository and working tree.
+* text=auto eol=lf
+
+# Windows command scripts require CRLF.
+*.bat text eol=crlf
+*.cmd text eol=crlf
+
+# Trellis framework tooling is not application source. Keep it visible in
+# diffs while excluding it from GitHub language statistics.
+.trellis/scripts/** linguist-vendored=true
+
+# Generated sources should not skew language statistics. The embedded admin
+# bundle is a single generated line, so suppress its unreviewable text diff.
+src/generated/** linguist-generated=true
+src/generated/admin-ui.ts -diff
+worker-configuration.d.ts linguist-generated=true
+
+# Images and documents.
+*.avif binary
+*.bmp binary
+*.gif binary
+*.ico binary
+*.jpeg binary
+*.jpg binary
+*.pdf binary
+*.png binary
+*.webp binary
+
+# Fonts and compiled web assets.
+*.eot binary
+*.otf binary
+*.ttf binary
+*.wasm binary
+*.woff binary
+*.woff2 binary
+
+# Audio and video.
+*.mp3 binary
+*.mp4 binary
+*.ogg binary
+*.wav binary
+*.webm binary
+
+# Archives and compressed assets.
+*.7z binary
+*.gz binary
+*.tar binary
+*.tgz binary
+*.zip binary
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..c864b7252f14400cb270c311dd458fe76793f4e6
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,25 @@
+node_modules/
+dist/
+dist-coverage/
+coverage/
+.wrangler/
+*.log
+AGENTS.md
+.env
+.env.*
+!.env.example
+.dev.vars
+.dev.vars.*
+!.dev.vars.example
+
+# Local agent and workspace state
+.claude/
+.codex/
+.cursor/
+.trellis/.backup-*
+.trellis/.cache/
+.trellis/.runtime/
+.trellis/.template-hashes.json
+.trellis/worktrees/
+.trellis/tasks/
+.trellis/workspace/
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..d7cc3a6538c9e531f4714bc4dd90427b33426063
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,30 @@
+FROM node:26-alpine AS deps
+
+WORKDIR /app
+ARG PNPM_VERSION=11.10.0
+RUN npm install -g pnpm@${PNPM_VERSION}
+
+COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
+RUN pnpm install --frozen-lockfile
+
+FROM deps AS build
+
+COPY tsconfig.json vitest.config.mjs wrangler.jsonc ./
+COPY scripts ./scripts
+COPY src ./src
+RUN pnpm build
+
+FROM node:26-alpine AS runtime
+
+WORKDIR /app
+# HuggingFace Space 默认路由到 7860 端口;docker-server 读 PORT 环境变量。
+ENV NODE_ENV=production \
+ HOST=0.0.0.0 \
+ PORT=7860 \
+ UPSTREAM_SOCKET=false
+
+COPY --from=build /app/dist/worker.js ./dist/worker.js
+COPY --from=build /app/scripts/docker-server.mjs ./scripts/docker-server.mjs
+
+EXPOSE 7860
+CMD ["node", "scripts/docker-server.mjs"]
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..9aed54809930d98c2e7b6df25cff8d7f182e1479
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Guardinary
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/biome.json b/biome.json
new file mode 100644
index 0000000000000000000000000000000000000000..aa0e8b975dfa6e1de84985abf2df434962674195
--- /dev/null
+++ b/biome.json
@@ -0,0 +1,119 @@
+{
+ "$schema": "https://biomejs.dev/schemas/2.5.3/schema.json",
+ "vcs": {
+ "enabled": true,
+ "clientKind": "git",
+ "useIgnoreFile": true
+ },
+ "files": {
+ "includes": [
+ "src/**/*.ts",
+ "src/**/*.tsx",
+ "scripts/**/*.mjs",
+ "tests/**/*.js",
+ "tests/**/*.mjs",
+ "src/**/*.css",
+ "*.json",
+ "*.jsonc",
+ "*.mjs"
+ ]
+ },
+ "javascript": {
+ "globals": ["FixedLengthStream"]
+ },
+ "formatter": {
+ "enabled": true,
+ "lineEnding": "lf"
+ },
+ "overrides": [
+ {
+ "includes": ["src/generated/**"],
+ "formatter": {
+ "enabled": false
+ },
+ "linter": {
+ "rules": {
+ "suspicious": {
+ "noTemplateCurlyInString": "off"
+ }
+ }
+ }
+ },
+ {
+ "includes": ["src/index.ts", "src/test-index.ts", "vitest.config.mjs"],
+ "linter": {
+ "rules": {
+ "style": {
+ "noDefaultExport": "off"
+ }
+ }
+ }
+ },
+ {
+ "includes": ["scripts/**/*.mjs"],
+ "linter": {
+ "rules": {
+ "suspicious": {
+ "noConsole": "off"
+ }
+ }
+ }
+ }
+ ],
+ "linter": {
+ "enabled": true,
+ "rules": {
+ "preset": "recommended",
+ "a11y": {
+ "preset": "all"
+ },
+ "correctness": {
+ "preset": "all",
+ "noNodejsModules": "off",
+ "noProcessGlobal": "off",
+ "noUnresolvedImports": "off",
+ "useImportExtensions": "off",
+ "useQwikValidLexicalScope": "off",
+ "useUniqueElementIds": "off"
+ },
+ "security": {
+ "preset": "all"
+ },
+ "performance": {
+ "recommended": true
+ },
+ "complexity": {
+ "recommended": true,
+ "noUselessStringConcat": "info"
+ },
+ "style": {
+ "recommended": true,
+ "noCommonJs": "warn",
+ "noDefaultExport": "warn",
+ "noEnum": "warn",
+ "noNamespace": "warn",
+ "noNestedTernary": "info",
+ "noParameterAssign": "warn",
+ "useAsConstAssertion": "info",
+ "useConsistentArrayType": "info",
+ "useThrowNewError": "info",
+ "useThrowOnlyError": "warn"
+ },
+ "suspicious": {
+ "preset": "all",
+ "noAlert": "off",
+ "noBitwiseOperators": "off",
+ "noControlCharactersInRegex": "off",
+ "noDeprecatedImports": "off",
+ "noEmptyBlockStatements": "off",
+ "noEqualsToNull": "off",
+ "noMisplacedAssertion": "off",
+ "noUnknownAttribute": "off",
+ "noUnnecessaryConditions": "off",
+ "useArraySortCompare": "off",
+ "useAwait": "off",
+ "useStaticResponseMethods": "off"
+ }
+ }
+ }
+}
diff --git a/compose.yaml b/compose.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..4ac6b5a88a5babc684e36b6e606e355b11aa5966
--- /dev/null
+++ b/compose.yaml
@@ -0,0 +1,30 @@
+services:
+ web2gem:
+ image: "${WEB2GEM_IMAGE:-ghcr.io/guardinary/web2gem:latest}"
+ pull_policy: always
+ restart: unless-stopped
+ ports:
+ - "${PORT:-52389}:${PORT:-52389}"
+ environment:
+ HOST: "0.0.0.0"
+ PORT: "${PORT:-52389}"
+ UPSTREAM_SOCKET: "${UPSTREAM_SOCKET:-false}"
+ API_KEYS: "${API_KEYS:-}"
+ GEMINI_COOKIE: "${GEMINI_COOKIE:-}"
+ SAPISID: "${SAPISID:-}"
+ GEMINI_BL: "${GEMINI_BL:-}"
+ GEMINI_ORIGIN: "${GEMINI_ORIGIN:-}"
+ RESIN_PROXY: "${RESIN_PROXY:-}"
+ AUTH_USER: "${AUTH_USER:-}"
+ XSRF_TOKEN: "${XSRF_TOKEN:-}"
+ DEFAULT_MODEL: "${DEFAULT_MODEL:-}"
+ RETRY_ATTEMPTS: "${RETRY_ATTEMPTS:-}"
+ RETRY_DELAY_SEC: "${RETRY_DELAY_SEC:-}"
+ REQUEST_TIMEOUT_SEC: "${REQUEST_TIMEOUT_SEC:-}"
+ REQUEST_BODY_MAX_BYTES: "${REQUEST_BODY_MAX_BYTES:-16777216}"
+ LOG_REQUESTS: "${LOG_REQUESTS:-}"
+ CURRENT_INPUT_FILE_ENABLED: "${CURRENT_INPUT_FILE_ENABLED:-}"
+ CURRENT_INPUT_FILE_MIN_BYTES: "${CURRENT_INPUT_FILE_MIN_BYTES:-}"
+ CURRENT_INPUT_FILE_NAME: "${CURRENT_INPUT_FILE_NAME:-}"
+ CURRENT_TOOLS_FILE_NAME: "${CURRENT_TOOLS_FILE_NAME:-}"
+ GENERIC_FILE_UPLOAD_MAX_BYTES: "${GENERIC_FILE_UPLOAD_MAX_BYTES:-}"
diff --git a/package.json b/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..912a460d5ddcf97fb4dd006b6778933fc5763209
--- /dev/null
+++ b/package.json
@@ -0,0 +1,41 @@
+{
+ "name": "web2gem",
+ "version": "1.1.0",
+ "private": true,
+ "type": "module",
+ "engines": {
+ "node": ">=22"
+ },
+ "packageManager": "pnpm@11.10.0",
+ "scripts": {
+ "build": "node scripts/build.mjs",
+ "check:static": "biome check --assist-enabled=false --diagnostic-level=warn --error-on-warnings",
+ "worker:types": "pnpm build && wrangler types worker-configuration.d.ts --env-interface WorkerBindings --include-runtime false --strict-vars false --env-file .dev.vars.example",
+ "check:worker-types": "pnpm build && wrangler types worker-configuration.d.ts --env-interface WorkerBindings --include-runtime false --strict-vars false --env-file .dev.vars.example --check",
+ "format": "biome format --write",
+ "typecheck": "tsc --noEmit",
+ "check:arch": "node scripts/check-architecture.mjs",
+ "check:size": "pnpm build && node scripts/check-bundle-size.mjs",
+ "check:bench": "node scripts/build.mjs --test-bundle && node scripts/check-benchmark.mjs",
+ "check:release": "node scripts/check-release.mjs",
+ "unit:quick": "node scripts/ensure-test-bundle-fresh.mjs && vitest run",
+ "unit": "node scripts/unit.mjs",
+ "coverage": "node scripts/coverage.mjs",
+ "coverage:ci": "node scripts/coverage.mjs --ci",
+ "smoke": "node scripts/build.mjs --test-bundle && node scripts/smoke.mjs",
+ "docker:smoke": "node scripts/docker-smoke.mjs",
+ "bench": "node scripts/build.mjs --test-bundle && node scripts/bench.mjs",
+ "docker:start": "node scripts/docker-server.mjs",
+ "dev": "pnpm build && wrangler dev",
+ "deploy": "pnpm build && wrangler deploy"
+ },
+ "devDependencies": {
+ "@biomejs/biome": "^2.5.3",
+ "@cloudflare/workers-types": "^5.20260712.1",
+ "@vitest/coverage-v8": "^4.1.10",
+ "esbuild": "^0.28.1",
+ "typescript": "^7.0.2",
+ "vitest": "^4.1.10",
+ "wrangler": "^4.110.0"
+ }
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..d70ed5c926f57ad7b0ae1782c7dab9440172c24f
--- /dev/null
+++ b/pnpm-lock.yaml
@@ -0,0 +1,2045 @@
+lockfileVersion: '9.0'
+
+settings:
+ autoInstallPeers: true
+ excludeLinksFromLockfile: false
+
+importers:
+
+ .:
+ devDependencies:
+ '@biomejs/biome':
+ specifier: ^2.5.3
+ version: 2.5.3
+ '@cloudflare/workers-types':
+ specifier: ^5.20260712.1
+ version: 5.20260712.1
+ '@vitest/coverage-v8':
+ specifier: ^4.1.10
+ version: 4.1.10(vitest@4.1.10)
+ esbuild:
+ specifier: ^0.28.1
+ version: 0.28.1
+ typescript:
+ specifier: ^7.0.2
+ version: 7.0.2
+ vitest:
+ specifier: ^4.1.10
+ version: 4.1.10(@vitest/coverage-v8@4.1.10)(vite@8.0.16(esbuild@0.28.1))
+ wrangler:
+ specifier: ^4.110.0
+ version: 4.110.0(@cloudflare/workers-types@5.20260712.1)
+
+packages:
+
+ '@babel/helper-string-parser@7.29.7':
+ resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/helper-validator-identifier@7.29.7':
+ resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/parser@7.29.7':
+ resolution: {integrity: sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==}
+ engines: {node: '>=6.0.0'}
+ hasBin: true
+
+ '@babel/types@7.29.7':
+ resolution: {integrity: sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==}
+ engines: {node: '>=6.9.0'}
+
+ '@bcoe/v8-coverage@1.0.2':
+ resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
+ engines: {node: '>=18'}
+
+ '@biomejs/biome@2.5.3':
+ resolution: {integrity: sha512-MrJswFdei9EfDwwUy2tQrPDpK0AO+RmMFvBoaaJ6ayBc3sUbHdCE+XG5N8vp+5So41ZupZJQm0roHFFhMGVD7A==}
+ engines: {node: '>=14.21.3'}
+ hasBin: true
+
+ '@biomejs/cli-darwin-arm64@2.5.3':
+ resolution: {integrity: sha512-QhYP9muVQ0nUO5zztFuPbEwi4+94sJWVjaZds9aMi1l/KNZBiUjdiSUrGHsTaMGDXrYl+r4AS2sUKfgH3w+V3g==}
+ engines: {node: '>=14.21.3'}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@biomejs/cli-darwin-x64@2.5.3':
+ resolution: {integrity: sha512-NC1Ss13UaW7QZX+y8j44bF7AP0jSJdBl6iRhe0MAkvaSqZy+mWg3GaXsrb+eSoHoGDBtaXWEbMVV0iVN2cZ7cQ==}
+ engines: {node: '>=14.21.3'}
+ cpu: [x64]
+ os: [darwin]
+
+ '@biomejs/cli-linux-arm64-musl@2.5.3':
+ resolution: {integrity: sha512-fccix0w6xp6csCXgxeC0dU/3ecgRQal0y+cv2SP9ajNlhe7Yrk2Ug7UDe2j9AT9ZDYitkXpvUKgZjjuoYeP4Vg==}
+ engines: {node: '>=14.21.3'}
+ cpu: [arm64]
+ os: [linux]
+ libc: [musl]
+
+ '@biomejs/cli-linux-arm64@2.5.3':
+ resolution: {integrity: sha512-ksx1KWeyYW18ILL04msF/J4ZBtBDN33znYK8Z/aNv/vlBVxL9/g3mGP+omgHJKy4+KWbK87vcmmpmurfNjSgiA==}
+ engines: {node: '>=14.21.3'}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ '@biomejs/cli-linux-x64-musl@2.5.3':
+ resolution: {integrity: sha512-O/yU9YKRUiHhmcjF2f38PSjseVk3G4VLWYc0G2HWpzdBVREV6G8IGWIVEFf7MFPfWIzNUIvPsEjeAZQIOgnLcQ==}
+ engines: {node: '>=14.21.3'}
+ cpu: [x64]
+ os: [linux]
+ libc: [musl]
+
+ '@biomejs/cli-linux-x64@2.5.3':
+ resolution: {integrity: sha512-yMkJtilsgvILDcVkh187aVLTb64xYsrxYajx5kym+r1ULkO5HUOfu9AYKLGQbOVLwJtT2utNw7hhFNg+17mUYA==}
+ engines: {node: '>=14.21.3'}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ '@biomejs/cli-win32-arm64@2.5.3':
+ resolution: {integrity: sha512-cX5z+GYwRcqEok0AH3KSfQGgqYd0Nomfp6Fbe1uiTtELE38hdH2k842wQ9wLNaF/JJ7r4rjJQ4VR+ce+fRmQbw==}
+ engines: {node: '>=14.21.3'}
+ cpu: [arm64]
+ os: [win32]
+
+ '@biomejs/cli-win32-x64@2.5.3':
+ resolution: {integrity: sha512-ExSaJWi4/u6+GXCszlSKpWSjKNbDseAYqqkCznsCsZ/4uidZ/BEqsCc5/3ctlq6dfIubdIIRSVLC/PG9xPl70Q==}
+ engines: {node: '>=14.21.3'}
+ cpu: [x64]
+ os: [win32]
+
+ '@cloudflare/kv-asset-handler@0.5.0':
+ resolution: {integrity: sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==}
+ engines: {node: '>=22.0.0'}
+
+ '@cloudflare/unenv-preset@2.16.1':
+ resolution: {integrity: sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw==}
+ peerDependencies:
+ unenv: 2.0.0-rc.24
+ workerd: '>1.20260305.0 <2.0.0-0'
+ peerDependenciesMeta:
+ workerd:
+ optional: true
+
+ '@cloudflare/workerd-darwin-64@1.20260708.1':
+ resolution: {integrity: sha512-HXFCvhS1wpg3uXO0CLUwmwC41i2loM5FSK69EUchOBpmYBAXxT1oHLm6EOA5lqhTk5Mu9kjRiQYxa1GwKPwfJg==}
+ engines: {node: '>=16'}
+ cpu: [x64]
+ os: [darwin]
+
+ '@cloudflare/workerd-darwin-arm64@1.20260708.1':
+ resolution: {integrity: sha512-JVlJaKDoRTVKSroHIlf8g3UCPjKj4iDbMZE2CNYht5qQ+2rL0FAUiVlV82G3BqKnnw9kHYnnsMzC08b9zVtdzA==}
+ engines: {node: '>=16'}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@cloudflare/workerd-linux-64@1.20260708.1':
+ resolution: {integrity: sha512-3daE60YdD7YX0Jtuzc9DE/r/qMkmx8ZvHTkF8Mzmp3F5tbzlV0DAzmu5PFUPF2WuvtKbAhZKbvC2cHmWpQYxnA==}
+ engines: {node: '>=16'}
+ cpu: [x64]
+ os: [linux]
+
+ '@cloudflare/workerd-linux-arm64@1.20260708.1':
+ resolution: {integrity: sha512-VLdNYOx5Hj+9C6isy0ACWZsbMtSxex2DIJWEe7cZxUdlphZ58ZT8zxNXK8yunFiowd34hn3VwGMopdvdj8lvmA==}
+ engines: {node: '>=16'}
+ cpu: [arm64]
+ os: [linux]
+
+ '@cloudflare/workerd-windows-64@1.20260708.1':
+ resolution: {integrity: sha512-bC/aSAwLy16Vjo24i9XU3aWH+eRgz7NeR5xPKavGbembO18ZywYTQbXh14eXtY6fAqN3RzRG8psijTdhX4xydA==}
+ engines: {node: '>=16'}
+ cpu: [x64]
+ os: [win32]
+
+ '@cloudflare/workers-types@5.20260712.1':
+ resolution: {integrity: sha512-tkQ18Lz41EPXLzh4cSuIGQzztDVueuGfTcjlP4M7Qa0rfHpVBNItf3GRkd9O0JgiXs9csAwz/kVv7sjYXSoF2w==}
+
+ '@cspotcode/source-map-support@0.8.1':
+ resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==}
+ engines: {node: '>=12'}
+
+ '@emnapi/core@1.10.0':
+ resolution: {integrity: sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==}
+
+ '@emnapi/runtime@1.10.0':
+ resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==}
+
+ '@emnapi/runtime@1.11.2':
+ resolution: {integrity: sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==}
+
+ '@emnapi/wasi-threads@1.2.1':
+ resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==}
+
+ '@esbuild/aix-ppc64@0.28.1':
+ resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==}
+ engines: {node: '>=18'}
+ cpu: [ppc64]
+ os: [aix]
+
+ '@esbuild/android-arm64@0.28.1':
+ resolution: {integrity: sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [android]
+
+ '@esbuild/android-arm@0.28.1':
+ resolution: {integrity: sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==}
+ engines: {node: '>=18'}
+ cpu: [arm]
+ os: [android]
+
+ '@esbuild/android-x64@0.28.1':
+ resolution: {integrity: sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [android]
+
+ '@esbuild/darwin-arm64@0.28.1':
+ resolution: {integrity: sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@esbuild/darwin-x64@0.28.1':
+ resolution: {integrity: sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [darwin]
+
+ '@esbuild/freebsd-arm64@0.28.1':
+ resolution: {integrity: sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [freebsd]
+
+ '@esbuild/freebsd-x64@0.28.1':
+ resolution: {integrity: sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@esbuild/linux-arm64@0.28.1':
+ resolution: {integrity: sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [linux]
+
+ '@esbuild/linux-arm@0.28.1':
+ resolution: {integrity: sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==}
+ engines: {node: '>=18'}
+ cpu: [arm]
+ os: [linux]
+
+ '@esbuild/linux-ia32@0.28.1':
+ resolution: {integrity: sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==}
+ engines: {node: '>=18'}
+ cpu: [ia32]
+ os: [linux]
+
+ '@esbuild/linux-loong64@0.28.1':
+ resolution: {integrity: sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==}
+ engines: {node: '>=18'}
+ cpu: [loong64]
+ os: [linux]
+
+ '@esbuild/linux-mips64el@0.28.1':
+ resolution: {integrity: sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==}
+ engines: {node: '>=18'}
+ cpu: [mips64el]
+ os: [linux]
+
+ '@esbuild/linux-ppc64@0.28.1':
+ resolution: {integrity: sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==}
+ engines: {node: '>=18'}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@esbuild/linux-riscv64@0.28.1':
+ resolution: {integrity: sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==}
+ engines: {node: '>=18'}
+ cpu: [riscv64]
+ os: [linux]
+
+ '@esbuild/linux-s390x@0.28.1':
+ resolution: {integrity: sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==}
+ engines: {node: '>=18'}
+ cpu: [s390x]
+ os: [linux]
+
+ '@esbuild/linux-x64@0.28.1':
+ resolution: {integrity: sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [linux]
+
+ '@esbuild/netbsd-arm64@0.28.1':
+ resolution: {integrity: sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [netbsd]
+
+ '@esbuild/netbsd-x64@0.28.1':
+ resolution: {integrity: sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [netbsd]
+
+ '@esbuild/openbsd-arm64@0.28.1':
+ resolution: {integrity: sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [openbsd]
+
+ '@esbuild/openbsd-x64@0.28.1':
+ resolution: {integrity: sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [openbsd]
+
+ '@esbuild/openharmony-arm64@0.28.1':
+ resolution: {integrity: sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [openharmony]
+
+ '@esbuild/sunos-x64@0.28.1':
+ resolution: {integrity: sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [sunos]
+
+ '@esbuild/win32-arm64@0.28.1':
+ resolution: {integrity: sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [win32]
+
+ '@esbuild/win32-ia32@0.28.1':
+ resolution: {integrity: sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==}
+ engines: {node: '>=18'}
+ cpu: [ia32]
+ os: [win32]
+
+ '@esbuild/win32-x64@0.28.1':
+ resolution: {integrity: sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [win32]
+
+ '@img/colour@1.1.0':
+ resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==}
+ engines: {node: '>=18'}
+
+ '@img/sharp-darwin-arm64@0.34.5':
+ resolution: {integrity: sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@img/sharp-darwin-x64@0.34.5':
+ resolution: {integrity: sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [x64]
+ os: [darwin]
+
+ '@img/sharp-libvips-darwin-arm64@1.2.4':
+ resolution: {integrity: sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@img/sharp-libvips-darwin-x64@1.2.4':
+ resolution: {integrity: sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==}
+ cpu: [x64]
+ os: [darwin]
+
+ '@img/sharp-libvips-linux-arm64@1.2.4':
+ resolution: {integrity: sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ '@img/sharp-libvips-linux-arm@1.2.4':
+ resolution: {integrity: sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==}
+ cpu: [arm]
+ os: [linux]
+ libc: [glibc]
+
+ '@img/sharp-libvips-linux-ppc64@1.2.4':
+ resolution: {integrity: sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==}
+ cpu: [ppc64]
+ os: [linux]
+ libc: [glibc]
+
+ '@img/sharp-libvips-linux-riscv64@1.2.4':
+ resolution: {integrity: sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==}
+ cpu: [riscv64]
+ os: [linux]
+ libc: [glibc]
+
+ '@img/sharp-libvips-linux-s390x@1.2.4':
+ resolution: {integrity: sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==}
+ cpu: [s390x]
+ os: [linux]
+ libc: [glibc]
+
+ '@img/sharp-libvips-linux-x64@1.2.4':
+ resolution: {integrity: sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ '@img/sharp-libvips-linuxmusl-arm64@1.2.4':
+ resolution: {integrity: sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==}
+ cpu: [arm64]
+ os: [linux]
+ libc: [musl]
+
+ '@img/sharp-libvips-linuxmusl-x64@1.2.4':
+ resolution: {integrity: sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==}
+ cpu: [x64]
+ os: [linux]
+ libc: [musl]
+
+ '@img/sharp-linux-arm64@0.34.5':
+ resolution: {integrity: sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ '@img/sharp-linux-arm@0.34.5':
+ resolution: {integrity: sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [arm]
+ os: [linux]
+ libc: [glibc]
+
+ '@img/sharp-linux-ppc64@0.34.5':
+ resolution: {integrity: sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [ppc64]
+ os: [linux]
+ libc: [glibc]
+
+ '@img/sharp-linux-riscv64@0.34.5':
+ resolution: {integrity: sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [riscv64]
+ os: [linux]
+ libc: [glibc]
+
+ '@img/sharp-linux-s390x@0.34.5':
+ resolution: {integrity: sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [s390x]
+ os: [linux]
+ libc: [glibc]
+
+ '@img/sharp-linux-x64@0.34.5':
+ resolution: {integrity: sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ '@img/sharp-linuxmusl-arm64@0.34.5':
+ resolution: {integrity: sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [arm64]
+ os: [linux]
+ libc: [musl]
+
+ '@img/sharp-linuxmusl-x64@0.34.5':
+ resolution: {integrity: sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [x64]
+ os: [linux]
+ libc: [musl]
+
+ '@img/sharp-wasm32@0.34.5':
+ resolution: {integrity: sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [wasm32]
+
+ '@img/sharp-win32-arm64@0.34.5':
+ resolution: {integrity: sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [arm64]
+ os: [win32]
+
+ '@img/sharp-win32-ia32@0.34.5':
+ resolution: {integrity: sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [ia32]
+ os: [win32]
+
+ '@img/sharp-win32-x64@0.34.5':
+ resolution: {integrity: sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+ cpu: [x64]
+ os: [win32]
+
+ '@jridgewell/resolve-uri@3.1.2':
+ resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}
+ engines: {node: '>=6.0.0'}
+
+ '@jridgewell/sourcemap-codec@1.5.5':
+ resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==}
+
+ '@jridgewell/trace-mapping@0.3.31':
+ resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
+
+ '@jridgewell/trace-mapping@0.3.9':
+ resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==}
+
+ '@napi-rs/wasm-runtime@1.1.5':
+ resolution: {integrity: sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==}
+ peerDependencies:
+ '@emnapi/core': ^1.7.1
+ '@emnapi/runtime': ^1.7.1
+
+ '@oxc-project/types@0.133.0':
+ resolution: {integrity: sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==}
+
+ '@poppinss/colors@4.1.6':
+ resolution: {integrity: sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==}
+
+ '@poppinss/dumper@0.6.5':
+ resolution: {integrity: sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==}
+
+ '@poppinss/exception@1.2.3':
+ resolution: {integrity: sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==}
+
+ '@rolldown/binding-android-arm64@1.0.3':
+ resolution: {integrity: sha512-454rs7jHngixp/NMxd5srYD57OnzSlZ/eFTETjORQHLwJG1lRtmNOJcBerZlfu4GjKqeq8aCCIQrMdHyhI51Hw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [android]
+
+ '@rolldown/binding-darwin-arm64@1.0.3':
+ resolution: {integrity: sha512-PcAhP+ynjURNyy8SKGl5DQP94aGuB/7JrXJb/t7P+hanXvQVMWzUvRRhBAcg/lNRadBhoUPqSoP4xw5tR/KBEA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@rolldown/binding-darwin-x64@1.0.3':
+ resolution: {integrity: sha512-9YpfeUvSE2RS7wysJ81uOZkXJz7f7Q55H2Gvp3VEw/EsahqDtrphrZ0EwDLK5vvKOzaCrBsjF8JmnMLcUt78Gg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [darwin]
+
+ '@rolldown/binding-freebsd-x64@1.0.3':
+ resolution: {integrity: sha512-yB1IlAsSNHncV6SCTL27/MVGR5htvQsoGxIv5KMGXALp+Ll1wYsn+x98M9MW7qa+NdSbvrrY7ANI4wLJ0n1e6g==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@rolldown/binding-linux-arm-gnueabihf@1.0.3':
+ resolution: {integrity: sha512-Yi30IVAAfLUCy2MseFjbB1jAMDl1VMCAas5StnYp8da9+CKvMd2H2cbEjWcw5NPaPqzvYkVIaF1nNUG+b7u/sw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm]
+ os: [linux]
+
+ '@rolldown/binding-linux-arm64-gnu@1.0.3':
+ resolution: {integrity: sha512-jsO7R8To+AdlYgUmN5sHSCZbfhtMBkO0WUx8iORQnPcMMdgr7qM2DQmMwgabs3GhNztdmoKkMKQFHD6DTMCIQw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ '@rolldown/binding-linux-arm64-musl@1.0.3':
+ resolution: {integrity: sha512-VWkUHwWriDciit80wleYwKILoR/KMvxh/IdwS/paX+ZgpuRpCrKLUdadJbc0NpBEiyhpYawsJ73j9aCvOH+f7Q==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [linux]
+ libc: [musl]
+
+ '@rolldown/binding-linux-ppc64-gnu@1.0.3':
+ resolution: {integrity: sha512-5f1laC0SlIR0yDbFCd8acUhvJIag6N3zC5P7oUPN6wX0aOma+uKJ0wBDH5aq7I1PVI2ttTlhJwzwRIBnLiSGEg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [ppc64]
+ os: [linux]
+ libc: [glibc]
+
+ '@rolldown/binding-linux-s390x-gnu@1.0.3':
+ resolution: {integrity: sha512-Iq4ko0r4XsgbrF/LunNgHtAGLRRVE2kXonAXQ/MV0mC6jQpMOhW1SvtZja2EhC/kd05++bP78dsqBeIQyYJ6Yg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [s390x]
+ os: [linux]
+ libc: [glibc]
+
+ '@rolldown/binding-linux-x64-gnu@1.0.3':
+ resolution: {integrity: sha512-B8m6tD5+/N5FeNQFbKlLA/2yVq9ycQP1SeedyEYYKWBNR3ZQbkvIUcNnDNM03lO1l5F2roiiFJGgvoLLyZXtSg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ '@rolldown/binding-linux-x64-musl@1.0.3':
+ resolution: {integrity: sha512-pSdpdUJHkuCxun9LE7jvgUB9qsRgaiyNNCX7m/AvHTcq67AiT/Yhoxvw5zPfhrM8k/BfP8ce/hMOpthKDpEUow==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [linux]
+ libc: [musl]
+
+ '@rolldown/binding-openharmony-arm64@1.0.3':
+ resolution: {integrity: sha512-OXXS3RKJgX2uLwM+gYyuH5omcH8fL1LJs96pZGgtetVCahON57+d4SJHzTgZiOjxgGkSnpXpOsWuPDGAKAigEg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [openharmony]
+
+ '@rolldown/binding-wasm32-wasi@1.0.3':
+ resolution: {integrity: sha512-JTtb8BWFynicNSoPrehsCzBtOKjZ6jhMiPFEmOiuXg1Fl8dn2KHQob+GuPSGR0dryQa1PQJbzjF3dqO/whhjLg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [wasm32]
+
+ '@rolldown/binding-win32-arm64-msvc@1.0.3':
+ resolution: {integrity: sha512-gEdFFEN70A/jxb2svrWsN3aDL7OUtmvlOy+6fa2jxG8K0wQ1ZbdeLGnidov6Yu5/733dI5ySfzFlQ/cb0bSz1g==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [win32]
+
+ '@rolldown/binding-win32-x64-msvc@1.0.3':
+ resolution: {integrity: sha512-eXB7CHuaQdqmJcc3koCNtNPmT/bj2gc999kUFgBxG8Ac0NdgXc4rkCHhqrgrhN3zddvvvrgzj1e90SuSfmyIXA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [win32]
+
+ '@rolldown/pluginutils@1.0.1':
+ resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}
+
+ '@sindresorhus/is@7.2.0':
+ resolution: {integrity: sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==}
+ engines: {node: '>=18'}
+
+ '@speed-highlight/core@1.2.17':
+ resolution: {integrity: sha512-Z92FwKpCtfaW1V0jTU/fh3QzYEZN8wDwrzRIBoADCJfn4mJCNcJN/XegifX7BDrQ8/h9Xh/JnbyMchL0FqXrkg==}
+
+ '@standard-schema/spec@1.1.0':
+ resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
+
+ '@tybys/wasm-util@0.10.2':
+ resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==}
+
+ '@types/chai@5.2.3':
+ resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
+
+ '@types/deep-eql@4.0.2':
+ resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
+
+ '@types/estree@1.0.9':
+ resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}
+
+ '@typescript/typescript-aix-ppc64@7.0.2':
+ resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==}
+ engines: {node: '>=16.20.0'}
+ cpu: [ppc64]
+ os: [aix]
+
+ '@typescript/typescript-darwin-arm64@7.0.2':
+ resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==}
+ engines: {node: '>=16.20.0'}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@typescript/typescript-darwin-x64@7.0.2':
+ resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==}
+ engines: {node: '>=16.20.0'}
+ cpu: [x64]
+ os: [darwin]
+
+ '@typescript/typescript-freebsd-arm64@7.0.2':
+ resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==}
+ engines: {node: '>=16.20.0'}
+ cpu: [arm64]
+ os: [freebsd]
+
+ '@typescript/typescript-freebsd-x64@7.0.2':
+ resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==}
+ engines: {node: '>=16.20.0'}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@typescript/typescript-linux-arm64@7.0.2':
+ resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==}
+ engines: {node: '>=16.20.0'}
+ cpu: [arm64]
+ os: [linux]
+
+ '@typescript/typescript-linux-arm@7.0.2':
+ resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==}
+ engines: {node: '>=16.20.0'}
+ cpu: [arm]
+ os: [linux]
+
+ '@typescript/typescript-linux-loong64@7.0.2':
+ resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==}
+ engines: {node: '>=16.20.0'}
+ cpu: [loong64]
+ os: [linux]
+
+ '@typescript/typescript-linux-mips64el@7.0.2':
+ resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==}
+ engines: {node: '>=16.20.0'}
+ cpu: [mips64el]
+ os: [linux]
+
+ '@typescript/typescript-linux-ppc64@7.0.2':
+ resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==}
+ engines: {node: '>=16.20.0'}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@typescript/typescript-linux-riscv64@7.0.2':
+ resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==}
+ engines: {node: '>=16.20.0'}
+ cpu: [riscv64]
+ os: [linux]
+
+ '@typescript/typescript-linux-s390x@7.0.2':
+ resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==}
+ engines: {node: '>=16.20.0'}
+ cpu: [s390x]
+ os: [linux]
+
+ '@typescript/typescript-linux-x64@7.0.2':
+ resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==}
+ engines: {node: '>=16.20.0'}
+ cpu: [x64]
+ os: [linux]
+
+ '@typescript/typescript-netbsd-arm64@7.0.2':
+ resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==}
+ engines: {node: '>=16.20.0'}
+ cpu: [arm64]
+ os: [netbsd]
+
+ '@typescript/typescript-netbsd-x64@7.0.2':
+ resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==}
+ engines: {node: '>=16.20.0'}
+ cpu: [x64]
+ os: [netbsd]
+
+ '@typescript/typescript-openbsd-arm64@7.0.2':
+ resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==}
+ engines: {node: '>=16.20.0'}
+ cpu: [arm64]
+ os: [openbsd]
+
+ '@typescript/typescript-openbsd-x64@7.0.2':
+ resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==}
+ engines: {node: '>=16.20.0'}
+ cpu: [x64]
+ os: [openbsd]
+
+ '@typescript/typescript-sunos-x64@7.0.2':
+ resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==}
+ engines: {node: '>=16.20.0'}
+ cpu: [x64]
+ os: [sunos]
+
+ '@typescript/typescript-win32-arm64@7.0.2':
+ resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==}
+ engines: {node: '>=16.20.0'}
+ cpu: [arm64]
+ os: [win32]
+
+ '@typescript/typescript-win32-x64@7.0.2':
+ resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==}
+ engines: {node: '>=16.20.0'}
+ cpu: [x64]
+ os: [win32]
+
+ '@vitest/coverage-v8@4.1.10':
+ resolution: {integrity: sha512-IM49HmthevbgAO4anp1hwtoT9wYe59w0LR00gr+eagHE+ZJ5lK4sLPeO0ubgoJcwLk6dehU3R24N+FbEEKDc8g==}
+ peerDependencies:
+ '@vitest/browser': 4.1.10
+ vitest: 4.1.10
+ peerDependenciesMeta:
+ '@vitest/browser':
+ optional: true
+
+ '@vitest/expect@4.1.10':
+ resolution: {integrity: sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==}
+
+ '@vitest/mocker@4.1.10':
+ resolution: {integrity: sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==}
+ peerDependencies:
+ msw: ^2.4.9
+ vite: ^6.0.0 || ^7.0.0 || ^8.0.0
+ peerDependenciesMeta:
+ msw:
+ optional: true
+ vite:
+ optional: true
+
+ '@vitest/pretty-format@4.1.10':
+ resolution: {integrity: sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==}
+
+ '@vitest/runner@4.1.10':
+ resolution: {integrity: sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==}
+
+ '@vitest/snapshot@4.1.10':
+ resolution: {integrity: sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==}
+
+ '@vitest/spy@4.1.10':
+ resolution: {integrity: sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==}
+
+ '@vitest/utils@4.1.10':
+ resolution: {integrity: sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==}
+
+ assertion-error@2.0.1:
+ resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
+ engines: {node: '>=12'}
+
+ ast-v8-to-istanbul@1.0.4:
+ resolution: {integrity: sha512-0bC0/4bTSrnwdhU3IsZDwEdojvuPrSg59OYZfKsLRtJZ0u8VBx9DebfqqG8bRdCC0I7vjgxmPi41P0lpkhJHtA==}
+
+ blake3-wasm@2.1.5:
+ resolution: {integrity: sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==}
+
+ chai@6.2.2:
+ resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}
+ engines: {node: '>=18'}
+
+ convert-source-map@2.0.0:
+ resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
+
+ cookie@1.1.1:
+ resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
+ engines: {node: '>=18'}
+
+ detect-libc@2.1.2:
+ resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
+ engines: {node: '>=8'}
+
+ error-stack-parser-es@1.0.5:
+ resolution: {integrity: sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==}
+
+ es-module-lexer@2.3.0:
+ resolution: {integrity: sha512-KLdwQm2NvGLDkQDCGvmiQrhkd0JbMzXthwQAUgWjQuQdBLFa3eiBP5arXZyA+f8x+x7OXgud6bq2rxjGtHV2tw==}
+
+ esbuild@0.28.1:
+ resolution: {integrity: sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==}
+ engines: {node: '>=18'}
+ hasBin: true
+
+ estree-walker@3.0.3:
+ resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
+
+ expect-type@1.4.0:
+ resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}
+ engines: {node: '>=12.0.0'}
+
+ fdir@6.5.0:
+ resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
+ engines: {node: '>=12.0.0'}
+ peerDependencies:
+ picomatch: ^3 || ^4
+ peerDependenciesMeta:
+ picomatch:
+ optional: true
+
+ fsevents@2.3.3:
+ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
+ os: [darwin]
+
+ has-flag@4.0.0:
+ resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==}
+ engines: {node: '>=8'}
+
+ html-escaper@2.0.2:
+ resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}
+
+ istanbul-lib-coverage@3.2.2:
+ resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}
+ engines: {node: '>=8'}
+
+ istanbul-lib-report@3.0.1:
+ resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==}
+ engines: {node: '>=10'}
+
+ istanbul-reports@3.2.0:
+ resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==}
+ engines: {node: '>=8'}
+
+ js-tokens@10.0.0:
+ resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==}
+
+ kleur@4.1.5:
+ resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==}
+ engines: {node: '>=6'}
+
+ lightningcss-android-arm64@1.32.0:
+ resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [android]
+
+ lightningcss-darwin-arm64@1.32.0:
+ resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [darwin]
+
+ lightningcss-darwin-x64@1.32.0:
+ resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [darwin]
+
+ lightningcss-freebsd-x64@1.32.0:
+ resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [freebsd]
+
+ lightningcss-linux-arm-gnueabihf@1.32.0:
+ resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm]
+ os: [linux]
+
+ lightningcss-linux-arm64-gnu@1.32.0:
+ resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ lightningcss-linux-arm64-musl@1.32.0:
+ resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [linux]
+ libc: [musl]
+
+ lightningcss-linux-x64-gnu@1.32.0:
+ resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ lightningcss-linux-x64-musl@1.32.0:
+ resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [linux]
+ libc: [musl]
+
+ lightningcss-win32-arm64-msvc@1.32.0:
+ resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [win32]
+
+ lightningcss-win32-x64-msvc@1.32.0:
+ resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [win32]
+
+ lightningcss@1.32.0:
+ resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==}
+ engines: {node: '>= 12.0.0'}
+
+ magic-string@0.30.21:
+ resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
+
+ magicast@0.5.3:
+ resolution: {integrity: sha512-pVKE4UdSQ7DvHzivsCIFx2BJn1mHG6KsyrFcaxFx6tONdneEuThrDx0Cj3AMg58KyN4pzYT+LHOotxDQDjNvkw==}
+
+ make-dir@4.0.0:
+ resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}
+ engines: {node: '>=10'}
+
+ miniflare@4.20260708.1:
+ resolution: {integrity: sha512-c94O9zRDISdqO18EHt6l0iF/fWgWt8p18PJvRsA/L/NJZ9Cfke3s/F5Blg1XXF7WDutVRzWVWy8Vy4LaT5ifsA==}
+ engines: {node: '>=22.0.0'}
+ hasBin: true
+
+ nanoid@3.3.13:
+ resolution: {integrity: sha512-sPdqC6ByMVVGvF1ynvvMo0/o+oD1VX7DaHhijt1bFgjvBkHBib4t49GoNDhf2NDta4oeUNlaGbSt5K7qjZ955Q==}
+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
+ hasBin: true
+
+ obug@2.1.3:
+ resolution: {integrity: sha512-9miFgM2OFba7hB+pRgvtV84pYTBaoTHohvmIgiRt6dRIzbwEOIaNaP+dIlGs2fNFoB0SeISs0Jz5WFVRid6Xyg==}
+ engines: {node: '>=12.20.0'}
+
+ path-to-regexp@6.3.0:
+ resolution: {integrity: sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==}
+
+ pathe@2.0.3:
+ resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
+
+ picocolors@1.1.1:
+ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
+
+ picomatch@4.0.5:
+ resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==}
+ engines: {node: '>=12'}
+
+ postcss@8.5.15:
+ resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==}
+ engines: {node: ^10 || ^12 || >=14}
+
+ rolldown@1.0.3:
+ resolution: {integrity: sha512-i00lAJ2ks1BYr7rjNjKC7BcqAS7nVfiT3QX1SI5aY+AFHblCmaUf9OE9dbdzDvW6dJxbi2ZCZiy9v3CcwOiX3g==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ hasBin: true
+
+ semver@7.8.5:
+ resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==}
+ engines: {node: '>=10'}
+ hasBin: true
+
+ sharp@0.34.5:
+ resolution: {integrity: sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==}
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
+
+ siginfo@2.0.0:
+ resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
+
+ source-map-js@1.2.1:
+ resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
+ engines: {node: '>=0.10.0'}
+
+ stackback@0.0.2:
+ resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
+
+ std-env@4.2.0:
+ resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==}
+
+ supports-color@10.2.2:
+ resolution: {integrity: sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==}
+ engines: {node: '>=18'}
+
+ supports-color@7.2.0:
+ resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}
+ engines: {node: '>=8'}
+
+ tinybench@2.9.0:
+ resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
+
+ tinyexec@1.2.4:
+ resolution: {integrity: sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==}
+ engines: {node: '>=18'}
+
+ tinyglobby@0.2.17:
+ resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
+ engines: {node: '>=12.0.0'}
+
+ tinyrainbow@3.1.0:
+ resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==}
+ engines: {node: '>=14.0.0'}
+
+ tslib@2.8.1:
+ resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
+
+ typescript@7.0.2:
+ resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==}
+ engines: {node: '>=16.20.0'}
+ hasBin: true
+
+ undici@7.28.0:
+ resolution: {integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==}
+ engines: {node: '>=20.18.1'}
+
+ unenv@2.0.0-rc.24:
+ resolution: {integrity: sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==}
+
+ vite@8.0.16:
+ resolution: {integrity: sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ hasBin: true
+ peerDependencies:
+ '@types/node': ^20.19.0 || >=22.12.0
+ '@vitejs/devtools': ^0.1.18
+ esbuild: ^0.27.0 || ^0.28.0
+ jiti: '>=1.21.0'
+ less: ^4.0.0
+ sass: ^1.70.0
+ sass-embedded: ^1.70.0
+ stylus: '>=0.54.8'
+ sugarss: ^5.0.0
+ terser: ^5.16.0
+ tsx: ^4.8.1
+ yaml: ^2.4.2
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+ '@vitejs/devtools':
+ optional: true
+ esbuild:
+ optional: true
+ jiti:
+ optional: true
+ less:
+ optional: true
+ sass:
+ optional: true
+ sass-embedded:
+ optional: true
+ stylus:
+ optional: true
+ sugarss:
+ optional: true
+ terser:
+ optional: true
+ tsx:
+ optional: true
+ yaml:
+ optional: true
+
+ vitest@4.1.10:
+ resolution: {integrity: sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==}
+ engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0}
+ hasBin: true
+ peerDependencies:
+ '@edge-runtime/vm': '*'
+ '@opentelemetry/api': ^1.9.0
+ '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0
+ '@vitest/browser-playwright': 4.1.10
+ '@vitest/browser-preview': 4.1.10
+ '@vitest/browser-webdriverio': 4.1.10
+ '@vitest/coverage-istanbul': 4.1.10
+ '@vitest/coverage-v8': 4.1.10
+ '@vitest/ui': 4.1.10
+ happy-dom: '*'
+ jsdom: '*'
+ vite: ^6.0.0 || ^7.0.0 || ^8.0.0
+ peerDependenciesMeta:
+ '@edge-runtime/vm':
+ optional: true
+ '@opentelemetry/api':
+ optional: true
+ '@types/node':
+ optional: true
+ '@vitest/browser-playwright':
+ optional: true
+ '@vitest/browser-preview':
+ optional: true
+ '@vitest/browser-webdriverio':
+ optional: true
+ '@vitest/coverage-istanbul':
+ optional: true
+ '@vitest/coverage-v8':
+ optional: true
+ '@vitest/ui':
+ optional: true
+ happy-dom:
+ optional: true
+ jsdom:
+ optional: true
+
+ why-is-node-running@2.3.0:
+ resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
+ engines: {node: '>=8'}
+ hasBin: true
+
+ workerd@1.20260708.1:
+ resolution: {integrity: sha512-WAK+Kt/VVCSldH2qSr8lx46XCJ4Q+bdlHNaFqUtOHthBEIB8C1N8HVW+VOLrxDoTCk0NGNv0zajnBeQK4JOB9w==}
+ engines: {node: '>=16'}
+ hasBin: true
+
+ wrangler@4.110.0:
+ resolution: {integrity: sha512-xZeXKYi7hxQRF5anL+v77RkufJNpF9f3Eqeyqq2QBsETpLZgh0Agj0jJ6JPtkbgn6ukZdh8OK5egsGPWIditgg==}
+ engines: {node: '>=22.0.0'}
+ hasBin: true
+ peerDependencies:
+ '@cloudflare/workers-types': ^5.20260708.1
+ peerDependenciesMeta:
+ '@cloudflare/workers-types':
+ optional: true
+
+ ws@8.21.0:
+ resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==}
+ engines: {node: '>=10.0.0'}
+ peerDependencies:
+ bufferutil: ^4.0.1
+ utf-8-validate: '>=5.0.2'
+ peerDependenciesMeta:
+ bufferutil:
+ optional: true
+ utf-8-validate:
+ optional: true
+
+ youch-core@0.3.3:
+ resolution: {integrity: sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==}
+
+ youch@4.1.0-beta.10:
+ resolution: {integrity: sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==}
+
+snapshots:
+
+ '@babel/helper-string-parser@7.29.7': {}
+
+ '@babel/helper-validator-identifier@7.29.7': {}
+
+ '@babel/parser@7.29.7':
+ dependencies:
+ '@babel/types': 7.29.7
+
+ '@babel/types@7.29.7':
+ dependencies:
+ '@babel/helper-string-parser': 7.29.7
+ '@babel/helper-validator-identifier': 7.29.7
+
+ '@bcoe/v8-coverage@1.0.2': {}
+
+ '@biomejs/biome@2.5.3':
+ optionalDependencies:
+ '@biomejs/cli-darwin-arm64': 2.5.3
+ '@biomejs/cli-darwin-x64': 2.5.3
+ '@biomejs/cli-linux-arm64': 2.5.3
+ '@biomejs/cli-linux-arm64-musl': 2.5.3
+ '@biomejs/cli-linux-x64': 2.5.3
+ '@biomejs/cli-linux-x64-musl': 2.5.3
+ '@biomejs/cli-win32-arm64': 2.5.3
+ '@biomejs/cli-win32-x64': 2.5.3
+
+ '@biomejs/cli-darwin-arm64@2.5.3':
+ optional: true
+
+ '@biomejs/cli-darwin-x64@2.5.3':
+ optional: true
+
+ '@biomejs/cli-linux-arm64-musl@2.5.3':
+ optional: true
+
+ '@biomejs/cli-linux-arm64@2.5.3':
+ optional: true
+
+ '@biomejs/cli-linux-x64-musl@2.5.3':
+ optional: true
+
+ '@biomejs/cli-linux-x64@2.5.3':
+ optional: true
+
+ '@biomejs/cli-win32-arm64@2.5.3':
+ optional: true
+
+ '@biomejs/cli-win32-x64@2.5.3':
+ optional: true
+
+ '@cloudflare/kv-asset-handler@0.5.0': {}
+
+ '@cloudflare/unenv-preset@2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260708.1)':
+ dependencies:
+ unenv: 2.0.0-rc.24
+ optionalDependencies:
+ workerd: 1.20260708.1
+
+ '@cloudflare/workerd-darwin-64@1.20260708.1':
+ optional: true
+
+ '@cloudflare/workerd-darwin-arm64@1.20260708.1':
+ optional: true
+
+ '@cloudflare/workerd-linux-64@1.20260708.1':
+ optional: true
+
+ '@cloudflare/workerd-linux-arm64@1.20260708.1':
+ optional: true
+
+ '@cloudflare/workerd-windows-64@1.20260708.1':
+ optional: true
+
+ '@cloudflare/workers-types@5.20260712.1': {}
+
+ '@cspotcode/source-map-support@0.8.1':
+ dependencies:
+ '@jridgewell/trace-mapping': 0.3.9
+
+ '@emnapi/core@1.10.0':
+ dependencies:
+ '@emnapi/wasi-threads': 1.2.1
+ tslib: 2.8.1
+ optional: true
+
+ '@emnapi/runtime@1.10.0':
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
+ '@emnapi/runtime@1.11.2':
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
+ '@emnapi/wasi-threads@1.2.1':
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
+ '@esbuild/aix-ppc64@0.28.1':
+ optional: true
+
+ '@esbuild/android-arm64@0.28.1':
+ optional: true
+
+ '@esbuild/android-arm@0.28.1':
+ optional: true
+
+ '@esbuild/android-x64@0.28.1':
+ optional: true
+
+ '@esbuild/darwin-arm64@0.28.1':
+ optional: true
+
+ '@esbuild/darwin-x64@0.28.1':
+ optional: true
+
+ '@esbuild/freebsd-arm64@0.28.1':
+ optional: true
+
+ '@esbuild/freebsd-x64@0.28.1':
+ optional: true
+
+ '@esbuild/linux-arm64@0.28.1':
+ optional: true
+
+ '@esbuild/linux-arm@0.28.1':
+ optional: true
+
+ '@esbuild/linux-ia32@0.28.1':
+ optional: true
+
+ '@esbuild/linux-loong64@0.28.1':
+ optional: true
+
+ '@esbuild/linux-mips64el@0.28.1':
+ optional: true
+
+ '@esbuild/linux-ppc64@0.28.1':
+ optional: true
+
+ '@esbuild/linux-riscv64@0.28.1':
+ optional: true
+
+ '@esbuild/linux-s390x@0.28.1':
+ optional: true
+
+ '@esbuild/linux-x64@0.28.1':
+ optional: true
+
+ '@esbuild/netbsd-arm64@0.28.1':
+ optional: true
+
+ '@esbuild/netbsd-x64@0.28.1':
+ optional: true
+
+ '@esbuild/openbsd-arm64@0.28.1':
+ optional: true
+
+ '@esbuild/openbsd-x64@0.28.1':
+ optional: true
+
+ '@esbuild/openharmony-arm64@0.28.1':
+ optional: true
+
+ '@esbuild/sunos-x64@0.28.1':
+ optional: true
+
+ '@esbuild/win32-arm64@0.28.1':
+ optional: true
+
+ '@esbuild/win32-ia32@0.28.1':
+ optional: true
+
+ '@esbuild/win32-x64@0.28.1':
+ optional: true
+
+ '@img/colour@1.1.0': {}
+
+ '@img/sharp-darwin-arm64@0.34.5':
+ optionalDependencies:
+ '@img/sharp-libvips-darwin-arm64': 1.2.4
+ optional: true
+
+ '@img/sharp-darwin-x64@0.34.5':
+ optionalDependencies:
+ '@img/sharp-libvips-darwin-x64': 1.2.4
+ optional: true
+
+ '@img/sharp-libvips-darwin-arm64@1.2.4':
+ optional: true
+
+ '@img/sharp-libvips-darwin-x64@1.2.4':
+ optional: true
+
+ '@img/sharp-libvips-linux-arm64@1.2.4':
+ optional: true
+
+ '@img/sharp-libvips-linux-arm@1.2.4':
+ optional: true
+
+ '@img/sharp-libvips-linux-ppc64@1.2.4':
+ optional: true
+
+ '@img/sharp-libvips-linux-riscv64@1.2.4':
+ optional: true
+
+ '@img/sharp-libvips-linux-s390x@1.2.4':
+ optional: true
+
+ '@img/sharp-libvips-linux-x64@1.2.4':
+ optional: true
+
+ '@img/sharp-libvips-linuxmusl-arm64@1.2.4':
+ optional: true
+
+ '@img/sharp-libvips-linuxmusl-x64@1.2.4':
+ optional: true
+
+ '@img/sharp-linux-arm64@0.34.5':
+ optionalDependencies:
+ '@img/sharp-libvips-linux-arm64': 1.2.4
+ optional: true
+
+ '@img/sharp-linux-arm@0.34.5':
+ optionalDependencies:
+ '@img/sharp-libvips-linux-arm': 1.2.4
+ optional: true
+
+ '@img/sharp-linux-ppc64@0.34.5':
+ optionalDependencies:
+ '@img/sharp-libvips-linux-ppc64': 1.2.4
+ optional: true
+
+ '@img/sharp-linux-riscv64@0.34.5':
+ optionalDependencies:
+ '@img/sharp-libvips-linux-riscv64': 1.2.4
+ optional: true
+
+ '@img/sharp-linux-s390x@0.34.5':
+ optionalDependencies:
+ '@img/sharp-libvips-linux-s390x': 1.2.4
+ optional: true
+
+ '@img/sharp-linux-x64@0.34.5':
+ optionalDependencies:
+ '@img/sharp-libvips-linux-x64': 1.2.4
+ optional: true
+
+ '@img/sharp-linuxmusl-arm64@0.34.5':
+ optionalDependencies:
+ '@img/sharp-libvips-linuxmusl-arm64': 1.2.4
+ optional: true
+
+ '@img/sharp-linuxmusl-x64@0.34.5':
+ optionalDependencies:
+ '@img/sharp-libvips-linuxmusl-x64': 1.2.4
+ optional: true
+
+ '@img/sharp-wasm32@0.34.5':
+ dependencies:
+ '@emnapi/runtime': 1.11.2
+ optional: true
+
+ '@img/sharp-win32-arm64@0.34.5':
+ optional: true
+
+ '@img/sharp-win32-ia32@0.34.5':
+ optional: true
+
+ '@img/sharp-win32-x64@0.34.5':
+ optional: true
+
+ '@jridgewell/resolve-uri@3.1.2': {}
+
+ '@jridgewell/sourcemap-codec@1.5.5': {}
+
+ '@jridgewell/trace-mapping@0.3.31':
+ dependencies:
+ '@jridgewell/resolve-uri': 3.1.2
+ '@jridgewell/sourcemap-codec': 1.5.5
+
+ '@jridgewell/trace-mapping@0.3.9':
+ dependencies:
+ '@jridgewell/resolve-uri': 3.1.2
+ '@jridgewell/sourcemap-codec': 1.5.5
+
+ '@napi-rs/wasm-runtime@1.1.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)':
+ dependencies:
+ '@emnapi/core': 1.10.0
+ '@emnapi/runtime': 1.10.0
+ '@tybys/wasm-util': 0.10.2
+ optional: true
+
+ '@oxc-project/types@0.133.0': {}
+
+ '@poppinss/colors@4.1.6':
+ dependencies:
+ kleur: 4.1.5
+
+ '@poppinss/dumper@0.6.5':
+ dependencies:
+ '@poppinss/colors': 4.1.6
+ '@sindresorhus/is': 7.2.0
+ supports-color: 10.2.2
+
+ '@poppinss/exception@1.2.3': {}
+
+ '@rolldown/binding-android-arm64@1.0.3':
+ optional: true
+
+ '@rolldown/binding-darwin-arm64@1.0.3':
+ optional: true
+
+ '@rolldown/binding-darwin-x64@1.0.3':
+ optional: true
+
+ '@rolldown/binding-freebsd-x64@1.0.3':
+ optional: true
+
+ '@rolldown/binding-linux-arm-gnueabihf@1.0.3':
+ optional: true
+
+ '@rolldown/binding-linux-arm64-gnu@1.0.3':
+ optional: true
+
+ '@rolldown/binding-linux-arm64-musl@1.0.3':
+ optional: true
+
+ '@rolldown/binding-linux-ppc64-gnu@1.0.3':
+ optional: true
+
+ '@rolldown/binding-linux-s390x-gnu@1.0.3':
+ optional: true
+
+ '@rolldown/binding-linux-x64-gnu@1.0.3':
+ optional: true
+
+ '@rolldown/binding-linux-x64-musl@1.0.3':
+ optional: true
+
+ '@rolldown/binding-openharmony-arm64@1.0.3':
+ optional: true
+
+ '@rolldown/binding-wasm32-wasi@1.0.3':
+ dependencies:
+ '@emnapi/core': 1.10.0
+ '@emnapi/runtime': 1.10.0
+ '@napi-rs/wasm-runtime': 1.1.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)
+ optional: true
+
+ '@rolldown/binding-win32-arm64-msvc@1.0.3':
+ optional: true
+
+ '@rolldown/binding-win32-x64-msvc@1.0.3':
+ optional: true
+
+ '@rolldown/pluginutils@1.0.1': {}
+
+ '@sindresorhus/is@7.2.0': {}
+
+ '@speed-highlight/core@1.2.17': {}
+
+ '@standard-schema/spec@1.1.0': {}
+
+ '@tybys/wasm-util@0.10.2':
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
+ '@types/chai@5.2.3':
+ dependencies:
+ '@types/deep-eql': 4.0.2
+ assertion-error: 2.0.1
+
+ '@types/deep-eql@4.0.2': {}
+
+ '@types/estree@1.0.9': {}
+
+ '@typescript/typescript-aix-ppc64@7.0.2':
+ optional: true
+
+ '@typescript/typescript-darwin-arm64@7.0.2':
+ optional: true
+
+ '@typescript/typescript-darwin-x64@7.0.2':
+ optional: true
+
+ '@typescript/typescript-freebsd-arm64@7.0.2':
+ optional: true
+
+ '@typescript/typescript-freebsd-x64@7.0.2':
+ optional: true
+
+ '@typescript/typescript-linux-arm64@7.0.2':
+ optional: true
+
+ '@typescript/typescript-linux-arm@7.0.2':
+ optional: true
+
+ '@typescript/typescript-linux-loong64@7.0.2':
+ optional: true
+
+ '@typescript/typescript-linux-mips64el@7.0.2':
+ optional: true
+
+ '@typescript/typescript-linux-ppc64@7.0.2':
+ optional: true
+
+ '@typescript/typescript-linux-riscv64@7.0.2':
+ optional: true
+
+ '@typescript/typescript-linux-s390x@7.0.2':
+ optional: true
+
+ '@typescript/typescript-linux-x64@7.0.2':
+ optional: true
+
+ '@typescript/typescript-netbsd-arm64@7.0.2':
+ optional: true
+
+ '@typescript/typescript-netbsd-x64@7.0.2':
+ optional: true
+
+ '@typescript/typescript-openbsd-arm64@7.0.2':
+ optional: true
+
+ '@typescript/typescript-openbsd-x64@7.0.2':
+ optional: true
+
+ '@typescript/typescript-sunos-x64@7.0.2':
+ optional: true
+
+ '@typescript/typescript-win32-arm64@7.0.2':
+ optional: true
+
+ '@typescript/typescript-win32-x64@7.0.2':
+ optional: true
+
+ '@vitest/coverage-v8@4.1.10(vitest@4.1.10)':
+ dependencies:
+ '@bcoe/v8-coverage': 1.0.2
+ '@vitest/utils': 4.1.10
+ ast-v8-to-istanbul: 1.0.4
+ istanbul-lib-coverage: 3.2.2
+ istanbul-lib-report: 3.0.1
+ istanbul-reports: 3.2.0
+ magicast: 0.5.3
+ obug: 2.1.3
+ std-env: 4.2.0
+ tinyrainbow: 3.1.0
+ vitest: 4.1.10(@vitest/coverage-v8@4.1.10)(vite@8.0.16(esbuild@0.28.1))
+
+ '@vitest/expect@4.1.10':
+ dependencies:
+ '@standard-schema/spec': 1.1.0
+ '@types/chai': 5.2.3
+ '@vitest/spy': 4.1.10
+ '@vitest/utils': 4.1.10
+ chai: 6.2.2
+ tinyrainbow: 3.1.0
+
+ '@vitest/mocker@4.1.10(vite@8.0.16(esbuild@0.28.1))':
+ dependencies:
+ '@vitest/spy': 4.1.10
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+ vite: 8.0.16(esbuild@0.28.1)
+
+ '@vitest/pretty-format@4.1.10':
+ dependencies:
+ tinyrainbow: 3.1.0
+
+ '@vitest/runner@4.1.10':
+ dependencies:
+ '@vitest/utils': 4.1.10
+ pathe: 2.0.3
+
+ '@vitest/snapshot@4.1.10':
+ dependencies:
+ '@vitest/pretty-format': 4.1.10
+ '@vitest/utils': 4.1.10
+ magic-string: 0.30.21
+ pathe: 2.0.3
+
+ '@vitest/spy@4.1.10': {}
+
+ '@vitest/utils@4.1.10':
+ dependencies:
+ '@vitest/pretty-format': 4.1.10
+ convert-source-map: 2.0.0
+ tinyrainbow: 3.1.0
+
+ assertion-error@2.0.1: {}
+
+ ast-v8-to-istanbul@1.0.4:
+ dependencies:
+ '@jridgewell/trace-mapping': 0.3.31
+ estree-walker: 3.0.3
+ js-tokens: 10.0.0
+
+ blake3-wasm@2.1.5: {}
+
+ chai@6.2.2: {}
+
+ convert-source-map@2.0.0: {}
+
+ cookie@1.1.1: {}
+
+ detect-libc@2.1.2: {}
+
+ error-stack-parser-es@1.0.5: {}
+
+ es-module-lexer@2.3.0: {}
+
+ esbuild@0.28.1:
+ optionalDependencies:
+ '@esbuild/aix-ppc64': 0.28.1
+ '@esbuild/android-arm': 0.28.1
+ '@esbuild/android-arm64': 0.28.1
+ '@esbuild/android-x64': 0.28.1
+ '@esbuild/darwin-arm64': 0.28.1
+ '@esbuild/darwin-x64': 0.28.1
+ '@esbuild/freebsd-arm64': 0.28.1
+ '@esbuild/freebsd-x64': 0.28.1
+ '@esbuild/linux-arm': 0.28.1
+ '@esbuild/linux-arm64': 0.28.1
+ '@esbuild/linux-ia32': 0.28.1
+ '@esbuild/linux-loong64': 0.28.1
+ '@esbuild/linux-mips64el': 0.28.1
+ '@esbuild/linux-ppc64': 0.28.1
+ '@esbuild/linux-riscv64': 0.28.1
+ '@esbuild/linux-s390x': 0.28.1
+ '@esbuild/linux-x64': 0.28.1
+ '@esbuild/netbsd-arm64': 0.28.1
+ '@esbuild/netbsd-x64': 0.28.1
+ '@esbuild/openbsd-arm64': 0.28.1
+ '@esbuild/openbsd-x64': 0.28.1
+ '@esbuild/openharmony-arm64': 0.28.1
+ '@esbuild/sunos-x64': 0.28.1
+ '@esbuild/win32-arm64': 0.28.1
+ '@esbuild/win32-ia32': 0.28.1
+ '@esbuild/win32-x64': 0.28.1
+
+ estree-walker@3.0.3:
+ dependencies:
+ '@types/estree': 1.0.9
+
+ expect-type@1.4.0: {}
+
+ fdir@6.5.0(picomatch@4.0.5):
+ optionalDependencies:
+ picomatch: 4.0.5
+
+ fsevents@2.3.3:
+ optional: true
+
+ has-flag@4.0.0: {}
+
+ html-escaper@2.0.2: {}
+
+ istanbul-lib-coverage@3.2.2: {}
+
+ istanbul-lib-report@3.0.1:
+ dependencies:
+ istanbul-lib-coverage: 3.2.2
+ make-dir: 4.0.0
+ supports-color: 7.2.0
+
+ istanbul-reports@3.2.0:
+ dependencies:
+ html-escaper: 2.0.2
+ istanbul-lib-report: 3.0.1
+
+ js-tokens@10.0.0: {}
+
+ kleur@4.1.5: {}
+
+ lightningcss-android-arm64@1.32.0:
+ optional: true
+
+ lightningcss-darwin-arm64@1.32.0:
+ optional: true
+
+ lightningcss-darwin-x64@1.32.0:
+ optional: true
+
+ lightningcss-freebsd-x64@1.32.0:
+ optional: true
+
+ lightningcss-linux-arm-gnueabihf@1.32.0:
+ optional: true
+
+ lightningcss-linux-arm64-gnu@1.32.0:
+ optional: true
+
+ lightningcss-linux-arm64-musl@1.32.0:
+ optional: true
+
+ lightningcss-linux-x64-gnu@1.32.0:
+ optional: true
+
+ lightningcss-linux-x64-musl@1.32.0:
+ optional: true
+
+ lightningcss-win32-arm64-msvc@1.32.0:
+ optional: true
+
+ lightningcss-win32-x64-msvc@1.32.0:
+ optional: true
+
+ lightningcss@1.32.0:
+ dependencies:
+ detect-libc: 2.1.2
+ optionalDependencies:
+ lightningcss-android-arm64: 1.32.0
+ lightningcss-darwin-arm64: 1.32.0
+ lightningcss-darwin-x64: 1.32.0
+ lightningcss-freebsd-x64: 1.32.0
+ lightningcss-linux-arm-gnueabihf: 1.32.0
+ lightningcss-linux-arm64-gnu: 1.32.0
+ lightningcss-linux-arm64-musl: 1.32.0
+ lightningcss-linux-x64-gnu: 1.32.0
+ lightningcss-linux-x64-musl: 1.32.0
+ lightningcss-win32-arm64-msvc: 1.32.0
+ lightningcss-win32-x64-msvc: 1.32.0
+
+ magic-string@0.30.21:
+ dependencies:
+ '@jridgewell/sourcemap-codec': 1.5.5
+
+ magicast@0.5.3:
+ dependencies:
+ '@babel/parser': 7.29.7
+ '@babel/types': 7.29.7
+ source-map-js: 1.2.1
+
+ make-dir@4.0.0:
+ dependencies:
+ semver: 7.8.5
+
+ miniflare@4.20260708.1:
+ dependencies:
+ '@cspotcode/source-map-support': 0.8.1
+ sharp: 0.34.5
+ undici: 7.28.0
+ workerd: 1.20260708.1
+ ws: 8.21.0
+ youch: 4.1.0-beta.10
+ transitivePeerDependencies:
+ - bufferutil
+ - utf-8-validate
+
+ nanoid@3.3.13: {}
+
+ obug@2.1.3: {}
+
+ path-to-regexp@6.3.0: {}
+
+ pathe@2.0.3: {}
+
+ picocolors@1.1.1: {}
+
+ picomatch@4.0.5: {}
+
+ postcss@8.5.15:
+ dependencies:
+ nanoid: 3.3.13
+ picocolors: 1.1.1
+ source-map-js: 1.2.1
+
+ rolldown@1.0.3:
+ dependencies:
+ '@oxc-project/types': 0.133.0
+ '@rolldown/pluginutils': 1.0.1
+ optionalDependencies:
+ '@rolldown/binding-android-arm64': 1.0.3
+ '@rolldown/binding-darwin-arm64': 1.0.3
+ '@rolldown/binding-darwin-x64': 1.0.3
+ '@rolldown/binding-freebsd-x64': 1.0.3
+ '@rolldown/binding-linux-arm-gnueabihf': 1.0.3
+ '@rolldown/binding-linux-arm64-gnu': 1.0.3
+ '@rolldown/binding-linux-arm64-musl': 1.0.3
+ '@rolldown/binding-linux-ppc64-gnu': 1.0.3
+ '@rolldown/binding-linux-s390x-gnu': 1.0.3
+ '@rolldown/binding-linux-x64-gnu': 1.0.3
+ '@rolldown/binding-linux-x64-musl': 1.0.3
+ '@rolldown/binding-openharmony-arm64': 1.0.3
+ '@rolldown/binding-wasm32-wasi': 1.0.3
+ '@rolldown/binding-win32-arm64-msvc': 1.0.3
+ '@rolldown/binding-win32-x64-msvc': 1.0.3
+
+ semver@7.8.5: {}
+
+ sharp@0.34.5:
+ dependencies:
+ '@img/colour': 1.1.0
+ detect-libc: 2.1.2
+ semver: 7.8.5
+ optionalDependencies:
+ '@img/sharp-darwin-arm64': 0.34.5
+ '@img/sharp-darwin-x64': 0.34.5
+ '@img/sharp-libvips-darwin-arm64': 1.2.4
+ '@img/sharp-libvips-darwin-x64': 1.2.4
+ '@img/sharp-libvips-linux-arm': 1.2.4
+ '@img/sharp-libvips-linux-arm64': 1.2.4
+ '@img/sharp-libvips-linux-ppc64': 1.2.4
+ '@img/sharp-libvips-linux-riscv64': 1.2.4
+ '@img/sharp-libvips-linux-s390x': 1.2.4
+ '@img/sharp-libvips-linux-x64': 1.2.4
+ '@img/sharp-libvips-linuxmusl-arm64': 1.2.4
+ '@img/sharp-libvips-linuxmusl-x64': 1.2.4
+ '@img/sharp-linux-arm': 0.34.5
+ '@img/sharp-linux-arm64': 0.34.5
+ '@img/sharp-linux-ppc64': 0.34.5
+ '@img/sharp-linux-riscv64': 0.34.5
+ '@img/sharp-linux-s390x': 0.34.5
+ '@img/sharp-linux-x64': 0.34.5
+ '@img/sharp-linuxmusl-arm64': 0.34.5
+ '@img/sharp-linuxmusl-x64': 0.34.5
+ '@img/sharp-wasm32': 0.34.5
+ '@img/sharp-win32-arm64': 0.34.5
+ '@img/sharp-win32-ia32': 0.34.5
+ '@img/sharp-win32-x64': 0.34.5
+
+ siginfo@2.0.0: {}
+
+ source-map-js@1.2.1: {}
+
+ stackback@0.0.2: {}
+
+ std-env@4.2.0: {}
+
+ supports-color@10.2.2: {}
+
+ supports-color@7.2.0:
+ dependencies:
+ has-flag: 4.0.0
+
+ tinybench@2.9.0: {}
+
+ tinyexec@1.2.4: {}
+
+ tinyglobby@0.2.17:
+ dependencies:
+ fdir: 6.5.0(picomatch@4.0.5)
+ picomatch: 4.0.5
+
+ tinyrainbow@3.1.0: {}
+
+ tslib@2.8.1:
+ optional: true
+
+ typescript@7.0.2:
+ optionalDependencies:
+ '@typescript/typescript-aix-ppc64': 7.0.2
+ '@typescript/typescript-darwin-arm64': 7.0.2
+ '@typescript/typescript-darwin-x64': 7.0.2
+ '@typescript/typescript-freebsd-arm64': 7.0.2
+ '@typescript/typescript-freebsd-x64': 7.0.2
+ '@typescript/typescript-linux-arm': 7.0.2
+ '@typescript/typescript-linux-arm64': 7.0.2
+ '@typescript/typescript-linux-loong64': 7.0.2
+ '@typescript/typescript-linux-mips64el': 7.0.2
+ '@typescript/typescript-linux-ppc64': 7.0.2
+ '@typescript/typescript-linux-riscv64': 7.0.2
+ '@typescript/typescript-linux-s390x': 7.0.2
+ '@typescript/typescript-linux-x64': 7.0.2
+ '@typescript/typescript-netbsd-arm64': 7.0.2
+ '@typescript/typescript-netbsd-x64': 7.0.2
+ '@typescript/typescript-openbsd-arm64': 7.0.2
+ '@typescript/typescript-openbsd-x64': 7.0.2
+ '@typescript/typescript-sunos-x64': 7.0.2
+ '@typescript/typescript-win32-arm64': 7.0.2
+ '@typescript/typescript-win32-x64': 7.0.2
+
+ undici@7.28.0: {}
+
+ unenv@2.0.0-rc.24:
+ dependencies:
+ pathe: 2.0.3
+
+ vite@8.0.16(esbuild@0.28.1):
+ dependencies:
+ lightningcss: 1.32.0
+ picomatch: 4.0.5
+ postcss: 8.5.15
+ rolldown: 1.0.3
+ tinyglobby: 0.2.17
+ optionalDependencies:
+ esbuild: 0.28.1
+ fsevents: 2.3.3
+
+ vitest@4.1.10(@vitest/coverage-v8@4.1.10)(vite@8.0.16(esbuild@0.28.1)):
+ dependencies:
+ '@vitest/expect': 4.1.10
+ '@vitest/mocker': 4.1.10(vite@8.0.16(esbuild@0.28.1))
+ '@vitest/pretty-format': 4.1.10
+ '@vitest/runner': 4.1.10
+ '@vitest/snapshot': 4.1.10
+ '@vitest/spy': 4.1.10
+ '@vitest/utils': 4.1.10
+ es-module-lexer: 2.3.0
+ expect-type: 1.4.0
+ magic-string: 0.30.21
+ obug: 2.1.3
+ pathe: 2.0.3
+ picomatch: 4.0.5
+ std-env: 4.2.0
+ tinybench: 2.9.0
+ tinyexec: 1.2.4
+ tinyglobby: 0.2.17
+ tinyrainbow: 3.1.0
+ vite: 8.0.16(esbuild@0.28.1)
+ why-is-node-running: 2.3.0
+ optionalDependencies:
+ '@vitest/coverage-v8': 4.1.10(vitest@4.1.10)
+ transitivePeerDependencies:
+ - msw
+
+ why-is-node-running@2.3.0:
+ dependencies:
+ siginfo: 2.0.0
+ stackback: 0.0.2
+
+ workerd@1.20260708.1:
+ optionalDependencies:
+ '@cloudflare/workerd-darwin-64': 1.20260708.1
+ '@cloudflare/workerd-darwin-arm64': 1.20260708.1
+ '@cloudflare/workerd-linux-64': 1.20260708.1
+ '@cloudflare/workerd-linux-arm64': 1.20260708.1
+ '@cloudflare/workerd-windows-64': 1.20260708.1
+
+ wrangler@4.110.0(@cloudflare/workers-types@5.20260712.1):
+ dependencies:
+ '@cloudflare/kv-asset-handler': 0.5.0
+ '@cloudflare/unenv-preset': 2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260708.1)
+ blake3-wasm: 2.1.5
+ esbuild: 0.28.1
+ miniflare: 4.20260708.1
+ path-to-regexp: 6.3.0
+ unenv: 2.0.0-rc.24
+ workerd: 1.20260708.1
+ optionalDependencies:
+ '@cloudflare/workers-types': 5.20260712.1
+ fsevents: 2.3.3
+ transitivePeerDependencies:
+ - bufferutil
+ - utf-8-validate
+
+ ws@8.21.0: {}
+
+ youch-core@0.3.3:
+ dependencies:
+ '@poppinss/exception': 1.2.3
+ error-stack-parser-es: 1.0.5
+
+ youch@4.1.0-beta.10:
+ dependencies:
+ '@poppinss/colors': 4.1.6
+ '@poppinss/dumper': 0.6.5
+ '@speed-highlight/core': 1.2.17
+ cookie: 1.1.1
+ youch-core: 0.3.3
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..dee8b7e5883e757bbeffd3af8a55e2682c8ce248
--- /dev/null
+++ b/pnpm-workspace.yaml
@@ -0,0 +1,40 @@
+packageImportMethod: copy
+allowBuilds:
+ esbuild: true
+ sharp: true
+ workerd: true
+minimumReleaseAgeExclude:
+ - '@cloudflare/workers-types@5.20260712.1'
+ - '@biomejs/biome@2.5.3'
+ - '@biomejs/cli-darwin-arm64@2.5.3'
+ - '@biomejs/cli-darwin-x64@2.5.3'
+ - '@biomejs/cli-linux-arm64-musl@2.5.3'
+ - '@biomejs/cli-linux-arm64@2.5.3'
+ - '@biomejs/cli-linux-x64-musl@2.5.3'
+ - '@biomejs/cli-linux-x64@2.5.3'
+ - '@biomejs/cli-win32-arm64@2.5.3'
+ - '@biomejs/cli-win32-x64@2.5.3'
+ - '@typescript/typescript-aix-ppc64@7.0.2'
+ - '@typescript/typescript-darwin-arm64@7.0.2'
+ - '@typescript/typescript-darwin-x64@7.0.2'
+ - '@typescript/typescript-freebsd-arm64@7.0.2'
+ - '@typescript/typescript-freebsd-x64@7.0.2'
+ - '@typescript/typescript-linux-arm64@7.0.2'
+ - '@typescript/typescript-linux-arm@7.0.2'
+ - '@typescript/typescript-linux-loong64@7.0.2'
+ - '@typescript/typescript-linux-mips64el@7.0.2'
+ - '@typescript/typescript-linux-ppc64@7.0.2'
+ - '@typescript/typescript-linux-riscv64@7.0.2'
+ - '@typescript/typescript-linux-s390x@7.0.2'
+ - '@typescript/typescript-linux-x64@7.0.2'
+ - '@typescript/typescript-netbsd-arm64@7.0.2'
+ - '@typescript/typescript-netbsd-x64@7.0.2'
+ - '@typescript/typescript-openbsd-arm64@7.0.2'
+ - '@typescript/typescript-openbsd-x64@7.0.2'
+ - '@typescript/typescript-sunos-x64@7.0.2'
+ - '@typescript/typescript-win32-arm64@7.0.2'
+ - '@typescript/typescript-win32-x64@7.0.2'
+ - typescript@7.0.2
+peerDependencyRules:
+ allowedVersions:
+ '@cloudflare/workers-types': '>=4.20260702.1 <6'
diff --git a/scripts/bench.mjs b/scripts/bench.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..f47622ffb656eb207148e2b87f4db615505affa4
--- /dev/null
+++ b/scripts/bench.mjs
@@ -0,0 +1,1150 @@
+import { resolve } from "node:path";
+import { performance } from "node:perf_hooks";
+import { pathToFileURL } from "node:url";
+import { errorLine, outputLine } from "./io.mjs";
+
+const benchmarkBundlePath = resolve(
+ process.cwd(),
+ process.env.BENCH_TEST_BUNDLE || "dist/worker.test.js",
+);
+let mod;
+try {
+ mod = await import(pathToFileURL(benchmarkBundlePath).href);
+} catch (error) {
+ errorLine(
+ `Benchmark bundle load failed: ${benchmarkBundlePath}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ process.exit(1);
+}
+
+const ITERATIONS = positiveInt(process.env.BENCH_ITERS, 2000);
+const JSON_OUTPUT = /^(1|true|yes|on)$/i.test(
+ String(process.env.BENCH_JSON || ""),
+);
+const WARMUP = positiveInt(
+ process.env.BENCH_WARMUP,
+ Math.min(500, Math.floor(ITERATIONS / 4)),
+);
+const SSE_CHUNKS = positiveInt(process.env.BENCH_SSE_CHUNKS, 512);
+const SSE_SLOW_CHUNKS = positiveInt(process.env.BENCH_SSE_SLOW_CHUNKS, 128);
+const SSE_SLOW_DELAY_MS = positiveInt(process.env.BENCH_SSE_SLOW_DELAY_MS, 1);
+const SOCKET_BODY_BYTES = positiveInt(
+ process.env.BENCH_SOCKET_BODY_BYTES,
+ 64 * 1024,
+);
+const SOCKET_CHUNK_BYTES = positiveInt(
+ process.env.BENCH_SOCKET_CHUNK_BYTES,
+ 1024,
+);
+const UNIQUE_ITEMS_COUNT = positiveInt(
+ process.env.BENCH_UNIQUE_ITEMS_COUNT,
+ 240,
+);
+const BASE64_BYTES = positiveInt(process.env.BENCH_BASE64_BYTES, 64 * 1024);
+const MULTIPART_BYTES = positiveInt(
+ process.env.BENCH_MULTIPART_BYTES,
+ 8 * 1024 * 1024,
+);
+const APP_HTML_BYTES = positiveInt(
+ process.env.BENCH_APP_HTML_BYTES,
+ 512 * 1024,
+);
+const APP_HTML_CHUNK_BYTES = positiveInt(
+ process.env.BENCH_APP_HTML_CHUNK_BYTES,
+ 4096,
+);
+const STRUCTURED_JSON_NOISE_BYTES = positiveInt(
+ process.env.BENCH_STRUCTURED_JSON_NOISE_BYTES,
+ 16 * 1024,
+);
+const STREAM_CUMULATIVE_STEPS = positiveInt(
+ process.env.BENCH_STREAM_CUMULATIVE_STEPS,
+ 160,
+);
+const STREAM_CUMULATIVE_STEP_CHARS = positiveInt(
+ process.env.BENCH_STREAM_CUMULATIVE_STEP_CHARS,
+ 256,
+);
+const STREAM_LONG_LINE_BYTES = positiveInt(
+ process.env.BENCH_STREAM_LONG_LINE_BYTES,
+ 64 * 1024,
+);
+const STREAM_LONG_LINE_CHUNK_BYTES = positiveInt(
+ process.env.BENCH_STREAM_LONG_LINE_CHUNK_BYTES,
+ 128,
+);
+const SOCKET_LONG_CHUNK_LINE_BYTES = positiveInt(
+ process.env.BENCH_SOCKET_LONG_CHUNK_LINE_BYTES,
+ 4096,
+);
+const CONFIG_CACHE_BENCH_ENVS = {
+ empty: {},
+ realistic: {
+ GEMINI_COOKIE: "__Secure-1PSID=bench-session; SAPISID=bench-sapisid",
+ SAPISID: "bench-sapisid",
+ API_KEYS: ["sk-bench-primary", "sk-bench-secondary"],
+ DEFAULT_MODEL: "gemini-3.5-flash",
+ },
+ large: {
+ GEMINI_COOKIE: `SID=${"x".repeat(64 * 1024)}`,
+ SAPISID: "s".repeat(4096),
+ API_KEYS: ["a".repeat(4096), "b".repeat(4096)],
+ },
+ maximum: {
+ GEMINI_COOKIE: `SID=${"x".repeat(1024 * 1024 - 4)}`,
+ SAPISID: "s".repeat(4096),
+ API_KEYS: ["a".repeat(4096), "b".repeat(4096)],
+ },
+};
+const ATTACHMENT_DEDUPE_BYTES = new Uint8Array(8 * 1024 * 1024);
+ATTACHMENT_DEDUPE_BYTES.fill(0x61);
+const ATTACHMENT_DEDUPE_INPUT = {
+ candidate: {},
+ bytes: ATTACHMENT_DEDUPE_BYTES,
+ mime: "application/octet-stream",
+ filename: "benchmark.bin",
+};
+const TOOL = {
+ type: "function",
+ function: {
+ name: "Read",
+ parameters: { type: "object", properties: { path: { type: "string" } } },
+ },
+};
+const CFG = {
+ gemini_bl: "bench",
+ gemini_origin: "https://gemini.google.com",
+ upstream_socket: false,
+ default_model: "gemini-3.5-flash",
+ retry_attempts: 1,
+ retry_delay_sec: 0,
+ request_timeout_sec: 1,
+ log_requests: false,
+ current_input_file_enabled: true,
+ current_input_file_min_bytes: 95000,
+ current_input_file_name: "message.txt",
+ current_tools_file_name: "tools.txt",
+ api_keys: [],
+ cookie: "",
+ sapisid: "",
+};
+const FAKE_PROVIDER = {
+ async generateText() {
+ return "ok";
+ },
+ async *streamText() {
+ yield "ok";
+ },
+ async resolveAttachments() {
+ return emptyAttachmentResult();
+ },
+ async uploadTextFile(_text, filename) {
+ return { ref: `/uploaded/${filename}`, name: filename };
+ },
+};
+
+const longFalsePositive = makeLongFalsePositiveText(96_000);
+const validDsml = [
+ "before",
+ '/tmp/a.txt',
+ "after",
+].join("\n");
+const messages = [
+ { role: "system", content: "You are concise." },
+ { role: "user", content: "Read the file and summarize it." },
+];
+const tools = [TOOL];
+const toolBundle = mod.createToolBundle(tools);
+const socketSingleBody = makeBytes(SOCKET_BODY_BYTES);
+const socketChunks = makeSocketChunks(SOCKET_BODY_BYTES, SOCKET_CHUNK_BYTES);
+const socketTextSingleResponse = makeHttpResponseChunks(
+ socketSingleBody,
+ SOCKET_BODY_BYTES,
+);
+const socketTextMultiResponse = makeHttpResponseChunks(
+ socketChunks,
+ SOCKET_BODY_BYTES,
+);
+const uniqueItemsValue = makeUniqueCompositeValues(UNIQUE_ITEMS_COUNT);
+const uniqueItemsRequirement = {
+ type: "json_schema",
+ schema: { type: "array", uniqueItems: true },
+};
+const structuredPatternValue = {
+ tag: "ok-ready",
+ slug: "item-123",
+ note: "alpha",
+};
+const structuredPatternRequirement = {
+ type: "json_schema",
+ schema: {
+ type: "object",
+ required: ["tag", "slug"],
+ properties: {
+ tag: { type: "string", pattern: "^ok-[a-z0-9-]{2,32}$" },
+ slug: { type: "string", pattern: "^[a-z]+-[0-9]{3}$" },
+ note: { type: "string", pattern: "^[a-z]+$" },
+ },
+ },
+};
+const base64Input = bytesToBase64(makeBytes(BASE64_BYTES));
+const multipartBytes = makeBytes(MULTIPART_BYTES);
+const appPageTokensHtml = makeAppHtml(
+ APP_HTML_BYTES,
+ '{"qKIAYe":"push-bench","SNlM0e":"at-bench"}',
+);
+const appBuildLabelHtml = makeAppHtml(
+ APP_HTML_BYTES,
+ '',
+);
+const structuredJsonNoise = "{".repeat(STRUCTURED_JSON_NOISE_BYTES);
+const markdownRestoreMasked = mod.maskMarkdownProtectedSpans(
+ makeMarkdownProtectedText(300),
+);
+const markdownRestorePlaceholderCount = countOccurrences(
+ markdownRestoreMasked.text,
+ "GEMINI_MD_PROTECTED_",
+);
+const largeJsonBody = JSON.stringify({
+ message: "x".repeat(128 * 1024),
+ ok: true,
+});
+const longHeldToolCandidate = makeLongHeldToolCandidate(240 * 1024);
+const cumulativeWrbLines = makeCumulativeWrbLines(
+ STREAM_CUMULATIVE_STEPS,
+ STREAM_CUMULATIVE_STEP_CHARS,
+);
+const longLineResponseChunks = makeLongLineStreamResponseChunks(
+ STREAM_LONG_LINE_BYTES,
+ STREAM_LONG_LINE_CHUNK_BYTES,
+);
+const socketLongChunkedLineResponse = makeSocketLongChunkedLineResponse(
+ SOCKET_LONG_CHUNK_LINE_BYTES,
+);
+const smallDeltaProvider = {
+ async generateText() {
+ return "ok";
+ },
+ async *streamText() {
+ for (let i = 0; i < SSE_CHUNKS; i++) yield "x";
+ },
+ async resolveAttachments() {
+ return emptyAttachmentResult();
+ },
+ async uploadTextFile(_text, filename) {
+ return { ref: `/uploaded/${filename}`, name: filename };
+ },
+};
+function emptyAttachmentResult() {
+ return {
+ fileRefs: null,
+ imageFileRefs: null,
+ genericFileRefs: null,
+ droppedNote: "",
+ usage: {
+ uploadedFiles: 0,
+ dedupedFiles: 0,
+ uploadedBytes: 0,
+ droppedFiles: 0,
+ },
+ };
+}
+
+const cases = [
+ {
+ name: "config_cache_empty",
+ fn: () => mod.getConfig(CONFIG_CACHE_BENCH_ENVS.empty),
+ },
+ {
+ name: "config_cache_realistic",
+ fn: () => mod.getConfig(CONFIG_CACHE_BENCH_ENVS.realistic),
+ },
+ {
+ name: "config_cache_large_secrets",
+ fn: () => mod.getConfig(CONFIG_CACHE_BENCH_ENVS.large),
+ iterations: Math.min(ITERATIONS, 1000),
+ warmup: Math.min(WARMUP, 100),
+ },
+ {
+ name: "config_cache_maximum_secrets",
+ fn: () => mod.getConfig(CONFIG_CACHE_BENCH_ENVS.maximum),
+ iterations: Math.min(ITERATIONS, 200),
+ warmup: Math.min(WARMUP, 20),
+ },
+ {
+ name: "attachment_dedupe_large",
+ fn: () => mod.attachmentDedupeKeyForTest(ATTACHMENT_DEDUPE_INPUT),
+ iterations: Math.min(ITERATIONS, 30),
+ warmup: Math.min(WARMUP, 5),
+ },
+ {
+ name: "route_options",
+ fn: () =>
+ mod.default.fetch(
+ new Request("https://worker.example/v1/models", { method: "OPTIONS" }),
+ {},
+ {},
+ ),
+ },
+ {
+ name: "route_health",
+ fn: () => mod.default.fetch(new Request("https://worker.example/"), {}, {}),
+ },
+ {
+ name: "route_models",
+ fn: () =>
+ mod.default.fetch(
+ new Request("https://worker.example/v1/models"),
+ {},
+ {},
+ ),
+ },
+ {
+ name: "json_invalid",
+ fn: () =>
+ mod.default.fetch(
+ new Request("https://worker.example/v1/chat/completions", {
+ method: "POST",
+ body: "{",
+ }),
+ {},
+ {},
+ ),
+ },
+ {
+ name: "json_large_strict",
+ fn: () => runReadLargeJsonStrict(),
+ iterations: Math.min(ITERATIONS, 500),
+ warmup: Math.min(WARMUP, 100),
+ },
+ {
+ name: "json_oversized_reject",
+ fn: () =>
+ mod.default.fetch(
+ new Request("https://worker.example/v1/chat/completions", {
+ method: "POST",
+ headers: { "content-length": "95001" },
+ body: "{}",
+ }),
+ {},
+ {},
+ ),
+ },
+ {
+ name: "messages_to_prompt",
+ fn: () =>
+ mod.messagesToPrompt(
+ messages,
+ toolBundle,
+ "auto",
+ toolBundle.defs,
+ "",
+ 1_000_000,
+ ),
+ },
+ {
+ name: "prepare_openai_context",
+ fn: () =>
+ mod.prepareOpenAIGeminiContext(
+ CFG,
+ FAKE_PROVIDER,
+ { model: "gemini-3.5-flash" },
+ messages,
+ toolBundle,
+ "auto",
+ null,
+ null,
+ ),
+ },
+ {
+ name: "parse_plain_long_false_positive",
+ fn: () => mod.parseToolCalls(longFalsePositive, tools),
+ },
+ { name: "parse_valid_dsml", fn: () => mod.parseToolCalls(validDsml, tools) },
+ {
+ name: "stream_sieve_plain_chunks",
+ fn: () => runPlainSieveChunks(longFalsePositive),
+ },
+ {
+ name: "stream_sieve_held_tool",
+ fn: () => runHeldToolCandidateChunks(longHeldToolCandidate),
+ iterations: Math.min(ITERATIONS, 300),
+ warmup: Math.min(WARMUP, 50),
+ },
+ {
+ name: "stream_text_cumulative_deltas",
+ fn: () => runStreamTextCumulativeDeltas(),
+ iterations: Math.min(ITERATIONS, 120),
+ warmup: Math.min(WARMUP, 20),
+ },
+ {
+ name: "gemini_stream_long_line_chunks",
+ fn: () => runGeminiStreamLongLineChunks(),
+ iterations: Math.min(ITERATIONS, 80),
+ warmup: Math.min(WARMUP, 10),
+ },
+ {
+ name: "responses_small_delta_stream",
+ fn: () => runResponsesSmallDeltaStream(),
+ iterations: Math.min(ITERATIONS, 60),
+ warmup: Math.min(WARMUP, 10),
+ },
+ {
+ name: "google_small_delta_stream",
+ fn: () => runGoogleSmallDeltaStream(),
+ iterations: Math.min(ITERATIONS, 60),
+ warmup: Math.min(WARMUP, 10),
+ },
+ {
+ name: "sse_many_small_delta",
+ fn: () => runSseChunks({ chunks: SSE_CHUNKS, delayMs: 0 }),
+ iterations: Math.min(ITERATIONS, 400),
+ warmup: Math.min(WARMUP, 100),
+ },
+ {
+ name: "sse_slow_consumer",
+ fn: () =>
+ runSseChunks({ chunks: SSE_SLOW_CHUNKS, delayMs: SSE_SLOW_DELAY_MS }),
+ iterations: Math.min(ITERATIONS, 30),
+ warmup: Math.min(WARMUP, 5),
+ },
+ {
+ name: "socket_single_chunk_body",
+ fn: () => runSocketSingleChunkBody(),
+ iterations: Math.min(ITERATIONS, 1000),
+ warmup: Math.min(WARMUP, 200),
+ },
+ {
+ name: "socket_multi_chunk_body",
+ fn: () => runSocketMultiChunkBody(),
+ iterations: Math.min(ITERATIONS, 1000),
+ warmup: Math.min(WARMUP, 200),
+ },
+ {
+ name: "socket_text_single_chunk",
+ fn: () => runSocketText(socketTextSingleResponse),
+ iterations: Math.min(ITERATIONS, 400),
+ warmup: Math.min(WARMUP, 100),
+ },
+ {
+ name: "socket_text_multi_chunk",
+ fn: () => runSocketText(socketTextMultiResponse),
+ iterations: Math.min(ITERATIONS, 400),
+ warmup: Math.min(WARMUP, 100),
+ },
+ {
+ name: "socket_chunked_long_split_line",
+ fn: () => runSocketText(socketLongChunkedLineResponse),
+ iterations: Math.min(ITERATIONS, 80),
+ warmup: Math.min(WARMUP, 10),
+ },
+ {
+ name: "structured_unique_items",
+ fn: () => runUniqueItemsValidation(),
+ iterations: Math.min(ITERATIONS, 200),
+ warmup: Math.min(WARMUP, 50),
+ },
+ {
+ name: "structured_pattern_schema",
+ fn: () => runStructuredPatternValidation(),
+ iterations: Math.min(ITERATIONS, 1000),
+ warmup: Math.min(WARMUP, 200),
+ },
+ {
+ name: "base64_decode_large",
+ fn: () => runBase64Decode(),
+ iterations: Math.min(ITERATIONS, 1000),
+ warmup: Math.min(WARMUP, 200),
+ },
+ {
+ name: "multipart_body_large",
+ fn: () => runMultipartBodyLarge(),
+ iterations: Math.min(ITERATIONS, 1000),
+ warmup: Math.min(WARMUP, 200),
+ },
+ {
+ name: "app_page_tokens_large",
+ fn: () => runAppPageTokensLarge(),
+ iterations: Math.min(ITERATIONS, 200),
+ warmup: Math.min(WARMUP, 50),
+ },
+ {
+ name: "app_build_label_large",
+ fn: () => runAppBuildLabelLarge(),
+ iterations: Math.min(ITERATIONS, 200),
+ warmup: Math.min(WARMUP, 50),
+ },
+ {
+ name: "structured_json_unclosed",
+ fn: () => runStructuredJsonUnclosed(),
+ iterations: Math.min(ITERATIONS, 100),
+ warmup: Math.min(WARMUP, 20),
+ },
+ { name: "rand_hex_32", fn: () => runRandHex32() },
+ {
+ name: "markdown_restore_many",
+ fn: () => runMarkdownRestoreMany(),
+ iterations: Math.min(ITERATIONS, 1000),
+ warmup: Math.min(WARMUP, 200),
+ },
+];
+
+const caseFilters = String(process.env.BENCH_CASES || "")
+ .split(",")
+ .map((value) => value.trim())
+ .filter(Boolean);
+const selectedCases = caseFilters.length
+ ? cases.filter((item) =>
+ caseFilters.some((filter) => item.name.includes(filter)),
+ )
+ : cases;
+if (!selectedCases.length) {
+ errorLine(`No benchmark cases matched BENCH_CASES=${caseFilters.join(",")}`);
+ process.exit(1);
+}
+
+const results = [];
+for (const item of selectedCases) {
+ const result = await bench(item.fn, item);
+ results.push({ name: item.name, ...result });
+}
+if (JSON_OUTPUT) {
+ outputLine(
+ JSON.stringify({
+ iterations: ITERATIONS,
+ warmup: WARMUP,
+ filters: caseFilters,
+ results,
+ }),
+ );
+} else {
+ outputLine(`Benchmark iterations=${ITERATIONS} warmup=${WARMUP}`);
+ if (caseFilters.length)
+ outputLine(`Benchmark filters=${caseFilters.join(",")}`);
+ for (const result of results) outputLine(formatResult(result.name, result));
+}
+
+async function bench(fn, options = {}) {
+ const iterations = positiveInt(options.iterations, ITERATIONS);
+ const warmup = positiveInt(options.warmup, WARMUP);
+ for (let i = 0; i < warmup; i++) await fn();
+ const samples = new Array(iterations);
+ let lastValue;
+ const totalStart = performance.now();
+ for (let i = 0; i < iterations; i++) {
+ const start = performance.now();
+ lastValue = await fn();
+ samples[i] = performance.now() - start;
+ }
+ const totalMs = performance.now() - totalStart;
+ samples.sort((a, b) => a - b);
+ return {
+ iterations,
+ warmup,
+ medianMs: percentile(samples, 0.5),
+ p95Ms: percentile(samples, 0.95),
+ p99Ms: percentile(samples, 0.99),
+ meanMs: totalMs / iterations,
+ opsPerSec: iterations / (totalMs / 1000),
+ details: benchmarkDetails(lastValue),
+ };
+}
+
+function formatResult(name, result) {
+ const fields = [
+ name.padEnd(30),
+ `n=${result.iterations}`,
+ `median=${formatMs(result.medianMs)}`,
+ `p95=${formatMs(result.p95Ms)}`,
+ `p99=${formatMs(result.p99Ms)}`,
+ `mean=${formatMs(result.meanMs)}`,
+ `ops/s=${Math.round(result.opsPerSec)}`,
+ ];
+ const details = formatDetails(result.details);
+ if (details) fields.push(details);
+ return fields.join(" ");
+}
+
+function benchmarkDetails(value) {
+ if (!value || typeof value !== "object" || !value.__benchDetails) return null;
+ return value.__benchDetails;
+}
+
+function formatDetails(details) {
+ if (!details || typeof details !== "object") return "";
+ return Object.entries(details)
+ .map(
+ ([key, val]) =>
+ `${key}=${typeof val === "number" ? Math.round(val) : String(val)}`,
+ )
+ .join(" ");
+}
+
+function percentile(sorted, p) {
+ if (!sorted.length) return 0;
+ const index = Math.min(
+ sorted.length - 1,
+ Math.max(0, Math.floor((sorted.length - 1) * p)),
+ );
+ return sorted[index] || 0;
+}
+
+function formatMs(ms) {
+ if (ms < 1) return `${(ms * 1000).toFixed(1)}us`;
+ return `${ms.toFixed(3)}ms`;
+}
+
+function positiveInt(value, fallback) {
+ const n = Number.parseInt(String(value ?? ""), 10);
+ return Number.isFinite(n) && n > 0 ? n : fallback;
+}
+
+function makeLongFalsePositiveText(bytes) {
+ const line =
+ "ordinary prose: a < b, parameterless discussion, invoke is just a word, tool_calls appears as text.\n";
+ let out = "";
+ while (out.length < bytes) out += line;
+ return out.slice(0, bytes);
+}
+
+function makeLongHeldToolCandidate(bytes) {
+ const prefix = '';
+ const suffix = "";
+ return (
+ prefix +
+ "x".repeat(Math.max(0, bytes - prefix.length - suffix.length)) +
+ suffix
+ );
+}
+
+function wrbLine(texts) {
+ const inner = [null, null, null, null, [[null, texts]], "x".repeat(160)];
+ return JSON.stringify([["wrb.fr", null, JSON.stringify(inner)]]);
+}
+
+function makeCumulativeWrbLines(steps, stepChars) {
+ const lines = [];
+ let text = "";
+ const piece = "x".repeat(stepChars);
+ for (let i = 0; i < steps; i++) {
+ text += piece;
+ lines.push(wrbLine([text]));
+ }
+ return lines;
+}
+
+function runStreamTextCumulativeDeltas() {
+ const extractor = mod.createStreamTextExtractor();
+ let deltas = 0;
+ let chars = 0;
+ for (const line of cumulativeWrbLines) {
+ for (const delta of extractor.consumeLine(line)) {
+ deltas += 1;
+ chars += delta.length;
+ }
+ }
+ return {
+ __benchDetails: {
+ lines: cumulativeWrbLines.length,
+ chars,
+ deltas,
+ },
+ };
+}
+
+async function runGeminiStreamLongLineChunks() {
+ const stats = installFetchChunks(longLineResponseChunks);
+ let chunks = 0;
+ let chars = 0;
+ try {
+ for await (const delta of mod.generateStream(
+ CFG,
+ "bench",
+ 1,
+ 0,
+ null,
+ null,
+ )) {
+ chunks += 1;
+ chars += delta.length;
+ }
+ } finally {
+ stats.restore();
+ }
+ return {
+ __benchDetails: {
+ responseChunks: stats.chunks,
+ chars,
+ chunks,
+ },
+ };
+}
+
+function makeLongLineStreamResponseChunks(totalBytes, chunkBytes) {
+ const text = "x".repeat(totalBytes);
+ const line = new TextEncoder().encode(`${wrbLine([text])}\n`);
+ const chunks = [];
+ for (let i = 0; i < line.length; i += chunkBytes) {
+ chunks.push(line.subarray(i, i + chunkBytes));
+ }
+ return chunks;
+}
+
+async function runReadLargeJsonStrict() {
+ const parsed = await mod.readJsonRequest(
+ new Request("https://worker.example/", {
+ method: "POST",
+ headers: { "content-length": String(largeJsonBody.length) },
+ body: largeJsonBody,
+ }),
+ );
+ return {
+ __benchDetails: {
+ bytes: parsed.bytes || 0,
+ ok: parsed.value?.ok ? 1 : 0,
+ },
+ };
+}
+
+function runPlainSieveChunks(text) {
+ const state = mod.createToolSieveState();
+ for (let i = 0; i < text.length; i += 1024) {
+ mod.processToolSieveChunk(state, text.slice(i, i + 1024));
+ }
+ return mod.flushToolSieve(state, tools);
+}
+
+function runHeldToolCandidateChunks(text) {
+ const state = mod.createToolSieveState();
+ for (let i = 0; i < text.length; i += 1024) {
+ mod.processToolSieveChunk(state, text.slice(i, i + 1024));
+ }
+ return mod.flushToolSieve(state, tools);
+}
+
+async function runResponsesSmallDeltaStream() {
+ let writes = 0;
+ await mod.streamResponsesWithToolSieve(
+ () => {
+ writes += 1;
+ },
+ CFG,
+ {
+ provider: smallDeltaProvider,
+ rid: "resp_bench",
+ rm: { name: "gemini-3.5-flash" },
+ prompt: "bench",
+ fileRefs: null,
+ tools: null,
+ toolPolicy: null,
+ promptTokens: 1,
+ signal: new AbortController().signal,
+ },
+ );
+ return {
+ __benchDetails: {
+ inputDeltas: SSE_CHUNKS,
+ writes,
+ },
+ };
+}
+
+async function runGoogleSmallDeltaStream() {
+ let writes = 0;
+ await mod.streamGooglePlain(
+ () => {
+ writes += 1;
+ },
+ CFG,
+ {
+ provider: smallDeltaProvider,
+ prompt: "bench",
+ rm: { name: "gemini-3.5-flash" },
+ fileRefs: null,
+ promptTokens: 1,
+ signal: new AbortController().signal,
+ },
+ );
+ return {
+ __benchDetails: {
+ inputDeltas: SSE_CHUNKS,
+ writes,
+ },
+ };
+}
+
+async function runSseChunks({ chunks, delayMs }) {
+ const frame = "data: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n";
+ let producedBytes = 0;
+ let consumedBytes = 0;
+ let peakBufferedBytes = 0;
+ const resp = mod.sseResponse(async (write) => {
+ for (let i = 0; i < chunks; i++) {
+ producedBytes += frame.length;
+ peakBufferedBytes = Math.max(
+ peakBufferedBytes,
+ producedBytes - consumedBytes,
+ );
+ await write(frame);
+ peakBufferedBytes = Math.max(
+ peakBufferedBytes,
+ producedBytes - consumedBytes,
+ );
+ }
+ });
+ const reader = resp.body.getReader();
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ consumedBytes += value ? value.length : 0;
+ peakBufferedBytes = Math.max(
+ peakBufferedBytes,
+ producedBytes - consumedBytes,
+ );
+ if (delayMs > 0) await delay(delayMs);
+ }
+ return {
+ __benchDetails: {
+ totalBytes: producedBytes,
+ peakBufferedBytes,
+ },
+ };
+}
+
+function delay(ms) {
+ return new Promise((done) => setTimeout(done, ms));
+}
+
+function runSocketSingleChunkBody() {
+ const queue = mod.createByteQueue(socketSingleBody);
+ const out = queue.read(socketSingleBody.length);
+ return {
+ __benchDetails: {
+ totalBytes: out.length,
+ sameBuffer:
+ out.buffer === socketSingleBody.buffer &&
+ out.byteOffset === socketSingleBody.byteOffset
+ ? 1
+ : 0,
+ },
+ };
+}
+
+function runSocketMultiChunkBody() {
+ const queue = mod.createByteQueue();
+ for (const chunk of socketChunks) queue.push(chunk);
+ const out = queue.read(SOCKET_BODY_BYTES);
+ return {
+ __benchDetails: {
+ totalBytes: out.length,
+ sameBuffer: socketChunks.some((chunk) => out.buffer === chunk.buffer)
+ ? 1
+ : 0,
+ },
+ };
+}
+
+function makeBytes(length) {
+ const out = new Uint8Array(length);
+ for (let i = 0; i < out.length; i++) out[i] = i & 255;
+ return out;
+}
+
+function bytesToBase64(bytes) {
+ const native = bytes.toBase64;
+ if (typeof native === "function") return native.call(bytes);
+ let binary = "";
+ const chunkSize = 0x8000;
+ for (let offset = 0; offset < bytes.byteLength; offset += chunkSize) {
+ const chunk = bytes.subarray(offset, offset + chunkSize);
+ binary += String.fromCharCode(...chunk);
+ }
+ return btoa(binary);
+}
+
+function makeSocketChunks(totalBytes, chunkBytes) {
+ const chunks = [];
+ let remaining = totalBytes;
+ let seed = 0;
+ while (remaining > 0) {
+ const size = Math.min(chunkBytes, remaining);
+ const chunk = new Uint8Array(size);
+ for (let i = 0; i < chunk.length; i++) chunk[i] = (seed + i) & 255;
+ chunks.push(chunk);
+ seed += size;
+ remaining -= size;
+ }
+ return chunks;
+}
+
+async function runSocketText(responseChunks) {
+ const resp = await mod.socketHttp(
+ fakeSocketConnect(responseChunks),
+ "https://example.test/text",
+ { timeoutMs: 0 },
+ );
+ const text = await resp.text();
+ return {
+ __benchDetails: {
+ totalChars: text.length,
+ chunks: responseChunks.length,
+ },
+ };
+}
+
+function makeHttpResponseChunks(bodyOrChunks, totalBytes) {
+ const head = new TextEncoder().encode(
+ `HTTP/1.1 200 OK\r\nContent-Length: ${totalBytes}\r\n\r\n`,
+ );
+ if (bodyOrChunks instanceof Uint8Array)
+ return [concatBytes(head, bodyOrChunks)];
+ return [head, ...bodyOrChunks];
+}
+
+function makeSocketLongChunkedLineResponse(lineBytes) {
+ const encoder = new TextEncoder();
+ const head = encoder.encode(
+ "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n",
+ );
+ const line = encoder.encode(`1;${"x".repeat(lineBytes)}\r\n`);
+ const tail = encoder.encode("a\r\n0\r\n\r\n");
+ const chunks = [head];
+ for (let i = 0; i < line.length; i++) chunks.push(line.subarray(i, i + 1));
+ chunks.push(tail);
+ return chunks;
+}
+
+function fakeSocketConnect(responseChunks) {
+ return () => ({
+ readable: new ReadableStream({
+ start(controller) {
+ for (const chunk of responseChunks) controller.enqueue(chunk);
+ controller.close();
+ },
+ }),
+ writable: new WritableStream({
+ write() {},
+ }),
+ close() {},
+ });
+}
+
+function concatBytes(a, b) {
+ const out = new Uint8Array(a.length + b.length);
+ out.set(a, 0);
+ out.set(b, a.length);
+ return out;
+}
+
+function runUniqueItemsValidation() {
+ const error = mod.validateStructuredOutputValue(
+ uniqueItemsValue,
+ uniqueItemsRequirement,
+ );
+ return {
+ __benchDetails: {
+ items: uniqueItemsValue.length,
+ ok: error ? 0 : 1,
+ },
+ };
+}
+
+function runStructuredPatternValidation() {
+ let error = "";
+ for (let i = 0; i < 100; i++) {
+ error = mod.validateStructuredOutputValue(
+ structuredPatternValue,
+ structuredPatternRequirement,
+ );
+ }
+ return {
+ __benchDetails: {
+ checks: 100,
+ ok: error ? 0 : 1,
+ },
+ };
+}
+
+function makeUniqueCompositeValues(count) {
+ const out = [];
+ for (let i = 0; i < count; i++) {
+ out.push({
+ id: i,
+ tags: [`tag-${i % 17}`, `group-${Math.floor(i / 17)}`],
+ nested: {
+ left: { value: i * 3, ok: (i & 1) === 0 },
+ right: [i, { label: `item-${i}` }],
+ },
+ });
+ }
+ return out;
+}
+
+function runBase64Decode() {
+ const bytes = mod.base64ToBytes(base64Input);
+ return {
+ __benchDetails: {
+ bytes: bytes.length,
+ },
+ };
+}
+
+function runMultipartBodyLarge() {
+ const multipart = mod.buildMultipartFileBody({
+ bytes: multipartBytes,
+ mime: "application/octet-stream",
+ filename: "large.bin",
+ });
+ return {
+ __benchDetails: {
+ bytes: multipart.contentLength,
+ },
+ };
+}
+
+async function runAppPageTokensLarge() {
+ mod.resetGeminiUploadCachesForTest();
+ const stats = installFetchResponse(appPageTokensHtml);
+ try {
+ const tokens = await mod.getPageTokens(CFG);
+ return {
+ __benchDetails: {
+ htmlBytes: stats.bytes,
+ pulls: stats.pulls,
+ canceled: stats.canceled,
+ ok: tokens.push_id === "push-bench" && tokens.at === "at-bench" ? 1 : 0,
+ },
+ };
+ } finally {
+ stats.restore();
+ }
+}
+
+async function runAppBuildLabelLarge() {
+ const stats = installFetchResponse(appBuildLabelHtml);
+ try {
+ const label = await mod.getFreshGeminiBuildLabel(CFG);
+ return {
+ __benchDetails: {
+ htmlBytes: stats.bytes,
+ pulls: stats.pulls,
+ canceled: stats.canceled,
+ ok: label === "bench-bl" ? 1 : 0,
+ },
+ };
+ } finally {
+ stats.restore();
+ }
+}
+
+function makeAppHtml(totalBytes, tokenBlock) {
+ const prefix = `
${tokenBlock}`;
+ const suffix = "";
+ const fillerUnit =
+ "app bootstrap payload: boq_assistant placeholder config data;\n";
+ let filler = "";
+ const target = Math.max(0, totalBytes - prefix.length - suffix.length);
+ while (filler.length < target) filler += fillerUnit;
+ return prefix + filler.slice(0, target) + suffix;
+}
+
+function installFetchResponse(text) {
+ const originalFetch = globalThis.fetch;
+ const encoded = new TextEncoder().encode(text);
+ const stats = {
+ bytes: encoded.length,
+ pulls: 0,
+ canceled: 0,
+ restore() {
+ globalThis.fetch = originalFetch;
+ },
+ };
+ globalThis.fetch = async () =>
+ new Response(
+ new ReadableStream({
+ pull(controller) {
+ const start = stats.pulls * APP_HTML_CHUNK_BYTES;
+ if (start >= encoded.length) {
+ controller.close();
+ return;
+ }
+ stats.pulls += 1;
+ controller.enqueue(
+ encoded.subarray(start, start + APP_HTML_CHUNK_BYTES),
+ );
+ },
+ cancel() {
+ stats.canceled += 1;
+ },
+ }),
+ );
+ return stats;
+}
+
+function installFetchChunks(chunks) {
+ const originalFetch = globalThis.fetch;
+ const stats = {
+ chunks: chunks.length,
+ restore() {
+ globalThis.fetch = originalFetch;
+ },
+ };
+ globalThis.fetch = async () =>
+ new Response(
+ new ReadableStream({
+ start(controller) {
+ for (const chunk of chunks) controller.enqueue(chunk);
+ controller.close();
+ },
+ }),
+ { status: 200 },
+ );
+ return stats;
+}
+
+function runStructuredJsonUnclosed() {
+ const candidate = mod.extractFirstJsonDocument(structuredJsonNoise);
+ return {
+ __benchDetails: {
+ bytes: structuredJsonNoise.length,
+ found: candidate ? 1 : 0,
+ },
+ };
+}
+
+function runRandHex32() {
+ const value = mod.randHex(32);
+ return {
+ __benchDetails: {
+ chars: value.length,
+ },
+ };
+}
+
+function runMarkdownRestoreMany() {
+ const restored = markdownRestoreMasked.restore(markdownRestoreMasked.text);
+ return {
+ __benchDetails: {
+ chars: restored.length,
+ placeholders: markdownRestorePlaceholderCount,
+ },
+ };
+}
+
+function makeMarkdownProtectedText(count) {
+ const parts = [];
+ for (let i = 0; i < count; i++) {
+ parts.push(`plain ${i} \`${i}\` tail`);
+ }
+ return parts.join("\n");
+}
+
+function countOccurrences(text, needle) {
+ let count = 0;
+ let index = String(text || "").indexOf(needle);
+ while (index >= 0) {
+ count += 1;
+ index = String(text || "").indexOf(needle, index + needle.length);
+ }
+ return count;
+}
diff --git a/scripts/build.mjs b/scripts/build.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..c72b0cee11600b98677f9cf40d1d40f4859bd2bb
--- /dev/null
+++ b/scripts/build.mjs
@@ -0,0 +1,49 @@
+import esbuild from "esbuild";
+import { mkdir, rm } from "node:fs/promises";
+
+const coverageBuild = /^(1|true|yes|on)$/i.test(process.env.COVERAGE || "");
+const includeTestBundle =
+ process.argv.includes("--test-bundle") ||
+ /^(1|true|yes|on)$/i.test(process.env.BUILD_TEST_BUNDLE || "");
+const outDir =
+ process.env.BUILD_DIR || (coverageBuild ? "dist-coverage" : "dist");
+
+if (coverageBuild) {
+ await rm(outDir, { recursive: true, force: true });
+}
+
+await mkdir(outDir, { recursive: true });
+
+if (!coverageBuild) {
+ await Promise.all([
+ rm(`${outDir}/worker.js.map`, { force: true }),
+ rm(`${outDir}/worker.test.js`, { force: true }),
+ rm(`${outDir}/worker.test.js.map`, { force: true }),
+ ]);
+}
+
+const common = {
+ bundle: true,
+ format: "esm",
+ target: "es2025",
+ platform: "browser",
+ sourcemap: coverageBuild ? "linked" : false,
+ sourcesContent: coverageBuild,
+ legalComments: "none",
+ external: ["cloudflare:sockets"],
+ logLevel: "info",
+};
+
+await esbuild.build({
+ ...common,
+ entryPoints: ["src/index.ts"],
+ outfile: `${outDir}/worker.js`,
+});
+
+if (includeTestBundle || coverageBuild) {
+ await esbuild.build({
+ ...common,
+ entryPoints: ["src/test-index.ts"],
+ outfile: `${outDir}/worker.test.js`,
+ });
+}
diff --git a/scripts/check-architecture.mjs b/scripts/check-architecture.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..bebcc780feb609888950ca8a9a77973cfa91993c
--- /dev/null
+++ b/scripts/check-architecture.mjs
@@ -0,0 +1,372 @@
+import { existsSync, readFileSync, statSync } from "node:fs";
+import { readFile } from "node:fs/promises";
+import { dirname, join, normalize, relative, resolve } from "node:path";
+import { globSync } from "node:fs";
+import { errorLine, outputLine } from "./io.mjs";
+
+const root = process.cwd();
+const rules = [
+ {
+ label: "attachment modules must stay provider-neutral",
+ files: "src/attachments/**/*.{ts,tsx}",
+ disallowed: ["../"],
+ allowed: ["../shared"],
+ },
+ {
+ label: "shared modules must stay leaf-level",
+ files: "src/shared/**/*.ts",
+ disallowed: [
+ "../gemini/",
+ "../http/",
+ "../promptcompat/",
+ "../toolcall/",
+ "../toolstream/",
+ "./gemini/",
+ "./http/",
+ "./promptcompat/",
+ "./toolcall/",
+ "./toolstream/",
+ ],
+ },
+ {
+ label: "gemini client must not depend on prompt compatibility",
+ files: "src/gemini/client/**/*.ts",
+ disallowed: ["../../promptcompat/", "../promptcompat/"],
+ },
+ {
+ label: "prompt compatibility must not depend on HTTP adapters",
+ files: "src/promptcompat/**/*.ts",
+ disallowed: ["../http/", "../../http/"],
+ },
+ {
+ label: "completion modules must not depend on HTTP adapters",
+ files: "src/completion/**/*.ts",
+ disallowed: ["../http/", "../../http/"],
+ },
+ {
+ label:
+ "completion modules must depend on provider ports instead of Gemini implementation packages",
+ files: "src/completion/**/*.ts",
+ disallowed: ["../gemini/", "../../gemini/"],
+ },
+ {
+ label:
+ "completion modules must import prompt compatibility owner modules instead of the compatibility barrel",
+ files: "src/completion/**/*.ts",
+ disallowed: [
+ "../promptcompat",
+ "../promptcompat/",
+ "../../promptcompat",
+ "../../promptcompat/",
+ ],
+ allowed: [
+ "../promptcompat/file-refs",
+ "../promptcompat/google",
+ "../promptcompat/history",
+ "../promptcompat/messages",
+ "../promptcompat/prompt-build",
+ "../promptcompat/responses-input",
+ "../../promptcompat/file-refs",
+ "../../promptcompat/google",
+ "../../promptcompat/history",
+ "../../promptcompat/messages",
+ "../../promptcompat/prompt-build",
+ "../../promptcompat/responses-input",
+ ],
+ },
+ {
+ label: "HTTP adapters must not call Gemini client directly",
+ files: "src/http/**/*.ts",
+ disallowed: [
+ "../gemini/client",
+ "../gemini/client/",
+ "../../gemini/client",
+ "../../gemini/client/",
+ ],
+ },
+ {
+ label:
+ "Gemini implementation must only depend on completion ports through its provider adapter",
+ files: "src/gemini/**/*.ts",
+ disallowed: [
+ "../completion",
+ "../completion/",
+ "../../completion",
+ "../../completion/",
+ ],
+ allowed: ["../completion/ports", "../../completion/ports"],
+ },
+ {
+ label:
+ "HTTP protocol adapters must import core helpers directly instead of the HTTP barrel",
+ files: "src/http/{openai,google}/**/*.ts",
+ disallowed: ["../index", "../index.ts", "../../http", "../../http/"],
+ },
+ {
+ label: "HTTP adapters must not consume tool stream state directly",
+ files: "src/http/**/*.ts",
+ disallowed: [
+ "../toolstream",
+ "../toolstream/",
+ "../../toolstream",
+ "../../toolstream/",
+ ],
+ },
+ {
+ label: "HTTP adapter barrels must not re-export lower-layer internals",
+ files: "src/http/**/index.ts",
+ disallowed: [
+ "../../completion",
+ "../../completion/",
+ "../../promptcompat",
+ "../../promptcompat/",
+ "../../toolcall",
+ "../../toolcall/",
+ "../../gemini",
+ "../../gemini/",
+ ],
+ },
+ {
+ label: "prompt compatibility must not perform Gemini uploads",
+ files: "src/promptcompat/**/*.ts",
+ disallowed: [
+ "../gemini/uploads",
+ "../gemini/uploads/",
+ "../../gemini/uploads",
+ "../../gemini/uploads/",
+ ],
+ },
+ {
+ label:
+ "prompt compatibility internals must not depend on completion modules",
+ files: "src/promptcompat/**/*.ts",
+ disallowed: [
+ "../completion",
+ "../completion/",
+ "../../completion",
+ "../../completion/",
+ ],
+ },
+ {
+ label: "google HTTP adapter must not depend on openai HTTP adapter",
+ files: "src/http/google/**/*.ts",
+ disallowed: ["../openai/", "../../http/openai/"],
+ },
+ {
+ label: "openai HTTP adapter must not depend on google HTTP adapter",
+ files: "src/http/openai/**/*.ts",
+ disallowed: ["../google/", "../../http/google/"],
+ },
+ {
+ label: "toolcall must not depend on prompt compatibility",
+ files: "src/toolcall/**/*.ts",
+ disallowed: ["../promptcompat/", "../../promptcompat/"],
+ },
+ {
+ label: "toolcall must not depend on HTTP adapters or stream state",
+ files: "src/toolcall/**/*.ts",
+ disallowed: [
+ "../http/",
+ "../../http/",
+ "../toolstream/",
+ "../../toolstream/",
+ ],
+ },
+ {
+ label: "toolcall must not depend on Gemini upload modules",
+ files: "src/toolcall/**/*.ts",
+ disallowed: [
+ "../gemini/uploads",
+ "../gemini/uploads/",
+ "../../gemini/uploads",
+ "../../gemini/uploads/",
+ ],
+ },
+ {
+ label:
+ "implementation modules must import toolcall owner modules instead of the compatibility barrel",
+ files: "src/{completion,promptcompat,toolstream,http}/**/*.ts",
+ disallowedExact: [
+ "../toolcall",
+ "../toolcall/index",
+ "../toolcall/index.ts",
+ "../../toolcall",
+ "../../toolcall/index",
+ "../../toolcall/index.ts",
+ ],
+ },
+ {
+ label:
+ "implementation modules must import attachment media owner modules instead of the shared media compatibility shim",
+ files:
+ "src/{completion,promptcompat,toolcall,toolstream,http,gemini}/**/*.ts",
+ disallowed: ["../shared/media", "../../shared/media"],
+ },
+];
+
+const importPattern =
+ /(?:import|export)\s+(?:[^"']*?\s+from\s+)?["']([^"']+)["']/g;
+const violations = [];
+
+for (const rule of rules) {
+ for (const file of globSync(rule.files, { cwd: root })) {
+ if (rule.exceptFiles?.includes(normalizeSourcePath(file))) continue;
+ const text = await readFile(resolve(root, file), "utf8");
+ for (const match of text.matchAll(importPattern)) {
+ const specifier = match[1];
+ if (
+ rule.allowed?.some(
+ (prefix) =>
+ specifier === prefix || specifier.startsWith(`${prefix}/`),
+ )
+ )
+ continue;
+ if (rule.disallowedExact?.includes(specifier)) {
+ violations.push(
+ `${normalizeSourcePath(relative(root, resolve(root, file)))}: ${specifier} (${rule.label})`,
+ );
+ continue;
+ }
+ if (
+ rule.disallowed?.some(
+ (prefix) => specifier === prefix || specifier.startsWith(prefix),
+ )
+ ) {
+ violations.push(
+ `${normalizeSourcePath(relative(root, resolve(root, file)))}: ${specifier} (${rule.label})`,
+ );
+ }
+ }
+ }
+}
+
+const sourceFiles = globSync("src/**/*.{ts,tsx}", { cwd: root }).map(
+ normalizeSourcePath,
+);
+const sourceFileSet = new Set(sourceFiles);
+const importGraph = new Map();
+
+for (const file of sourceFiles) {
+ const text = await readFile(resolve(root, file), "utf8");
+ const deps = [];
+ for (const match of text.matchAll(importPattern)) {
+ const specifier = match[1];
+ if (!specifier.startsWith(".")) continue;
+ const dep = resolveSourceImport(file, specifier);
+ if (dep && sourceFileSet.has(dep)) deps.push(dep);
+ }
+ importGraph.set(file, deps);
+}
+
+for (const cycle of findImportCycles(importGraph)) {
+ violations.push(
+ `${cycle.join(" -> ")} (source modules must not form import cycles)`,
+ );
+}
+
+const packageGraph = buildPackageGraph(sourceFiles, sourceFileSet);
+for (const cycle of findImportCycles(packageGraph)) {
+ violations.push(
+ `${cycle.join(" -> ")} (source directories must not form dependency cycles)`,
+ );
+}
+
+if (violations.length) {
+ errorLine("Architecture check failed:");
+ for (const violation of violations) errorLine(`- ${violation}`);
+ process.exit(1);
+}
+
+outputLine("Architecture check passed");
+
+function resolveSourceImport(fromFile, specifier) {
+ const base = normalizeSourcePath(join(dirname(fromFile), specifier));
+ const candidates = [
+ base,
+ `${base}.ts`,
+ `${base}.tsx`,
+ normalizeSourcePath(join(base, "index.ts")),
+ normalizeSourcePath(join(base, "index.tsx")),
+ ];
+ for (const candidate of candidates) {
+ const absolute = resolve(root, candidate);
+ if (existsSync(absolute) && statSync(absolute).isFile())
+ return normalizeSourcePath(candidate);
+ }
+ return null;
+}
+
+function findImportCycles(graph) {
+ const cycles = [];
+ const seen = new Set();
+ const active = new Set();
+ const stack = [];
+ const cycleKeys = new Set();
+
+ function visit(node) {
+ seen.add(node);
+ active.add(node);
+ stack.push(node);
+ for (const dep of graph.get(node) || []) {
+ if (!graph.has(dep)) continue;
+ if (!seen.has(dep)) {
+ visit(dep);
+ continue;
+ }
+ if (!active.has(dep)) continue;
+ const start = stack.indexOf(dep);
+ const cycle = stack.slice(start).concat(dep);
+ const key = cycle.slice(0, -1).sort().join("|");
+ if (!cycleKeys.has(key)) {
+ cycleKeys.add(key);
+ cycles.push(cycle);
+ }
+ }
+ stack.pop();
+ active.delete(node);
+ }
+
+ for (const node of graph.keys()) {
+ if (!seen.has(node)) visit(node);
+ }
+ return cycles;
+}
+
+function buildPackageGraph(files, fileSet) {
+ const graph = new Map();
+ const packageOwners = new Set(
+ files.map(sourcePackage).filter((owner) => owner && owner !== "generated"),
+ );
+ for (const owner of packageOwners) graph.set(owner, []);
+
+ for (const file of files) {
+ const fromOwner = sourcePackage(file);
+ if (!packageOwners.has(fromOwner)) continue;
+ const text = readSourceFileSync(file);
+ for (const match of text.matchAll(importPattern)) {
+ const specifier = match[1];
+ if (!specifier.startsWith(".")) continue;
+ const dep = resolveSourceImport(file, specifier);
+ if (!dep || !fileSet.has(dep)) continue;
+ const toOwner = sourcePackage(dep);
+ if (!packageOwners.has(toOwner) || toOwner === fromOwner) continue;
+ const deps = graph.get(fromOwner);
+ if (deps && !deps.includes(toOwner)) deps.push(toOwner);
+ }
+ }
+
+ return graph;
+}
+
+function sourcePackage(file) {
+ const match = /^src\/([^/]+)\//.exec(file);
+ return match?.[1] ? match[1] : "";
+}
+
+function readSourceFileSync(file) {
+ return readFileSync(resolve(root, file), "utf8");
+}
+
+function normalizeSourcePath(file) {
+ return normalize(file).replaceAll("\\", "/");
+}
diff --git a/scripts/check-benchmark.mjs b/scripts/check-benchmark.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..d2f75d804cc54140f3c507745e5cd63854ba53bf
--- /dev/null
+++ b/scripts/check-benchmark.mjs
@@ -0,0 +1,161 @@
+import { readFile } from "node:fs/promises";
+import { errorLine, outputLine } from "./io.mjs";
+import { outputCommand } from "./process.mjs";
+
+const DEFAULT_CASE = "stream_sieve_held_tool";
+const DEFAULT_MAX_MEDIAN_MS = 20;
+const DEFAULT_ITERS = "80";
+const DEFAULT_WARMUP = "10";
+const DEFAULT_BUDGETS = Object.freeze({
+ stream_sieve_held_tool: 8,
+ stream_text_cumulative_deltas: 12,
+ socket_chunked_long_split_line: 8,
+ structured_unique_items: 4,
+});
+
+const outputPath = process.argv[2] || "";
+
+try {
+ const budgets = benchmarkBudgets(outputPath);
+ const output = outputPath
+ ? await readFile(outputPath, "utf8")
+ : await runBenchmark(Object.keys(budgets));
+ const results = parseBenchmarkResults(output);
+ for (const [caseName, maxMedianMs] of Object.entries(budgets)) {
+ const medianMs = results.get(caseName)?.medianMs ?? null;
+ if (medianMs == null) fail(`missing benchmark median for ${caseName}`);
+ if (medianMs > maxMedianMs) {
+ fail(
+ `${caseName} median ${formatMs(medianMs)} exceeds ${formatMs(maxMedianMs)}`,
+ );
+ }
+ outputLine(
+ `benchmark gate ok: ${caseName} median ${formatMs(medianMs)} <= ${formatMs(maxMedianMs)}`,
+ );
+ }
+} catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ fail(message);
+}
+
+function benchmarkBudgets(inputPath) {
+ const rawBudgets = String(process.env.BENCH_GATE_BUDGETS || "").trim();
+ if (rawBudgets) {
+ let parsed;
+ try {
+ parsed = JSON.parse(rawBudgets);
+ } catch (_) {
+ throw new Error("BENCH_GATE_BUDGETS must be a JSON object");
+ }
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
+ throw new Error("BENCH_GATE_BUDGETS must be a JSON object");
+ const out = {};
+ for (const [name, value] of Object.entries(parsed)) {
+ const budget = positiveNumber(value, 0);
+ if (!name.trim() || budget <= 0)
+ throw new Error(`invalid benchmark budget for ${name || ""}`);
+ out[name] = budget;
+ }
+ if (!Object.keys(out).length)
+ throw new Error("BENCH_GATE_BUDGETS must not be empty");
+ return out;
+ }
+
+ const explicitCase = String(process.env.BENCH_GATE_CASE || "").trim();
+ if (explicitCase || inputPath) {
+ return {
+ [explicitCase || DEFAULT_CASE]: positiveNumber(
+ process.env.BENCH_MAX_MEDIAN_MS,
+ DEFAULT_MAX_MEDIAN_MS,
+ ),
+ };
+ }
+ return { ...DEFAULT_BUDGETS };
+}
+
+function runBenchmark(targetCases) {
+ return outputCommand(process.execPath, ["scripts/bench.mjs"], {
+ env: {
+ ...process.env,
+ BENCH_CASES: targetCases.join(","),
+ BENCH_ITERS: process.env.BENCH_ITERS || DEFAULT_ITERS,
+ BENCH_WARMUP: process.env.BENCH_WARMUP || DEFAULT_WARMUP,
+ BENCH_JSON: "1",
+ },
+ });
+}
+
+export function parseBenchmarkResults(output) {
+ const raw = String(output || "").trim();
+ if (raw.startsWith("{")) {
+ let parsed;
+ try {
+ parsed = JSON.parse(raw);
+ } catch (_) {
+ throw new Error("invalid benchmark JSON output");
+ }
+ if (!Array.isArray(parsed?.results))
+ throw new Error("benchmark JSON output is missing results");
+ const out = new Map();
+ for (const result of parsed.results) {
+ const name = String(result?.name || "").trim();
+ const medianMs = result?.medianMs;
+ if (name && typeof medianMs === "number" && Number.isFinite(medianMs))
+ out.set(name, { medianMs });
+ }
+ return out;
+ }
+
+ const out = new Map();
+ for (const line of raw.split(/\r?\n/)) {
+ const name = /^\s*([^\s]+)\s+/.exec(line)?.[1] || "";
+ if (!name) continue;
+ const medianMs = parseBenchmarkMetric(line, name, "median");
+ if (medianMs != null) out.set(name, { medianMs });
+ }
+ return out;
+}
+
+export function parseBenchmarkMetric(output, benchmarkCaseName, metricName) {
+ const line = String(output || "")
+ .split(/\r?\n/)
+ .find((candidate) =>
+ candidate.trimStart().startsWith(`${benchmarkCaseName} `),
+ );
+ if (!line) return null;
+ const match = new RegExp(
+ `\\b${escapeRegex(metricName)}=([0-9]+(?:\\.[0-9]+)?)(us|ms|s)\\b`,
+ ).exec(line);
+ if (!match) return null;
+ const value = Number(match[1]);
+ if (!Number.isFinite(value)) return null;
+ switch (match[2]) {
+ case "us":
+ return value / 1000;
+ case "ms":
+ return value;
+ case "s":
+ return value * 1000;
+ default:
+ return null;
+ }
+}
+
+function positiveNumber(value, fallback) {
+ const n = Number(value);
+ return Number.isFinite(n) && n > 0 ? n : fallback;
+}
+
+function formatMs(ms) {
+ if (ms < 1) return `${(ms * 1000).toFixed(1)}us`;
+ return `${ms.toFixed(3)}ms`;
+}
+
+function escapeRegex(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+function fail(message) {
+ errorLine(`Benchmark gate failed: ${message}`);
+ process.exit(1);
+}
diff --git a/scripts/check-bundle-size.mjs b/scripts/check-bundle-size.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..855542e717643a265392c7f3614b5126d47ee6e1
--- /dev/null
+++ b/scripts/check-bundle-size.mjs
@@ -0,0 +1,51 @@
+import { readFile } from "node:fs/promises";
+import { gzipSync } from "node:zlib";
+import { errorLine, outputLine } from "./io.mjs";
+
+const bundlePath = process.argv[2] || "dist/worker.js";
+const defaultLimitBytes = 3 * 1024 * 1024;
+const limitBytes = parseLimit(
+ process.env.BUNDLE_GZIP_SIZE_LIMIT_BYTES,
+ defaultLimitBytes,
+);
+
+try {
+ const bundle = await readFile(bundlePath);
+ if (bundle.length <= 0) {
+ fail(`${bundlePath} is missing or empty`);
+ }
+ const gzipBytes = gzipSync(bundle, { level: 9 }).length;
+ if (gzipBytes > limitBytes) {
+ fail(
+ `${bundlePath} gzip size is ${formatBytes(gzipBytes)}, limit ${formatBytes(limitBytes)}`,
+ );
+ }
+ outputLine(
+ `bundle size ok: ${bundlePath} raw ${formatBytes(bundle.length)}, gzip ${formatBytes(gzipBytes)} <= ${formatBytes(limitBytes)}, headroom ${formatBytes(limitBytes - gzipBytes)}`,
+ );
+} catch (error) {
+ if (
+ error &&
+ typeof error === "object" &&
+ "code" in error &&
+ error.code === "ENOENT"
+ ) {
+ fail(`${bundlePath} does not exist; run pnpm build first`);
+ }
+ throw error;
+}
+
+function parseLimit(value, fallback) {
+ if (value == null || value === "") return fallback;
+ const n = Number(value);
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback;
+}
+
+function formatBytes(bytes) {
+ return `${bytes} bytes`;
+}
+
+function fail(message) {
+ errorLine(`Bundle size gate failed: ${message}`);
+ process.exit(1);
+}
diff --git a/scripts/check-coverage.mjs b/scripts/check-coverage.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..ea5b066f1db755bceb63c81a8ed54eeee8f588b7
--- /dev/null
+++ b/scripts/check-coverage.mjs
@@ -0,0 +1,141 @@
+import { readFile } from "node:fs/promises";
+import { relative } from "node:path";
+import { errorLine, outputLine } from "./io.mjs";
+
+const summaryPath = process.argv[2] || "coverage/coverage-summary.json";
+
+const sourceGates = [
+ ["statements", 69],
+ ["branches", 55],
+ ["functions", 82],
+ ["lines", 75],
+];
+
+const lineGates = [
+ ["src/attachments", 88],
+ ["src/completion", 92],
+ ["src/config", 95],
+ ["src/gemini", 88],
+ ["src/gemini/completion-provider.ts", 95],
+ ["src/gemini/client", 88],
+ ["src/gemini/transport", 90],
+ ["src/gemini/uploads", 90],
+ ["src/http/core", 92],
+ ["src/http/google", 92],
+ ["src/http/openai", 92],
+ ["src/http/stream", 94],
+ ["src/models", 95],
+ ["src/promptcompat", 94],
+ ["src/shared", 85],
+ ["src/toolcall", 90],
+ ["src/toolstream", 85],
+];
+
+const branchGates = [
+ ["src/attachments", 75],
+ ["src/gemini/client", 75],
+ ["src/gemini/client/parser.ts", 75],
+ ["src/gemini/transport", 78],
+ ["src/gemini/app-page.ts", 70],
+ ["src/gemini/completion-provider.ts", 85],
+ ["src/http/google/handlers.ts", 65],
+ ["src/http/openai/chat.ts", 65],
+ ["src/http/openai", 78],
+ ["src/http/openai/responses.ts", 72],
+ ["src/http/openai/responses-stream.ts", 72],
+ ["src/promptcompat", 78],
+ ["src/promptcompat/history.ts", 75],
+ ["src/promptcompat/responses-input.ts", 78],
+ ["src/shared/tokens.ts", 70],
+ ["src/toolcall/markdown.ts", 68],
+ ["src/toolcall/structured.ts", 75],
+ ["src/toolstream/index.ts", 65],
+];
+
+const summary = JSON.parse(await readFile(summaryPath, "utf8"));
+const cwd = process.cwd();
+
+function normalizePath(path) {
+ const rel = path.startsWith(cwd) ? relative(cwd, path) : path;
+ return rel.split("\\").join("/");
+}
+
+function statsForDir(dir, metric) {
+ let covered = 0;
+ let total = 0;
+
+ for (const [key, entry] of Object.entries(summary)) {
+ if (key === "total") continue;
+ const rel = normalizePath(key);
+ if (!rel.startsWith(`${dir}/`)) continue;
+ if (!entry || typeof entry !== "object" || !entry[metric]) continue;
+ const stats = entry[metric];
+ covered += Number(stats.covered || 0);
+ total += Number(stats.total || 0);
+ }
+
+ return { covered, total, pct: total > 0 ? (covered / total) * 100 : 0 };
+}
+
+function statsForPath(path, metric) {
+ let covered = 0;
+ let total = 0;
+ const normalizedPath = path.split("\\").join("/");
+
+ for (const [key, entry] of Object.entries(summary)) {
+ if (key === "total") continue;
+ const rel = normalizePath(key);
+ if (rel !== normalizedPath) continue;
+ if (!entry || typeof entry !== "object" || !entry[metric]) continue;
+ const stats = entry[metric];
+ covered += Number(stats.covered || 0);
+ total += Number(stats.total || 0);
+ }
+
+ return { covered, total, pct: total > 0 ? (covered / total) * 100 : 0 };
+}
+
+function statsForTarget(target, metric) {
+ if (/\.tsx?$/.test(target)) return statsForPath(target, metric);
+ return statsForDir(target, metric);
+}
+
+const failures = [];
+
+for (const [metric, threshold] of sourceGates) {
+ checkGate("src", threshold, metric);
+}
+
+for (const [target, threshold] of lineGates) {
+ checkGate(target, threshold, "lines");
+}
+
+for (const [target, threshold] of branchGates) {
+ checkGate(target, threshold, "branches");
+}
+
+function checkGate(target, threshold, metric) {
+ const stats = statsForTarget(target, metric);
+ const pct = Number(stats.pct.toFixed(2));
+ const rendered = `${target}: ${pct.toFixed(2)}% ${metric} (${stats.covered}/${stats.total}), required ${threshold.toFixed(2)}%`;
+
+ if (stats.total === 0) {
+ failures.push(`${target}: missing ${metric} coverage data`);
+ return;
+ }
+
+ if (pct + 0.001 < threshold) {
+ failures.push(rendered);
+ return;
+ }
+
+ outputLine(`coverage ok: ${rendered}`);
+}
+
+if (failures.length) {
+ errorLine("Coverage gate failed:");
+ for (const failure of failures) errorLine(`- ${failure}`);
+ process.exit(1);
+}
+
+outputLine("Coverage gates passed");
diff --git a/scripts/check-release.mjs b/scripts/check-release.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..20e9cb357d8c6b33695aae341d79d4f020afc150
--- /dev/null
+++ b/scripts/check-release.mjs
@@ -0,0 +1,16 @@
+import { runPnpm } from "./process.mjs";
+
+export const RELEASE_CHECKS = [
+ "check:static",
+ "check:worker-types",
+ "typecheck",
+ "check:arch",
+ "coverage:ci",
+ "smoke",
+ "check:bench",
+ "check:size",
+];
+
+for (const check of RELEASE_CHECKS) {
+ await runPnpm([check]);
+}
diff --git a/scripts/ci-change-risk.mjs b/scripts/ci-change-risk.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..9f00e620815a0ec1c27052ba2107fa77636ed19d
--- /dev/null
+++ b/scripts/ci-change-risk.mjs
@@ -0,0 +1,18 @@
+const DOC_ONLY_ROOT_FILES = new Set(["LICENSE", "README.md", "README.zh.md"]);
+
+export function classifyChangedFiles(files) {
+ const normalized = files
+ .map((file) =>
+ String(file || "")
+ .replaceAll("\\", "/")
+ .trim(),
+ )
+ .filter(Boolean);
+ if (!normalized.length) return "runtime";
+ return normalized.every(isDocumentationOnlyPath) ? "docs" : "runtime";
+}
+
+function isDocumentationOnlyPath(path) {
+ if (DOC_ONLY_ROOT_FILES.has(path)) return true;
+ return path.startsWith("docs/");
+}
diff --git a/scripts/classify-ci-changes.mjs b/scripts/classify-ci-changes.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..15f88c0e3253d241902d0677a9262f35fdd65cda
--- /dev/null
+++ b/scripts/classify-ci-changes.mjs
@@ -0,0 +1,21 @@
+import { classifyChangedFiles } from "./ci-change-risk.mjs";
+import { outputLine } from "./io.mjs";
+
+const files = process.env.CI_CHANGED_FILES_JSON
+ ? JSON.parse(process.env.CI_CHANGED_FILES_JSON)
+ : await readNullSeparatedStdin();
+const risk = classifyChangedFiles(Array.isArray(files) ? files : []);
+outputLine(risk);
+if (process.env.GITHUB_OUTPUT) {
+ const { appendFile } = await import("node:fs/promises");
+ await appendFile(
+ process.env.GITHUB_OUTPUT,
+ `risk=${risk}\nruntime=${risk === "runtime"}\n`,
+ );
+}
+
+async function readNullSeparatedStdin() {
+ const chunks = [];
+ for await (const chunk of process.stdin) chunks.push(chunk);
+ return Buffer.concat(chunks).toString("utf8").split("\0");
+}
diff --git a/scripts/coverage.mjs b/scripts/coverage.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..720efa296c704e5d1689d6c692799a0a2fdf1a28
--- /dev/null
+++ b/scripts/coverage.mjs
@@ -0,0 +1,25 @@
+import { runCommand, runPnpm } from "./process.mjs";
+
+const ci = process.argv.includes("--ci");
+const coverageBuildDir = "dist-coverage";
+
+await runPnpm(["build"], {
+ env: {
+ ...process.env,
+ BUILD_DIR: coverageBuildDir,
+ BUILD_TEST_BUNDLE: "1",
+ COVERAGE: "1",
+ },
+});
+
+await runPnpm(["exec", "vitest", "run", "--coverage"], {
+ env: {
+ ...process.env,
+ TEST_BUNDLE: `../../${coverageBuildDir}/worker.test.js`,
+ BENCH_TEST_BUNDLE: `${coverageBuildDir}/worker.test.js`,
+ },
+});
+
+if (ci) {
+ await runCommand(process.execPath, ["scripts/check-coverage.mjs"]);
+}
diff --git a/scripts/docker-server.mjs b/scripts/docker-server.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..249736a25a71de45f696a458ae6d66d44032aadd
--- /dev/null
+++ b/scripts/docker-server.mjs
@@ -0,0 +1,129 @@
+import http from "node:http";
+import { Readable } from "node:stream";
+import { finished } from "node:stream/promises";
+import { pathToFileURL } from "node:url";
+
+const port = Number(process.env.PORT || 52389);
+const host = process.env.HOST || "0.0.0.0";
+const env = { ...process.env };
+let defaultWorkerPromise = null;
+
+export function requestHeaders(rawHeaders) {
+ const headers = new Headers();
+ for (let i = 0; i < rawHeaders.length; i += 2) {
+ const name = rawHeaders[i];
+ const value = rawHeaders[i + 1];
+ if (name && value !== undefined) headers.append(name, value);
+ }
+ return headers;
+}
+
+export function requestUrl(req, fallbackPort = port) {
+ const scheme =
+ firstForwardedHeaderValue(req.headers["x-forwarded-proto"]) || "http";
+ const forwardedHost = firstForwardedHeaderValue(
+ req.headers["x-forwarded-host"],
+ );
+ const authority =
+ forwardedHost ||
+ firstForwardedHeaderValue(req.headers.host) ||
+ `localhost:${fallbackPort}`;
+ return `${scheme}://${authority}${req.url || "/"}`;
+}
+
+function firstForwardedHeaderValue(value) {
+ const raw = Array.isArray(value) ? value[0] : value;
+ return String(raw || "")
+ .split(",")[0]
+ .trim();
+}
+
+export function executionContext() {
+ const pending = new Set();
+ return {
+ waitUntil(promise) {
+ const p = Promise.resolve(promise).catch((err) => {
+ console.error("waitUntil failed:", err);
+ });
+ pending.add(p);
+ p.finally(() => pending.delete(p));
+ },
+ passThroughOnException() {},
+ };
+}
+
+export async function handleDockerRequest(req, res, options = {}) {
+ const workerImpl = options.worker || (await defaultWorker());
+ const requestEnv = options.env || env;
+ const fallbackPort = Number(options.port || port);
+ const method = req.method || "GET";
+ const init = {
+ method,
+ headers: requestHeaders(req.rawHeaders),
+ };
+
+ if (method !== "GET" && method !== "HEAD") {
+ init.body = Readable.toWeb(req);
+ init.duplex = "half";
+ }
+
+ const request = new Request(requestUrl(req, fallbackPort), init);
+ const response = await workerImpl.fetch(
+ request,
+ requestEnv,
+ executionContext(),
+ );
+
+ res.statusCode = response.status;
+ response.headers.forEach((value, key) => {
+ res.setHeader(key, value);
+ });
+
+ if (!response.body || method === "HEAD") {
+ res.end();
+ return;
+ }
+
+ const body = Readable.fromWeb(response.body);
+ body.pipe(res);
+ await finished(res);
+}
+
+async function defaultWorker() {
+ if (!defaultWorkerPromise) {
+ defaultWorkerPromise = import("../dist/worker.js").then(
+ (mod) => mod.default || mod,
+ );
+ }
+ return defaultWorkerPromise;
+}
+
+export function createDockerServer(options = {}) {
+ return http.createServer((req, res) => {
+ handleDockerRequest(req, res, options).catch((err) => {
+ console.error("request failed:", err);
+ if (!res.headersSent) {
+ res.statusCode = 500;
+ res.setHeader("content-type", "application/json; charset=utf-8");
+ }
+ res.end(JSON.stringify({ error: { message: "internal server error" } }));
+ });
+ });
+}
+
+export function startDockerServer(options = {}) {
+ const server = createDockerServer(options);
+ const listenPort = Number(options.port || port);
+ const listenHost = options.host || host;
+ server.listen(listenPort, listenHost, () => {
+ console.log(`web2gem listening on http://${listenHost}:${listenPort}`);
+ });
+ return server;
+}
+
+if (
+ process.argv[1] &&
+ import.meta.url === pathToFileURL(process.argv[1]).href
+) {
+ startDockerServer();
+}
diff --git a/scripts/docker-smoke.mjs b/scripts/docker-smoke.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..de1649a2ebb68ab4695f08c9166ffd1deb2cf468
--- /dev/null
+++ b/scripts/docker-smoke.mjs
@@ -0,0 +1,115 @@
+import { outputLine } from "./io.mjs";
+import { commandAvailable, outputCommand, runCommand } from "./process.mjs";
+
+if (!(await commandAvailable("docker"))) {
+ outputLine("Docker smoke skipped: docker executable not found");
+ process.exit(0);
+}
+
+const image = `web2gem:smoke-${process.pid}`;
+let container = "";
+
+try {
+ await runCommand("docker", ["build", "-t", image, "."]);
+ container = (
+ await outputCommand("docker", [
+ "run",
+ "-d",
+ "--rm",
+ "-p",
+ "127.0.0.1::52389",
+ "-e",
+ "API_KEYS=smoke-key",
+ "-e",
+ "CURRENT_INPUT_FILE_ENABLED=false",
+ image,
+ ])
+ ).trim();
+
+ const port = await mappedPort(container);
+ const base = `http://127.0.0.1:${port}`;
+ await waitForHealth(base);
+
+ const health = await fetch(`${base}/`);
+ assert(health.status === 200, `health status ${health.status}`);
+ const healthBody = await health.json();
+ assert(healthBody.status === "ok", "health payload did not report ok");
+
+ const authFailure = await fetch(`${base}/v1/models`);
+ assert(
+ authFailure.status === 401,
+ `auth failure status ${authFailure.status}`,
+ );
+
+ const models = await fetch(`${base}/v1/models`, {
+ headers: { Authorization: "Bearer smoke-key" },
+ });
+ assert(models.status === 200, `authenticated models status ${models.status}`);
+
+ const invalidModel = await fetch(`${base}/v1/chat/completions`, {
+ method: "POST",
+ headers: {
+ Authorization: "Bearer smoke-key",
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ model: "not-a-model",
+ messages: [{ role: "user", content: "hello" }],
+ }),
+ });
+ assert(
+ invalidModel.status === 400,
+ `invalid model status ${invalidModel.status}`,
+ );
+ const invalidBody = await invalidModel.json();
+ assert(
+ invalidBody.error && invalidBody.error.code === "model_not_found",
+ "invalid model did not return model_not_found",
+ );
+
+ outputLine("Docker smoke check passed");
+} finally {
+ if (container) {
+ await outputCommand("docker", ["stop", container], { allowFailure: true });
+ }
+ await outputCommand("docker", ["rmi", image], { allowFailure: true });
+}
+
+async function mappedPort(containerId) {
+ for (let i = 0; i < 30; i++) {
+ const raw = (
+ await outputCommand("docker", ["port", containerId, "52389/tcp"], {
+ allowFailure: true,
+ })
+ ).trim();
+ const match = /:(\d+)\s*$/.exec(raw);
+ if (match) return Number(match[1]);
+ await delay(250);
+ }
+ throw new Error("Docker smoke failed: container port was not mapped");
+}
+
+async function waitForHealth(base) {
+ let lastError = null;
+ for (let i = 0; i < 60; i++) {
+ try {
+ const resp = await fetch(`${base}/`);
+ if (resp.status === 200) return;
+ lastError = new Error(`health status ${resp.status}`);
+ } catch (err) {
+ lastError = err;
+ }
+ await delay(250);
+ }
+ throw new Error(
+ `Docker smoke failed: health route did not become ready: ${lastError}`,
+ );
+}
+
+function delay(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function assert(ok, message) {
+ if (!ok) throw new Error(`Docker smoke failed: ${message}`);
+}
diff --git a/scripts/ensure-test-bundle-fresh.mjs b/scripts/ensure-test-bundle-fresh.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..6897a14bdb0dfc6c63769a5f040417908e4386ce
--- /dev/null
+++ b/scripts/ensure-test-bundle-fresh.mjs
@@ -0,0 +1,29 @@
+import { existsSync, globSync, statSync } from "node:fs";
+import { runCommand } from "./process.mjs";
+
+const bundlePaths = ["dist/worker.test.js", "dist/worker.js"];
+const sourceGlobs = [
+ "src/**/*.ts",
+ "scripts/build.mjs",
+ "package.json",
+ "tsconfig.json",
+];
+
+if (needsBuild()) {
+ await runCommand(process.execPath, ["scripts/build.mjs", "--test-bundle"]);
+}
+
+function needsBuild() {
+ if (bundlePaths.some((path) => !existsSync(path))) return true;
+
+ const oldestBundleMtime = Math.min(
+ ...bundlePaths.map((path) => statSync(path).mtimeMs),
+ );
+
+ for (const pattern of sourceGlobs) {
+ for (const path of globSync(pattern)) {
+ if (statSync(path).mtimeMs > oldestBundleMtime) return true;
+ }
+ }
+ return false;
+}
diff --git a/scripts/io.mjs b/scripts/io.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..e35f7d3d4d3394dbc5d6649d7e6dac8410cbeb2d
--- /dev/null
+++ b/scripts/io.mjs
@@ -0,0 +1,25 @@
+export function outputLine(...values) {
+ writeLine(process.stdout, values);
+}
+
+export function errorLine(...values) {
+ writeLine(process.stderr, values);
+}
+
+function writeLine(stream, values) {
+ stream.write(`${values.map(formatValue).join(" ")}\n`);
+}
+
+function formatValue(value) {
+ if (value instanceof Error) return value.stack || value.message;
+ if (typeof value === "string") return value;
+ if (value === null || value === undefined) return String(value);
+ if (typeof value === "object") {
+ try {
+ return JSON.stringify(value);
+ } catch (_) {
+ return String(value);
+ }
+ }
+ return String(value);
+}
diff --git a/scripts/process.mjs b/scripts/process.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..7cd17de76558836284ac79ae067cbcfba161e449
--- /dev/null
+++ b/scripts/process.mjs
@@ -0,0 +1,88 @@
+import { spawn } from "node:child_process";
+
+export function runPnpm(args, options = {}) {
+ const env = options.env || process.env;
+ const npmExecPath = env.npm_execpath || process.env.npm_execpath;
+ if (npmExecPath) {
+ if (/\.(?:c?js|mjs)$/i.test(npmExecPath)) {
+ return runCommand(process.execPath, [npmExecPath, ...args], options);
+ }
+ return runCommand(npmExecPath, args, options);
+ }
+ return runCommand(
+ process.platform === "win32" ? "pnpm.cmd" : "pnpm",
+ args,
+ options,
+ );
+}
+
+export function runCommand(command, args, options = {}) {
+ return spawnCommand(command, args, {
+ ...options,
+ stdio: options.stdio || "inherit",
+ });
+}
+
+export function outputCommand(command, args, options = {}) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(command, args, {
+ cwd: options.cwd || process.cwd(),
+ env: options.env || process.env,
+ stdio: ["ignore", "pipe", options.allowFailure ? "ignore" : "inherit"],
+ });
+ let stdout = "";
+ child.stdout.setEncoding("utf8");
+ child.stdout.on("data", (chunk) => {
+ stdout += chunk;
+ });
+ child.on("error", reject);
+ child.on("exit", (code, signal) => {
+ if (code === 0 || options.allowFailure) {
+ resolve(stdout);
+ return;
+ }
+ reject(commandFailure(command, args, code, signal));
+ });
+ });
+}
+
+export async function commandAvailable(command) {
+ try {
+ await outputCommand(command, ["--version"], { allowFailure: true });
+ return true;
+ } catch (error) {
+ return !isMissingExecutableError(error);
+ }
+}
+
+function spawnCommand(command, args, options) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(command, args, {
+ cwd: options.cwd || process.cwd(),
+ env: options.env || process.env,
+ stdio: options.stdio,
+ });
+ child.on("error", reject);
+ child.on("exit", (code, signal) => {
+ if (code === 0 || options.allowFailure) {
+ resolve({ code, signal });
+ return;
+ }
+ reject(commandFailure(command, args, code, signal));
+ });
+ });
+}
+
+function commandFailure(command, args, code, signal) {
+ const suffix = signal ? `signal ${signal}` : `exit code ${code}`;
+ return new Error(`${command} ${args.join(" ")} failed with ${suffix}`);
+}
+
+function isMissingExecutableError(error) {
+ return (
+ error &&
+ typeof error === "object" &&
+ "code" in error &&
+ error.code === "ENOENT"
+ );
+}
diff --git a/scripts/smoke.mjs b/scripts/smoke.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..80ea9f16f6febd230c0e0bcbffd7b4e435cd64d2
--- /dev/null
+++ b/scripts/smoke.mjs
@@ -0,0 +1,225 @@
+const prod = await import("../dist/worker.js");
+const testMod = await import("../dist/worker.test.js");
+
+const expectedProductionExports = [
+ "MODELS",
+ "VERSION",
+ "default",
+ "generate",
+ "generateStream",
+ "getConfig",
+ "parseToolCalls",
+ "resolveModel",
+];
+
+const productionExports = Object.keys(prod).sort();
+const missingProductionExports = expectedProductionExports.filter(
+ (name) => !productionExports.includes(name),
+);
+const unexpectedProductionExports = productionExports.filter(
+ (name) => !expectedProductionExports.includes(name),
+);
+if (missingProductionExports.length || unexpectedProductionExports.length) {
+ const details = [
+ missingProductionExports.length
+ ? `missing: ${missingProductionExports.join(", ")}`
+ : "",
+ unexpectedProductionExports.length
+ ? `unexpected: ${unexpectedProductionExports.join(", ")}`
+ : "",
+ ]
+ .filter(Boolean)
+ .join("; ");
+ console.error(
+ `Smoke check failed: production bundle exports changed (${details})`,
+ );
+ process.exit(1);
+}
+
+const checks = [
+ ["default.fetch", prod.default && typeof prod.default.fetch === "function"],
+ ["MODELS", prod.MODELS && typeof prod.MODELS === "object"],
+ ["resolveModel", typeof prod.resolveModel === "function"],
+ ["getConfig", typeof prod.getConfig === "function"],
+ ["parseToolCalls", typeof prod.parseToolCalls === "function"],
+ ["test.buildPayload", typeof testMod.buildPayload === "function"],
+ [
+ "test.buildToolCallInstructions",
+ typeof testMod.buildToolCallInstructions === "function",
+ ],
+ [
+ "test.normalizeResponsesInputAsMessages",
+ typeof testMod.normalizeResponsesInputAsMessages === "function",
+ ],
+];
+
+const failed = checks.filter(([, ok]) => !ok).map(([name]) => name);
+if (failed.length) {
+ console.error(`Smoke check failed: ${failed.join(", ")}`);
+ process.exit(1);
+}
+
+const health = await prod.default.fetch(
+ new Request("https://worker.example/"),
+ {},
+ {},
+);
+if (health.status !== 200) {
+ console.error(`Smoke check failed: health status ${health.status}`);
+ process.exit(1);
+}
+
+const preflight = await prod.default.fetch(
+ new Request("https://worker.example/v1/chat/completions", {
+ method: "OPTIONS",
+ headers: {
+ Origin: "https://client.example",
+ "Access-Control-Request-Headers":
+ "content-type, x-custom, x-ds2-internal-token",
+ "Access-Control-Request-Private-Network": "true",
+ },
+ }),
+ {},
+ {},
+);
+if (preflight.status !== 204) {
+ console.error(
+ `Smoke check failed: CORS preflight status ${preflight.status}`,
+ );
+ process.exit(1);
+}
+if (
+ preflight.headers.get("Access-Control-Allow-Origin") !==
+ "https://client.example"
+) {
+ console.error("Smoke check failed: CORS origin was not reflected");
+ process.exit(1);
+}
+const allowHeaders =
+ preflight.headers.get("Access-Control-Allow-Headers") || "";
+if (
+ !allowHeaders.includes("x-custom") ||
+ /x-ds2-internal-token/i.test(allowHeaders)
+) {
+ console.error(
+ "Smoke check failed: CORS allow headers filtering is incorrect",
+ );
+ process.exit(1);
+}
+
+const authFailure = await prod.default.fetch(
+ new Request("https://worker.example/v1/models"),
+ {
+ API_KEYS: "secret",
+ },
+ {},
+);
+if (authFailure.status !== 401) {
+ console.error(
+ `Smoke check failed: auth failure status ${authFailure.status}`,
+ );
+ process.exit(1);
+}
+
+const googleModel = await prod.default.fetch(
+ new Request("https://worker.example/v1beta/models/gemini-3.5-flash"),
+ {},
+ {},
+);
+if (googleModel.status !== 200) {
+ console.error(
+ `Smoke check failed: Google model detail status ${googleModel.status}`,
+ );
+ process.exit(1);
+}
+const googleModelBody = await googleModel.json();
+if (
+ googleModelBody.name !== "models/gemini-3.5-flash" ||
+ googleModelBody.models
+) {
+ console.error(
+ "Smoke check failed: Google model detail did not return a single model",
+ );
+ process.exit(1);
+}
+
+const openAIReject = await prod.default.fetch(
+ new Request("https://worker.example/v1/chat/completions", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ model: "not-a-model",
+ messages: [{ role: "user", content: "hello" }],
+ }),
+ }),
+ {
+ API_KEYS: "",
+ CURRENT_INPUT_FILE_ENABLED: "false",
+ },
+ {},
+);
+if (openAIReject.status !== 400) {
+ console.error(
+ `Smoke check failed: OpenAI route status ${openAIReject.status}`,
+ );
+ process.exit(1);
+}
+const openAIRejectBody = await openAIReject.json();
+if (openAIRejectBody.error?.code !== "model_not_found") {
+ console.error(
+ "Smoke check failed: OpenAI route did not return model_not_found",
+ );
+ process.exit(1);
+}
+
+const googleReject = await prod.default.fetch(
+ new Request(
+ "https://worker.example/v1beta/models/gemini-3.5-flash:generateContent",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ contents: [{ role: "user", parts: [{ text: "call a tool" }] }],
+ toolConfig: { functionCallingConfig: { mode: "ANY" } },
+ }),
+ },
+ ),
+ {
+ API_KEYS: "",
+ CURRENT_INPUT_FILE_ENABLED: "false",
+ },
+ {},
+);
+if (googleReject.status !== 400) {
+ console.error(
+ `Smoke check failed: Google route status ${googleReject.status}`,
+ );
+ process.exit(1);
+}
+const googleRejectBody = await googleReject.json();
+if (googleRejectBody.error?.code !== "invalid_tool_choice") {
+ console.error(
+ "Smoke check failed: Google route did not return invalid_tool_choice",
+ );
+ process.exit(1);
+}
+
+const toolInstructions = testMod.buildToolCallInstructions(["Read"]);
+if (!toolInstructions.includes("Read-tool cache guard")) {
+ console.error(
+ "Smoke check failed: buildToolCallInstructions did not render read-tool guard",
+ );
+ process.exit(1);
+}
+
+const [, toolCalls] = prod.parseToolCalls(
+ '<|DSML|tool_calls><|DSML|invoke name="Read"><|DSML|parameter name="file_path">|DSML|parameter>|DSML|invoke>|DSML|tool_calls>',
+);
+if (!toolCalls.length || toolCalls[0].function.name !== "Read") {
+ console.error(
+ "Smoke check failed: parseToolCalls did not parse DSML tool call",
+ );
+ process.exit(1);
+}
+
+console.log("Smoke check passed");
diff --git a/scripts/unit.mjs b/scripts/unit.mjs
new file mode 100644
index 0000000000000000000000000000000000000000..f1ccd06d9a915e875f39ab63c252bf65685a7729
--- /dev/null
+++ b/scripts/unit.mjs
@@ -0,0 +1,10 @@
+import { runCommand, runPnpm } from "./process.mjs";
+
+const vitestArgs = normalizeVitestArgs(process.argv.slice(2));
+
+await runCommand(process.execPath, ["scripts/build.mjs", "--test-bundle"]);
+await runPnpm(["exec", "vitest", "run", ...vitestArgs]);
+
+function normalizeVitestArgs(args) {
+ return args[0] === "--" ? args.slice(1) : args;
+}
diff --git a/src/app.ts b/src/app.ts
new file mode 100644
index 0000000000000000000000000000000000000000..11d3786e72dff036d984935ed8ebc267e0779d7c
--- /dev/null
+++ b/src/app.ts
@@ -0,0 +1,301 @@
+import { createRuntimeConfig, getConfig, RuntimeConfigError } from "./config";
+import {
+ authorized,
+ corsHeaders,
+ jsonResponse,
+ jsonTextResponse,
+ openAIErrorResponse,
+ withCORS,
+} from "./http";
+import {
+ handleChat,
+ handleImageEdits,
+ handleImageEditsMultipart,
+ handleImageGenerations,
+ handleResponses,
+} from "./http/openai";
+import { handleGoogleGenerate } from "./http/google/handlers";
+import {
+ GOOGLE_MODEL_JSON_BY_ID,
+ GOOGLE_MODEL_LIST_JSON,
+ HEALTH_JSON,
+ NOT_FOUND_JSON,
+ OPENAI_MODEL_JSON_BY_ID,
+ OPENAI_MODEL_LIST_JSON,
+} from "./http/core/model-routes";
+import { googleJsonError, readRouteJsonPost } from "./http/core/route-json";
+import { createGeminiCompletionProvider } from "./gemini/completion-provider";
+import { elapsedMs, log, logStage, nowMs } from "./shared/logging";
+import { errorLogSummary } from "./shared/errors";
+import { uuid } from "./shared/crypto";
+import type { RuntimeConfig, WorkerEnv } from "./config";
+import type { RouteJsonPostResult } from "./http/core/route-json";
+
+const GOOGLE_GENERATE_PATH_RE =
+ /^\/v(?:1beta|1)\/models\/[^/?#]+:generateContent$/;
+const GOOGLE_STREAM_GENERATE_PATH_RE =
+ /^\/v(?:1beta|1)\/models\/[^/?#]+:streamGenerateContent$/;
+
+export type ApplicationExecutionContext = Pick<
+ ExecutionContext,
+ "waitUntil"
+> & {
+ runtimeProfile?: "docker";
+};
+
+type ApplicationRequestContext = {
+ request: Request;
+ env: WorkerEnv;
+ cfg: RuntimeConfig;
+ url: URL;
+ path: string;
+};
+
+export async function handleApplicationRequest(
+ request: Request,
+ env: WorkerEnv,
+ executionContext: ApplicationExecutionContext,
+): Promise {
+ const method = request.method.toUpperCase();
+ const url = new URL(request.url);
+ const path = url.pathname;
+ const requestId = uuid();
+ let activeConfig: RuntimeConfig | undefined;
+ let requestStartMs = 0;
+ const respond = (response: Response) => {
+ const corsResponse = withCORS(response, request);
+ const completed = withResponseHeader(
+ corsResponse,
+ "x-request-id",
+ requestId,
+ );
+ if (activeConfig?.log_requests) {
+ logStage(activeConfig, "request_complete", {
+ requestId,
+ method,
+ path,
+ status: completed.status,
+ ms: elapsedMs(requestStartMs),
+ });
+ }
+ return completed;
+ };
+
+ if (method === "OPTIONS") {
+ return new Response(null, {
+ status: 204,
+ headers: corsHeaders(request),
+ });
+ }
+
+ let cfg: RuntimeConfig;
+ try {
+ cfg = createRuntimeConfig(getConfig(env), {
+ execution_ctx: executionContext,
+ runtime_profile:
+ executionContext.runtimeProfile === "docker" ? "docker" : "worker",
+ });
+ activeConfig = cfg;
+ if (cfg.log_requests) requestStartMs = nowMs();
+ } catch (error) {
+ return respond(invalidRuntimeConfigResponse(error));
+ }
+
+ if (path !== "/" && !authorized(request, url, cfg)) {
+ return respond(openAIErrorResponse("invalid api key", 401));
+ }
+
+ const context: ApplicationRequestContext = {
+ request,
+ env,
+ cfg,
+ url,
+ path,
+ };
+ try {
+ const response = await dispatchApplicationRoute(method, context);
+ return respond(response);
+ } catch (error) {
+ log(cfg, `error: ${errorLogSummary(error)}`);
+ return respond(
+ jsonResponse(
+ {
+ error: {
+ message: "internal server error",
+ code: "internal_server_error",
+ },
+ },
+ 500,
+ ),
+ );
+ }
+}
+
+function withResponseHeader(
+ response: Response,
+ name: string,
+ value: string,
+): Response {
+ try {
+ response.headers.set(name, value);
+ return response;
+ } catch (_) {
+ const headers = new Headers(response.headers);
+ headers.set(name, value);
+ return new Response(response.body, {
+ status: response.status,
+ statusText: response.statusText,
+ headers,
+ });
+ }
+}
+
+async function dispatchApplicationRoute(
+ method: string,
+ context: ApplicationRequestContext,
+): Promise {
+ if (method === "GET") return handleGetRoute(context.path);
+ if (method === "POST") return handlePostRoute(context);
+ return jsonTextResponse(NOT_FOUND_JSON, 404);
+}
+
+function handleGetRoute(path: string): Response {
+ if (path === "/v1/models") return jsonTextResponse(OPENAI_MODEL_LIST_JSON);
+ if (path.startsWith("/v1/models/")) {
+ const id = decodeURIComponent(path.slice("/v1/models/".length));
+ const modelJson = OPENAI_MODEL_JSON_BY_ID.get(id);
+ if (!modelJson)
+ return openAIErrorResponse(
+ `model ${id} is not available`,
+ 404,
+ "model_not_found",
+ );
+ return jsonTextResponse(modelJson);
+ }
+ if (path === "/v1beta/models")
+ return jsonTextResponse(GOOGLE_MODEL_LIST_JSON);
+ if (path.startsWith("/v1beta/models/")) {
+ const id = decodeURIComponent(path.slice("/v1beta/models/".length));
+ const modelJson = GOOGLE_MODEL_JSON_BY_ID.get(id);
+ if (!modelJson)
+ return jsonResponse(
+ {
+ error: {
+ message: `model ${id} is not available`,
+ code: "model_not_found",
+ },
+ },
+ 404,
+ );
+ return jsonTextResponse(modelJson);
+ }
+ if (path === "/") return jsonTextResponse(HEALTH_JSON);
+ return jsonTextResponse(NOT_FOUND_JSON, 404);
+}
+
+async function handlePostRoute(
+ context: ApplicationRequestContext,
+): Promise {
+ const { request, cfg, path } = context;
+ if (path === "/v1/chat/completions") {
+ return handleOpenAIJsonPost(request, cfg, path, (body) =>
+ handleChat(body, cfg, createProvider(cfg)),
+ );
+ }
+ if (path === "/v1/responses") {
+ return handleOpenAIJsonPost(request, cfg, path, (body) =>
+ handleResponses(body, cfg, createProvider(cfg)),
+ );
+ }
+ if (path === "/v1/images/generations") {
+ return handleOpenAIJsonPost(request, cfg, path, (body) =>
+ handleImageGenerations(body, cfg, createProvider(cfg)),
+ );
+ }
+ if (path === "/v1/images/edits") {
+ if (isMultipartFormRequest(request)) {
+ return handleImageEditsMultipart(request, cfg, createProvider(cfg));
+ }
+ return handleOpenAIJsonPost(request, cfg, path, (body) =>
+ handleImageEdits(body, cfg, createProvider(cfg)),
+ );
+ }
+ if (GOOGLE_GENERATE_PATH_RE.test(path)) {
+ return handleGoogleJsonPost(request, cfg, path, (body) =>
+ handleGoogleGenerate(body, cfg, createProvider(cfg), path, false),
+ );
+ }
+ if (GOOGLE_STREAM_GENERATE_PATH_RE.test(path)) {
+ return handleGoogleJsonPost(request, cfg, path, (body) =>
+ handleGoogleGenerate(body, cfg, createProvider(cfg), path, true),
+ );
+ }
+ return jsonTextResponse(NOT_FOUND_JSON, 404);
+}
+
+function createProvider(cfg: RuntimeConfig) {
+ return createGeminiCompletionProvider(cfg);
+}
+
+async function handleOpenAIJsonPost(
+ request: Request,
+ cfg: RuntimeConfig,
+ path: string,
+ handler: (
+ body: NonNullable,
+ ) => Promise,
+): Promise {
+ const parsed = await readRouteJsonPost(request, cfg, path);
+ if (parsed.error !== undefined)
+ return openAIErrorResponse(parsed.error, parsed.status || 400, parsed.code);
+ return handler(parsed.value);
+}
+
+async function handleGoogleJsonPost(
+ request: Request,
+ cfg: RuntimeConfig,
+ path: string,
+ handler: (
+ body: NonNullable,
+ ) => Promise,
+): Promise {
+ const parsed = await readRouteJsonPost(request, cfg, path);
+ if (parsed.error !== undefined)
+ return jsonResponse(
+ googleJsonError(parsed.error, parsed.code),
+ parsed.status || 400,
+ );
+ return handler(parsed.value);
+}
+
+function isMultipartFormRequest(request: Request): boolean {
+ const contentType = request.headers.get("content-type") || "";
+ return (
+ contentType.split(";", 1)[0]?.trim().toLowerCase() === "multipart/form-data"
+ );
+}
+
+function invalidRuntimeConfigResponse(error: unknown): Response {
+ if (error instanceof RuntimeConfigError) {
+ return jsonResponse(
+ {
+ error: {
+ message: "invalid runtime configuration",
+ code: error.code,
+ setting: error.setting,
+ reason: error.reason,
+ },
+ },
+ 500,
+ );
+ }
+ return jsonResponse(
+ {
+ error: {
+ message: "invalid runtime configuration",
+ code: "invalid_runtime_config",
+ },
+ },
+ 500,
+ );
+}
diff --git a/src/attachments/base64.ts b/src/attachments/base64.ts
new file mode 100644
index 0000000000000000000000000000000000000000..abfbf84036b4bf921ea36072b38b067a81b3c8ff
--- /dev/null
+++ b/src/attachments/base64.ts
@@ -0,0 +1,65 @@
+export function base64DecodedByteLength(raw: string): number {
+ const compact = String(raw || "").replace(/\s+/g, "");
+ if (!compact) return 0;
+ return Math.floor((compact.replace(/=+$/, "").length * 3) / 4);
+}
+
+export function validateBase64Shape(raw: unknown): string {
+ const compact = String(raw || "").replace(/\s+/g, "");
+ if (
+ compact &&
+ (!/^[A-Za-z0-9+/_-]+={0,2}$/.test(compact) ||
+ compact.length % 4 === 1 ||
+ /=(?=.*[^=])/.test(compact))
+ )
+ throw new Error("invalid base64 payload");
+ return compact;
+}
+
+export function base64ToBytes(value: unknown): Uint8Array {
+ const source = String(value || "");
+ const nativeFromBase64 = (Uint8Array as Uint8ArrayBase64Constructor)
+ .fromBase64;
+ if (typeof nativeFromBase64 === "function") {
+ try {
+ return nativeFromBase64(
+ source,
+ /[-_]/.test(source) ? { alphabet: "base64url" } : undefined,
+ );
+ } catch (_) {
+ throw new Error("invalid base64 payload");
+ }
+ }
+ const compact = validateBase64Shape(source);
+ const standard = /[-_]/.test(compact)
+ ? compact.replace(/-/g, "+").replace(/_/g, "/")
+ : compact;
+ const binary = atob(standard.padEnd(Math.ceil(standard.length / 4) * 4, "="));
+ const bytes = new Uint8Array(binary.length);
+ for (let index = 0; index < binary.length; index++)
+ bytes[index] = binary.charCodeAt(index);
+ return bytes;
+}
+
+export function bytesToBase64(bytes: Uint8Array): string {
+ const nativeToBase64 = (bytes as Uint8ArrayBase64).toBase64;
+ if (typeof nativeToBase64 === "function") return nativeToBase64.call(bytes);
+ let binary = "";
+ for (let offset = 0; offset < bytes.byteLength; offset += 0x8000)
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
+ return btoa(binary);
+}
+
+type Uint8ArrayBase64Alphabet = "base64" | "base64url";
+type Uint8ArrayBase64Constructor = typeof Uint8Array & {
+ fromBase64?: (
+ value: string,
+ options?: { alphabet?: Uint8ArrayBase64Alphabet },
+ ) => Uint8Array;
+};
+type Uint8ArrayBase64 = Uint8Array & {
+ toBase64?: (options?: {
+ alphabet?: Uint8ArrayBase64Alphabet;
+ omitPadding?: boolean;
+ }) => string;
+};
diff --git a/src/attachments/collect-openai.ts b/src/attachments/collect-openai.ts
new file mode 100644
index 0000000000000000000000000000000000000000..25756d4f3606fe277ea12dae8e1c2f23f0cfeaa6
--- /dev/null
+++ b/src/attachments/collect-openai.ts
@@ -0,0 +1,161 @@
+import { isRecord } from "../shared/types";
+import {
+ imageFilenameFromObject,
+ normalizeUploadFileInput,
+ parseImageUrl,
+ uploadMimeFromObject,
+ type UploadFileInput,
+} from "./input";
+import { createAttachmentPlan } from "./plan";
+import { collectOpenAIRefFileIDs } from "./refs";
+import type { AttachmentPlan } from "./types";
+
+const FULL_INLINE_UPLOAD_KEYS = [
+ "messages",
+ "input",
+ "attachments",
+ "content",
+ "files",
+ "items",
+ "data",
+ "source",
+ "file",
+ "image_url",
+];
+const CONTAINER_INLINE_UPLOAD_KEYS = [
+ "attachments",
+ "files",
+ "items",
+ "data",
+ "source",
+ "file",
+ "image_url",
+];
+const FILE_BLOCK_CONTAINER_KEYS = ["attachments", "files", "items"];
+
+export function collectOpenAIRequestAttachmentPlan(
+ req: unknown,
+): AttachmentPlan {
+ const inline = collectOpenAIInlineUploads(req);
+ return createAttachmentPlan({
+ existingFileRefs: collectOpenAIRefFileIDs(req),
+ images: inline.images,
+ files: inline.files,
+ });
+}
+
+export function collectOpenAIInlineUploadFiles(
+ req: unknown,
+): UploadFileInput[] | null {
+ return collectOpenAIInlineUploads(req).files;
+}
+
+export function collectOpenAIInlineUploadImages(
+ req: unknown,
+): Array<{ b64: string; mime: string; filename?: string }> | null {
+ return collectOpenAIInlineUploads(req).images;
+}
+
+function collectOpenAIInlineUploads(req: unknown): {
+ files: UploadFileInput[] | null;
+ images: Array<{ b64: string; mime: string; filename?: string }> | null;
+} {
+ if (!isRecord(req)) return { files: null, images: null };
+ const state: InlineUploadState = { files: [], images: [] };
+ for (const key of ["attachments", "files"])
+ appendOpenAIInlineUploadInputs(state, req[key], "full");
+ for (const key of ["messages", "input"])
+ appendOpenAIInlineUploadInputs(state, req[key], "container");
+ return {
+ files: state.files.length ? state.files : null,
+ images: state.images.length ? state.images : null,
+ };
+}
+
+type InlineUploadWalkMode = "full" | "container";
+type InlineUploadState = {
+ files: UploadFileInput[];
+ images: Array<{ b64: string; mime: string; filename?: string }>;
+};
+
+function appendOpenAIInlineUploadInputs(
+ state: InlineUploadState,
+ raw: unknown,
+ mode: InlineUploadWalkMode,
+): void {
+ if (raw == null) return;
+ if (Array.isArray(raw)) {
+ for (const item of raw) appendOpenAIInlineUploadInputs(state, item, mode);
+ return;
+ }
+ if (!isRecord(raw)) return;
+ if (mode === "full") {
+ const image = normalizeImageUploadInput(raw);
+ if (image) {
+ state.images.push(image);
+ return;
+ }
+ const input = normalizeUploadFileInput(raw);
+ if (input) {
+ state.files.push(input);
+ return;
+ }
+ }
+ const keys = inlineUploadNestedKeys(raw, mode);
+ for (const key of keys) {
+ if (!(key in raw)) continue;
+ const nextMode: InlineUploadWalkMode =
+ key === "attachments" || key === "files" || key === "file"
+ ? "full"
+ : mode;
+ appendOpenAIInlineUploadInputs(state, raw[key], nextMode);
+ }
+}
+
+function inlineUploadNestedKeys(
+ raw: Record,
+ mode: InlineUploadWalkMode,
+): readonly string[] {
+ if (mode === "full") return FULL_INLINE_UPLOAD_KEYS;
+ if (isOpenAIFileBlock(raw)) return FILE_BLOCK_CONTAINER_KEYS;
+ return CONTAINER_INLINE_UPLOAD_KEYS;
+}
+
+function isOpenAIFileBlock(raw: Record): boolean {
+ const typ = String(raw.type || "")
+ .trim()
+ .toLowerCase();
+ return typ === "input_file" || typ === "file";
+}
+
+function normalizeImageUploadInput(
+ raw: Record,
+): { b64: string; mime: string; filename?: string } | null {
+ const typ = String(raw.type || "")
+ .trim()
+ .toLowerCase();
+ if (
+ typ !== "image_url" &&
+ typ !== "image" &&
+ typ !== "input_image" &&
+ !("image_url" in raw)
+ )
+ return null;
+ const source = isRecord(raw.source) ? raw.source : null;
+ if (source && source.data != null) {
+ const out = {
+ b64: String(source.data || ""),
+ mime: uploadMimeFromObject(raw) || "image/png",
+ };
+ const filename = imageFilenameFromObject(raw);
+ return filename ? { ...out, filename } : out;
+ }
+ const imageUrl = raw.image_url != null ? raw.image_url : raw.url;
+ const parsed = parseImageUrl(
+ isRecord(imageUrl) ? imageUrl.url : imageUrl,
+ uploadMimeFromObject(raw),
+ );
+ if (!parsed) return null;
+ const filename = imageFilenameFromObject(raw);
+ return filename ? { ...parsed, filename } : parsed;
+}
diff --git a/src/attachments/input.ts b/src/attachments/input.ts
new file mode 100644
index 0000000000000000000000000000000000000000..39ec72608c442a89a59899d849c1d157ce15a512
--- /dev/null
+++ b/src/attachments/input.ts
@@ -0,0 +1,303 @@
+import { firstRecord, isRecord, type UnknownRecord } from "../shared/types";
+import { TEXT_ENCODER } from "../shared/encoding";
+import { bytesToBase64 } from "./base64";
+import {
+ cleanUploadMime,
+ firstNonEmptyString,
+ mimeFromFilename,
+ sanitizeUploadFilename,
+} from "./mime";
+
+export type ParsedUploadUrl = { b64: string; mime: string };
+export type ParsedImageUrl = ParsedUploadUrl;
+export type ParsedDataUrl = { b64: string; mime: string };
+export type UploadFileInput = {
+ b64?: unknown;
+ mime?: unknown;
+ filename?: unknown;
+ name?: unknown;
+ invalidReason?: string;
+};
+
+export function parseDataUrl(url: unknown): ParsedDataUrl | null {
+ if (!url || typeof url !== "string") return null;
+ const trimmed = url.trim();
+ if (!isDataUrl(trimmed)) return null;
+ const comma = trimmed.indexOf(",");
+ if (comma < 0) return null;
+ const header = trimmed.slice(0, comma);
+ const payload = trimmed.slice(comma + 1);
+ const meta = header.slice(5);
+ const mime = cleanUploadMime((meta.split(";")[0] || "").toLowerCase());
+ if (/;base64(?:;|$)/i.test(meta)) return { b64: payload, mime };
+ try {
+ return {
+ b64: bytesToBase64(TEXT_ENCODER.encode(decodeURIComponent(payload))),
+ mime,
+ };
+ } catch (_) {
+ return null;
+ }
+}
+
+export function parseUploadUrl(url: unknown): ParsedUploadUrl | null {
+ if (!url || typeof url !== "string") return null;
+ const data = parseDataUrl(url);
+ if (data) return data;
+ return null;
+}
+
+export function parseImageUrl(
+ url: unknown,
+ explicitMime?: unknown,
+): ParsedImageUrl | null {
+ const parsed = parseUploadUrl(url);
+ if (!parsed) return null;
+ return {
+ ...parsed,
+ mime: firstNonEmptyString(
+ cleanUploadMime(explicitMime),
+ parsed.mime,
+ "image/png",
+ ),
+ };
+}
+
+export function uploadFilenameFromObject(obj: unknown): string {
+ if (!isRecord(obj)) return "";
+ const record = obj;
+ const source = isRecord(record.source) ? record.source : null;
+ const imageUrl = isRecord(record.image_url) ? record.image_url : null;
+ const inlineData =
+ asOptionalRecord(record.inlineData) || asOptionalRecord(record.inline_data);
+ const fileData =
+ asOptionalRecord(record.fileData) || asOptionalRecord(record.file_data);
+ const file = isRecord(record.file) ? record.file : null;
+ return firstNonEmptyString(
+ ...[
+ record.filename,
+ record.fileName,
+ record.file_name,
+ record.name,
+ record.displayName,
+ record.display_name,
+ source &&
+ (source.filename ||
+ source.fileName ||
+ source.file_name ||
+ source.name ||
+ source.displayName ||
+ source.display_name),
+ imageUrl &&
+ (imageUrl.filename ||
+ imageUrl.fileName ||
+ imageUrl.file_name ||
+ imageUrl.name ||
+ imageUrl.displayName ||
+ imageUrl.display_name),
+ inlineData &&
+ (inlineData.filename ||
+ inlineData.fileName ||
+ inlineData.file_name ||
+ inlineData.name ||
+ inlineData.displayName ||
+ inlineData.display_name),
+ fileData &&
+ (fileData.filename ||
+ fileData.fileName ||
+ fileData.file_name ||
+ fileData.name ||
+ fileData.displayName ||
+ fileData.display_name),
+ file &&
+ (file.filename ||
+ file.fileName ||
+ file.file_name ||
+ file.name ||
+ file.displayName ||
+ file.display_name),
+ ].map(sanitizeUploadFilename),
+ );
+}
+
+export function imageFilenameFromObject(obj: unknown): string {
+ return uploadFilenameFromObject(obj);
+}
+
+export function uploadMimeFromObject(obj: unknown): string {
+ if (!isRecord(obj)) return "";
+ const record = obj;
+ const source = isRecord(record.source) ? record.source : null;
+ const imageUrl = isRecord(record.image_url) ? record.image_url : null;
+ const inlineData =
+ asOptionalRecord(record.inlineData) || asOptionalRecord(record.inline_data);
+ const fileData =
+ asOptionalRecord(record.fileData) || asOptionalRecord(record.file_data);
+ const file = isRecord(record.file) ? record.file : null;
+ return firstNonEmptyString(
+ record.mime,
+ record.mime_type,
+ record.mimeType,
+ record.media_type,
+ record.mediaType,
+ record.content_type,
+ record.contentType,
+ source &&
+ (source.mime ||
+ source.mime_type ||
+ source.mimeType ||
+ source.media_type ||
+ source.mediaType ||
+ source.content_type ||
+ source.contentType),
+ imageUrl &&
+ (imageUrl.mime ||
+ imageUrl.mime_type ||
+ imageUrl.mimeType ||
+ imageUrl.content_type ||
+ imageUrl.contentType),
+ inlineData &&
+ (inlineData.mime ||
+ inlineData.mime_type ||
+ inlineData.mimeType ||
+ inlineData.media_type ||
+ inlineData.mediaType ||
+ inlineData.content_type ||
+ inlineData.contentType),
+ fileData &&
+ (fileData.mime ||
+ fileData.mime_type ||
+ fileData.mimeType ||
+ fileData.media_type ||
+ fileData.mediaType ||
+ fileData.content_type ||
+ fileData.contentType),
+ file &&
+ (file.mime ||
+ file.mime_type ||
+ file.mimeType ||
+ file.media_type ||
+ file.mediaType ||
+ file.content_type ||
+ file.contentType),
+ );
+}
+
+export function normalizeUploadFileInput(
+ file: unknown,
+): UploadFileInput | null {
+ if (typeof file === "string") {
+ const parsed = parseUploadUrl(file);
+ if (!parsed) return null;
+ return { b64: parsed.b64, mime: parsed.mime || "application/octet-stream" };
+ }
+ if (!isRecord(file)) return null;
+ const source = isRecord(file.source) ? file.source : null;
+ const nestedFile = isRecord(file.file) ? file.file : null;
+ const fileData = firstRecord(file.fileData, file.file_data);
+ const filename = uploadFilenameFromObject(file);
+ const explicitMime = uploadMimeFromObject(file);
+ const urlValue = firstNonEmptyString(
+ file.url,
+ file.file_url,
+ file.fileUrl,
+ source?.url,
+ nestedFile && (nestedFile.url || nestedFile.file_url || nestedFile.fileUrl),
+ fileData?.url,
+ );
+ const dataValue = firstNonNil(
+ fileData &&
+ (fileData.data ??
+ fileData.b64 ??
+ fileData.base64 ??
+ fileData.fileData ??
+ fileData.file_data),
+ file.file_data,
+ file.fileData,
+ file.data,
+ file.b64,
+ file.base64,
+ source && (source.data ?? source.b64 ?? source.base64),
+ nestedFile && (nestedFile.data ?? nestedFile.b64 ?? nestedFile.base64),
+ );
+ const parsedUrl = parseUploadUrl(urlValue);
+ if (parsedUrl)
+ return uploadInputFromParsed(parsedUrl, explicitMime, filename);
+ const parsedData = parseUploadUrl(dataValue);
+ if (parsedData)
+ return uploadInputFromParsed(parsedData, explicitMime, filename);
+ if (dataValue != null && typeof dataValue !== "object") {
+ const out: UploadFileInput = { b64: dataValue };
+ const mime = firstNonEmptyString(explicitMime, mimeFromFilename(filename));
+ if (mime) out.mime = mime;
+ if (filename) out.filename = filename;
+ return out;
+ }
+ if (
+ isExplicitUploadFileInput(file) &&
+ !hasExistingUploadFileReference(file) &&
+ !(fileData && (fileData.fileUri || fileData.file_uri))
+ ) {
+ const out: UploadFileInput = {
+ invalidReason: "missing generic file upload data",
+ };
+ const mime = firstNonEmptyString(explicitMime, mimeFromFilename(filename));
+ if (mime) out.mime = mime;
+ if (filename) out.filename = filename;
+ return out;
+ }
+ return null;
+}
+
+export function hasInlineUploadFilePayload(raw: unknown): boolean {
+ return !!normalizeUploadFileInput(raw);
+}
+
+export function isDataUrl(raw: string): boolean {
+ return /^data:/i.test(raw.trim());
+}
+
+function uploadInputFromParsed(
+ parsed: ParsedUploadUrl,
+ explicitMime: string,
+ filename: string,
+): UploadFileInput {
+ const out: UploadFileInput = {
+ b64: parsed.b64,
+ mime:
+ firstNonEmptyString(
+ explicitMime,
+ parsed.mime,
+ mimeFromFilename(filename),
+ ) || "application/octet-stream",
+ };
+ if (filename) out.filename = filename;
+ return out;
+}
+
+function firstNonNil(...values: unknown[]): unknown {
+ for (const value of values) {
+ if (value !== undefined && value !== null) return value;
+ }
+ return undefined;
+}
+
+function isExplicitUploadFileInput(file: UnknownRecord): boolean {
+ const typ = String(file.type || "")
+ .trim()
+ .toLowerCase();
+ return typ === "input_file" || typ === "file";
+}
+
+function hasExistingUploadFileReference(file: UnknownRecord): boolean {
+ if (file.file_id != null || file.id != null) return true;
+ const nestedFile = isRecord(file.file) ? file.file : null;
+ return !!(
+ nestedFile &&
+ (nestedFile.file_id != null || nestedFile.id != null)
+ );
+}
+
+function asOptionalRecord(value: unknown): UnknownRecord | null {
+ return isRecord(value) ? value : null;
+}
diff --git a/src/attachments/materialize.ts b/src/attachments/materialize.ts
new file mode 100644
index 0000000000000000000000000000000000000000..db753a6b7aabd2f739555950fc1c9e87811f56d5
--- /dev/null
+++ b/src/attachments/materialize.ts
@@ -0,0 +1,140 @@
+import type { ErrorWithMetadata } from "../shared/types";
+import { base64DecodedByteLength, base64ToBytes } from "./base64";
+import {
+ chooseUploadMime,
+ detectUploadMimeFromBytes,
+ firstNonEmptyString,
+ genericFilenameFromMime,
+ imageFilenameFromMime,
+ mimeFromFilename,
+} from "./mime";
+import type { AttachmentCandidate, AttachmentDropReason } from "./types";
+
+export type AttachmentLimits = {
+ maxFileBytes: number;
+ maxImageBytes: number;
+};
+
+export type MaterializedAttachment = {
+ candidate: AttachmentCandidate;
+ bytes: Uint8Array;
+ mime: string;
+ filename: string;
+};
+
+export const DEFAULT_ATTACHMENT_MAX_BYTES = 20 * 1024 * 1024;
+
+export async function materializeAttachment(
+ candidate: AttachmentCandidate,
+ limits: AttachmentLimits,
+): Promise {
+ const maxBytes = maxBytesForCandidate(candidate, limits);
+ if (candidate.source.type === "bytes") {
+ ensureWithinLimit(candidate, candidate.source.bytes.byteLength, maxBytes);
+ const mime = mimeForCandidate(candidate, candidate.source.bytes);
+ return {
+ candidate,
+ bytes: candidate.source.bytes,
+ mime,
+ filename: filenameForCandidate(candidate, mime),
+ };
+ }
+ const compact = String(candidate.source.data || "").replace(/\s+/g, "");
+ ensureWithinLimit(candidate, base64DecodedByteLength(compact), maxBytes);
+ try {
+ const bytes = base64ToBytes(compact);
+ ensureWithinLimit(candidate, bytes.byteLength, maxBytes);
+ const mime = mimeForCandidate(candidate, bytes);
+ return {
+ candidate,
+ bytes,
+ mime,
+ filename: filenameForCandidate(candidate, mime),
+ };
+ } catch (e) {
+ throw attachmentMaterializeFailure(
+ candidate,
+ "invalid_base64",
+ "invalid base64 payload",
+ 400,
+ e,
+ );
+ }
+}
+
+export function joinByteChunks(
+ chunks: readonly Uint8Array[],
+ total: number,
+): Uint8Array {
+ const out = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) {
+ out.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return out;
+}
+
+export function attachmentMaterializeFailure(
+ candidate: AttachmentCandidate,
+ code: AttachmentDropReason,
+ message: string,
+ status: number,
+ cause?: unknown,
+): ErrorWithMetadata {
+ const err: ErrorWithMetadata = new Error(message);
+ err.code = code;
+ err.status = status;
+ (err as ErrorWithMetadata & { attachmentKind?: string }).attachmentKind =
+ candidate.kind;
+ if (cause !== undefined) err.cause = cause;
+ return err;
+}
+
+function maxBytesForCandidate(
+ candidate: AttachmentCandidate,
+ limits: AttachmentLimits,
+): number {
+ if (candidate.kind === "image") return Math.max(0, limits.maxImageBytes);
+ return Math.max(0, limits.maxFileBytes);
+}
+
+function ensureWithinLimit(
+ candidate: AttachmentCandidate,
+ bytes: number,
+ maxBytes: number,
+): void {
+ if (bytes > maxBytes) {
+ throw attachmentMaterializeFailure(
+ candidate,
+ candidate.kind === "image" ? "image_too_large" : "file_too_large",
+ `${candidate.kind} attachment is too large (${bytes} bytes > ${maxBytes} bytes)`,
+ 413,
+ );
+ }
+}
+
+function mimeForCandidate(
+ candidate: AttachmentCandidate,
+ bytes: Uint8Array,
+): string {
+ return chooseUploadMime(
+ candidate.mime,
+ mimeFromFilename(candidate.filename),
+ detectUploadMimeFromBytes(bytes),
+ );
+}
+
+function filenameForCandidate(
+ candidate: AttachmentCandidate,
+ mimeHint: unknown,
+): string {
+ const explicit = firstNonEmptyString(candidate.filename);
+ if (explicit) return explicit;
+ if (candidate.kind === "image")
+ return imageFilenameFromMime(candidate.mime || mimeHint || "image/png", 1);
+ return genericFilenameFromMime(
+ candidate.mime || mimeHint || "application/octet-stream",
+ 1,
+ );
+}
diff --git a/src/attachments/media.ts b/src/attachments/media.ts
new file mode 100644
index 0000000000000000000000000000000000000000..79e9112b6798535a6f2410ee0b479a94d54ea0a6
--- /dev/null
+++ b/src/attachments/media.ts
@@ -0,0 +1,3 @@
+export * from "./base64";
+export * from "./input";
+export * from "./mime";
diff --git a/src/attachments/mime.ts b/src/attachments/mime.ts
new file mode 100644
index 0000000000000000000000000000000000000000..cac4545ce846618320c9073eac61d08c86bf5c19
--- /dev/null
+++ b/src/attachments/mime.ts
@@ -0,0 +1,173 @@
+import { TEXT_DECODER, UTF8_FATAL_DECODER } from "../shared/encoding";
+
+const MIME_MAX_LENGTH = 180;
+
+export function firstNonEmptyString(...values: unknown[]): string {
+ for (const value of values) {
+ if (typeof value === "string" && value.trim()) return value.trim();
+ }
+ return "";
+}
+
+export function sanitizeUploadFilename(name: unknown): string {
+ if (typeof name !== "string" && typeof name !== "number") return "";
+ let safeName = String(name || "").trim();
+ if (!safeName) return "";
+ safeName = safeName
+ .replace(/\0/g, "")
+ .replace(/[\r\n\t]/g, " ")
+ .trim();
+ safeName = safeName.split(/[\\/]/).filter(Boolean).pop() || "";
+ safeName = safeName.replace(/[\u0000-\u001f\u007f]/g, "").trim();
+ if (!safeName || safeName === "." || safeName === "..") return "";
+ return safeName.slice(0, 180);
+}
+
+export function filenameFromUrl(url: unknown): string {
+ if (!url || typeof url !== "string") return "";
+ try {
+ const parsed = new URL(url);
+ return sanitizeUploadFilename(
+ decodeURIComponent(
+ parsed.pathname.split("/").filter(Boolean).pop() || "",
+ ),
+ );
+ } catch (_) {
+ return sanitizeUploadFilename(String(url).split(/[?#]/)[0]);
+ }
+}
+
+export function mimeFromFilename(name: unknown): string {
+ const safeName = sanitizeUploadFilename(name).toLowerCase();
+ const extension = safeName.includes(".")
+ ? safeName.split(".").pop() || ""
+ : "";
+ const types: Record = {
+ txt: "text/plain",
+ log: "text/plain",
+ md: "text/markdown",
+ markdown: "text/markdown",
+ csv: "text/csv",
+ json: "application/json",
+ jsonl: "application/x-ndjson",
+ js: "text/javascript",
+ mjs: "text/javascript",
+ cjs: "text/javascript",
+ ts: "text/typescript",
+ tsx: "text/typescript",
+ py: "text/x-python",
+ html: "text/html",
+ htm: "text/html",
+ css: "text/css",
+ xml: "application/xml",
+ pdf: "application/pdf",
+ };
+ return types[extension] || "";
+}
+
+export function genericFilenameFromMime(mime: unknown, index: number): string {
+ const base = `file-${Math.max(1, Math.floor(index) || 1)}`;
+ const type = normalizeMimeType(mime);
+ const extensions: Record = {
+ "text/markdown": "md",
+ "text/csv": "csv",
+ "application/json": "json",
+ "application/x-ndjson": "jsonl",
+ "text/javascript": "js",
+ "application/javascript": "js",
+ "text/typescript": "ts",
+ "text/x-python": "py",
+ "text/html": "html",
+ "text/css": "css",
+ "application/xml": "xml",
+ "text/xml": "xml",
+ "application/pdf": "pdf",
+ "text/plain": "txt",
+ };
+ return `${base}.${extensions[type] || (type.startsWith("text/") ? "txt" : "bin")}`;
+}
+
+export function imageFilenameFromMime(mime: unknown, index: number): string {
+ const base = `image${index > 1 ? `-${index}` : ""}`;
+ const extensions: Record = {
+ "image/jpeg": "jpg",
+ "image/jpg": "jpg",
+ "image/webp": "webp",
+ "image/gif": "gif",
+ "image/bmp": "bmp",
+ "image/heic": "heic",
+ "image/heif": "heif",
+ };
+ return `${base}.${extensions[normalizeMimeType(mime)] || "png"}`;
+}
+
+export function cleanUploadMime(value: unknown): string {
+ if (typeof value !== "string" && typeof value !== "number") return "";
+ return String(value || "")
+ .replace(/[\r\n]/g, "")
+ .trim()
+ .slice(0, MIME_MAX_LENGTH);
+}
+
+export function chooseUploadMime(...values: unknown[]): string {
+ for (const value of values) {
+ const mime = cleanUploadMime(value);
+ if (mime) return mime;
+ }
+ return "application/octet-stream";
+}
+
+export function normalizeMimeType(value: unknown): string {
+ return (String(value || "").split(";")[0] || "").trim().toLowerCase();
+}
+
+export function detectUploadMimeFromBytes(bytes: Uint8Array): string {
+ if (!bytes?.byteLength) return "";
+ if (startsWithBytes(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
+ return "image/png";
+ if (startsWithBytes(bytes, [0xff, 0xd8, 0xff])) return "image/jpeg";
+ if (startsWithAscii(bytes, "GIF87a") || startsWithAscii(bytes, "GIF89a"))
+ return "image/gif";
+ if (startsWithAscii(bytes, "RIFF") && asciiAt(bytes, 8, "WEBP"))
+ return "image/webp";
+ if (startsWithAscii(bytes, "%PDF-")) return "application/pdf";
+ if (startsWithBytes(bytes, [0x50, 0x4b, 0x03, 0x04]))
+ return "application/zip";
+ if (!looksLikeUtf8Text(bytes)) return "";
+ const text = TEXT_DECODER.decode(
+ bytes.slice(0, Math.min(bytes.byteLength, 4096)),
+ ).trimStart();
+ return text.startsWith("{") || text.startsWith("[")
+ ? "application/json"
+ : "text/plain";
+}
+
+function startsWithBytes(
+ bytes: Uint8Array,
+ prefix: readonly number[],
+): boolean {
+ return (
+ bytes.byteLength >= prefix.length &&
+ prefix.every((value, index) => bytes[index] === value)
+ );
+}
+function startsWithAscii(bytes: Uint8Array, prefix: string): boolean {
+ return asciiAt(bytes, 0, prefix);
+}
+function asciiAt(bytes: Uint8Array, offset: number, text: string): boolean {
+ if (bytes.byteLength < offset + text.length) return false;
+ for (let index = 0; index < text.length; index++)
+ if (bytes[offset + index] !== text.charCodeAt(index)) return false;
+ return true;
+}
+function looksLikeUtf8Text(bytes: Uint8Array): boolean {
+ const sample = bytes.slice(0, Math.min(bytes.byteLength, 4096));
+ for (const byte of sample)
+ if (byte === 0 || byte < 0x09 || (byte > 0x0d && byte < 0x20)) return false;
+ try {
+ UTF8_FATAL_DECODER.decode(sample);
+ return true;
+ } catch (_) {
+ return false;
+ }
+}
diff --git a/src/attachments/notes.ts b/src/attachments/notes.ts
new file mode 100644
index 0000000000000000000000000000000000000000..3821d4aaf8f2404fc059e73e7507b49d10506097
--- /dev/null
+++ b/src/attachments/notes.ts
@@ -0,0 +1,61 @@
+import { sanitizeUploadFilename } from "./mime";
+import type { AttachmentDrop, AttachmentKind } from "./types";
+
+export function droppedAttachmentNote(
+ drops: readonly AttachmentDrop[] | null | undefined,
+): string {
+ if (!drops?.length) return "";
+ const groups = new Map<
+ string,
+ { kind: AttachmentKind; message: string; count: number }
+ >();
+ for (const drop of drops) {
+ const key = `${drop.kind}\x00${drop.message}`;
+ const existing = groups.get(key);
+ if (existing) existing.count += 1;
+ else groups.set(key, { kind: drop.kind, message: drop.message, count: 1 });
+ }
+ return [...groups.values()]
+ .map(
+ (group) =>
+ `\n\n[Note: ${group.count} ${group.kind}(s) were provided but ignored - ${group.message}.]`,
+ )
+ .join("");
+}
+
+export function attachmentDrop(
+ kind: AttachmentKind,
+ code: AttachmentDrop["code"],
+ message?: string,
+ filename?: unknown,
+): AttachmentDrop {
+ const drop: AttachmentDrop = {
+ kind,
+ code,
+ message: message || defaultDropMessage(code),
+ };
+ const safeName = sanitizeUploadFilename(filename);
+ if (safeName) drop.filename = safeName;
+ return drop;
+}
+
+function defaultDropMessage(code: AttachmentDrop["code"]): string {
+ switch (code) {
+ case "invalid_image_input":
+ return "invalid image input";
+ case "invalid_file_input":
+ return "invalid file input";
+ case "invalid_base64":
+ return "invalid base64 payload";
+ case "invalid_remote_url":
+ return "invalid remote URL";
+ case "file_too_large":
+ return "file attachment is too large";
+ case "image_too_large":
+ return "image attachment is too large";
+ case "too_many_files":
+ return "too many attachments";
+ case "upload_failed":
+ return "attachment upload failed";
+ }
+}
diff --git a/src/attachments/plan.ts b/src/attachments/plan.ts
new file mode 100644
index 0000000000000000000000000000000000000000..34544a54b6cceca31c6db13b63fd541e4eb25f71
--- /dev/null
+++ b/src/attachments/plan.ts
@@ -0,0 +1,215 @@
+import { isRecord } from "../shared/types";
+import {
+ firstNonEmptyString,
+ genericFilenameFromMime,
+ imageFilenameFromMime,
+ mimeFromFilename,
+ sanitizeUploadFilename,
+} from "./mime";
+import {
+ imageFilenameFromObject,
+ normalizeUploadFileInput,
+ type UploadFileInput,
+} from "./input";
+import { attachmentDrop } from "./notes";
+import { appendExistingFileRefs } from "./refs";
+import type {
+ AttachmentCandidate,
+ AttachmentDrop,
+ AttachmentFileRef,
+ AttachmentKind,
+ AttachmentPlan,
+} from "./types";
+
+export const MAX_ATTACHMENTS_PER_REQUEST = 50;
+
+type PlanState = {
+ candidates: AttachmentCandidate[];
+ existingFileRefs: AttachmentFileRef[];
+ dropped: AttachmentDrop[];
+ maxFiles: number;
+ nextID: number;
+};
+
+type CreatePlanInput = {
+ images?: unknown;
+ files?: unknown;
+ existingFileRefs?: unknown;
+ maxFiles?: number;
+};
+
+export function createAttachmentPlan(
+ input: CreatePlanInput = {},
+): AttachmentPlan {
+ const state: PlanState = {
+ candidates: [],
+ existingFileRefs: [],
+ dropped: [],
+ maxFiles: normalizeMaxFiles(input.maxFiles),
+ nextID: 1,
+ };
+ appendExistingFileRefs(state.existingFileRefs, input.existingFileRefs);
+ appendImageInputs(state, input.images);
+ appendFileInputs(state, input.files);
+ return finishPlan(state);
+}
+
+export function mergeAttachmentPlans(
+ ...plans: Array
+): AttachmentPlan {
+ const state: PlanState = {
+ candidates: [],
+ existingFileRefs: [],
+ dropped: [],
+ maxFiles: MAX_ATTACHMENTS_PER_REQUEST,
+ nextID: 1,
+ };
+ for (const plan of plans) {
+ if (!plan) continue;
+ state.maxFiles = Math.min(state.maxFiles, normalizeMaxFiles(plan.maxFiles));
+ appendExistingFileRefs(state.existingFileRefs, plan.existingFileRefs);
+ for (const candidate of plan.candidates) {
+ const meta: { filename?: string; mime?: string } = {};
+ if (candidate.filename) meta.filename = candidate.filename;
+ if (candidate.mime) meta.mime = candidate.mime;
+ addCandidate(state, candidate.kind, candidate.source, meta);
+ }
+ state.dropped.push(...plan.dropped);
+ }
+ return finishPlan(state);
+}
+
+function appendImageInputs(state: PlanState, raw: unknown): void {
+ if (!Array.isArray(raw)) return;
+ for (let i = 0; i < raw.length; i++) {
+ const image = raw[i];
+ if (!isRecord(image)) continue;
+ const b64 = image.b64;
+ if (b64 == null) {
+ state.dropped.push(
+ attachmentDrop(
+ "image",
+ "invalid_image_input",
+ "invalid image input",
+ imageFilenameFromObject(image),
+ ),
+ );
+ continue;
+ }
+ const name =
+ firstNonEmptyString(
+ sanitizeUploadFilename(image.filename),
+ sanitizeUploadFilename(image.name),
+ ) ||
+ imageFilenameFromMime(
+ image.mime || "image/png",
+ state.candidates.length + 1,
+ );
+ const source = { type: "base64" as const, data: b64 };
+ const mime = firstNonEmptyString(image.mime, "image/png");
+ addCandidate(state, "image", source, {
+ filename: name,
+ mime,
+ });
+ }
+}
+
+function appendFileInputs(state: PlanState, raw: unknown): void {
+ if (!Array.isArray(raw)) return;
+ for (const item of raw) {
+ const input = isNormalizedUploadFileInput(item)
+ ? item
+ : normalizeUploadFileInput(item);
+ if (!input) continue;
+ appendUploadFileInput(state, input);
+ }
+}
+
+function appendUploadFileInput(state: PlanState, input: UploadFileInput): void {
+ const nameHint = firstNonEmptyString(
+ sanitizeUploadFilename(input.filename),
+ sanitizeUploadFilename(input.name),
+ );
+ const mime = firstNonEmptyString(input.mime, mimeFromFilename(nameHint));
+ if (input.invalidReason) {
+ state.dropped.push(
+ attachmentDrop(
+ "file",
+ "invalid_file_input",
+ String(input.invalidReason || "invalid file input"),
+ nameHint,
+ ),
+ );
+ return;
+ }
+ if (input.b64 != null) {
+ const meta: { filename?: string; mime?: string } = {};
+ if (nameHint) meta.filename = nameHint;
+ else if (mime)
+ meta.filename = genericFilenameFromMime(
+ mime,
+ state.candidates.length + 1,
+ );
+ if (mime) meta.mime = mime;
+ addCandidate(
+ state,
+ "file",
+ { type: "base64", data: input.b64 },
+ {
+ ...meta,
+ },
+ );
+ }
+}
+
+function addCandidate(
+ state: PlanState,
+ kind: AttachmentKind,
+ source: AttachmentCandidate["source"],
+ meta: { filename?: string; mime?: string } = {},
+): void {
+ if (state.candidates.length >= state.maxFiles) {
+ state.dropped.push(
+ attachmentDrop(
+ kind,
+ "too_many_files",
+ `exceeded maximum of ${state.maxFiles} attachments per request`,
+ meta.filename,
+ ),
+ );
+ return;
+ }
+ const candidate: AttachmentCandidate = {
+ id: `att_${state.nextID++}`,
+ kind,
+ role: "request",
+ source,
+ };
+ const filename = sanitizeUploadFilename(meta.filename);
+ if (filename) candidate.filename = filename;
+ const mime = firstNonEmptyString(meta.mime);
+ if (mime) candidate.mime = mime;
+ state.candidates.push(candidate);
+}
+
+function finishPlan(state: PlanState): AttachmentPlan {
+ return {
+ candidates: state.candidates,
+ existingFileRefs: state.existingFileRefs.length
+ ? state.existingFileRefs
+ : null,
+ dropped: state.dropped,
+ maxFiles: state.maxFiles,
+ };
+}
+
+function normalizeMaxFiles(value: unknown): number {
+ const n = Number(value);
+ if (!Number.isFinite(n) || n <= 0) return MAX_ATTACHMENTS_PER_REQUEST;
+ return Math.max(1, Math.floor(n));
+}
+
+function isNormalizedUploadFileInput(value: unknown): value is UploadFileInput {
+ if (!isRecord(value)) return false;
+ return "invalidReason" in value || "b64" in value;
+}
diff --git a/src/attachments/refs.ts b/src/attachments/refs.ts
new file mode 100644
index 0000000000000000000000000000000000000000..7ddd301629a05ff1acf3bad06b5e20994d18a30c
--- /dev/null
+++ b/src/attachments/refs.ts
@@ -0,0 +1,133 @@
+import { isRecord } from "../shared/types";
+import { imageFilenameFromObject, normalizeUploadFileInput } from "./input";
+import { sanitizeUploadFilename } from "./mime";
+import type { AttachmentFileRef } from "./types";
+
+type ExistingRefState = {
+ out: AttachmentFileRef[];
+ seen: Set;
+};
+
+export function collectOpenAIRefFileIDs(
+ req: unknown,
+): AttachmentFileRef[] | null {
+ if (!isRecord(req)) return null;
+ const state: ExistingRefState = { out: [], seen: new Set() };
+ for (const key of [
+ "ref_file_ids",
+ "file_ids",
+ "attachments",
+ "messages",
+ "input",
+ ]) {
+ const raw = req[key];
+ if (raw == null) continue;
+ if ((key === "messages" || key === "input") && typeof raw === "string")
+ continue;
+ appendOpenAIRefFileIDs(state, raw);
+ }
+ return state.out.length ? state.out : null;
+}
+
+export function appendExistingFileRefs(
+ out: AttachmentFileRef[],
+ refs: unknown,
+): void {
+ const state: ExistingRefState = {
+ out,
+ seen: new Set(out.map(refKey).filter(Boolean) as string[]),
+ };
+ appendDirectOrOpenAIRefFileIDs(state, refs);
+}
+
+function appendOpenAIRefFileIDs(state: ExistingRefState, raw: unknown): void {
+ if (raw == null) return;
+ if (typeof raw === "string") {
+ addOpenAIRefFileID(state, raw);
+ return;
+ }
+ if (Array.isArray(raw)) {
+ for (const item of raw) appendOpenAIRefFileIDs(state, item);
+ return;
+ }
+ if (!isRecord(raw)) return;
+
+ const rawFilename = imageFilenameFromObject(raw);
+ if (raw.file_id != null) addOpenAIRefFileID(state, raw.file_id, rawFilename);
+ const typ = String(raw.type || "")
+ .trim()
+ .toLowerCase();
+ const hasInlinePayload =
+ typ.includes("file") && !!normalizeUploadFileInput(raw);
+ if (typ.includes("file") && !hasInlinePayload && raw.id != null)
+ addOpenAIRefFileID(state, raw.id, rawFilename);
+ const file = isRecord(raw.file) ? raw.file : null;
+ if (file) {
+ const fileFilename = imageFilenameFromObject(file) || rawFilename;
+ const nestedInlinePayload = !!normalizeUploadFileInput(file);
+ if (file.file_id != null)
+ addOpenAIRefFileID(state, file.file_id, fileFilename);
+ if (!nestedInlinePayload && file.id != null)
+ addOpenAIRefFileID(state, file.id, fileFilename);
+ }
+ for (const key of [
+ "ref_file_ids",
+ "file_ids",
+ "attachments",
+ "messages",
+ "input",
+ "content",
+ "files",
+ "items",
+ "data",
+ "source",
+ ]) {
+ if (!(key in raw)) continue;
+ if (hasInlinePayload && (key === "data" || key === "source")) continue;
+ const nested = raw[key];
+ if ((key === "content" || key === "input") && typeof nested === "string")
+ continue;
+ appendOpenAIRefFileIDs(state, nested);
+ }
+}
+
+function appendDirectOrOpenAIRefFileIDs(
+ state: ExistingRefState,
+ refs: unknown,
+): void {
+ if (refs == null) return;
+ if (typeof refs === "string") {
+ addOpenAIRefFileID(state, refs);
+ return;
+ }
+ if (Array.isArray(refs)) {
+ for (const ref of refs) appendDirectOrOpenAIRefFileIDs(state, ref);
+ return;
+ }
+ if (isRecord(refs)) {
+ const id = refs.ref || refs.fileRef || refs.id || refs.file_id;
+ const name = refs.name || refs.filename || refs.file_name;
+ if (id != null) {
+ addOpenAIRefFileID(state, id, name);
+ return;
+ }
+ }
+ appendOpenAIRefFileIDs(state, refs);
+}
+
+function addOpenAIRefFileID(
+ state: ExistingRefState,
+ fileID: unknown,
+ filename: unknown = undefined,
+): void {
+ const id = String(fileID || "").trim();
+ if (!id || state.seen.has(id)) return;
+ state.seen.add(id);
+ const name = sanitizeUploadFilename(filename);
+ state.out.push(name ? { id, name } : id);
+}
+
+function refKey(ref: AttachmentFileRef): string {
+ if (typeof ref === "string") return ref;
+ return ref.ref || ref.fileRef || ref.id || "";
+}
diff --git a/src/attachments/types.ts b/src/attachments/types.ts
new file mode 100644
index 0000000000000000000000000000000000000000..382c70db0bb979d090926a4067464e272e733cb3
--- /dev/null
+++ b/src/attachments/types.ts
@@ -0,0 +1,71 @@
+export type AttachmentFileRef =
+ | string
+ | {
+ ref?: string;
+ fileRef?: string;
+ id?: string;
+ name?: string;
+ filename?: string;
+ };
+
+export type AttachmentKind = "image" | "file";
+
+export type AttachmentRole = "request" | "context";
+
+export type AttachmentSource =
+ | { type: "base64"; data: unknown }
+ | { type: "bytes"; bytes: Uint8Array };
+
+export type AttachmentCandidate = {
+ id: string;
+ kind: AttachmentKind;
+ role: AttachmentRole;
+ source: AttachmentSource;
+ filename?: string;
+ mime?: string;
+};
+
+export type AttachmentDropReason =
+ | "invalid_image_input"
+ | "invalid_file_input"
+ | "invalid_base64"
+ | "invalid_remote_url"
+ | "file_too_large"
+ | "image_too_large"
+ | "too_many_files"
+ | "upload_failed";
+
+export type AttachmentDrop = {
+ kind: AttachmentKind;
+ code: AttachmentDropReason;
+ message: string;
+ filename?: string;
+};
+
+export type AttachmentPlan = {
+ candidates: AttachmentCandidate[];
+ existingFileRefs: AttachmentFileRef[] | null;
+ dropped: AttachmentDrop[];
+ maxFiles: number;
+};
+
+export type AttachmentUsage = {
+ uploadedFiles: number;
+ dedupedFiles: number;
+ uploadedBytes: number;
+ fileRefBytes: number;
+ inlinedFiles: number;
+ inlinedBytes: number;
+ droppedFiles: number;
+ multipartUploads: number;
+};
+
+export type AttachmentUploadResult = {
+ fileRefs: AttachmentFileRef[] | null;
+ imageFileRefs: AttachmentFileRef[] | null;
+ genericFileRefs: AttachmentFileRef[] | null;
+ promptText: string;
+ droppedNote: string;
+ supportsFileRefs: boolean;
+ usage: AttachmentUsage;
+};
diff --git a/src/completion/context-files.ts b/src/completion/context-files.ts
new file mode 100644
index 0000000000000000000000000000000000000000..96608e8cc38cc2684485b6c70fc88ff613f06945
--- /dev/null
+++ b/src/completion/context-files.ts
@@ -0,0 +1,361 @@
+import { currentInputFilePrompt } from "../toolcall/content";
+import { toolsContextTranscriptFor } from "../toolcall/tool-bundle";
+import { elapsedMs, log, logStage, nowMs } from "../shared/logging";
+import { errorLogSummary } from "../shared/errors";
+import {
+ buildTextWithTokens,
+ promptByteLength,
+ promptByteLengthBounded,
+ promptByteLengthGreaterThan,
+} from "../shared/tokens";
+import type { PromptByteLengthBounded } from "../shared/tokens";
+import type { ErrorWithMetadata } from "../shared/types";
+import type {
+ ContextFileFailure,
+ ContextFileResult,
+ FileRef,
+ ToolDef,
+} from "./types";
+
+type ContextFileConfig = {
+ current_input_file_enabled?: unknown;
+ current_input_file_min_bytes?: unknown;
+ current_input_file_name?: unknown;
+ current_tools_file_name?: unknown;
+ supports_authenticated_session?: unknown;
+ cookie?: unknown;
+ log_requests?: unknown;
+};
+export type TextFileUploader = (
+ text: string,
+ filename: string,
+) => Promise;
+export type ContextFilePromptByteCheck = PromptByteLengthBounded & {
+ thresholdBytes: number;
+};
+
+export function buildToolsContextTranscript(
+ toolDefs: readonly ToolDef[] | null | undefined,
+ choiceInstruction: unknown,
+ filename: unknown = "tools.txt",
+): string {
+ return toolsContextTranscriptFor(toolDefs, choiceInstruction, filename);
+}
+
+export function contextFileThreshold(cfg: ContextFileConfig): number {
+ return Math.max(0, Number(cfg.current_input_file_min_bytes) || 95000);
+}
+
+export function contextFilePromptByteCheck(
+ cfg: ContextFileConfig,
+ promptText: unknown,
+): ContextFilePromptByteCheck {
+ const thresholdBytes = contextFileThreshold(cfg);
+ return {
+ ...promptByteLengthBounded(promptText || "", thresholdBytes),
+ thresholdBytes,
+ };
+}
+
+export function contextFileConfigUnavailableReason(
+ cfg: ContextFileConfig,
+): string {
+ if (!cfg.current_input_file_enabled)
+ return "CURRENT_INPUT_FILE_ENABLED is disabled";
+ if (!(cfg.supports_authenticated_session ?? !!cfg.cookie))
+ return "GEMINI_COOKIE is not configured";
+ return "";
+}
+
+export function contextFileUploadUnavailableReason(
+ cfg: ContextFileConfig,
+ uploader?: TextFileUploader | null,
+): string {
+ return (
+ contextFileConfigUnavailableReason(cfg) ||
+ (uploader ? "" : "text file uploader is not configured")
+ );
+}
+
+export function shouldConsiderContextFiles(
+ cfg: ContextFileConfig,
+ promptText: unknown,
+ promptByteCheck?: ContextFilePromptByteCheck,
+): boolean {
+ if (contextFileConfigUnavailableReason(cfg)) return false;
+ return (promptByteCheck || contextFilePromptByteCheck(cfg, promptText))
+ .exceeded;
+}
+
+export function shouldUseContextFiles(
+ cfg: ContextFileConfig,
+ historyText: unknown,
+ latestInputText: unknown,
+ promptText: unknown,
+ promptByteCheck?: ContextFilePromptByteCheck,
+): boolean {
+ if (
+ !shouldConsiderContextFiles(cfg, promptText || historyText, promptByteCheck)
+ )
+ return false;
+ const latest = String(latestInputText || "").trim();
+ if (!latest) return false;
+ if (!String(historyText || "").trim()) return false;
+ return true;
+}
+
+export function oversizedInlineContextFailure(
+ cfg: ContextFileConfig,
+ promptText: unknown,
+ promptByteCheck?: ContextFilePromptByteCheck,
+ reason?: unknown,
+): ErrorWithMetadata {
+ const check = promptByteCheck || contextFilePromptByteCheck(cfg, promptText);
+ const unavailable = String(
+ reason ||
+ contextFileConfigUnavailableReason(cfg) ||
+ "context-file attachments are unavailable",
+ );
+ const err: ErrorWithMetadata = new Error(
+ `context is too long to send inline (${formatPromptByteComparison(check)}) and ${unavailable}; configure GEMINI_COOKIE with CURRENT_INPUT_FILE_ENABLED=true so this worker can use text attachments, or reduce the request size`,
+ );
+ err.code = "large_context_inline_unsupported";
+ err.status = 413;
+ err.promptBytes = check.bytes;
+ err.promptBytesExact = check.exact;
+ err.thresholdBytes = check.thresholdBytes;
+ return err;
+}
+
+export function contextFileUploadFailure(
+ kind: unknown,
+ promptText: unknown,
+ cause: unknown,
+ promptByteCheck?: ContextFilePromptByteCheck,
+): ErrorWithMetadata {
+ const check = promptByteCheck || null;
+ const err: ErrorWithMetadata = new Error(
+ `failed to upload ${kind || "context"} text file for large prompt; refusing to fall back to oversized inline context`,
+ );
+ err.code = "large_context_file_upload_failed";
+ err.promptBytes = check ? check.bytes : promptByteLength(promptText || "");
+ err.promptBytesExact = check ? check.exact : true;
+ if (check) err.thresholdBytes = check.thresholdBytes;
+ err.cause = cause;
+ return err;
+}
+
+export function latestInputInlineLimit(cfg: ContextFileConfig): number {
+ return Math.max(
+ 4000,
+ Math.min(16000, Math.floor(contextFileThreshold(cfg) / 6)),
+ );
+}
+
+export function latestInputPromptForContextFile(
+ cfg: ContextFileConfig,
+ latestInputText: unknown,
+): string {
+ const latest = String(latestInputText || "").trim();
+ if (!latest) return "";
+ if (!promptByteLengthGreaterThan(latest, latestInputInlineLimit(cfg)))
+ return `Latest user request:\n${latest}`;
+ const historyName =
+ String(cfg?.current_input_file_name || "message.txt").trim() ||
+ "message.txt";
+ return [
+ `The latest user request is at the end of \`${historyName}\`; do not duplicate it inline.`,
+ "Read it from the txt file and answer directly.",
+ ].join("\n");
+}
+
+export async function prepareContextFiles(
+ cfg: ContextFileConfig,
+ historyText: string,
+ toolDefs: readonly ToolDef[] | null | undefined,
+ choiceInstruction: unknown,
+ latestInputText: unknown,
+ promptText: unknown,
+ uploader?: TextFileUploader,
+ promptByteCheck?: ContextFilePromptByteCheck,
+ toolPromptSource?: unknown,
+): Promise {
+ if (!uploader) {
+ if (
+ !shouldUseContextFiles(
+ cfg,
+ historyText,
+ latestInputText,
+ promptText,
+ promptByteCheck,
+ )
+ )
+ return null;
+ return {
+ error: contextFileUploadFailure(
+ "context",
+ promptText,
+ new Error("text file uploader is not configured"),
+ promptByteCheck,
+ ),
+ };
+ }
+ return prepareContextFilesWithUploader(
+ cfg,
+ historyText,
+ toolDefs,
+ choiceInstruction,
+ latestInputText,
+ promptText,
+ uploader,
+ promptByteCheck,
+ toolPromptSource,
+ );
+}
+
+export async function prepareContextFilesWithUploader(
+ cfg: ContextFileConfig,
+ historyText: string,
+ toolDefs: readonly ToolDef[] | null | undefined,
+ choiceInstruction: unknown,
+ latestInputText: unknown,
+ promptText: unknown,
+ uploader: TextFileUploader,
+ promptByteCheck?: ContextFilePromptByteCheck,
+ toolPromptSource?: unknown,
+): Promise {
+ if (
+ !shouldUseContextFiles(
+ cfg,
+ historyText,
+ latestInputText,
+ promptText,
+ promptByteCheck,
+ )
+ )
+ return null;
+ const refs: FileRef[] = [];
+ const toolSource = toolPromptSource || toolDefs;
+ const toolsText = toolsContextTranscriptFor(
+ toolSource,
+ choiceInstruction,
+ cfg.current_tools_file_name || "tools.txt",
+ toolDefs || [],
+ );
+ let toolsAttached = false;
+ const uploadJobs = [
+ uploader(historyText, String(cfg.current_input_file_name || "message.txt")),
+ ];
+ const hasToolsText = !!toolsText.trim();
+ if (hasToolsText)
+ uploadJobs.push(
+ uploader(toolsText, String(cfg.current_tools_file_name || "tools.txt")),
+ );
+ const logRequests = !!cfg.log_requests;
+ const uploadStart = logRequests ? nowMs() : 0;
+ const uploadResults = await Promise.allSettled(uploadJobs);
+ const historyUpload = uploadResults[0];
+ if (historyUpload && historyUpload.status === "fulfilled") {
+ refs.push(historyUpload.value);
+ } else {
+ const e = historyUpload?.reason || "missing history upload result";
+ log(
+ cfg,
+ `history context file upload failed for large prompt ${errorLogSummary(e)}`,
+ );
+ return {
+ error: contextFileUploadFailure(
+ "history context",
+ promptText,
+ e,
+ promptByteCheck,
+ ),
+ };
+ }
+ if (hasToolsText) {
+ const toolsUpload = uploadResults[1];
+ if (toolsUpload && toolsUpload.status === "fulfilled") {
+ refs.push(toolsUpload.value);
+ toolsAttached = true;
+ } else if (toolsUpload) {
+ const e = toolsUpload.reason;
+ log(
+ cfg,
+ `tools context file upload failed for large prompt ${errorLogSummary(e)}`,
+ );
+ return {
+ error: contextFileUploadFailure(
+ "tools context",
+ promptText,
+ e,
+ promptByteCheck,
+ ),
+ };
+ }
+ }
+ const livePrompt = [
+ currentInputFilePrompt(cfg, toolsAttached),
+ latestInputPromptForContextFile(cfg, latestInputText),
+ toolsText.trim() && !toolsAttached ? toolsText : "",
+ ]
+ .filter((s: unknown) => String(s || "").trim())
+ .join("\n\n");
+ const promptTokenParts = promptTokenTextParts(
+ historyText,
+ toolsText,
+ livePrompt,
+ );
+ const promptTokenPrepared = buildTextWithTokens(promptTokenParts, false);
+ if (logRequests) {
+ const threshold = contextFileThreshold(cfg);
+ logStage(cfg, "context_file_upload", {
+ ms: elapsedMs(uploadStart),
+ refs: refs.length,
+ toolsAttached,
+ historyBytes: formatByteLengthCheck(
+ promptByteLengthBounded(historyText, threshold),
+ ),
+ toolsBytes: formatByteLengthCheck(
+ promptByteLengthBounded(toolsText, threshold),
+ ),
+ latestBytes: formatByteLengthCheck(
+ promptByteLengthBounded(latestInputText, latestInputInlineLimit(cfg)),
+ ),
+ livePromptBytes: formatByteLengthCheck(
+ promptByteLengthBounded(livePrompt, threshold),
+ ),
+ });
+ }
+ const result: ContextFileResult = {
+ fileRefs: refs,
+ prompt: livePrompt,
+ promptTokenCounts: promptTokenPrepared.counts,
+ promptTokenText: "",
+ };
+ Object.defineProperty(result, "promptTokenText", {
+ enumerable: false,
+ get() {
+ return promptTokenParts.join("");
+ },
+ });
+ return result;
+}
+
+function formatByteLengthCheck(check: PromptByteLengthBounded): string {
+ return check.exact ? String(check.bytes) : `>${check.maxBytes}`;
+}
+
+function formatPromptByteComparison(check: ContextFilePromptByteCheck): string {
+ const prefix = check.exact ? "" : "at least ";
+ return `${prefix}${check.bytes} UTF-8 bytes > ${check.thresholdBytes}`;
+}
+
+function promptTokenTextParts(...texts: string[]): string[] {
+ const parts: string[] = [];
+ for (const text of texts) {
+ if (!text) continue;
+ if (parts.length) parts.push("\n");
+ parts.push(text);
+ }
+ return parts;
+}
diff --git a/src/completion/context.ts b/src/completion/context.ts
new file mode 100644
index 0000000000000000000000000000000000000000..53614db1efa59d77c7bb7a76dd5841c2b103ac5b
--- /dev/null
+++ b/src/completion/context.ts
@@ -0,0 +1,581 @@
+import {
+ googleToolDefs,
+ mergeFileRefs,
+ openAIToolDefs,
+} from "../toolcall/content";
+import { buildToolChoiceInstructionFromPolicy } from "../toolcall/policy-openai";
+import type { ToolBundle } from "../toolcall/tool-bundle";
+import {
+ googleContentsToPrompt,
+ googleToolChoiceInstruction,
+} from "../promptcompat/google";
+import {
+ appendStructuredOutputInstructionToPrepared,
+ appendTextToPreparedWithTokens,
+ structuredInstruction,
+ withGeminiNativeHiddenToolsPromptForPrepared,
+ withGeminiNativeHiddenToolsPromptWithTokens,
+} from "../promptcompat/prompt-build";
+import {
+ buildGoogleHistoryTranscript,
+ buildOpenAIHistoryTranscript,
+ latestGoogleUserInputText,
+ latestOpenAIUserInputText,
+} from "../promptcompat/history";
+import { collectOpenAIRequestAttachmentPlan } from "../attachments/collect-openai";
+import { droppedAttachmentNote } from "../attachments/notes";
+import {
+ createAttachmentPlan,
+ mergeAttachmentPlans,
+} from "../attachments/plan";
+import { messagesToPrompt } from "../promptcompat/messages";
+import type { RuntimeConfig } from "../config";
+import { logStage } from "../shared/logging";
+
+import {
+ prepareContextFiles,
+ shouldConsiderContextFiles,
+} from "./context-files";
+import {
+ contextFilePromptByteCheck,
+ contextFileThreshold,
+ contextFileUploadUnavailableReason,
+ oversizedInlineContextFailure,
+} from "./context-files";
+import type {
+ ContextFileFailure,
+ ContextFileResult,
+ FileRef,
+ GeminiContextPrepareResult,
+ LooseRequest,
+ PromptWithTokens,
+ ToolDef,
+} from "./types";
+import type { PromptMetadata } from "./types";
+import { hasCompletionError } from "./types";
+import type { CompletionProvider } from "./ports";
+import type { ToolChoicePolicy } from "../toolcall/policy-openai";
+import type { ContextFilePromptByteCheck } from "./context-files";
+import {
+ buildTextWithTokens,
+ createPromptByteLengthSniffer,
+ type PromptByteLengthBounded,
+} from "../shared/tokens";
+import type { AttachmentPlan } from "../attachments/types";
+
+export { currentInputFilePrompt } from "../toolcall/content";
+export {
+ buildToolsContextTranscript,
+ contextFilePromptByteCheck,
+ contextFileThreshold,
+ contextFileUploadFailure,
+ latestInputInlineLimit,
+ latestInputPromptForContextFile,
+ oversizedInlineContextFailure,
+ prepareContextFiles,
+ prepareContextFilesWithUploader,
+ shouldConsiderContextFiles,
+ shouldUseContextFiles,
+} from "./context-files";
+
+export async function prepareOpenAIGeminiContext(
+ cfg: RuntimeConfig,
+ provider: CompletionProvider,
+ req: LooseRequest,
+ messages: unknown,
+ tools: unknown,
+ promptToolChoice: unknown,
+ toolPolicy: ToolChoicePolicy | null | undefined,
+ structured: unknown,
+): Promise {
+ const toolDefs = openAIToolDefs(tools) as ToolDef[];
+ const toolChoiceInstruction =
+ buildToolChoiceInstructionFromPolicy(toolPolicy);
+ const promptResult = messagesToPrompt(
+ messages,
+ tools,
+ promptToolChoice,
+ toolDefs,
+ toolChoiceInstruction,
+ contextFileThreshold(cfg),
+ );
+ const [prompt0, images] = promptResult as [string, unknown];
+ const attachmentPlan = mergeAttachmentPlans(
+ createAttachmentPlan({ images, files: promptResult.files }),
+ collectOpenAIRequestAttachmentPlan(req),
+ );
+ return preparePromptWithAttachments({
+ cfg,
+ provider,
+ basePrompt: prompt0,
+ basePromptPrepared: promptResultToPrepared(promptResult, prompt0),
+ basePromptByteCheck: contextFilePromptByteCheckFromBounded(
+ cfg,
+ promptResult.byteCheck,
+ ),
+ hiddenPromptInsertOffset: promptResult.hiddenPromptInsertOffset,
+ attachmentPlan,
+ toolDefs,
+ toolPromptSource: tools,
+ toolChoiceInstruction,
+ basePromptMetadata: promptResultMetadata(promptResult),
+ buildHistoryText: () =>
+ buildOpenAIHistoryTranscript(
+ messages,
+ cfg.current_input_file_name || "message.txt",
+ ),
+ getLatestInputText: () =>
+ promptResult.latestInputText != null
+ ? promptResult.latestInputText
+ : latestOpenAIUserInputText(messages),
+ structured,
+ buildFileRefGroups: (
+ contextFileRefs,
+ existingFileRefs,
+ genericFileRefs,
+ imageFileRefs,
+ ) => [contextFileRefs, existingFileRefs, genericFileRefs, imageFileRefs],
+ });
+}
+
+export async function prepareGoogleGeminiContext(
+ cfg: RuntimeConfig,
+ provider: CompletionProvider,
+ effectiveReq: LooseRequest,
+ hasTools: boolean,
+ toolBundle?: ToolBundle | null,
+ toolChoiceInstructionOverride?: string,
+): Promise {
+ const toolDefs = (
+ hasTools ? googleToolDefs(toolBundle || effectiveReq) : []
+ ) as ToolDef[];
+ const toolChoiceInstruction =
+ toolChoiceInstructionOverride ?? googleToolChoiceInstruction(effectiveReq);
+ const promptResult = googleContentsToPrompt(
+ effectiveReq,
+ toolDefs,
+ contextFileThreshold(cfg),
+ toolBundle || effectiveReq,
+ );
+ const [prompt0, images] = promptResult as [string, unknown];
+ const attachmentPlan = createAttachmentPlan({
+ images,
+ files: promptResult.files,
+ });
+ return preparePromptWithAttachments({
+ cfg,
+ provider,
+ basePrompt: prompt0,
+ basePromptPrepared: promptResultToPrepared(promptResult, prompt0),
+ basePromptByteCheck: contextFilePromptByteCheckFromBounded(
+ cfg,
+ promptResult.byteCheck,
+ ),
+ hiddenPromptInsertOffset: promptResult.hiddenPromptInsertOffset,
+ attachmentPlan,
+ toolDefs,
+ toolPromptSource: toolBundle || effectiveReq,
+ toolChoiceInstruction,
+ basePromptMetadata: promptResultMetadata(promptResult),
+ buildHistoryText: () =>
+ buildGoogleHistoryTranscript(
+ effectiveReq,
+ cfg.current_input_file_name || "message.txt",
+ ),
+ getLatestInputText: () =>
+ promptResult.latestInputText != null
+ ? promptResult.latestInputText
+ : latestGoogleUserInputText(effectiveReq),
+ structured: null,
+ buildFileRefGroups: (
+ contextFileRefs,
+ _existingFileRefs,
+ genericFileRefs,
+ imageFileRefs,
+ ) => [imageFileRefs, contextFileRefs, genericFileRefs],
+ });
+}
+
+type PromptWithAttachmentParams = {
+ cfg: RuntimeConfig;
+ provider: CompletionProvider;
+ basePrompt: string;
+ basePromptPrepared?: PromptWithTokens | null;
+ basePromptByteCheck?: ContextFilePromptByteCheck | null;
+ hiddenPromptInsertOffset?: number | undefined;
+ attachmentPlan: AttachmentPlan;
+ toolDefs: ToolDef[];
+ toolPromptSource?: unknown;
+ toolChoiceInstruction: string;
+ basePromptMetadata?: PromptMetadata;
+ buildHistoryText: () => string;
+ getLatestInputText: () => unknown;
+ structured: unknown;
+ buildFileRefGroups: (
+ contextFileRefs: FileRef[] | null,
+ existingFileRefs: FileRef[] | null,
+ genericFileRefs: FileRef[] | null,
+ imageFileRefs: FileRef[] | null,
+ ) => Array;
+};
+
+async function preparePromptWithAttachments(
+ params: PromptWithAttachmentParams,
+): Promise {
+ const plannedDroppedNote = droppedAttachmentNote(
+ params.attachmentPlan.dropped,
+ );
+ const preUploadPromptDecision = promptDecisionForDroppedNote(
+ params,
+ plannedDroppedNote,
+ );
+ if (preUploadPromptDecision.promptByteCheck.exceeded) {
+ const contextUnavailableReason = contextFileUploadUnavailableReason(
+ params.cfg,
+ params.provider.uploadTextFile,
+ );
+ if (contextUnavailableReason) {
+ return {
+ error: oversizedInlineContextFailure(
+ params.cfg,
+ preUploadPromptDecision.contextPromptText,
+ preUploadPromptDecision.promptByteCheck,
+ contextUnavailableReason,
+ ),
+ };
+ }
+ }
+
+ let contextFiles: ContextFileResult | null = null;
+ if (preUploadPromptDecision.considerContextFiles) {
+ const prepared = await prepareContextFilesForDecision(
+ params,
+ preUploadPromptDecision,
+ );
+ if (prepared && hasCompletionError(prepared))
+ return { error: prepared.error };
+ contextFiles = prepared;
+ }
+
+ const attachmentResult = await params.provider.resolveAttachments(
+ params.attachmentPlan,
+ );
+ const attachmentPromptText =
+ (attachmentResult.promptText || "") + (attachmentResult.droppedNote || "");
+ let basePromptWithAttachmentTextPrepared: PromptWithTokens | null = null;
+ const getBasePromptWithAttachmentTextPrepared =
+ (): PromptWithTokens | null => {
+ if (!params.basePromptPrepared) return null;
+ if (!basePromptWithAttachmentTextPrepared) {
+ basePromptWithAttachmentTextPrepared = appendTextToPreparedWithTokens(
+ params.basePromptPrepared,
+ [attachmentPromptText],
+ ) as PromptWithTokens;
+ }
+ return basePromptWithAttachmentTextPrepared;
+ };
+ let inlinePreparedPrompt: PromptWithTokens | null = null;
+ const getInlinePreparedPrompt = (): PromptWithTokens => {
+ if (!inlinePreparedPrompt) {
+ const preparedBase = getBasePromptWithAttachmentTextPrepared();
+ const inlineHiddenToolsPrompt = preparedBase
+ ? (withGeminiNativeHiddenToolsPromptForPrepared(
+ preparedBase,
+ true,
+ params.hiddenPromptInsertOffset,
+ ) as PromptWithTokens)
+ : (withGeminiNativeHiddenToolsPromptWithTokens(
+ params.basePrompt + attachmentPromptText,
+ true,
+ params.hiddenPromptInsertOffset,
+ ) as PromptWithTokens);
+ inlinePreparedPrompt = prepareStructuredPrompt(
+ inlineHiddenToolsPrompt,
+ params.structured,
+ );
+ }
+ return inlinePreparedPrompt;
+ };
+ let contextPromptText = preUploadPromptDecision.contextPromptText;
+ let promptCheckSource = preUploadPromptDecision.promptCheckSource;
+ let promptByteCheck = preUploadPromptDecision.promptByteCheck;
+ if (!contextFiles) {
+ const promptDecision = promptDecisionForDroppedNote(
+ params,
+ attachmentPromptText,
+ getInlinePreparedPrompt,
+ );
+ contextPromptText = promptDecision.contextPromptText;
+ promptCheckSource = promptDecision.promptCheckSource;
+ promptByteCheck = promptDecision.promptByteCheck;
+
+ const contextUnavailableReason = promptByteCheck.exceeded
+ ? contextFileUploadUnavailableReason(
+ params.cfg,
+ params.provider.uploadTextFile,
+ )
+ : "";
+ if (promptByteCheck.exceeded && contextUnavailableReason) {
+ return {
+ error: oversizedInlineContextFailure(
+ params.cfg,
+ contextPromptText,
+ promptByteCheck,
+ contextUnavailableReason,
+ ),
+ };
+ }
+
+ if (promptDecision.considerContextFiles) {
+ const prepared = await prepareContextFilesForDecision(
+ params,
+ promptDecision,
+ );
+ if (prepared && hasCompletionError(prepared))
+ return { error: prepared.error };
+ contextFiles = prepared;
+ }
+ }
+ if (params.cfg.log_requests) {
+ const contextPrepareStageFields: Record = {
+ promptCheck: promptCheckSource,
+ promptBytes: promptByteCheck.exact
+ ? promptByteCheck.bytes
+ : `>${promptByteCheck.thresholdBytes}`,
+ threshold: promptByteCheck.thresholdBytes,
+ exceeded: promptByteCheck.exceeded,
+ contextFiles: !!contextFiles,
+ contextRefs: contextFiles ? contextFiles.fileRefs.length : 0,
+ genericFileRefs: attachmentResult.genericFileRefs
+ ? attachmentResult.genericFileRefs.length
+ : 0,
+ imageRefs: attachmentResult.imageFileRefs
+ ? attachmentResult.imageFileRefs.length
+ : 0,
+ droppedAttachments: attachmentResult.usage.droppedFiles,
+ dedupedAttachments: attachmentResult.usage.dedupedFiles,
+ toolDefs: params.toolDefs.length,
+ };
+ contextPrepareStageFields.basePromptHasToolBlock = String(
+ params.basePrompt || "",
+ ).includes("Available tools");
+ contextPrepareStageFields.basePromptHasToolNames = promptContainsToolNames(
+ params.basePrompt,
+ params.toolDefs,
+ );
+ logStage(params.cfg, "context_prepare", contextPrepareStageFields);
+ }
+
+ const contextFileRefs = contextFiles ? contextFiles.fileRefs : null;
+ const fileRefs = attachmentResult.supportsFileRefs
+ ? mergeFileRefs(
+ ...params.buildFileRefGroups(
+ contextFileRefs,
+ params.attachmentPlan.existingFileRefs as FileRef[] | null,
+ attachmentResult.genericFileRefs as FileRef[] | null,
+ attachmentResult.imageFileRefs as FileRef[] | null,
+ ),
+ )
+ : null;
+ const livePreparedPrompt = contextFiles
+ ? prepareStructuredPrompt(
+ buildTextWithTokens([
+ contextFiles.prompt,
+ attachmentPromptText,
+ ]) as PromptWithTokens,
+ params.structured,
+ )
+ : getInlinePreparedPrompt();
+ const usagePreparedPrompt = contextFiles
+ ? prepareStructuredPrompt(
+ appendTextToPreparedWithTokens(
+ { text: "", tokens: 0, counts: contextFiles.promptTokenCounts },
+ [attachmentPromptText],
+ false,
+ ) as PromptWithTokens,
+ params.structured,
+ false,
+ )
+ : livePreparedPrompt;
+ const attachmentFileRefTokens = attachmentFileRefTokenEstimate(
+ attachmentResult.usage,
+ );
+
+ return {
+ toolDefs: params.toolDefs,
+ toolChoiceInstruction: params.toolChoiceInstruction,
+ prompt: livePreparedPrompt.text,
+ promptTokens: usagePreparedPrompt.tokens + attachmentFileRefTokens,
+ fileRefs,
+ contextFiles,
+ promptMetadata: contextFiles
+ ? { hasToolInstructions: true }
+ : params.basePromptMetadata || {},
+ };
+}
+
+function attachmentFileRefTokenEstimate(
+ usage: { fileRefBytes?: unknown; uploadedBytes?: unknown } | null | undefined,
+): number {
+ if (!usage) return 0;
+ const bytes = Number(usage.fileRefBytes ?? usage.uploadedBytes);
+ if (!Number.isFinite(bytes) || bytes <= 0) return 0;
+ return Math.floor(bytes / 3);
+}
+
+type PromptDecision = {
+ contextPromptText: string;
+ promptCheckSource: string;
+ promptByteCheck: ContextFilePromptByteCheck;
+ considerContextFiles: boolean;
+};
+
+function promptDecisionForDroppedNote(
+ params: PromptWithAttachmentParams,
+ droppedNote: string,
+ getInlinePreparedPrompt?: () => PromptWithTokens,
+): PromptDecision {
+ let contextPromptText = params.basePrompt + droppedNote;
+ let promptCheckSource = "base";
+ let promptByteCheck = droppedNote
+ ? contextFilePromptByteCheck(params.cfg, contextPromptText)
+ : params.basePromptByteCheck ||
+ contextFilePromptByteCheck(params.cfg, contextPromptText);
+ let considerContextFiles = shouldConsiderContextFiles(
+ params.cfg,
+ contextPromptText,
+ promptByteCheck,
+ );
+ if (!promptByteCheck.exceeded) {
+ const inlineByteCheck = inlinePreparedPromptByteCheck(
+ params.cfg,
+ contextPromptText,
+ params.structured,
+ params.hiddenPromptInsertOffset,
+ );
+ if (inlineByteCheck.exceeded) {
+ promptByteCheck = inlineByteCheck;
+ promptCheckSource = "inline_estimate";
+ } else {
+ contextPromptText = getInlinePreparedPrompt
+ ? getInlinePreparedPrompt().text
+ : contextPromptText;
+ promptByteCheck = getInlinePreparedPrompt
+ ? contextFilePromptByteCheck(params.cfg, contextPromptText)
+ : inlineByteCheck;
+ promptCheckSource = getInlinePreparedPrompt
+ ? "inline"
+ : "inline_estimate";
+ }
+ considerContextFiles = shouldConsiderContextFiles(
+ params.cfg,
+ contextPromptText,
+ promptByteCheck,
+ );
+ }
+ return {
+ contextPromptText,
+ promptCheckSource,
+ promptByteCheck,
+ considerContextFiles,
+ };
+}
+
+async function prepareContextFilesForDecision(
+ params: PromptWithAttachmentParams,
+ decision: PromptDecision,
+): Promise {
+ const historyText = params.buildHistoryText();
+ const latestInputText = params.getLatestInputText();
+ return prepareContextFiles(
+ params.cfg,
+ historyText,
+ params.toolDefs,
+ params.toolChoiceInstruction,
+ latestInputText,
+ decision.contextPromptText,
+ params.provider.uploadTextFile,
+ decision.promptByteCheck,
+ params.toolPromptSource || params.toolDefs,
+ );
+}
+
+function prepareStructuredPrompt(
+ prompt: PromptWithTokens,
+ structured: unknown,
+ keepText = true,
+): PromptWithTokens {
+ return structured
+ ? (appendStructuredOutputInstructionToPrepared(
+ prompt,
+ structured,
+ keepText,
+ ) as PromptWithTokens)
+ : prompt;
+}
+
+function promptResultToPrepared(
+ promptResult: { tokens?: number; counts?: unknown },
+ text: string,
+): PromptWithTokens | null {
+ if (!promptResult?.counts) return null;
+ return {
+ text,
+ tokens: promptResult.tokens || 0,
+ counts: promptResult.counts,
+ };
+}
+
+function promptResultMetadata(promptResult: {
+ hasToolPrompt?: boolean;
+ hasToolInstructions?: boolean;
+}): PromptMetadata {
+ return {
+ hasToolPrompt: !!promptResult.hasToolPrompt,
+ hasToolInstructions: !!promptResult.hasToolInstructions,
+ };
+}
+
+function contextFilePromptByteCheckFromBounded(
+ cfg: RuntimeConfig,
+ check: PromptByteLengthBounded | null | undefined,
+): ContextFilePromptByteCheck | null {
+ if (!check) return null;
+ const thresholdBytes = contextFileThreshold(cfg);
+ if (check.maxBytes !== thresholdBytes) return null;
+ return { ...check, thresholdBytes };
+}
+
+function inlinePreparedPromptByteCheck(
+ cfg: RuntimeConfig,
+ prompt: string,
+ structured: unknown,
+ hiddenPromptInsertOffset?: number,
+): ContextFilePromptByteCheck {
+ const thresholdBytes = contextFileThreshold(cfg);
+ const sniffer = createPromptByteLengthSniffer(thresholdBytes);
+ const prepared = withGeminiNativeHiddenToolsPromptWithTokens(
+ prompt,
+ true,
+ hiddenPromptInsertOffset,
+ ).text;
+ const hasText = !!prepared;
+ if (prepared) sniffer.append(prepared);
+ const instruction = structuredInstruction(structured);
+ if (instruction) {
+ if (hasText) sniffer.append("\n\n");
+ sniffer.append(instruction);
+ }
+ return { ...sniffer.result(), thresholdBytes };
+}
+
+function promptContainsToolNames(
+ prompt: unknown,
+ toolDefs: readonly ToolDef[],
+): boolean {
+ const text = String(prompt || "");
+ const names = toolDefs
+ .map((tool) => String(tool.name || "").trim())
+ .filter(Boolean);
+ return !!names.length && names.every((name) => text.includes(name));
+}
diff --git a/src/completion/google-request.ts b/src/completion/google-request.ts
new file mode 100644
index 0000000000000000000000000000000000000000..2614ae7a3ad573805d4a4684fb63c8ae70e9cac9
--- /dev/null
+++ b/src/completion/google-request.ts
@@ -0,0 +1,130 @@
+import type { RuntimeConfig } from "../config";
+import type { CompletionProvider } from "./ports";
+import { resolveModel } from "../models";
+import type { ResolvedModel } from "../models";
+import {
+ googleFunctionCallingConfig,
+ parseGoogleToolChoicePolicy,
+ validateGoogleToolChoiceConfig,
+} from "../toolcall/policy-google";
+import {
+ createToolBundle,
+ filterToolBundleByPolicy,
+} from "../toolcall/tool-bundle";
+import { googleToolChoiceInstruction } from "../promptcompat/google";
+import { log } from "../shared/logging";
+import {
+ upstreamErrorCode,
+ upstreamErrorMessage,
+ upstreamErrorStatus,
+} from "../shared/errors";
+import { prepareGoogleGeminiContext } from "./context";
+import { ensureInlineToolPrompt } from "./tool-prompt-guard";
+import type { ContextFileResult, FileRef, LooseRequest } from "./types";
+import { hasCompletionError } from "./types";
+
+export type GoogleCompletionPrepareError = {
+ message: string;
+ status: number;
+ code?: string;
+};
+
+export type PreparedGoogleCompletion = {
+ rm: Extract;
+ effectiveReq: LooseRequest;
+ effectiveGoogleTools: LooseRequest[] | null;
+ hasTools: boolean;
+ prompt: string;
+ fileRefs: FileRef[] | null;
+ promptTokens: number;
+ contextFiles: ContextFileResult | null;
+};
+
+export async function prepareGoogleCompletion(
+ cfg: RuntimeConfig,
+ provider: CompletionProvider,
+ req: LooseRequest,
+ path: string,
+): Promise {
+ const m = /\/v(?:1beta|1)\/models\/([^:?/]+)/.exec(path);
+ const modelFromPath = m?.[1]
+ ? decodeURIComponent(m[1]).replace(/^models\//, "")
+ : undefined;
+ const rm = resolveModel(modelFromPath, cfg.default_model);
+ if (rm.name === undefined) {
+ log(
+ cfg,
+ `google completion model rejected model=${String(modelFromPath ?? "(default)")}`,
+ );
+ return {
+ error: { message: rm.error, status: 400, code: "model_not_found" },
+ };
+ }
+
+ const toolBundle = createToolBundle(req.tools);
+ const toolConfigViolation = validateGoogleToolChoiceConfig(req, toolBundle);
+ if (toolConfigViolation) {
+ return {
+ error: {
+ message: toolConfigViolation.message,
+ status: 400,
+ code: "invalid_tool_choice",
+ },
+ };
+ }
+
+ const fcMode = String(googleFunctionCallingConfig(req).mode || "AUTO")
+ .trim()
+ .toUpperCase();
+ const toolPolicy = parseGoogleToolChoicePolicy(req, toolBundle);
+ const effectiveToolBundle = filterToolBundleByPolicy(toolBundle, toolPolicy);
+ const effectiveGoogleTools = effectiveToolBundle.openAIFunctionTools.length
+ ? effectiveToolBundle.openAIFunctionTools
+ : null;
+ const effectiveReq = { ...req, tools: effectiveGoogleTools || [] };
+ const hasTools = !!effectiveGoogleTools && fcMode !== "NONE";
+ const toolChoiceInstruction = googleToolChoiceInstruction(effectiveReq);
+ const ctx = await prepareGoogleGeminiContext(
+ cfg,
+ provider,
+ effectiveReq,
+ hasTools,
+ effectiveToolBundle,
+ toolChoiceInstruction,
+ );
+ if (hasCompletionError(ctx)) {
+ const code = upstreamErrorCode(ctx.error) || "context_file_upload_failed";
+ return {
+ error: {
+ message: upstreamErrorMessage(ctx.error),
+ status: upstreamErrorStatus(ctx.error) || 502,
+ code,
+ },
+ };
+ }
+ let { prompt } = ctx;
+ const { fileRefs, promptTokens, contextFiles } = ctx;
+ const promptToolSource = effectiveToolBundle.defs.length
+ ? effectiveToolBundle
+ : toolBundle;
+ prompt = ensureInlineToolPrompt(
+ prompt,
+ promptToolSource,
+ toolChoiceInstruction,
+ contextFiles,
+ ctx.promptMetadata,
+ );
+ if (!String(prompt || "").trim())
+ return { error: { message: "empty content", status: 400 } };
+
+ return {
+ rm,
+ effectiveReq,
+ effectiveGoogleTools,
+ hasTools,
+ prompt,
+ fileRefs,
+ promptTokens,
+ contextFiles,
+ };
+}
diff --git a/src/completion/google-turn.ts b/src/completion/google-turn.ts
new file mode 100644
index 0000000000000000000000000000000000000000..db3df7b93c4c56898e63925a26a912d27b919f6f
--- /dev/null
+++ b/src/completion/google-turn.ts
@@ -0,0 +1,82 @@
+import { parseGoogleFunctionCalls } from "../toolcall/google";
+import { validateGoogleFunctionCalls } from "../toolcall/policy-google";
+import type { GoogleFunctionCall } from "../toolcall/google";
+import type { LooseRequest } from "./types";
+
+export type GoogleResponsePart =
+ | { text: string }
+ | { functionCall: GoogleFunctionCall };
+
+export type GoogleCompletionTurn =
+ | {
+ responseParts: GoogleResponsePart[];
+ upstreamEmpty: boolean;
+ error?: undefined;
+ }
+ | {
+ error: {
+ message: string;
+ status: number;
+ code?: string;
+ };
+ responseParts?: undefined;
+ upstreamEmpty?: undefined;
+ };
+
+export function finalizeGoogleCompletionResult(
+ text: unknown,
+ options: {
+ effectiveReq: LooseRequest;
+ effectiveGoogleTools: LooseRequest[] | null;
+ hasTools: boolean;
+ },
+): GoogleCompletionTurn {
+ const source = String(text || "");
+ const responseParts: GoogleResponsePart[] = [];
+ if (options.hasTools && source) {
+ const [clean, fcs] = parseGoogleFunctionCalls(
+ source,
+ options.effectiveGoogleTools,
+ );
+ const googleToolViolation = validateGoogleFunctionCalls(
+ options.effectiveReq,
+ fcs,
+ );
+ if (googleToolViolation) {
+ return {
+ error: {
+ message: googleToolViolation.message,
+ status: 422,
+ code: googleToolViolation.code,
+ },
+ };
+ }
+ if (fcs.length) {
+ if (clean) responseParts.push({ text: clean });
+ for (const fc of fcs)
+ responseParts.push({ functionCall: { name: fc.name, args: fc.args } });
+ } else {
+ responseParts.push({ text: source });
+ }
+ } else {
+ const googleToolViolation = validateGoogleFunctionCalls(
+ options.effectiveReq,
+ [],
+ );
+ if (googleToolViolation) {
+ return {
+ error: {
+ message: googleToolViolation.message,
+ status: 422,
+ code: googleToolViolation.code,
+ },
+ };
+ }
+ responseParts.push({
+ text:
+ source ||
+ "I apologize, but I was unable to generate a response. Please try again.",
+ });
+ }
+ return { responseParts, upstreamEmpty: !source };
+}
diff --git a/src/completion/google.ts b/src/completion/google.ts
new file mode 100644
index 0000000000000000000000000000000000000000..da6cc7dae8e9e2a7c5c4fe278be138df2c75027b
--- /dev/null
+++ b/src/completion/google.ts
@@ -0,0 +1,124 @@
+import { streamBufferedToolTextCompletionEvents } from "./runtime";
+import type { CompletionProvider } from "./ports";
+import type { ResolvedModel } from "../models";
+import {
+ combinedTokenCount,
+ createTokenCounter,
+ emptyTokenCounts,
+} from "../shared/tokens";
+import { parseGoogleFunctionCalls } from "../toolcall/google";
+import { validateGoogleFunctionCalls } from "../toolcall/policy-google";
+import type { ToolPolicyViolation } from "../toolcall/policy-openai";
+import type { GoogleFunctionCall } from "../toolcall/google";
+import type { GoogleResponsePart } from "./google-turn";
+import type { FileRef, LooseRequest } from "./types";
+import { EMPTY_UPSTREAM_MSG } from "./turn";
+
+export type GoogleToolCompletionEvent =
+ | {
+ type: "candidate";
+ parts: GoogleResponsePart[] | null;
+ finishReason: string | null;
+ }
+ | { type: "warning"; error: unknown; message?: string }
+ | { type: "error"; error: unknown }
+ | { type: "tool_policy_violation"; violation: ToolPolicyViolation }
+ | {
+ type: "done";
+ usageMetadata: {
+ promptTokenCount: number;
+ candidatesTokenCount: number;
+ totalTokenCount: number;
+ };
+ };
+
+type GoogleToolCompletionParams = {
+ prompt: string;
+ rm: Extract;
+ fileRefs: FileRef[] | null;
+ tools: LooseRequest[] | null;
+ effectiveReq: LooseRequest;
+ promptTokens: number;
+ signal: AbortSignal;
+};
+
+export async function* streamGoogleToolCompletionEvents(
+ provider: CompletionProvider,
+ params: GoogleToolCompletionParams,
+): AsyncIterable {
+ const { prompt, rm, fileRefs, tools, effectiveReq, promptTokens, signal } =
+ params;
+ const extraTokenCounter = createTokenCounter();
+ let completionCounts = emptyTokenCounts();
+ let buffered = "";
+ let emittedText = false;
+ let issue: { error: unknown } | null = null;
+
+ for await (const event of streamBufferedToolTextCompletionEvents(
+ provider,
+ { prompt, rm, fileRefs },
+ { signal },
+ )) {
+ if (event.type === "text_delta") {
+ emittedText = true;
+ yield {
+ type: "candidate",
+ parts: [{ text: event.text }],
+ finishReason: null,
+ };
+ } else if (event.type === "buffered_text") {
+ buffered += event.text;
+ } else if (event.type === "warning" || event.type === "stream_error") {
+ issue = event;
+ } else if (event.type === "done") {
+ completionCounts = event.completionCounts;
+ }
+ }
+
+ const [clean, functionCalls]: [string, GoogleFunctionCall[]] =
+ parseGoogleFunctionCalls(buffered, tools);
+ if (clean) {
+ extraTokenCounter.append(clean);
+ yield { type: "candidate", parts: [{ text: clean }], finishReason: null };
+ }
+
+ const violation = validateGoogleFunctionCalls(effectiveReq, functionCalls);
+ if (violation) {
+ yield { type: "tool_policy_violation", violation };
+ return;
+ }
+ if (functionCalls?.length) {
+ if (issue) yield { type: "warning", error: issue.error };
+ yield {
+ type: "candidate",
+ parts: functionCalls.map((fc) => ({
+ functionCall: { name: fc.name, args: fc.args || {} },
+ })),
+ finishReason: null,
+ };
+ } else if (!emittedText && !clean) {
+ yield {
+ type: "error",
+ error: issue?.error || {
+ message: EMPTY_UPSTREAM_MSG,
+ code: "upstream_empty",
+ },
+ };
+ return;
+ } else if (issue) {
+ yield { type: "warning", error: issue.error };
+ }
+ const candidateTokens = combinedTokenCount(
+ completionCounts,
+ extraTokenCounter,
+ );
+ const promptTokenCount = Math.max(0, Number(promptTokens) || 0);
+ yield {
+ type: "done",
+ usageMetadata: {
+ promptTokenCount,
+ candidatesTokenCount: candidateTokens,
+ totalTokenCount: promptTokenCount + candidateTokens,
+ },
+ };
+}
diff --git a/src/completion/image-generation.ts b/src/completion/image-generation.ts
new file mode 100644
index 0000000000000000000000000000000000000000..edb84f0ab744cb6942863367a4ab419c9bc0d279
--- /dev/null
+++ b/src/completion/image-generation.ts
@@ -0,0 +1,681 @@
+import { base64ToBytes } from "../attachments/base64";
+import {
+ detectUploadMimeFromBytes,
+ firstNonEmptyString,
+ imageFilenameFromMime,
+ normalizeMimeType,
+ sanitizeUploadFilename,
+} from "../attachments/mime";
+import {
+ imageFilenameFromObject,
+ normalizeUploadFileInput,
+ parseImageUrl,
+ uploadFilenameFromObject,
+ uploadMimeFromObject,
+} from "../attachments/input";
+import { MAX_ATTACHMENTS_PER_REQUEST } from "../attachments/plan";
+import type {
+ AttachmentCandidate,
+ AttachmentFileRef,
+ AttachmentPlan,
+} from "../attachments/types";
+import type { RuntimeConfig } from "../config";
+import { resolveModel, type ResolvedModel } from "../models";
+import { log } from "../shared/logging";
+import {
+ upstreamErrorCode,
+ upstreamErrorMessage,
+ upstreamErrorStatus,
+} from "../shared/errors";
+import { firstRecord, isRecord, type UnknownRecord } from "../shared/types";
+import { promptByteLength, tokenEst } from "../shared/tokens";
+import { contextFileThreshold } from "./context-files";
+import type { CompletionProvider } from "./ports";
+import type {
+ AttachmentResolutionResult,
+ FileRef,
+ LooseRequest,
+} from "./types";
+
+export type ImageGenerationPrepareError = {
+ message: string;
+ status: number;
+ code: string;
+};
+
+export type PreparedImageGenerationCompletion = {
+ rm: Extract;
+ prompt: string;
+ userPrompt: string;
+ fileRefs: FileRef[] | null;
+ promptTokens: number;
+};
+
+export type ImageGenerationRouteKind = "responses" | "chat";
+
+export type ImageGenerationByteInput = {
+ bytes: Uint8Array;
+ filename?: string;
+ mime?: string;
+};
+
+export type ImageGenerationUserImageInput =
+ | { type: "part"; part: UnknownRecord }
+ | { type: "bytes"; image: ImageGenerationByteInput };
+
+export type OpenAIImageGenerationUserInput = {
+ model?: unknown;
+ prompt: unknown;
+ imageInputs?: readonly ImageGenerationUserImageInput[];
+ imageParts?: readonly UnknownRecord[];
+ imageBytes?: readonly ImageGenerationByteInput[];
+};
+
+type FileSlot =
+ | { type: "existing"; ref: AttachmentFileRef }
+ | { type: "candidate"; index: number };
+
+type ExtractionState = {
+ textParts: string[];
+ candidates: AttachmentCandidate[];
+ slots: FileSlot[];
+ error: ImageGenerationPrepareError | null;
+ nextID: number;
+};
+
+const IMAGE_GENERATION_INSTRUCTION = [
+ "IMAGE GENERATION ENABLED: Return a real generated image matching the user's request.",
+ "For edits to attached images, apply the requested changes and return a new generated version.",
+ "Do not provide explanations, process notes, placeholders, or apologies without an actual generated image attachment.",
+].join("\n");
+
+const FORCED_IMAGE_GENERATION_INSTRUCTION =
+ "Image generation was explicitly requested. Return at least one generated image; a response without a generated image is a failure.";
+
+export async function prepareOpenAIImageGenerationCompletion(
+ cfg: RuntimeConfig,
+ provider: CompletionProvider,
+ req: LooseRequest,
+ route: ImageGenerationRouteKind,
+ forced: boolean,
+): Promise<
+ PreparedImageGenerationCompletion | { error: ImageGenerationPrepareError }
+> {
+ const state = createExtractionState();
+ if (route === "responses") extractResponsesUserInput(state, req.input);
+ else extractLatestChatUserInput(state, req.messages);
+ return prepareImageGenerationFromState(
+ cfg,
+ provider,
+ req.model,
+ state,
+ forced,
+ );
+}
+
+export async function prepareOpenAIImageGenerationFromUserInput(
+ cfg: RuntimeConfig,
+ provider: CompletionProvider,
+ input: OpenAIImageGenerationUserInput,
+ forced: boolean,
+): Promise<
+ PreparedImageGenerationCompletion | { error: ImageGenerationPrepareError }
+> {
+ const state = createExtractionState();
+ appendText(state, input.prompt);
+ if (input.imageInputs) {
+ for (const imageInput of input.imageInputs) {
+ if (state.error) break;
+ if (imageInput.type === "part") appendImagePart(state, imageInput.part);
+ else appendImageBytes(state, imageInput.image);
+ }
+ } else if (input.imageParts) {
+ for (const part of input.imageParts) {
+ if (state.error) break;
+ appendImagePart(state, part);
+ }
+ }
+ if (!input.imageInputs && input.imageBytes) {
+ for (const image of input.imageBytes) {
+ if (state.error) break;
+ appendImageBytes(state, image);
+ }
+ }
+ return prepareImageGenerationFromState(
+ cfg,
+ provider,
+ input.model,
+ state,
+ forced,
+ );
+}
+
+async function prepareImageGenerationFromState(
+ cfg: RuntimeConfig,
+ provider: CompletionProvider,
+ model: unknown,
+ state: ExtractionState,
+ forced: boolean,
+): Promise<
+ PreparedImageGenerationCompletion | { error: ImageGenerationPrepareError }
+> {
+ if (!(provider.supportsAuthenticatedSession ?? !!cfg.cookie)) {
+ return {
+ error: {
+ message: "image generation requires GEMINI_COOKIE",
+ status: 401,
+ code: "image_generation_requires_cookie",
+ },
+ };
+ }
+
+ const rm = resolveModel(model, cfg.default_model);
+ if (rm.name === undefined) {
+ log(
+ cfg,
+ `openai image generation model rejected model=${String(model ?? "(default)")}`,
+ );
+ return {
+ error: { message: rm.error, status: 400, code: "model_not_found" },
+ };
+ }
+
+ if (state.error) return { error: state.error };
+
+ const userPrompt = state.textParts
+ .map((part) => part.trim())
+ .filter(Boolean)
+ .join("\n")
+ .trim();
+ if (!userPrompt) {
+ return {
+ error: {
+ message: "image generation requires non-empty user prompt text",
+ status: 400,
+ code: "image_generation_empty_prompt",
+ },
+ };
+ }
+
+ const prompt = [
+ userPrompt,
+ IMAGE_GENERATION_INSTRUCTION,
+ forced ? FORCED_IMAGE_GENERATION_INSTRUCTION : "",
+ ]
+ .filter(Boolean)
+ .join("\n\n");
+ const promptBytes = promptByteLength(prompt);
+ const threshold = contextFileThreshold(cfg);
+ if (promptBytes > threshold) {
+ return {
+ error: {
+ message: `image generation prompt is too large for pass-through mode (${promptBytes} UTF-8 bytes > ${threshold})`,
+ status: 413,
+ code: "image_generation_prompt_too_large",
+ },
+ };
+ }
+
+ const fileRefsResult = await resolveImageGenerationFileRefs(provider, state);
+ if ("error" in fileRefsResult) return fileRefsResult;
+
+ return {
+ rm,
+ prompt,
+ userPrompt,
+ fileRefs: fileRefsResult.fileRefs,
+ promptTokens: tokenEst(prompt),
+ };
+}
+
+function createExtractionState(): ExtractionState {
+ return { textParts: [], candidates: [], slots: [], error: null, nextID: 1 };
+}
+
+function extractResponsesUserInput(
+ state: ExtractionState,
+ input: unknown,
+): void {
+ if (state.error || input == null) return;
+ if (typeof input === "string") {
+ appendText(state, input);
+ return;
+ }
+ if (Array.isArray(input)) {
+ for (const item of input) {
+ if (state.error) return;
+ extractResponseItem(state, item);
+ }
+ return;
+ }
+ extractResponseItem(state, input);
+}
+
+function extractResponseItem(state: ExtractionState, item: unknown): void {
+ if (state.error || item == null) return;
+ if (typeof item === "string") {
+ appendText(state, item);
+ return;
+ }
+ if (!isRecord(item)) return;
+ const role = normalizedType(item.role);
+ const typ = normalizedType(item.type);
+ if (role && role !== "user") return;
+ if (
+ typ === "output_text" ||
+ typ === "summary_text" ||
+ typ === "reasoning" ||
+ typ === "thinking" ||
+ typ === "function_call" ||
+ typ === "function_call_output"
+ )
+ return;
+ if (typ === "input_text" || typ === "text") {
+ appendText(state, item.text);
+ return;
+ }
+ if (isImagePartType(typ)) {
+ appendImagePart(state, item);
+ return;
+ }
+ if (isFilePartType(typ)) {
+ appendFilePart(state, item);
+ return;
+ }
+ if (role === "user" || typ === "message" || typ === "input_message") {
+ if (item.content != null) extractContent(state, item.content);
+ else appendText(state, item.text);
+ }
+}
+
+function extractLatestChatUserInput(
+ state: ExtractionState,
+ messages: unknown,
+): void {
+ if (!Array.isArray(messages)) return;
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const msg = messages[i];
+ if (!isRecord(msg) || normalizedType(msg.role) !== "user") continue;
+ extractContent(state, msg.content != null ? msg.content : msg.text);
+ return;
+ }
+}
+
+function extractContent(state: ExtractionState, content: unknown): void {
+ if (state.error || content == null) return;
+ if (typeof content === "string") {
+ appendText(state, content);
+ return;
+ }
+ if (Array.isArray(content)) {
+ for (const part of content) {
+ if (state.error) return;
+ extractContentPart(state, part);
+ }
+ return;
+ }
+ extractContentPart(state, content);
+}
+
+function extractContentPart(state: ExtractionState, part: unknown): void {
+ if (state.error || part == null) return;
+ if (typeof part === "string") {
+ appendText(state, part);
+ return;
+ }
+ if (!isRecord(part)) return;
+ const typ = normalizedType(part.type);
+ if (typ === "text" || typ === "input_text") {
+ appendText(state, part.text);
+ return;
+ }
+ if (
+ typ === "output_text" ||
+ typ === "summary_text" ||
+ typ === "reasoning" ||
+ typ === "thinking"
+ )
+ return;
+ if (isImagePartType(typ) || part.image_url != null) {
+ appendImagePart(state, part);
+ return;
+ }
+ if (isFilePartType(typ)) appendFilePart(state, part);
+}
+
+function appendText(state: ExtractionState, value: unknown): void {
+ const text =
+ typeof value === "string" || typeof value === "number"
+ ? String(value).trim()
+ : "";
+ if (text) state.textParts.push(text);
+}
+
+function appendImagePart(state: ExtractionState, part: UnknownRecord): void {
+ if (remoteUrlFromPart(part)) {
+ state.error = unsupportedImageInput(
+ "remote image/file URLs are not supported in image generation mode",
+ );
+ return;
+ }
+ const existing = existingRefFromPart(part);
+ const hasInline = hasImageInlinePayload(part);
+ if (existing && !hasInline) {
+ state.slots.push({ type: "existing", ref: existing });
+ return;
+ }
+
+ const image = imageCandidateFromPart(part, state.nextID);
+ if ("error" in image) {
+ state.error = image.error;
+ return;
+ }
+ addCandidateSlot(state, image.candidate);
+}
+
+function appendImageBytes(
+ state: ExtractionState,
+ image: ImageGenerationByteInput,
+): void {
+ const detected = detectUploadMimeFromBytes(image.bytes);
+ if (!normalizeMimeType(detected).startsWith("image/")) {
+ state.error = unsupportedImageInput(
+ "image input bytes are not a supported image",
+ );
+ return;
+ }
+ const mime = firstNonEmptyString(detected, image.mime, "image/png");
+ const candidate: AttachmentCandidate = {
+ id: `att_${state.nextID}`,
+ kind: "image",
+ role: "request",
+ source: { type: "bytes", bytes: image.bytes },
+ };
+ const filename = firstNonEmptyString(
+ sanitizeUploadFilename(image.filename),
+ imageFilenameFromMime(mime, state.nextID),
+ );
+ if (filename) candidate.filename = filename;
+ if (mime) candidate.mime = mime;
+ addCandidateSlot(state, candidate);
+}
+
+function appendFilePart(state: ExtractionState, part: UnknownRecord): void {
+ if (remoteUrlFromPart(part)) {
+ state.error = unsupportedImageInput(
+ "remote image/file URLs are not supported in image generation mode",
+ );
+ return;
+ }
+ const existing = existingRefFromPart(part);
+ const input = normalizeUploadFileInput(part);
+ if (existing && !(input && input.b64 != null)) {
+ state.slots.push({ type: "existing", ref: existing });
+ return;
+ }
+ if (!input || input.b64 == null) {
+ state.error = unsupportedImageInput(
+ "image generation file input must be an inline payload or existing file reference",
+ );
+ return;
+ }
+ let bytes: Uint8Array;
+ try {
+ bytes = base64ToBytes(input.b64);
+ } catch (_) {
+ state.error = unsupportedImageInput("invalid file base64 payload");
+ return;
+ }
+ const detected = detectUploadMimeFromBytes(bytes);
+ if (!normalizeMimeType(detected).startsWith("image/")) {
+ state.error = unsupportedImageInput(
+ "image generation file input bytes are not a supported image",
+ );
+ return;
+ }
+ const mime = firstNonEmptyString(
+ detected,
+ input.mime,
+ uploadMimeFromObject(part),
+ "image/png",
+ );
+ const candidate: AttachmentCandidate = {
+ id: `att_${state.nextID}`,
+ kind: "image",
+ role: "request",
+ source: { type: "bytes", bytes },
+ };
+ const filename = firstNonEmptyString(
+ sanitizeUploadFilename(input.filename),
+ uploadFilenameFromObject(part),
+ imageFilenameFromMime(mime, state.nextID),
+ );
+ if (filename) candidate.filename = filename;
+ if (mime) candidate.mime = mime;
+ addCandidateSlot(state, candidate);
+}
+
+function imageCandidateFromPart(
+ part: UnknownRecord,
+ nextID: number,
+): { candidate: AttachmentCandidate } | { error: ImageGenerationPrepareError } {
+ const parsed = imagePayloadFromPart(part);
+ if (!parsed)
+ return {
+ error: unsupportedImageInput(
+ "image input must be an inline image payload or existing file reference",
+ ),
+ };
+ let bytes: Uint8Array;
+ try {
+ bytes = base64ToBytes(parsed.b64);
+ } catch (_) {
+ return { error: unsupportedImageInput("invalid image base64 payload") };
+ }
+ const detected = detectUploadMimeFromBytes(bytes);
+ if (!normalizeMimeType(detected).startsWith("image/")) {
+ return {
+ error: unsupportedImageInput(
+ "image input bytes are not a supported image",
+ ),
+ };
+ }
+ const mime = firstNonEmptyString(
+ detected,
+ parsed.mime,
+ uploadMimeFromObject(part),
+ "image/png",
+ );
+ const candidate: AttachmentCandidate = {
+ id: `att_${nextID}`,
+ kind: "image",
+ role: "request",
+ source: { type: "bytes", bytes },
+ };
+ const filename = firstNonEmptyString(
+ imageFilenameFromObject(part),
+ imageFilenameFromMime(mime, nextID),
+ );
+ if (filename) candidate.filename = filename;
+ if (mime) candidate.mime = mime;
+ return { candidate };
+}
+
+function imagePayloadFromPart(
+ part: UnknownRecord,
+): { b64: unknown; mime: string } | null {
+ const source = isRecord(part.source) ? part.source : null;
+ if (source && source.data != null) {
+ return {
+ b64: source.data,
+ mime: firstNonEmptyString(
+ uploadMimeFromObject(part),
+ source.media_type,
+ source.mime_type,
+ source.mimeType,
+ "image/png",
+ ),
+ };
+ }
+ const imageUrl = part.image_url != null ? part.image_url : part.url;
+ const rawUrl = isRecord(imageUrl) ? imageUrl.url : imageUrl;
+ const parsed = parseImageUrl(rawUrl, uploadMimeFromObject(part));
+ if (parsed) return parsed;
+ return null;
+}
+
+function hasImageInlinePayload(part: UnknownRecord): boolean {
+ const source = isRecord(part.source) ? part.source : null;
+ if (source && source.data != null) return true;
+ const imageUrl = part.image_url != null ? part.image_url : part.url;
+ const rawUrl = isRecord(imageUrl) ? imageUrl.url : imageUrl;
+ return typeof rawUrl === "string" && /^data:/i.test(rawUrl.trim());
+}
+
+function addCandidateSlot(
+ state: ExtractionState,
+ candidate: AttachmentCandidate,
+): void {
+ if (state.candidates.length >= MAX_ATTACHMENTS_PER_REQUEST) {
+ state.error = {
+ message: `image generation supports at most ${MAX_ATTACHMENTS_PER_REQUEST} user attachments`,
+ status: 400,
+ code: "image_input_unsupported",
+ };
+ return;
+ }
+ const index = state.candidates.length;
+ state.candidates.push(candidate);
+ state.slots.push({ type: "candidate", index });
+ state.nextID += 1;
+}
+
+async function resolveImageGenerationFileRefs(
+ provider: CompletionProvider,
+ state: ExtractionState,
+): Promise<
+ { fileRefs: FileRef[] | null } | { error: ImageGenerationPrepareError }
+> {
+ if (
+ !state.candidates.length &&
+ !state.slots.some((slot) => slot.type === "existing")
+ )
+ return { fileRefs: null };
+ const plan: AttachmentPlan = {
+ candidates: state.candidates,
+ existingFileRefs: state.slots
+ .filter(
+ (slot): slot is { type: "existing"; ref: AttachmentFileRef } =>
+ slot.type === "existing",
+ )
+ .map((slot) => slot.ref),
+ dropped: [],
+ maxFiles: MAX_ATTACHMENTS_PER_REQUEST,
+ };
+ let result: AttachmentResolutionResult;
+ try {
+ result = await provider.resolveAttachments(plan);
+ } catch (e) {
+ return {
+ error: {
+ message: `failed to upload image generation input: ${upstreamErrorMessage(e)}`,
+ status: upstreamErrorStatus(e) || 502,
+ code: upstreamErrorCode(e) || "image_input_upload_failed",
+ },
+ };
+ }
+ const uploaded = result.fileRefs || [];
+ const out: FileRef[] = [];
+ for (const slot of state.slots) {
+ if (slot.type === "existing") {
+ out.push(slot.ref);
+ continue;
+ }
+ const ref = uploaded[slot.index];
+ if (!ref) {
+ return {
+ error: {
+ message: "failed to upload image generation input",
+ status: 502,
+ code: "image_input_upload_failed",
+ },
+ };
+ }
+ out.push(ref);
+ }
+ return { fileRefs: out.length ? out : null };
+}
+
+function existingRefFromPart(part: UnknownRecord): AttachmentFileRef | null {
+ const id =
+ part.file_id ?? part.fileId ?? part.file_ref ?? part.fileRef ?? part.ref;
+ if (id == null) {
+ const file = isRecord(part.file) ? part.file : null;
+ const nested = file
+ ? (file.file_id ??
+ file.fileId ??
+ file.file_ref ??
+ file.fileRef ??
+ file.ref ??
+ file.id)
+ : null;
+ if (nested == null) return null;
+ const name = firstNonEmptyString(
+ uploadFilenameFromObject(file),
+ uploadFilenameFromObject(part),
+ );
+ return name ? { id: String(nested), name } : String(nested);
+ }
+ const name = uploadFilenameFromObject(part);
+ return name ? { id: String(id), name } : String(id);
+}
+
+function remoteUrlFromPart(part: UnknownRecord): string {
+ const direct = firstNonEmptyString(part.url, part.file_url, part.fileUrl);
+ if (isRemoteUrl(direct)) return direct;
+ const source = isRecord(part.source) ? part.source : null;
+ const sourceUrl = source
+ ? firstNonEmptyString(
+ source.url,
+ source.file_url,
+ source.fileUrl,
+ source.file_uri,
+ source.fileUri,
+ )
+ : "";
+ if (isRemoteUrl(sourceUrl)) return sourceUrl;
+ const imageUrl = isRecord(part.image_url) ? part.image_url : null;
+ if (imageUrl && isRemoteUrl(imageUrl.url)) return String(imageUrl.url);
+ const file = isRecord(part.file) ? part.file : null;
+ const fileUrl = file
+ ? firstNonEmptyString(file.url, file.file_url, file.fileUrl)
+ : "";
+ if (isRemoteUrl(fileUrl)) return fileUrl;
+ const fileData = firstRecord(part.fileData, part.file_data);
+ const nestedUrl = fileData
+ ? firstNonEmptyString(fileData.url, fileData.file_uri, fileData.fileUri)
+ : "";
+ return isRemoteUrl(nestedUrl) ? nestedUrl : "";
+}
+
+function isRemoteUrl(value: unknown): boolean {
+ return typeof value === "string" && /^https?:\/\//i.test(value.trim());
+}
+
+function unsupportedImageInput(message: string): ImageGenerationPrepareError {
+ return { message, status: 400, code: "image_input_unsupported" };
+}
+
+function normalizedType(value: unknown): string {
+ return String(value || "")
+ .trim()
+ .toLowerCase();
+}
+
+function isImagePartType(typ: string): boolean {
+ return typ === "image_url" || typ === "image" || typ === "input_image";
+}
+
+function isFilePartType(typ: string): boolean {
+ return typ === "input_file" || typ === "file";
+}
diff --git a/src/completion/index.ts b/src/completion/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..3b8c8a7e6428d3885c44a6f0a19715f737c80eb1
--- /dev/null
+++ b/src/completion/index.ts
@@ -0,0 +1,23 @@
+export {
+ EMPTY_UPSTREAM_MSG,
+ finalizeOpenAICompletionResult,
+ upstreamEmptyWarning,
+} from "./turn";
+export type {
+ CompletionProvider,
+ CompletionProviderOptions,
+ CompletionRichOutput,
+ CompletionTextInput,
+ GeneratedImage,
+} from "./ports";
+export type {
+ CompletionStreamEvent,
+ CompletionStreamLifecycle,
+} from "./runtime";
+export {
+ createCompletionStreamLifecycle,
+ recordCompletionStreamEvent,
+ streamBufferedToolTextCompletionEvents,
+ streamPlainCompletionEvents,
+ streamToolSieveCompletionEvents,
+} from "./runtime";
diff --git a/src/completion/openai.ts b/src/completion/openai.ts
new file mode 100644
index 0000000000000000000000000000000000000000..f25f2f50badf8e662431aea9fb489e38884221b9
--- /dev/null
+++ b/src/completion/openai.ts
@@ -0,0 +1,158 @@
+import type { RuntimeConfig } from "../config";
+import type { CompletionProvider } from "./ports";
+import { resolveModel } from "../models";
+import type { ResolvedModel } from "../models";
+import {
+ getStructuredResponseFormat,
+ buildStructuredOutputRequirement,
+} from "../toolcall/structured";
+import {
+ buildToolChoiceInstructionFromPolicy,
+ parseOpenAIToolChoicePolicy,
+} from "../toolcall/policy-openai";
+import type { ToolChoicePolicy } from "../toolcall/policy-openai";
+import {
+ createToolBundle,
+ filterToolBundleByPolicy,
+} from "../toolcall/tool-bundle";
+import { log } from "../shared/logging";
+import {
+ upstreamErrorCode,
+ upstreamErrorMessage,
+ upstreamErrorStatus,
+} from "../shared/errors";
+import { prepareOpenAIGeminiContext } from "./context";
+import { ensureInlineToolPrompt } from "./tool-prompt-guard";
+import type { ContextFileResult, FileRef, LooseRequest } from "./types";
+import { hasCompletionError } from "./types";
+
+export type OpenAICompletionPrepareError = {
+ message: string;
+ status: number;
+ code?: string;
+};
+
+export type PreparedOpenAICompletion = {
+ rm: Extract;
+ structured: unknown;
+ allTools: unknown[];
+ tools: unknown[] | null;
+ toolPolicy: ToolChoicePolicy;
+ promptToolChoice: "none" | "required" | "auto";
+ prompt: string;
+ fileRefs: FileRef[] | null;
+ promptTokens: number;
+ contextFiles: ContextFileResult | null;
+};
+
+export type PrepareOpenAICompletionOptions = {
+ emptyPromptMessage: string;
+};
+
+export async function prepareOpenAICompletion(
+ cfg: RuntimeConfig,
+ provider: CompletionProvider,
+ req: LooseRequest,
+ messages: unknown,
+ toolsRaw: unknown,
+ options: PrepareOpenAICompletionOptions,
+): Promise {
+ const rm = resolveModel(req.model, cfg.default_model);
+ if (rm.name === undefined) {
+ log(
+ cfg,
+ `openai completion model rejected model=${String(req.model ?? "(default)")}`,
+ );
+ return {
+ error: { message: rm.error, status: 400, code: "model_not_found" },
+ };
+ }
+
+ const structured = buildStructuredOutputRequirement(
+ getStructuredResponseFormat(req),
+ );
+ if (structured?.error) {
+ return {
+ error: {
+ message: structured.error,
+ status: 400,
+ code: "invalid_response_format",
+ },
+ };
+ }
+
+ const toolBundle = createToolBundle(toolsRaw);
+ const toolPolicy = parseOpenAIToolChoicePolicy(
+ req.tool_choice != null ? req.tool_choice : "auto",
+ toolBundle,
+ );
+ if (toolPolicy.error)
+ return {
+ error: {
+ message: toolPolicy.error,
+ status: 400,
+ code: "invalid_tool_choice",
+ },
+ };
+
+ const filteredToolBundle = filterToolBundleByPolicy(toolBundle, toolPolicy);
+ const allTools = toolBundle.openAIFunctionTools;
+ const tools = filteredToolBundle.openAIFunctionTools.length
+ ? filteredToolBundle.openAIFunctionTools
+ : null;
+ let promptToolChoice: "auto" | "none" | "required" = "auto";
+ if (toolPolicy.mode === "none") promptToolChoice = "none";
+ else if (toolPolicy.mode === "required" || toolPolicy.mode === "forced")
+ promptToolChoice = "required";
+ const ctx = await prepareOpenAIGeminiContext(
+ cfg,
+ provider,
+ req,
+ messages,
+ filteredToolBundle,
+ promptToolChoice,
+ toolPolicy,
+ structured,
+ );
+ if (hasCompletionError(ctx)) {
+ const code = upstreamErrorCode(ctx.error);
+ const error: OpenAICompletionPrepareError = {
+ message: upstreamErrorMessage(ctx.error),
+ status: upstreamErrorStatus(ctx.error) || 502,
+ };
+ if (code) error.code = code;
+ return {
+ error,
+ };
+ }
+ let { prompt } = ctx;
+ const { fileRefs, promptTokens, contextFiles } = ctx;
+ let promptToolSource: unknown = [];
+ if (toolPolicy.mode !== "none") {
+ promptToolSource = filteredToolBundle.defs.length
+ ? filteredToolBundle
+ : toolBundle;
+ }
+ prompt = ensureInlineToolPrompt(
+ prompt,
+ promptToolSource,
+ buildToolChoiceInstructionFromPolicy(toolPolicy),
+ contextFiles,
+ ctx.promptMetadata,
+ );
+ if (!String(prompt || "").trim())
+ return { error: { message: options.emptyPromptMessage, status: 400 } };
+
+ return {
+ rm,
+ structured,
+ allTools,
+ tools,
+ toolPolicy,
+ promptToolChoice,
+ prompt,
+ fileRefs,
+ promptTokens,
+ contextFiles,
+ };
+}
diff --git a/src/completion/ports.ts b/src/completion/ports.ts
new file mode 100644
index 0000000000000000000000000000000000000000..c1c5aad98d7f711b135ff62909a5c5cb227a9a9e
--- /dev/null
+++ b/src/completion/ports.ts
@@ -0,0 +1,51 @@
+import type { ResolvedModel } from "../models";
+import type { AttachmentPlan } from "../attachments/types";
+import type { AttachmentResolutionResult, FileRef } from "./types";
+
+export type CompletionTextInput = {
+ prompt: string;
+ rm: ResolvedModel;
+ fileRefs?: FileRef[] | null;
+};
+
+export type GeneratedImage = {
+ url: string;
+ source: "generated" | "web";
+ title?: string;
+ alt?: string;
+ imageId?: string;
+ cid?: string;
+ rid?: string;
+ rcid?: string;
+ base64?: string;
+ outputFormat?: "png" | "jpeg" | "gif" | "webp";
+};
+
+export type CompletionRichOutput = {
+ text: string;
+ images: GeneratedImage[];
+};
+
+export type CompletionProviderOptions = {
+ signal?: AbortSignal;
+};
+
+export type CompletionRichOptions = {
+ hydrateGeneratedImageBytes?: boolean;
+};
+
+export type CompletionProvider = {
+ supportsAuthenticatedSession?: boolean;
+ generateText(input: CompletionTextInput): Promise;
+ generateRich?(
+ input: CompletionTextInput,
+ options?: CompletionRichOptions,
+ ): Promise;
+ streamText(
+ input: CompletionTextInput,
+ options?: CompletionProviderOptions,
+ ): AsyncIterable;
+ resolveAttachments(plan: AttachmentPlan): Promise;
+ uploadTextFile(text: string, filename: string): Promise;
+ dispose?(): void | Promise;
+};
diff --git a/src/completion/runtime.ts b/src/completion/runtime.ts
new file mode 100644
index 0000000000000000000000000000000000000000..d0f1e823cddba789324d837ac448312b6bb1b2fa
--- /dev/null
+++ b/src/completion/runtime.ts
@@ -0,0 +1,13 @@
+export type { StreamConsumeOptions } from "./stream-coalesce";
+export type {
+ CompletionStreamEvent,
+ CompletionStreamLifecycle,
+ GeminiCompletionInput,
+} from "./stream-events";
+export {
+ createCompletionStreamLifecycle,
+ streamBufferedToolTextCompletionEvents,
+ streamPlainCompletionEvents,
+ streamToolSieveCompletionEvents,
+ recordCompletionStreamEvent,
+} from "./stream-events";
diff --git a/src/completion/stream-coalesce.ts b/src/completion/stream-coalesce.ts
new file mode 100644
index 0000000000000000000000000000000000000000..c7cb8541adcc26182a3244bf7478874e0cf5bce1
--- /dev/null
+++ b/src/completion/stream-coalesce.ts
@@ -0,0 +1,135 @@
+import { codePointLengthAtLeast } from "../shared/tokens";
+import { isAbortError } from "../shared/abort";
+import type {
+ CompletionProvider,
+ CompletionProviderOptions,
+ CompletionTextInput,
+} from "./ports";
+
+export type StreamConsumeOptions = CompletionProviderOptions;
+
+export type TextDeltaCoalesceOptions = {
+ coalesceTextDeltas?: boolean;
+ minCoalescedTextChars?: number;
+ maxCoalescedTextWaitMs?: number;
+};
+
+export type StreamConsumeInternalOptions = StreamConsumeOptions &
+ TextDeltaCoalesceOptions;
+
+type CoalescedTextRaceResult =
+ | { type: "next"; value: IteratorResult }
+ | { type: "timer" };
+
+const MIN_COALESCED_TEXT_DELTA_CHARS = 64;
+const MAX_COALESCED_TEXT_DELTA_WAIT_MS = 20;
+
+function streamCompletionText(
+ provider: CompletionProvider,
+ input: CompletionTextInput,
+ options: StreamConsumeOptions = {},
+) {
+ const providerOptions: CompletionProviderOptions = {};
+ if (options.signal) providerOptions.signal = options.signal;
+ return provider.streamText(input, providerOptions);
+}
+
+async function* coalesceTextDeltas(
+ deltas: AsyncIterable,
+ options: TextDeltaCoalesceOptions = {},
+): AsyncIterable {
+ const minChars = positiveCoalesceNumber(
+ options.minCoalescedTextChars,
+ MIN_COALESCED_TEXT_DELTA_CHARS,
+ );
+ const maxWaitMs = nonNegativeCoalesceNumber(
+ options.maxCoalescedTextWaitMs,
+ MAX_COALESCED_TEXT_DELTA_WAIT_MS,
+ );
+ const iterator = deltas[Symbol.asyncIterator]();
+ let next = iterator.next();
+ let pending = "";
+ let timer: Promise | null = null;
+ let firstText = true;
+
+ const scheduleTimer = () => {
+ if (!timer && maxWaitMs > 0)
+ timer = new Promise((resolve) =>
+ setTimeout(() => resolve({ type: "timer" }), maxWaitMs),
+ );
+ };
+ const flush = () => {
+ const out = pending;
+ pending = "";
+ timer = null;
+ return out;
+ };
+
+ try {
+ while (true) {
+ const nextResult: Promise = next.then(
+ (value) => ({ type: "next", value }),
+ );
+ const result: CoalescedTextRaceResult = timer
+ ? await Promise.race([nextResult, timer])
+ : await nextResult;
+
+ if (result.type === "timer") {
+ if (pending) yield flush();
+ continue;
+ }
+
+ const item = result.value;
+ if (item.done) {
+ if (pending) yield flush();
+ return;
+ }
+ next = iterator.next();
+
+ const text = String(item.value || "");
+ if (!text) continue;
+ if (firstText) {
+ firstText = false;
+ yield text;
+ continue;
+ }
+
+ pending += text;
+ if (codePointLengthAtLeast(pending, minChars)) {
+ yield flush();
+ } else {
+ scheduleTimer();
+ }
+ }
+ } catch (e) {
+ if (!isAbortError(e) && pending) yield flush();
+ throw e;
+ } finally {
+ if (iterator.return) {
+ try {
+ await iterator.return();
+ } catch (_) {}
+ }
+ }
+}
+
+export function completionTextDeltas(
+ provider: CompletionProvider,
+ input: CompletionTextInput,
+ options: StreamConsumeInternalOptions = {},
+): AsyncIterable {
+ const deltas = streamCompletionText(provider, input, options);
+ return options.coalesceTextDeltas
+ ? coalesceTextDeltas(deltas, options)
+ : deltas;
+}
+
+function positiveCoalesceNumber(value: unknown, fallback: number): number {
+ const n = Math.floor(Number(value));
+ return Number.isFinite(n) && n > 0 ? n : fallback;
+}
+
+function nonNegativeCoalesceNumber(value: unknown, fallback: number): number {
+ const n = Math.floor(Number(value));
+ return Number.isFinite(n) && n >= 0 ? n : fallback;
+}
diff --git a/src/completion/stream-events.ts b/src/completion/stream-events.ts
new file mode 100644
index 0000000000000000000000000000000000000000..ae8072019a8aaef65c76b984e213085b8ed65da6
--- /dev/null
+++ b/src/completion/stream-events.ts
@@ -0,0 +1,237 @@
+import { createTokenCounter, emptyTokenCounts } from "../shared/tokens";
+import type { TokenCharCounts } from "../shared/tokens";
+import { isAbortError } from "../shared/abort";
+import {
+ createToolSieveState,
+ flushToolSieve,
+ processToolSieveChunk,
+ toolSieveBufferedText,
+} from "../toolstream";
+import { validateRequiredToolCalls } from "../toolcall/policy-openai";
+import type { CompletionProvider, CompletionTextInput } from "./ports";
+import type { OpenAIToolCall } from "../toolcall/openai-format";
+import type {
+ ToolChoicePolicy,
+ ToolPolicyViolation,
+} from "../toolcall/policy-openai";
+import { completionTextDeltas } from "./stream-coalesce";
+import type { StreamConsumeInternalOptions } from "./stream-coalesce";
+
+export type GeminiCompletionInput = CompletionTextInput;
+
+export type CompletionStreamEvent =
+ | { type: "text_delta"; text: string }
+ | { type: "buffered_text"; text: string }
+ | { type: "tool_calls"; toolCalls: OpenAIToolCall[] }
+ | { type: "tool_policy_violation"; violation: ToolPolicyViolation }
+ | { type: "warning"; error: unknown; message: string }
+ | { type: "stream_error"; error: unknown; message: string }
+ | { type: "empty" }
+ | {
+ type: "done";
+ emittedText: boolean;
+ completionTokens: number;
+ completionCounts: TokenCharCounts & { hasText: boolean };
+ };
+
+export type CompletionStreamLifecycle = {
+ emittedText: boolean;
+ empty: boolean;
+ issue: Extract<
+ CompletionStreamEvent,
+ { type: "warning" } | { type: "stream_error" }
+ > | null;
+ toolCalls: OpenAIToolCall[] | null;
+ violation: ToolPolicyViolation | null;
+ completionCounts: TokenCharCounts & { hasText: boolean };
+};
+
+export function createCompletionStreamLifecycle(): CompletionStreamLifecycle {
+ return {
+ emittedText: false,
+ empty: false,
+ issue: null,
+ toolCalls: null,
+ violation: null,
+ completionCounts: emptyTokenCounts(),
+ };
+}
+
+export function recordCompletionStreamEvent(
+ lifecycle: CompletionStreamLifecycle,
+ event: CompletionStreamEvent,
+): void {
+ switch (event.type) {
+ case "text_delta":
+ case "buffered_text":
+ lifecycle.emittedText ||= !!event.text;
+ break;
+ case "warning":
+ case "stream_error":
+ lifecycle.issue = event;
+ break;
+ case "tool_calls":
+ lifecycle.toolCalls = event.toolCalls;
+ break;
+ case "tool_policy_violation":
+ lifecycle.violation = event.violation;
+ break;
+ case "empty":
+ lifecycle.empty = true;
+ break;
+ case "done":
+ lifecycle.emittedText ||= event.emittedText;
+ lifecycle.completionCounts = event.completionCounts;
+ }
+}
+
+export async function* streamPlainCompletionEvents(
+ provider: CompletionProvider,
+ input: GeminiCompletionInput,
+ options: StreamConsumeInternalOptions = {},
+): AsyncIterable {
+ let emittedText = false;
+ let streamErr: unknown = null;
+ const completionTokenCounter = createTokenCounter();
+
+ try {
+ for await (const delta of completionTextDeltas(provider, input, options)) {
+ if (!delta) continue;
+ const text = String(delta);
+ if (!text) continue;
+ emittedText = true;
+ completionTokenCounter.append(text);
+ yield { type: "text_delta", text };
+ }
+ } catch (e) {
+ if (isAbortError(e)) throw e;
+ streamErr = e;
+ }
+
+ if (streamErr) {
+ yield streamErrorEvent(streamErr, emittedText);
+ } else if (!emittedText) {
+ yield { type: "empty" };
+ }
+ yield {
+ type: "done",
+ emittedText,
+ completionTokens: completionTokenCounter.tokens(),
+ completionCounts: completionTokenCounter.counts(),
+ };
+}
+
+export async function* streamToolSieveCompletionEvents(
+ provider: CompletionProvider,
+ input: GeminiCompletionInput & {
+ tools: unknown;
+ toolPolicy?: ToolChoicePolicy | null | undefined;
+ },
+ options: StreamConsumeInternalOptions = {},
+): AsyncIterable {
+ const state = createToolSieveState();
+ let emittedText = false;
+ let streamErr: unknown = null;
+ const completionTokenCounter = createTokenCounter();
+
+ try {
+ for await (const deltaText of completionTextDeltas(
+ provider,
+ input,
+ options,
+ )) {
+ for (const text of processToolSieveChunk(state, deltaText)) {
+ if (!text) continue;
+ emittedText = true;
+ completionTokenCounter.append(text);
+ yield { type: "text_delta", text };
+ }
+ }
+ } catch (e) {
+ if (isAbortError(e)) throw e;
+ streamErr = e;
+ }
+
+ const flushed = flushToolSieve(state, input.tools);
+ if (flushed.text) {
+ emittedText = true;
+ completionTokenCounter.append(flushed.text);
+ yield { type: "text_delta", text: flushed.text };
+ }
+ const toolCalls = flushed.toolCalls;
+ const violation = validateRequiredToolCalls(input.toolPolicy, toolCalls);
+
+ if (streamErr)
+ yield streamErrorEvent(streamErr, emittedText || !!toolCalls?.length);
+ if (violation) yield { type: "tool_policy_violation", violation };
+ if (toolCalls?.length) yield { type: "tool_calls", toolCalls };
+ if (!streamErr && !emittedText && !toolCalls?.length) yield { type: "empty" };
+ yield {
+ type: "done",
+ emittedText,
+ completionTokens: completionTokenCounter.tokens(),
+ completionCounts: completionTokenCounter.counts(),
+ };
+}
+
+export async function* streamBufferedToolTextCompletionEvents(
+ provider: CompletionProvider,
+ input: GeminiCompletionInput,
+ options: StreamConsumeInternalOptions = {},
+): AsyncIterable {
+ const state = createToolSieveState();
+ let emittedText = false;
+ let streamErr: unknown = null;
+ const completionTokenCounter = createTokenCounter();
+
+ try {
+ for await (const deltaText of completionTextDeltas(
+ provider,
+ input,
+ options,
+ )) {
+ for (const text of processToolSieveChunk(state, deltaText)) {
+ if (!text) continue;
+ emittedText = true;
+ completionTokenCounter.append(text);
+ yield { type: "text_delta", text };
+ }
+ }
+ } catch (e) {
+ if (isAbortError(e)) throw e;
+ streamErr = e;
+ }
+
+ const bufferedText = toolSieveBufferedText(state);
+ if (bufferedText) yield { type: "buffered_text", text: bufferedText };
+ if (streamErr) {
+ yield streamErrorEvent(streamErr, emittedText);
+ } else if (!emittedText && !bufferedText) {
+ yield { type: "empty" };
+ }
+ yield {
+ type: "done",
+ emittedText,
+ completionTokens: completionTokenCounter.tokens(),
+ completionCounts: completionTokenCounter.counts(),
+ };
+}
+
+function streamErrorEvent(
+ error: unknown,
+ afterPartialOutput: boolean,
+): CompletionStreamEvent {
+ return {
+ type: afterPartialOutput ? "warning" : "stream_error",
+ error,
+ message: errorMessage(error),
+ };
+}
+
+function errorMessage(error: unknown): string {
+ return String(
+ error && typeof error === "object" && "message" in error
+ ? (error as { message?: unknown }).message
+ : error,
+ );
+}
diff --git a/src/completion/tool-prompt-guard.ts b/src/completion/tool-prompt-guard.ts
new file mode 100644
index 0000000000000000000000000000000000000000..f9babc741ab8d1bec7648f27455194e5a13fbc64
--- /dev/null
+++ b/src/completion/tool-prompt-guard.ts
@@ -0,0 +1,45 @@
+import {
+ toolCallInstructionsFor,
+ toolNamesForPromptSource,
+ toolPromptBlockFor,
+} from "../toolcall/tool-bundle";
+import type { PromptMetadata } from "./types";
+
+export function ensureInlineToolPrompt(
+ prompt: string,
+ toolDefs: unknown,
+ toolChoiceInstruction: string,
+ contextFiles?: unknown,
+ metadata?: PromptMetadata,
+): string {
+ const text = String(prompt || "");
+ const toolNames = toolNamesForPromptSource(toolDefs || []);
+ if (contextFiles) {
+ if (metadata?.hasToolInstructions) return text;
+ if (!toolNames.length)
+ return withMissingInstruction(text, toolChoiceInstruction);
+ if (!metadata && text.includes("<|DSML|tool_calls>")) return text;
+ return [toolCallInstructionsFor(toolDefs), toolChoiceInstruction, text]
+ .filter((part) => part.trim())
+ .join("\n\n");
+ }
+ if (!toolNames.length) {
+ return withMissingInstruction(text, toolChoiceInstruction);
+ }
+ if (metadata?.hasToolPrompt && metadata.hasToolInstructions) return text;
+ if (
+ !metadata &&
+ text.includes("Available tools") &&
+ text.includes("<|DSML|tool_calls>")
+ )
+ return text;
+ return [toolPromptBlockFor(toolDefs, toolChoiceInstruction), text]
+ .filter((part) => part.trim())
+ .join("\n\n");
+}
+
+function withMissingInstruction(text: string, instruction: string): string {
+ const trimmed = String(instruction || "").trim();
+ if (!trimmed || text.includes(trimmed)) return text;
+ return [instruction, text].filter((part) => part.trim()).join("\n\n");
+}
diff --git a/src/completion/turn.ts b/src/completion/turn.ts
new file mode 100644
index 0000000000000000000000000000000000000000..df23df56b8049e3f5dbdfcdc4b9aa0404a01bb6f
--- /dev/null
+++ b/src/completion/turn.ts
@@ -0,0 +1,90 @@
+import { finalizeStructuredOutputText } from "../toolcall/structured";
+import { parseToolCalls } from "../toolcall/dsml";
+import { validateRequiredToolCalls } from "../toolcall/policy-openai";
+import type { OpenAIToolCall } from "../toolcall/openai-format";
+import type { ToolChoicePolicy } from "../toolcall/policy-openai";
+
+export const EMPTY_UPSTREAM_MSG =
+ "⚠️ Upstream Gemini returned an empty response. " +
+ "The Worker could not extract any final text from the upstream response. " +
+ "Check `wrangler tail` for upstream status, retry/fallback logs, and whether the request is being blocked or returned in an unsupported shape.";
+
+export type OpenAICompletionTurnOptions = {
+ tools?: unknown;
+ noneModeTools?: unknown;
+ promptToolChoice?: string;
+ structured?: unknown;
+ toolPolicy?: ToolChoicePolicy | null | undefined;
+};
+
+export type OpenAICompletionTurn =
+ | {
+ text: string;
+ toolCalls: OpenAIToolCall[] | null;
+ upstreamEmpty: boolean;
+ error?: undefined;
+ }
+ | {
+ error: {
+ message: string;
+ status: number;
+ code: string;
+ };
+ text?: undefined;
+ toolCalls?: undefined;
+ upstreamEmpty?: undefined;
+ };
+
+export function upstreamEmptyWarning(
+ cfg: { gemini_bl?: unknown } | null | undefined,
+) {
+ return {
+ code: "upstream_empty",
+ message: EMPTY_UPSTREAM_MSG,
+ hint: "Current GEMINI_BL is included for diagnostics; empty responses are not always caused by an outdated build label.",
+ gemini_bl: cfg?.gemini_bl,
+ };
+}
+
+export function finalizeOpenAICompletionResult(
+ text: unknown,
+ options: OpenAICompletionTurnOptions,
+): OpenAICompletionTurn {
+ const { tools, noneModeTools, promptToolChoice, structured, toolPolicy } =
+ options || {};
+ let outText = String(text || "");
+ let toolCalls: OpenAIToolCall[] | null = null;
+
+ if (tools && outText && promptToolChoice !== "none") {
+ const [clean, tc] = parseToolCalls(outText, tools);
+ outText = String(clean || "");
+ toolCalls = tc.length ? tc : null;
+ } else if (noneModeTools && outText && promptToolChoice === "none") {
+ const [, tc] = parseToolCalls(outText, noneModeTools);
+ toolCalls = tc.length ? tc : null;
+ }
+ if (!toolCalls && structured) {
+ const finalized = finalizeStructuredOutputText(outText, structured);
+ if (finalized.error) {
+ return {
+ error: {
+ message: finalized.error,
+ status: 502,
+ code: "structured_output_validation_failed",
+ },
+ };
+ }
+ outText = finalized.text;
+ }
+ const violation = validateRequiredToolCalls(toolPolicy, toolCalls);
+ if (violation) {
+ return {
+ error: { message: violation.message, status: 422, code: violation.code },
+ };
+ }
+ return {
+ text: outText,
+ toolCalls,
+ upstreamEmpty: !outText && !toolCalls,
+ };
+}
diff --git a/src/completion/types.ts b/src/completion/types.ts
new file mode 100644
index 0000000000000000000000000000000000000000..ce49fc1425809b5a0a1713457628139ce785821f
--- /dev/null
+++ b/src/completion/types.ts
@@ -0,0 +1,64 @@
+import type { ErrorWithMetadata, UnknownRecord } from "../shared/types";
+import type { TokenCharCounts } from "../shared/tokens";
+import type {
+ AttachmentFileRef,
+ AttachmentUploadResult,
+} from "../attachments/types";
+
+export type FileRef = AttachmentFileRef;
+
+export type ToolDef = {
+ name: string;
+ description?: string;
+ parameters?: unknown;
+};
+
+export type PromptWithTokens = {
+ text: string;
+ tokens: number;
+ counts?: unknown;
+};
+
+export type PromptMetadata = {
+ hasToolPrompt?: boolean;
+ hasToolInstructions?: boolean;
+};
+
+export type AttachmentResolutionResult = AttachmentUploadResult;
+
+export type ImageResolutionResult = AttachmentResolutionResult;
+
+export type FileResolutionResult = AttachmentResolutionResult;
+
+export type ContextFileResult = {
+ fileRefs: FileRef[];
+ prompt: string;
+ promptTokenCounts: TokenCharCounts & { hasText: boolean };
+ promptTokenText: string;
+};
+
+export type ContextFileFailure = {
+ error: ErrorWithMetadata;
+};
+
+export type PreparedGeminiContext = {
+ toolDefs: ToolDef[];
+ toolChoiceInstruction: string;
+ prompt: string;
+ promptTokens: number;
+ fileRefs: FileRef[] | null;
+ contextFiles: ContextFileResult | null;
+ promptMetadata?: PromptMetadata;
+};
+
+export type GeminiContextPrepareResult =
+ | PreparedGeminiContext
+ | ContextFileFailure;
+
+export type LooseRequest = UnknownRecord;
+
+export function hasCompletionError(
+ value: T | ContextFileFailure,
+): value is ContextFileFailure {
+ return !!value && typeof value === "object" && "error" in value;
+}
diff --git a/src/config/index.ts b/src/config/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..5747dbec77db505030e020077637917b1bafd035
--- /dev/null
+++ b/src/config/index.ts
@@ -0,0 +1,575 @@
+export const VERSION = "1.1.0-worker";
+
+export type WorkerEnv = Partial>;
+
+export type RuntimeProfile = "worker" | "docker";
+
+export type StaticRuntimeConfig = Readonly<{
+ gemini_bl: string;
+ gemini_origin: string;
+ resin_proxy: string;
+ auth_user: string;
+ xsrf_token: string;
+ upstream_socket: boolean;
+ default_model: string;
+ retry_attempts: number;
+ retry_delay_sec: number;
+ request_timeout_sec: number;
+ request_body_max_bytes: number;
+ log_requests: boolean;
+ current_input_file_enabled: boolean;
+ current_input_file_min_bytes: number;
+ current_input_file_name: string;
+ current_tools_file_name: string;
+ generic_file_upload_max_bytes: number;
+ api_keys: readonly string[];
+ cookie: string;
+ sapisid: string;
+}>;
+
+export type RuntimeExecutionContext = {
+ supports_authenticated_session?: boolean;
+ execution_ctx?: Pick;
+ runtime_profile?: RuntimeProfile;
+};
+
+export type RuntimeConfig = StaticRuntimeConfig & RuntimeExecutionContext;
+
+export function createRuntimeConfig(
+ config: StaticRuntimeConfig,
+ execution: RuntimeExecutionContext = {},
+): RuntimeConfig {
+ return {
+ ...config,
+ ...execution,
+ supports_authenticated_session:
+ execution.supports_authenticated_session ?? !!config.cookie,
+ };
+}
+
+const DEFAULT_CONFIG = Object.freeze({
+ GEMINI_COOKIE: "",
+ SAPISID: "",
+ GEMINI_BL: "boq_assistant-bard-web-server_20260716.08_p0",
+ GEMINI_ORIGIN: "https://gemini.google.com",
+ RESIN_PROXY: "",
+ AUTH_USER: "",
+ XSRF_TOKEN: "",
+ UPSTREAM_SOCKET: true,
+ DEFAULT_MODEL: "gemini-3.6-flash",
+ RETRY_ATTEMPTS: 3,
+ RETRY_DELAY_SEC: 2,
+ REQUEST_TIMEOUT_SEC: 180,
+ REQUEST_BODY_MAX_BYTES: 16 * 1024 * 1024,
+ LOG_REQUESTS: false,
+ CURRENT_INPUT_FILE_ENABLED: true,
+ CURRENT_INPUT_FILE_MIN_BYTES: 95000,
+ CURRENT_INPUT_FILE_NAME: "message.txt",
+ CURRENT_TOOLS_FILE_NAME: "tools.txt",
+ GENERIC_FILE_UPLOAD_MAX_BYTES: 20 * 1024 * 1024,
+ API_KEYS: [] as string[],
+});
+
+export class RuntimeConfigError extends Error {
+ readonly code = "invalid_runtime_config";
+
+ constructor(
+ readonly setting: string,
+ readonly reason: string,
+ ) {
+ super(`invalid runtime configuration: ${setting} ${reason}`);
+ this.name = "RuntimeConfigError";
+ }
+}
+
+export const CONFIG_ENV_KEYS = [
+ "GEMINI_COOKIE",
+ "SAPISID",
+ "GEMINI_BL",
+ "GEMINI_ORIGIN",
+ "RESIN_PROXY",
+ "AUTH_USER",
+ "XSRF_TOKEN",
+ "UPSTREAM_SOCKET",
+ "DEFAULT_MODEL",
+ "RETRY_ATTEMPTS",
+ "RETRY_DELAY_SEC",
+ "REQUEST_TIMEOUT_SEC",
+ "REQUEST_BODY_MAX_BYTES",
+ "LOG_REQUESTS",
+ "CURRENT_INPUT_FILE_ENABLED",
+ "CURRENT_INPUT_FILE_MIN_BYTES",
+ "CURRENT_INPUT_FILE_NAME",
+ "CURRENT_TOOLS_FILE_NAME",
+ "GENERIC_FILE_UPLOAD_MAX_BYTES",
+ "API_KEYS",
+] as const;
+const CONFIG_CACHE_ENV_KEYS = CONFIG_ENV_KEYS;
+type ConfigCacheSnapshot = readonly unknown[];
+let _configCacheSnapshot: ConfigCacheSnapshot | null = null;
+let _configCacheValue: StaticRuntimeConfig | null = null;
+let _configCacheEnv: WorkerEnv | null = null;
+const DEFAULT_ENV: WorkerEnv = {};
+type ConfigCacheEntry = {
+ snapshot: ConfigCacheSnapshot;
+ value: StaticRuntimeConfig;
+};
+const _configCacheByEnv = new WeakMap();
+
+export function getConfig(env: WorkerEnv = DEFAULT_ENV): StaticRuntimeConfig {
+ const activeEnv = env || DEFAULT_ENV;
+ if (
+ _configCacheValue &&
+ _configCacheEnv === activeEnv &&
+ _configCacheSnapshot &&
+ configSnapshotMatches(_configCacheSnapshot, activeEnv)
+ )
+ return _configCacheValue;
+ const cachedByEnv = _configCacheByEnv.get(activeEnv);
+ if (cachedByEnv && configSnapshotMatches(cachedByEnv.snapshot, activeEnv)) {
+ _configCacheEnv = activeEnv;
+ _configCacheSnapshot = cachedByEnv.snapshot;
+ _configCacheValue = cachedByEnv.value;
+ return cachedByEnv.value;
+ }
+ if (
+ _configCacheValue &&
+ _configCacheSnapshot &&
+ configSnapshotMatches(_configCacheSnapshot, activeEnv)
+ ) {
+ _configCacheEnv = activeEnv;
+ _configCacheByEnv.set(activeEnv, {
+ snapshot: _configCacheSnapshot,
+ value: _configCacheValue,
+ });
+ return _configCacheValue;
+ }
+ const cfg: StaticRuntimeConfig = Object.freeze({
+ ...parseCookieConfig(activeEnv),
+ gemini_bl: parseNonEmptyString(
+ "GEMINI_BL",
+ configValue(activeEnv, "GEMINI_BL", DEFAULT_CONFIG.GEMINI_BL),
+ 512,
+ ),
+ gemini_origin: parseHttpOrigin(
+ "GEMINI_ORIGIN",
+ configValue(activeEnv, "GEMINI_ORIGIN", DEFAULT_CONFIG.GEMINI_ORIGIN),
+ ),
+ resin_proxy: parseResinProxy(
+ configValue(activeEnv, "RESIN_PROXY", DEFAULT_CONFIG.RESIN_PROXY),
+ ),
+ auth_user: parseAuthUser(
+ configValue(activeEnv, "AUTH_USER", DEFAULT_CONFIG.AUTH_USER),
+ ),
+ xsrf_token: parseOptionalToken(
+ "XSRF_TOKEN",
+ configValue(activeEnv, "XSRF_TOKEN", DEFAULT_CONFIG.XSRF_TOKEN),
+ ),
+ upstream_socket: parseStrictBoolean(
+ "UPSTREAM_SOCKET",
+ configValue(activeEnv, "UPSTREAM_SOCKET", DEFAULT_CONFIG.UPSTREAM_SOCKET),
+ ),
+ default_model: parseNonEmptyString(
+ "DEFAULT_MODEL",
+ configValue(activeEnv, "DEFAULT_MODEL", DEFAULT_CONFIG.DEFAULT_MODEL),
+ 256,
+ ),
+ retry_attempts: parseStrictInteger(
+ "RETRY_ATTEMPTS",
+ configValue(activeEnv, "RETRY_ATTEMPTS", DEFAULT_CONFIG.RETRY_ATTEMPTS),
+ 1,
+ 10,
+ ),
+ retry_delay_sec: parseStrictInteger(
+ "RETRY_DELAY_SEC",
+ configValue(activeEnv, "RETRY_DELAY_SEC", DEFAULT_CONFIG.RETRY_DELAY_SEC),
+ 0,
+ 60,
+ ),
+ request_timeout_sec: parseStrictInteger(
+ "REQUEST_TIMEOUT_SEC",
+ configValue(
+ activeEnv,
+ "REQUEST_TIMEOUT_SEC",
+ DEFAULT_CONFIG.REQUEST_TIMEOUT_SEC,
+ ),
+ 1,
+ 3600,
+ ),
+ request_body_max_bytes: parseStrictInteger(
+ "REQUEST_BODY_MAX_BYTES",
+ configValue(
+ activeEnv,
+ "REQUEST_BODY_MAX_BYTES",
+ DEFAULT_CONFIG.REQUEST_BODY_MAX_BYTES,
+ ),
+ 1,
+ 100 * 1024 * 1024,
+ ),
+ log_requests: parseStrictBoolean(
+ "LOG_REQUESTS",
+ configValue(activeEnv, "LOG_REQUESTS", DEFAULT_CONFIG.LOG_REQUESTS),
+ ),
+ current_input_file_enabled: parseStrictBoolean(
+ "CURRENT_INPUT_FILE_ENABLED",
+ configValue(
+ activeEnv,
+ "CURRENT_INPUT_FILE_ENABLED",
+ DEFAULT_CONFIG.CURRENT_INPUT_FILE_ENABLED,
+ ),
+ ),
+ current_input_file_min_bytes: parseStrictInteger(
+ "CURRENT_INPUT_FILE_MIN_BYTES",
+ configValue(
+ activeEnv,
+ "CURRENT_INPUT_FILE_MIN_BYTES",
+ DEFAULT_CONFIG.CURRENT_INPUT_FILE_MIN_BYTES,
+ ),
+ 0,
+ 10 * 1024 * 1024,
+ ),
+ current_input_file_name: parseFilename(
+ "CURRENT_INPUT_FILE_NAME",
+ configValue(
+ activeEnv,
+ "CURRENT_INPUT_FILE_NAME",
+ DEFAULT_CONFIG.CURRENT_INPUT_FILE_NAME,
+ ),
+ ),
+ current_tools_file_name: parseFilename(
+ "CURRENT_TOOLS_FILE_NAME",
+ configValue(
+ activeEnv,
+ "CURRENT_TOOLS_FILE_NAME",
+ DEFAULT_CONFIG.CURRENT_TOOLS_FILE_NAME,
+ ),
+ ),
+ generic_file_upload_max_bytes: parseStrictInteger(
+ "GENERIC_FILE_UPLOAD_MAX_BYTES",
+ configValue(
+ activeEnv,
+ "GENERIC_FILE_UPLOAD_MAX_BYTES",
+ DEFAULT_CONFIG.GENERIC_FILE_UPLOAD_MAX_BYTES,
+ ),
+ 0,
+ 100 * 1024 * 1024,
+ ),
+ api_keys: Object.freeze(
+ parseKeyList(
+ "API_KEYS",
+ configValue(activeEnv, "API_KEYS", DEFAULT_CONFIG.API_KEYS),
+ ),
+ ),
+ });
+ const snapshot = captureConfigSnapshot(activeEnv);
+ _configCacheSnapshot = snapshot;
+ _configCacheValue = cfg;
+ _configCacheEnv = activeEnv;
+ _configCacheByEnv.set(activeEnv, { snapshot, value: cfg });
+ return cfg;
+}
+
+export function assertRuntimeConfig(env: WorkerEnv = DEFAULT_ENV): void {
+ void getConfig(env);
+}
+
+function configValue(
+ env: WorkerEnv,
+ key: keyof WorkerBindings,
+ fallback: unknown,
+): unknown {
+ const value = env[key];
+ return value === undefined || value === null || value === ""
+ ? fallback
+ : value;
+}
+
+function parseCookieConfig(
+ env: WorkerEnv,
+): Pick {
+ const cookieValue = configValue(
+ env,
+ "GEMINI_COOKIE",
+ DEFAULT_CONFIG.GEMINI_COOKIE,
+ );
+ const sapisidValue = configValue(env, "SAPISID", DEFAULT_CONFIG.SAPISID);
+ if (typeof cookieValue !== "string")
+ throw new RuntimeConfigError("GEMINI_COOKIE", "must be a string");
+ if (typeof sapisidValue !== "string")
+ throw new RuntimeConfigError("SAPISID", "must be a string");
+ if (cookieValue.length > 1024 * 1024)
+ throw new RuntimeConfigError(
+ "GEMINI_COOKIE",
+ "must not be longer than 1048576 characters",
+ );
+ if (sapisidValue.length > 4096)
+ throw new RuntimeConfigError(
+ "SAPISID",
+ "must not be longer than 4096 characters",
+ );
+
+ let cookie = cookieValue;
+ let sapisid = sapisidValue;
+ if (cookie.trim().startsWith("{")) {
+ try {
+ const parsed: unknown = JSON.parse(cookie);
+ if (isConfigObject(parsed)) {
+ const normalized = cookieFromJsonConfig(parsed);
+ cookie = normalized.cookie;
+ if (!sapisid) sapisid = normalized.sapisid;
+ }
+ } catch (_) {
+ // Preserve compatibility by treating malformed JSON-looking values as
+ // raw Cookie headers.
+ }
+ }
+ if (cookie && !sapisid) {
+ const match = /(?:^|;\s*)SAPISID=([^;]+)/.exec(cookie);
+ if (match?.[1]) sapisid = match[1];
+ }
+ return { cookie, sapisid };
+}
+
+function isConfigObject(value: unknown): value is Record {
+ return !!value && typeof value === "object" && !Array.isArray(value);
+}
+
+function cookieFromJsonConfig(
+ config: Record,
+): Pick {
+ const rawCookie = configString(config, "cookie");
+ const sapisid = configString(config, "sapisid", "SAPISID");
+ if (rawCookie) return { cookie: rawCookie, sapisid };
+ const parts: string[] = [];
+ appendCookiePart(
+ parts,
+ "__Secure-1PSID",
+ configString(config, "secure_1psid", "secure1psid", "__Secure-1PSID"),
+ );
+ appendCookiePart(
+ parts,
+ "__Secure-1PSIDTS",
+ configString(config, "secure_1psidts", "secure1psidts", "__Secure-1PSIDTS"),
+ );
+ appendCookiePart(parts, "SAPISID", sapisid);
+ return { cookie: parts.join("; "), sapisid };
+}
+
+function configString(
+ config: Record,
+ ...keys: string[]
+): string {
+ for (const key of keys) {
+ const value = config[key];
+ if (value !== undefined && value !== null && value !== "")
+ return String(value);
+ }
+ return "";
+}
+
+function appendCookiePart(parts: string[], name: string, value: string): void {
+ if (value) parts.push(`${name}=${value}`);
+}
+
+function parseStrictBoolean(setting: string, value: unknown): boolean {
+ if (typeof value === "boolean") return value;
+ if (value === "true") return true;
+ if (value === "false") return false;
+ throw new RuntimeConfigError(setting, "must be true or false");
+}
+
+function parseStrictInteger(
+ setting: string,
+ value: unknown,
+ min: number,
+ max: number,
+): number {
+ let parsed: number;
+ if (typeof value === "number") {
+ parsed = value;
+ } else if (typeof value === "string" && /^(?:0|[1-9]\d*)$/.test(value)) {
+ parsed = Number(value);
+ } else {
+ throw new RuntimeConfigError(
+ setting,
+ `must be an integer between ${min} and ${max}`,
+ );
+ }
+ if (!Number.isSafeInteger(parsed) || parsed < min || parsed > max) {
+ throw new RuntimeConfigError(
+ setting,
+ `must be an integer between ${min} and ${max}`,
+ );
+ }
+ return parsed;
+}
+
+function parseNonEmptyString(
+ setting: string,
+ value: unknown,
+ maxLength: number,
+): string {
+ if (typeof value !== "string")
+ throw new RuntimeConfigError(setting, "must be a string");
+ const parsed = value.trim();
+ if (!parsed) throw new RuntimeConfigError(setting, "must not be empty");
+ if (parsed.length > maxLength)
+ throw new RuntimeConfigError(
+ setting,
+ `must be at most ${maxLength} characters`,
+ );
+ return parsed;
+}
+
+function parseHttpOrigin(setting: string, value: unknown): string {
+ const raw = parseNonEmptyString(setting, value, 2048);
+ let parsed: URL;
+ try {
+ parsed = new URL(raw);
+ } catch (_) {
+ throw new RuntimeConfigError(setting, "must be an absolute HTTP(S) origin");
+ }
+ if (
+ (parsed.protocol !== "https:" && parsed.protocol !== "http:") ||
+ parsed.username ||
+ parsed.password ||
+ parsed.pathname !== "/" ||
+ parsed.search ||
+ parsed.hash
+ ) {
+ throw new RuntimeConfigError(setting, "must be an absolute HTTP(S) origin");
+ }
+ return parsed.origin;
+}
+
+function parseResinProxy(value: unknown): string {
+ if (typeof value !== "string")
+ throw new RuntimeConfigError("RESIN_PROXY", "must be a string");
+ const raw = value.trim();
+ if (!raw) return "";
+ if (raw.length > 2048)
+ throw new RuntimeConfigError(
+ "RESIN_PROXY",
+ "must be at most 2048 characters",
+ );
+ if (!/^https:\/\//.test(raw))
+ throw new RuntimeConfigError("RESIN_PROXY", "must start with https://");
+ return raw.replace(/\/$/, "");
+}
+
+function parseAuthUser(value: unknown): string {
+ if (typeof value !== "string")
+ throw new RuntimeConfigError("AUTH_USER", "must be a string");
+ const raw = value.trim();
+ if (!raw) return "";
+ if (!/^\d{1,4}$/.test(raw))
+ throw new RuntimeConfigError("AUTH_USER", "must be a non-negative integer");
+ return raw;
+}
+
+function parseOptionalToken(setting: string, value: unknown): string {
+ if (typeof value !== "string")
+ throw new RuntimeConfigError(setting, "must be a string");
+ const raw = value.trim();
+ if (raw.length > 4096)
+ throw new RuntimeConfigError(setting, "must be at most 4096 characters");
+ return raw;
+}
+
+function parseFilename(setting: string, value: unknown): string {
+ const parsed = parseNonEmptyString(setting, value, 255);
+ if (
+ /[/\\\u0000-\u001f\u007f]/.test(parsed) ||
+ parsed === "." ||
+ parsed === ".."
+ )
+ throw new RuntimeConfigError(setting, "must be a plain filename");
+ return parsed;
+}
+
+function parseKeyList(setting: string, value: unknown): string[] {
+ let items: unknown[];
+ if (Array.isArray(value)) {
+ items = value;
+ } else if (typeof value === "string") {
+ const raw = value.trim();
+ if (!raw) return [];
+ if (raw.startsWith("[")) {
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (!Array.isArray(parsed))
+ throw new RuntimeConfigError(
+ setting,
+ "must be a comma-separated list or JSON array",
+ );
+ items = parsed;
+ } catch (error) {
+ if (error instanceof RuntimeConfigError) throw error;
+ throw new RuntimeConfigError(
+ setting,
+ "must be a comma-separated list or valid JSON array",
+ );
+ }
+ } else {
+ items = raw.split(",");
+ }
+ } else {
+ throw new RuntimeConfigError(
+ setting,
+ "must be a comma-separated list or JSON array",
+ );
+ }
+ const out: string[] = [];
+ const seen = new Set();
+ for (const item of items) {
+ if (typeof item !== "string")
+ throw new RuntimeConfigError(setting, "must contain only strings");
+ const key = item.trim();
+ if (!key)
+ throw new RuntimeConfigError(setting, "must not contain empty entries");
+ if (key.length > 4096)
+ throw new RuntimeConfigError(
+ setting,
+ "contains an entry longer than 4096 characters",
+ );
+ if (seen.has(key))
+ throw new RuntimeConfigError(
+ setting,
+ "must not contain duplicate entries",
+ );
+ seen.add(key);
+ out.push(key);
+ }
+ return out;
+}
+
+function captureConfigSnapshot(env: WorkerEnv): ConfigCacheSnapshot {
+ return CONFIG_CACHE_ENV_KEYS.map((key) => {
+ const value = env[key];
+ return key === "API_KEYS" && Array.isArray(value)
+ ? Object.freeze([...value])
+ : value;
+ });
+}
+
+function configSnapshotMatches(
+ snapshot: ConfigCacheSnapshot,
+ env: WorkerEnv,
+): boolean {
+ let index = 0;
+ for (const key of CONFIG_CACHE_ENV_KEYS) {
+ const expected = snapshot[index];
+ const actual = env[key];
+ if (key === "API_KEYS" && Array.isArray(expected)) {
+ if (!Array.isArray(actual) || actual.length !== expected.length)
+ return false;
+ for (let item = 0; item < expected.length; item++) {
+ if (!Object.is(actual[item], expected[item])) return false;
+ }
+ } else if (!Object.is(actual, expected)) {
+ return false;
+ }
+ index += 1;
+ }
+ return true;
+}
diff --git a/src/gemini/app-page.ts b/src/gemini/app-page.ts
new file mode 100644
index 0000000000000000000000000000000000000000..f7f9fd28a4d1b0e9544c635e170bba1cbcfd7cc0
--- /dev/null
+++ b/src/gemini/app-page.ts
@@ -0,0 +1,212 @@
+export type GeminiAppPageTokens = { push_id?: string; at?: string };
+
+type TextStreamResponse = {
+ body?: ReadableStream | null;
+ text: () => Promise;
+};
+type QuotedMarkerSpec = { key: K; marker: string };
+
+const APP_PAGE_TOKEN_MARKERS: QuotedMarkerSpec[] = [
+ { key: "push_id", marker: '"qKIAYe":"' },
+ { key: "at", marker: '"SNlM0e":"' },
+];
+const PUSH_ID_MARKER: QuotedMarkerSpec<"push_id"> = {
+ key: "push_id",
+ marker: '"qKIAYe":"',
+};
+const CFB2H_MARKER = '"cfb2h":"';
+const BUILD_LABEL_PREFIX = "boq_assistant-bard-web-server_";
+const BUILD_LABEL_KEEP_CHARS = BUILD_LABEL_PREFIX.length + 128;
+const MAX_QUOTED_MARKER_VALUE_CHARS = 8 * 1024;
+
+export async function extractGeminiAppPageTokens(
+ resp: TextStreamResponse,
+): Promise {
+ const scanner = createQuotedMarkerScanner(APP_PAGE_TOKEN_MARKERS);
+ await scanResponseText(resp, (chunk) => {
+ scanner.push(chunk);
+ return scanner.done;
+ });
+ return scanner.result;
+}
+
+export async function extractGeminiPushId(
+ resp: TextStreamResponse,
+): Promise {
+ const scanner = createQuotedMarkerScanner([PUSH_ID_MARKER]);
+ await scanResponseText(resp, (chunk) => {
+ scanner.push(chunk);
+ return scanner.done;
+ });
+ return scanner.result.push_id || "";
+}
+
+export async function extractGeminiBuildLabel(
+ resp: TextStreamResponse,
+): Promise {
+ const scanner = createBuildLabelScanner();
+ await scanResponseText(resp, (chunk) => scanner.push(chunk));
+ return scanner.label || scanner.finish();
+}
+
+async function scanResponseText(
+ resp: TextStreamResponse,
+ onChunk: (text: string) => boolean,
+): Promise {
+ const body = resp.body;
+ if (!body || typeof body.getReader !== "function") {
+ onChunk(await resp.text());
+ return;
+ }
+ const reader = body.getReader();
+ const decoder = new TextDecoder();
+ let shouldCancel = false;
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (!value?.length) continue;
+ const text = decoder.decode(value, { stream: true });
+ if (text && onChunk(text)) {
+ shouldCancel = true;
+ break;
+ }
+ }
+ if (!shouldCancel) {
+ const tail = decoder.decode();
+ if (tail) shouldCancel = onChunk(tail);
+ }
+ if (shouldCancel) await reader.cancel().catch(() => undefined);
+ } finally {
+ try {
+ reader.releaseLock();
+ } catch (_) {}
+ }
+}
+
+function createQuotedMarkerScanner(
+ specs: readonly QuotedMarkerSpec[],
+) {
+ const result: Partial> = {};
+ const found = new Set();
+ const keepChars = Math.max(0, ...specs.map((spec) => spec.marker.length - 1));
+ let pending = "";
+ let active: { key: K; value: string } | null = null;
+
+ const push = (text: string): void => {
+ pending += text;
+ let pos = 0;
+ for (;;) {
+ if (active) {
+ const end = pending.indexOf('"', pos);
+ if (end < 0) {
+ const nextValue = active.value + pending.slice(pos);
+ if (nextValue.length > MAX_QUOTED_MARKER_VALUE_CHARS) {
+ active = null;
+ pending = pending.slice(Math.max(pos, pending.length - keepChars));
+ return;
+ }
+ active.value = nextValue;
+ pending = "";
+ return;
+ }
+ const value = active.value + pending.slice(pos, end);
+ if (value.length <= MAX_QUOTED_MARKER_VALUE_CHARS) {
+ result[active.key] = value;
+ found.add(active.key);
+ }
+ active = null;
+ pos = end + 1;
+ continue;
+ }
+
+ let bestIndex = -1;
+ let bestSpec: QuotedMarkerSpec | null = null;
+ for (const spec of specs) {
+ if (found.has(spec.key)) continue;
+ const index = pending.indexOf(spec.marker, pos);
+ if (index >= 0 && (bestIndex < 0 || index < bestIndex)) {
+ bestIndex = index;
+ bestSpec = spec;
+ }
+ }
+ if (!bestSpec) {
+ pending = pending.slice(Math.max(pos, pending.length - keepChars));
+ return;
+ }
+ pos = bestIndex + bestSpec.marker.length;
+ active = { key: bestSpec.key, value: "" };
+ }
+ };
+
+ return {
+ result: result as Partial>,
+ push,
+ get done() {
+ return found.size >= specs.length;
+ },
+ };
+}
+
+function createBuildLabelScanner() {
+ const quoted = createQuotedMarkerScanner([
+ { key: "label", marker: CFB2H_MARKER },
+ ]);
+ let pending = "";
+ let label = "";
+
+ const scanPrefixLabel = (final: boolean): string => {
+ const start = pending.indexOf(BUILD_LABEL_PREFIX);
+ if (start < 0) {
+ pending = pending.slice(-BUILD_LABEL_KEEP_CHARS);
+ return "";
+ }
+ let end = start + BUILD_LABEL_PREFIX.length;
+ while (end < pending.length && isBuildLabelChar(pending.charCodeAt(end)))
+ end += 1;
+ if (end === pending.length && !final) {
+ pending = pending.slice(start);
+ return "";
+ }
+ if (end > start + BUILD_LABEL_PREFIX.length)
+ return pending.slice(start, end);
+ pending = pending.slice(
+ Math.max(start, pending.length - BUILD_LABEL_KEEP_CHARS),
+ );
+ return "";
+ };
+
+ return {
+ get label() {
+ return label;
+ },
+ push(text: string): boolean {
+ quoted.push(text);
+ const quotedLabel = quoted.result.label;
+ if (quotedLabel) {
+ label = quotedLabel;
+ return true;
+ }
+ pending += text;
+ label = scanPrefixLabel(false);
+ return !!label;
+ },
+ finish(): string {
+ if (label) return label;
+ const quotedLabel = quoted.result.label;
+ if (quotedLabel) return quotedLabel;
+ return scanPrefixLabel(true);
+ },
+ };
+}
+
+function isBuildLabelChar(code: number): boolean {
+ return (
+ (code >= 48 && code <= 57) ||
+ (code >= 65 && code <= 90) ||
+ (code >= 97 && code <= 122) ||
+ code === 45 ||
+ code === 46 ||
+ code === 95
+ );
+}
diff --git a/src/gemini/auth.ts b/src/gemini/auth.ts
new file mode 100644
index 0000000000000000000000000000000000000000..4efdcd80238d021220a686f671efec0eb9b5efb2
--- /dev/null
+++ b/src/gemini/auth.ts
@@ -0,0 +1,20 @@
+import { bytesToHex } from "../shared/crypto";
+import { TEXT_ENCODER } from "../shared/encoding";
+
+export let _sapisidHashCache: { key: string; value: string } = {
+ key: "",
+ value: "",
+};
+
+export async function makeSapisidHash(sapisid: string): Promise {
+ const timestamp = Math.floor(Date.now() / 1000);
+ const cacheKey = `${timestamp}\x00${sapisid}`;
+ if (_sapisidHashCache.key === cacheKey) return _sapisidHashCache.value;
+ const data = TEXT_ENCODER.encode(
+ `${timestamp} ${sapisid} https://gemini.google.com`,
+ );
+ const digest = await crypto.subtle.digest("SHA-1", data);
+ const value = `SAPISIDHASH ${timestamp}_${bytesToHex(new Uint8Array(digest))}`;
+ _sapisidHashCache = { key: cacheKey, value };
+ return value;
+}
diff --git a/src/gemini/cache.ts b/src/gemini/cache.ts
new file mode 100644
index 0000000000000000000000000000000000000000..d8d22137b15917e7d8144c6ba4cb05e260848611
--- /dev/null
+++ b/src/gemini/cache.ts
@@ -0,0 +1,200 @@
+import type { RuntimeConfig } from "../config";
+import { errorLogSummary } from "../shared/errors";
+import { log } from "../shared/logging";
+
+type OriginScopedStringCacheOptions = {
+ cachePrefix: string;
+ ttlSec: number;
+ payloadKey: string;
+ logLabel: string;
+ l1MaxEntries?: number;
+};
+
+type OriginScopedStringCachePayload = Record & {
+ created_at_ms?: unknown;
+};
+
+function geminiOrigin(cfg: RuntimeConfig): string {
+ return (cfg.gemini_origin || "https://gemini.google.com").replace(/\/$/, "");
+}
+
+function geminiCacheScope(cfg: RuntimeConfig): string {
+ return geminiOrigin(cfg);
+}
+
+function workerCache(): Cache | null {
+ if (typeof caches === "undefined") return null;
+ const cacheStorage = caches as CacheStorage & { default?: Cache };
+ return cacheStorage.default || null;
+}
+
+export function createOriginScopedStringCache(
+ options: OriginScopedStringCacheOptions,
+) {
+ const refreshes = new Map>();
+ const l1 = new Map();
+ const l1MaxEntries = positiveInt(options.l1MaxEntries, 32);
+
+ const cacheKey = (scope: string): Request =>
+ new Request(`${options.cachePrefix}${encodeURIComponent(scope)}`);
+
+ const setL1 = (
+ scope: string,
+ value: string,
+ now: number = Date.now(),
+ ): void => {
+ l1.delete(scope);
+ l1.set(scope, {
+ value,
+ expiresAt: now + options.ttlSec * 1000,
+ });
+ while (l1.size > l1MaxEntries) {
+ const oldestScope = l1.keys().next().value;
+ if (oldestScope === undefined) break;
+ l1.delete(oldestScope);
+ }
+ };
+
+ const clearL1 = (scope?: string): void => {
+ if (scope) l1.delete(scope);
+ else l1.clear();
+ };
+
+ const put = (
+ cfg: RuntimeConfig,
+ scope: string,
+ value: string,
+ now: number,
+ ): Promise => {
+ const cache = workerCache();
+ if (!cache) return Promise.resolve();
+ return cache
+ .put(
+ cacheKey(scope),
+ new Response(
+ JSON.stringify({
+ [options.payloadKey]: value,
+ created_at_ms: now,
+ }),
+ {
+ headers: {
+ "Content-Type": "application/json",
+ "Cache-Control": `public, max-age=${options.ttlSec}`,
+ },
+ },
+ ),
+ )
+ .catch((e) => {
+ logCacheError(cfg, `failed to cache ${options.logLabel}`, e);
+ });
+ };
+
+ const getCached = async (cfg: RuntimeConfig): Promise => {
+ const scope = geminiCacheScope(cfg);
+ const now = Date.now();
+ const cached = l1.get(scope);
+ if (cached && cached.expiresAt > now) {
+ l1.delete(scope);
+ l1.set(scope, cached);
+ return cached.value;
+ }
+ clearL1(scope);
+ const cache = workerCache();
+ if (!cache) return "";
+ try {
+ const resp = await cache.match(cacheKey(scope));
+ if (!resp) return "";
+ const data = (await resp
+ .json()
+ .catch(() => null)) as OriginScopedStringCachePayload | null;
+ const value = validString(data?.[options.payloadKey]);
+ const createdAt = Number(data?.created_at_ms);
+ if (!value || !Number.isFinite(createdAt)) return "";
+ if (now - createdAt > options.ttlSec * 1000) {
+ await cache.delete(cacheKey(scope)).catch(() => false);
+ return "";
+ }
+ setL1(scope, value, createdAt);
+ return value;
+ } catch (e) {
+ logCacheError(cfg, `failed to read cached ${options.logLabel}`, e);
+ return "";
+ }
+ };
+
+ const deleteCached = async (cfg: RuntimeConfig): Promise => {
+ const scope = geminiCacheScope(cfg);
+ clearL1(scope);
+ const cache = workerCache();
+ if (!cache) return;
+ await cache.delete(cacheKey(scope)).catch(() => false);
+ };
+
+ const setCached = async (
+ cfg: RuntimeConfig,
+ rawValue: string,
+ ): Promise => {
+ const value = validString(rawValue);
+ if (!value) return;
+ const scope = geminiCacheScope(cfg);
+ const now = Date.now();
+ setL1(scope, value, now);
+ const write = put(cfg, scope, value, now);
+ if (cfg.execution_ctx) {
+ cfg.execution_ctx.waitUntil(write);
+ return;
+ }
+ await write;
+ };
+
+ const getFresh = async (
+ cfg: RuntimeConfig,
+ fetchFresh: (cfg: RuntimeConfig) => Promise,
+ ): Promise => {
+ const refreshKey = geminiCacheScope(cfg);
+ const pending = refreshes.get(refreshKey);
+ if (pending) return pending;
+
+ const refresh = (async () => {
+ const value = validString(await fetchFresh(cfg));
+ if (value) await setCached(cfg, value);
+ return value;
+ })();
+ refreshes.set(refreshKey, refresh);
+ try {
+ return await refresh;
+ } finally {
+ refreshes.delete(refreshKey);
+ }
+ };
+
+ return {
+ getCached,
+ setCached,
+ deleteCached,
+ getFresh,
+ reset(): void {
+ clearL1();
+ refreshes.clear();
+ },
+ };
+}
+
+function validString(value: unknown): string {
+ const text = typeof value === "string" ? value.trim() : "";
+ return text ? text : "";
+}
+
+function positiveInt(value: number | undefined, fallback: number): number {
+ return Number.isInteger(value) && Number(value) > 0
+ ? Number(value)
+ : fallback;
+}
+
+function logCacheError(
+ cfg: RuntimeConfig,
+ prefix: string,
+ error: unknown,
+): void {
+ log(cfg, `${prefix} ${errorLogSummary(error)}`);
+}
diff --git a/src/gemini/client/errors.ts b/src/gemini/client/errors.ts
new file mode 100644
index 0000000000000000000000000000000000000000..e11708d26163dbc7ea952e1e6796017703ff0c91
--- /dev/null
+++ b/src/gemini/client/errors.ts
@@ -0,0 +1,207 @@
+import type { ErrorWithMetadata } from "../../shared/types";
+import { promptByteLength } from "../../shared/tokens";
+
+export const LARGE_PROMPT_EMPTY_RESPONSE_MIN_BYTES = 95000;
+export const LARGE_PROMPT_EMPTY_RESPONSE_CODE = "large_prompt_empty_response";
+export const DATA_ANALYSIS_EMPTY_RESPONSE_CODE = "data_analysis_empty_response";
+export const INVALID_GEMINI_COOKIE_CODE = "invalid_gemini_cookie";
+export const UPSTREAM_EMPTY_RESPONSE_CODE = "upstream_empty_response";
+export const UPSTREAM_IMAGE_GENERATION_EMPTY_CODE =
+ "upstream_image_generation_empty";
+export const UPSTREAM_IMAGE_FETCH_FAILED_CODE = "upstream_image_fetch_failed";
+export const UPSTREAM_IMAGE_PROVIDER_ERROR_CODE =
+ "upstream_image_provider_error";
+
+const AUTH_FAILURE_STATUSES = new Set([401, 403]);
+
+type LargePromptConfig =
+ | { current_input_file_min_bytes?: unknown }
+ | null
+ | undefined;
+type CookieConfig = { cookie?: unknown } | null | undefined;
+
+const COOKIE_DIAGNOSTIC_MESSAGES: Record = {
+ missing_cookie: "no Gemini cookie is configured",
+ missing_secure_1psid: "configured cookie is missing __Secure-1PSID",
+ recent_rotation:
+ "cookie rotation was skipped because a rotation ran recently",
+ rotation_rejected: "Google rejected the RotateCookies request",
+ rotation_failed: "RotateCookies returned a non-success status",
+ rotation_no_update:
+ "RotateCookies completed but did not return an updated cookie",
+ rotation_error: "RotateCookies could not be completed",
+ rotation_updated:
+ "cookie rotation succeeded but Gemini still rejected the request",
+ missing_page_at_token: "Gemini page did not return the required auth token",
+};
+
+export function largePromptEmptyResponseThreshold(
+ cfg: LargePromptConfig,
+): number {
+ return Math.max(
+ 0,
+ Number(cfg?.current_input_file_min_bytes) ||
+ LARGE_PROMPT_EMPTY_RESPONSE_MIN_BYTES,
+ );
+}
+
+export function largePromptEmptyResponseError(
+ prompt: unknown,
+ status: unknown,
+ rawLength: number | null,
+ thresholdBytes: unknown = LARGE_PROMPT_EMPTY_RESPONSE_MIN_BYTES,
+): ErrorWithMetadata | null {
+ const bytes = promptByteLength(prompt);
+ const threshold = Math.max(
+ 0,
+ Number(thresholdBytes) || LARGE_PROMPT_EMPTY_RESPONSE_MIN_BYTES,
+ );
+ if (bytes <= threshold) return null;
+ const err: ErrorWithMetadata = new Error(
+ `Context is too long and triggered Gemini Web risk controls, so Gemini returned an empty response ` +
+ `(${bytes} UTF-8 bytes > ${threshold}). This is unrelated to GEMINI_BL; ` +
+ "configure GEMINI_COOKIE so this worker can route long context through txt attachments, or reduce the latest inline request size.",
+ );
+ err.code = LARGE_PROMPT_EMPTY_RESPONSE_CODE;
+ err.promptBytes = bytes;
+ err.thresholdBytes = threshold;
+ err.upstreamStatus = Number(status);
+ err.rawLength = rawLength;
+ return err;
+}
+
+export function isLargePromptEmptyResponseError(e: unknown): boolean {
+ return (
+ !!e &&
+ typeof e === "object" &&
+ (e as Partial).code === LARGE_PROMPT_EMPTY_RESPONSE_CODE
+ );
+}
+
+export function dataAnalysisEmptyResponseError(
+ rawSnippet: unknown,
+ fileRefs: unknown,
+): ErrorWithMetadata | null {
+ if (!fileRefs || !String(rawSnippet || "").includes("data_analysis_tool"))
+ return null;
+ const err: ErrorWithMetadata = new Error(
+ "Gemini accepted the uploaded context file but routed it into the internal data_analysis_tool and returned no final text. " +
+ "This Worker does not implement Gemini Web's follow-up data-analysis tool loop. Try the markdown context-file defaults, lower CURRENT_INPUT_FILE_MIN_BYTES, or disable CURRENT_INPUT_FILE_ENABLED for this request.",
+ );
+ err.code = DATA_ANALYSIS_EMPTY_RESPONSE_CODE;
+ return err;
+}
+
+export function isDataAnalysisEmptyResponseError(e: unknown): boolean {
+ return (
+ !!e &&
+ typeof e === "object" &&
+ (e as Partial).code === DATA_ANALYSIS_EMPTY_RESPONSE_CODE
+ );
+}
+
+export function upstreamEmptyResponseError(
+ status: unknown,
+ rawLength: number | null,
+ context = "",
+): ErrorWithMetadata {
+ const httpStatus = Number(status);
+ const err: ErrorWithMetadata = new Error(
+ `Gemini upstream HTTP ${Number.isFinite(httpStatus) ? httpStatus : String(status)} returned no parseable text` +
+ (context ? ` (${context})` : "") +
+ ". The upstream request completed but the Worker could not extract a final model response.",
+ );
+ err.code = UPSTREAM_EMPTY_RESPONSE_CODE;
+ err.status = 502;
+ err.upstreamStatus = httpStatus;
+ err.rawLength = rawLength;
+ return err;
+}
+
+export function upstreamImageGenerationEmptyError(
+ status: unknown,
+ rawLength: number | null,
+ context = "",
+): ErrorWithMetadata {
+ const httpStatus = Number(status);
+ const err: ErrorWithMetadata = new Error(
+ `Gemini upstream HTTP ${Number.isFinite(httpStatus) ? httpStatus : String(status)} returned no usable generated image` +
+ (context ? ` (${context})` : "") +
+ ". The upstream request completed but the Worker could not extract generated image output.",
+ );
+ err.code = UPSTREAM_IMAGE_GENERATION_EMPTY_CODE;
+ err.status = 502;
+ err.upstreamStatus = httpStatus;
+ err.rawLength = rawLength;
+ return err;
+}
+
+export function upstreamImageFetchFailedError(
+ message: unknown,
+ status: unknown = 502,
+): ErrorWithMetadata {
+ const err: ErrorWithMetadata = new Error(
+ `failed to fetch generated image bytes: ${String(message || "unknown error")}`,
+ );
+ err.code = UPSTREAM_IMAGE_FETCH_FAILED_CODE;
+ err.status = 502;
+ const upstreamStatus = Number(status);
+ if (Number.isFinite(upstreamStatus)) err.upstreamStatus = upstreamStatus;
+ return err;
+}
+
+export function upstreamImageProviderError(code: unknown): ErrorWithMetadata {
+ const err: ErrorWithMetadata = new Error(
+ `Gemini returned image generation provider error code ${String(code || "unknown")}`,
+ );
+ err.code = UPSTREAM_IMAGE_PROVIDER_ERROR_CODE;
+ err.status = 502;
+ return err;
+}
+
+export function invalidGeminiCookieError(
+ cfg: CookieConfig,
+ status: unknown,
+ rawLength: number | null = null,
+ diagnosticReason: unknown = "",
+): ErrorWithMetadata | null {
+ if (!cfg?.cookie || !AUTH_FAILURE_STATUSES.has(Number(status))) return null;
+ const reason = cookieDiagnosticMessage(diagnosticReason);
+ const err: ErrorWithMetadata = new Error(
+ `Gemini rejected the selected account credentials (upstream HTTP ${status}). ` +
+ (reason ? `Diagnostic: ${reason}. ` : "") +
+ "Update GEMINI_COOKIE with valid, unexpired Gemini web session credentials.",
+ );
+ err.code = INVALID_GEMINI_COOKIE_CODE;
+ err.status = 401;
+ err.upstreamStatus = Number(status);
+ err.rawLength = rawLength;
+ if (reason) err.reason = reason;
+ return err;
+}
+
+export function unverifiedGeminiCookieError(
+ reason = "missing Gemini page auth token",
+) {
+ const messageReason = cookieDiagnosticMessage(reason) || reason;
+ const err: ErrorWithMetadata = new Error(
+ `Could not verify the selected Gemini account credentials (${messageReason}). ` +
+ "Update GEMINI_COOKIE with valid, unexpired Gemini web session credentials.",
+ );
+ err.code = INVALID_GEMINI_COOKIE_CODE;
+ err.status = 401;
+ return err;
+}
+
+export function isInvalidGeminiCookieError(e: unknown): boolean {
+ return (
+ !!e &&
+ typeof e === "object" &&
+ (e as Partial).code === INVALID_GEMINI_COOKIE_CODE
+ );
+}
+
+function cookieDiagnosticMessage(reason: unknown): string {
+ const key = String(reason || "").trim();
+ return COOKIE_DIAGNOSTIC_MESSAGES[key] || "";
+}
diff --git a/src/gemini/client/generated-images.ts b/src/gemini/client/generated-images.ts
new file mode 100644
index 0000000000000000000000000000000000000000..15d0cc1034f5ae5985b18e5cdaa6e4da2741bf3a
--- /dev/null
+++ b/src/gemini/client/generated-images.ts
@@ -0,0 +1,218 @@
+import { bytesToBase64 } from "../../attachments/base64";
+import { detectUploadMimeFromBytes } from "../../attachments/mime";
+import type { RuntimeConfig } from "../../config";
+import { errorLogSummary } from "../../shared/errors";
+import { log } from "../../shared/logging";
+import { GEMINI_WEB_USER_AGENT } from "../constants";
+import { httpFetch } from "../transport";
+import { upstreamImageFetchFailedError } from "./errors";
+import type { GeminiParsedImage } from "./parser";
+
+export type GeminiImageOutputFormat = "png" | "jpeg" | "gif" | "webp";
+
+export type GeminiRichImage = GeminiParsedImage & {
+ base64?: string;
+ outputFormat?: GeminiImageOutputFormat;
+};
+
+export type GeneratedImageHydrationLimits = {
+ maxImageBytes: number;
+ maxTotalBytes: number;
+};
+
+export const DEFAULT_GENERATED_IMAGE_HYDRATION_LIMITS = Object.freeze({
+ maxImageBytes: 16 * 1024 * 1024,
+ maxTotalBytes: 48 * 1024 * 1024,
+});
+
+type FetchedImageBytes = {
+ base64: string;
+ outputFormat: GeminiImageOutputFormat;
+ byteLength: number;
+};
+
+class GeneratedImageLimitError extends Error {}
+
+export async function hydrateGeneratedImages(
+ cfg: RuntimeConfig,
+ activeCfg: RuntimeConfig,
+ images: GeminiParsedImage[],
+ limits: GeneratedImageHydrationLimits = DEFAULT_GENERATED_IMAGE_HYDRATION_LIMITS,
+): Promise {
+ const out: GeminiRichImage[] = [];
+ let remainingBytes = Math.max(0, Math.floor(limits.maxTotalBytes));
+ for (const image of images) {
+ if (image.source !== "generated") {
+ out.push(image);
+ continue;
+ }
+ try {
+ if (remainingBytes <= 0)
+ throw new GeneratedImageLimitError(
+ "generated image aggregate byte limit reached",
+ );
+ const fetched = await fetchGeneratedImageBytes(
+ cfg,
+ activeCfg,
+ image,
+ Math.min(remainingBytes, Math.max(0, Math.floor(limits.maxImageBytes))),
+ );
+ remainingBytes -= fetched.byteLength;
+ out.push({
+ ...image,
+ base64: fetched.base64,
+ outputFormat: fetched.outputFormat,
+ });
+ } catch (e) {
+ log(
+ cfg,
+ `generated image fetch failed; returning source url only ${errorLogSummary(e)}`,
+ );
+ out.push(image);
+ }
+ }
+ return out;
+}
+
+async function fetchGeneratedImageBytes(
+ cfg: RuntimeConfig,
+ activeCfg: RuntimeConfig,
+ image: GeminiParsedImage,
+ maxBytes: number,
+): Promise {
+ const headers = generatedImageFetchHeaders(activeCfg);
+ let lastErr: unknown = null;
+ for (const target of generatedImagePreviewFetchUrls(image.url)) {
+ try {
+ return await fetchGeneratedImageBytesFromUrl(
+ cfg,
+ target,
+ headers,
+ maxBytes,
+ );
+ } catch (e) {
+ if (e instanceof GeneratedImageLimitError) throw e;
+ lastErr = e;
+ }
+ }
+ if (lastErr) throw lastErr;
+ throw upstreamImageFetchFailedError("no generated image URL candidates");
+}
+
+async function fetchGeneratedImageBytesFromUrl(
+ cfg: RuntimeConfig,
+ target: string,
+ headers: Record,
+ maxBytes: number,
+): Promise {
+ try {
+ if (maxBytes <= 0)
+ throw new GeneratedImageLimitError("generated image byte limit reached");
+ const resp = await httpFetch(target, {
+ method: "GET",
+ headers,
+ timeoutMs: cfg.request_timeout_sec * 1000,
+ socket: false,
+ cfg,
+ });
+ const bytes = await responseBytes(resp, maxBytes);
+ if (!resp.ok)
+ throw upstreamImageFetchFailedError(
+ `upstream HTTP ${resp.status}`,
+ resp.status,
+ );
+ const outputFormat = outputFormatFromMime(detectUploadMimeFromBytes(bytes));
+ if (!outputFormat)
+ throw upstreamImageFetchFailedError(
+ "response body is not a supported image",
+ resp.status,
+ );
+ return {
+ base64: bytesToBase64(bytes),
+ outputFormat,
+ byteLength: bytes.byteLength,
+ };
+ } catch (e) {
+ if (e instanceof GeneratedImageLimitError) throw e;
+ throw upstreamImageFetchFailedError(e);
+ }
+}
+
+export function generatedImagePreviewFetchUrls(url: string): string[] {
+ const upgraded = generatedImageFetchUpsizedUrl(url);
+ if (!upgraded || upgraded === url) return [url];
+ if (url.includes("=s1024-rj")) return [upgraded, url];
+ return [url, upgraded];
+}
+
+function generatedImageFetchUpsizedUrl(url: string): string {
+ if (url.includes("=s1024-rj")) return url.replace("=s1024-rj", "=s2048-rj");
+ if (/=s\d+-rj(?:$|[])/.test(url)) return url;
+ return `${url}${url.includes("=") ? "" : "=s2048-rj"}`;
+}
+
+export function generatedImageFetchHeaders(
+ cfg: RuntimeConfig,
+): Record {
+ const headers: Record = {
+ Accept: "image/avif,image/webp,image/apng,image/*,*/*;q=0.8",
+ "Accept-Language": "en-US,en;q=0.9",
+ Origin: "https://gemini.google.com",
+ Referer: "https://gemini.google.com/app",
+ "User-Agent": GEMINI_WEB_USER_AGENT,
+ };
+ if (cfg.cookie) headers.Cookie = cfg.cookie;
+ return headers;
+}
+
+async function responseBytes(
+ resp: Awaited>,
+ maxBytes: number,
+): Promise {
+ if (!resp.body) return new Uint8Array(0);
+ const declaredLength = Number(resp.headers.get("content-length"));
+ if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
+ await resp.body.cancel().catch(() => undefined);
+ throw new GeneratedImageLimitError(
+ `generated image exceeds ${maxBytes} byte limit`,
+ );
+ }
+ const reader = resp.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (!value) continue;
+ if (total + value.byteLength > maxBytes) {
+ await reader.cancel().catch(() => undefined);
+ throw new GeneratedImageLimitError(
+ `generated image exceeds ${maxBytes} byte limit`,
+ );
+ }
+ chunks.push(value);
+ total += value.byteLength;
+ }
+ const out = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) {
+ out.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return out;
+}
+
+function outputFormatFromMime(mime: string): GeminiImageOutputFormat | "" {
+ switch (mime) {
+ case "image/png":
+ return "png";
+ case "image/jpeg":
+ return "jpeg";
+ case "image/gif":
+ return "gif";
+ case "image/webp":
+ return "webp";
+ default:
+ return "";
+ }
+}
diff --git a/src/gemini/client/index.ts b/src/gemini/client/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..a21bbf258970d236f377ea15a8a94afb87bc8f1a
--- /dev/null
+++ b/src/gemini/client/index.ts
@@ -0,0 +1,544 @@
+import { getPageTokens } from "../uploads/index";
+import { httpFetch } from "../transport";
+import { abortError, isAbortError, throwIfAborted } from "../../shared/abort";
+import { log } from "../../shared/logging";
+import { uuid } from "../../shared/crypto";
+import {
+ dataAnalysisEmptyResponseError,
+ invalidGeminiCookieError,
+ isDataAnalysisEmptyResponseError,
+ isInvalidGeminiCookieError,
+ isLargePromptEmptyResponseError,
+ largePromptEmptyResponseError,
+ largePromptEmptyResponseThreshold,
+ upstreamImageGenerationEmptyError,
+ upstreamImageProviderError,
+ upstreamEmptyResponseError,
+ unverifiedGeminiCookieError,
+} from "./errors";
+import { buildHeaders, buildPayload, getUrl } from "./protocol";
+import {
+ createStreamTextExtractor,
+ extractResponseParts,
+ extractResponseText,
+ richResponseShapeSummary,
+ wrbResponseShapeSummary,
+} from "./parser";
+import { hydrateGeneratedImages } from "./generated-images";
+import type { GeminiRichImage } from "./generated-images";
+import {
+ configWithCachedGeminiBuildLabel,
+ refreshGeminiBuildLabelForRetry,
+ waitBeforeRetry,
+} from "./retry";
+import {
+ configWithFreshGeminiCookie,
+ rotateGeminiCookieForRetryWithReason,
+} from "../cookies";
+import type { RuntimeConfig } from "../../config";
+import type { ErrorWithMetadata } from "../../shared/types";
+
+type GeminiFileRef =
+ | string
+ | {
+ ref?: unknown;
+ fileRef?: unknown;
+ id?: unknown;
+ name?: unknown;
+ filename?: unknown;
+ };
+
+type GeminiStreamOptions = {
+ signal?: AbortSignal;
+};
+
+type GeminiRichOptions = {
+ hydrateGeneratedImageBytes?: boolean;
+};
+
+export type { GeminiRichImage } from "./generated-images";
+
+export type GeminiRichOutput = {
+ text: string;
+ images: GeminiRichImage[];
+};
+
+export {
+ cleanText,
+ extractResponseParts,
+ extractResponseText,
+ extractTextsFromLine,
+ richResponseShapeSummary,
+ wrbResponseShapeSummary,
+} from "./parser";
+export { buildHeaders, buildPayload, getUrl } from "./protocol";
+export { getFreshGeminiBuildLabel } from "./retry";
+
+async function appendGeminiPageToken(
+ cfg: RuntimeConfig,
+ body: string,
+): Promise {
+ if (cfg.xsrf_token) return `${body}&at=${encodeURIComponent(cfg.xsrf_token)}`;
+ if (!cfg.cookie) return body;
+ const tokens = await getPageTokens(cfg);
+ if (!tokens.at) {
+ log(cfg, "gemini cookie verification failed reason=missing_page_at_token");
+ throw unverifiedGeminiCookieError("missing_page_at_token");
+ }
+ return `${body}&at=${encodeURIComponent(tokens.at)}`;
+}
+
+async function fetchGeminiStreamGenerate(
+ cfg: RuntimeConfig,
+ activeCfg: RuntimeConfig,
+ body: string,
+ signal: AbortSignal | null | undefined = undefined,
+ modelHeaders: Record | null = null,
+ requestId: string | null = null,
+) {
+ const url = getUrl(activeCfg);
+ const headers = await buildHeaders(activeCfg, modelHeaders, requestId);
+ const requestBody = await appendGeminiPageToken(activeCfg, body);
+ return httpFetch(url, {
+ method: "POST",
+ headers,
+ body: requestBody,
+ timeoutMs: cfg.request_timeout_sec * 1000,
+ socket: cfg.upstream_socket,
+ socketFallback: "never",
+ signal,
+ cfg,
+ });
+}
+
+export async function generate(
+ cfg: RuntimeConfig,
+ prompt: string,
+ modelId: number,
+ thinkMode: number,
+ extra: Record | null,
+ fileRefs: GeminiFileRef[] | null | undefined,
+ modelHeaders: Record | null = null,
+): Promise {
+ let lastErr: unknown;
+ let activeCfg = await configWithCachedGeminiBuildLabel(
+ await configWithFreshGeminiCookie(cfg),
+ );
+ let refreshedBL = false;
+ let refreshedCookie = false;
+ const requestId = uuid().toUpperCase();
+ const body = buildPayload(
+ prompt,
+ modelId,
+ thinkMode,
+ fileRefs || null,
+ extra,
+ requestId,
+ );
+ for (let attempt = 0; attempt < cfg.retry_attempts; attempt++) {
+ try {
+ const resp = await fetchGeminiStreamGenerate(
+ cfg,
+ activeCfg,
+ body,
+ undefined,
+ modelHeaders,
+ requestId,
+ );
+ const cookieErr = invalidGeminiCookieError(cfg, resp.status);
+ if (cookieErr) throw cookieErr;
+ const raw = await resp.text();
+ const text = extractResponseText(raw);
+ if (!resp.ok || !text) {
+ const shape =
+ cfg.log_requests && !text ? ` ${wrbResponseShapeSummary(raw)}` : "";
+ log(
+ cfg,
+ `upstream status=${resp.status} rawLen=${raw.length} parsedLen=${text.length}${shape}`,
+ );
+ }
+ if (!text) {
+ const dataAnalysisErr = dataAnalysisEmptyResponseError(raw, fileRefs);
+ if (dataAnalysisErr) throw dataAnalysisErr;
+ const largePromptErr = largePromptEmptyResponseError(
+ prompt,
+ resp.status,
+ raw.length,
+ largePromptEmptyResponseThreshold(cfg),
+ );
+ if (largePromptErr) throw largePromptErr;
+ const refreshedCfg = await refreshGeminiBuildLabelForRetry(
+ cfg,
+ activeCfg,
+ refreshedBL,
+ "",
+ );
+ if (refreshedCfg) {
+ refreshedBL = true;
+ activeCfg = refreshedCfg;
+ continue;
+ }
+ throw upstreamEmptyResponseError(resp.status, raw.length, "non-stream");
+ }
+ return text;
+ } catch (e) {
+ if (isInvalidGeminiCookieError(e) && !refreshedCookie) {
+ const rotated = await rotateGeminiCookieForRetryWithReason(activeCfg);
+ if (rotated.config) {
+ refreshedCookie = true;
+ activeCfg = await configWithCachedGeminiBuildLabel(rotated.config);
+ continue;
+ }
+ throw invalidCookieErrorWithRotationReason(cfg, e, rotated.reason);
+ }
+ if (isInvalidGeminiCookieError(e) && refreshedCookie)
+ throw invalidCookieErrorWithRotationReason(cfg, e, "rotation_updated");
+ if (
+ isLargePromptEmptyResponseError(e) ||
+ isDataAnalysisEmptyResponseError(e) ||
+ isInvalidGeminiCookieError(e)
+ )
+ throw e;
+ lastErr = e;
+ await waitBeforeRetry(cfg, attempt, e, "Retry");
+ }
+ }
+ throw lastErr;
+}
+
+export async function generateRich(
+ cfg: RuntimeConfig,
+ prompt: string,
+ modelId: number,
+ thinkMode: number,
+ extra: Record | null,
+ fileRefs: GeminiFileRef[] | null | undefined,
+ modelHeaders: Record | null = null,
+ options: GeminiRichOptions = {},
+): Promise {
+ let lastErr: unknown;
+ let activeCfg = await configWithCachedGeminiBuildLabel(
+ await configWithFreshGeminiCookie(cfg),
+ );
+ let refreshedBL = false;
+ let refreshedCookie = false;
+ const requestId = uuid().toUpperCase();
+ const body = buildPayload(
+ prompt,
+ modelId,
+ thinkMode,
+ fileRefs || null,
+ extra,
+ requestId,
+ );
+ for (let attempt = 0; attempt < cfg.retry_attempts; attempt++) {
+ try {
+ const resp = await fetchGeminiStreamGenerate(
+ cfg,
+ activeCfg,
+ body,
+ undefined,
+ modelHeaders,
+ requestId,
+ );
+ const cookieErr = invalidGeminiCookieError(cfg, resp.status);
+ if (cookieErr) throw cookieErr;
+ const raw = await resp.text();
+ const parts = extractResponseParts(raw);
+ if (parts.fatalCode) throw upstreamImageProviderError(parts.fatalCode);
+ if (!resp.ok || (!parts.text && !parts.images.length)) {
+ const shape = cfg.log_requests
+ ? ` ${richResponseShapeSummary(raw)}`
+ : "";
+ log(
+ cfg,
+ `rich upstream status=${resp.status} rawLen=${raw.length} parsedTextLen=${parts.text.length} images=${parts.images.length}${shape}`,
+ );
+ }
+ if (!parts.text && !parts.images.length) {
+ const dataAnalysisErr = dataAnalysisEmptyResponseError(raw, fileRefs);
+ if (dataAnalysisErr) throw dataAnalysisErr;
+ const largePromptErr = largePromptEmptyResponseError(
+ prompt,
+ resp.status,
+ raw.length,
+ largePromptEmptyResponseThreshold(cfg),
+ );
+ if (largePromptErr) throw largePromptErr;
+ const refreshedCfg = await refreshGeminiBuildLabelForRetry(
+ cfg,
+ activeCfg,
+ refreshedBL,
+ "",
+ );
+ if (refreshedCfg) {
+ refreshedBL = true;
+ activeCfg = refreshedCfg;
+ continue;
+ }
+ throw upstreamImageGenerationEmptyError(
+ resp.status,
+ raw.length,
+ "non-stream",
+ );
+ }
+ const images =
+ options.hydrateGeneratedImageBytes === false
+ ? parts.images
+ : await hydrateGeneratedImages(cfg, activeCfg, parts.images);
+ return { text: parts.text, images };
+ } catch (e) {
+ if (isInvalidGeminiCookieError(e) && !refreshedCookie) {
+ const rotated = await rotateGeminiCookieForRetryWithReason(activeCfg);
+ if (rotated.config) {
+ refreshedCookie = true;
+ activeCfg = await configWithCachedGeminiBuildLabel(rotated.config);
+ continue;
+ }
+ throw invalidCookieErrorWithRotationReason(cfg, e, rotated.reason);
+ }
+ if (isInvalidGeminiCookieError(e) && refreshedCookie)
+ throw invalidCookieErrorWithRotationReason(cfg, e, "rotation_updated");
+ if (
+ isLargePromptEmptyResponseError(e) ||
+ isDataAnalysisEmptyResponseError(e) ||
+ isInvalidGeminiCookieError(e)
+ )
+ throw e;
+ lastErr = e;
+ await waitBeforeRetry(cfg, attempt, e, "Rich retry");
+ }
+ }
+ throw lastErr;
+}
+
+export async function* generateStream(
+ cfg: RuntimeConfig,
+ prompt: string,
+ modelId: number,
+ thinkMode: number,
+ extra: Record | null,
+ fileRefs: GeminiFileRef[] | null | undefined,
+ options: GeminiStreamOptions = {},
+ modelHeaders: Record | null = null,
+): AsyncIterable {
+ let lastErr: unknown;
+ let yielded = false;
+ let activeCfg = await configWithCachedGeminiBuildLabel(
+ await configWithFreshGeminiCookie(cfg),
+ );
+ let refreshedBL = false;
+ let refreshedCookie = false;
+ const requestId = uuid().toUpperCase();
+ const body = buildPayload(
+ prompt,
+ modelId,
+ thinkMode,
+ fileRefs || null,
+ extra,
+ requestId,
+ );
+ const signal = options?.signal;
+
+ for (let attempt = 0; attempt < cfg.retry_attempts; attempt++) {
+ try {
+ throwIfAborted(signal);
+ const resp = await fetchGeminiStreamGenerate(
+ cfg,
+ activeCfg,
+ body,
+ signal,
+ modelHeaders,
+ requestId,
+ );
+ const cookieErr = invalidGeminiCookieError(cfg, resp.status);
+ if (cookieErr) throw cookieErr;
+ if (!resp.body) {
+ const raw = await resp.text();
+ const text = extractResponseText(raw);
+ if (text) {
+ yielded = true;
+ yield text;
+ }
+ if (!text) {
+ const shape = cfg.log_requests
+ ? ` ${wrbResponseShapeSummary(raw)}`
+ : "";
+ log(
+ cfg,
+ `stream upstream produced no text without body (status=${resp.status}) rawLen=${raw.length}${shape}`,
+ );
+ const dataAnalysisErr = dataAnalysisEmptyResponseError(raw, fileRefs);
+ if (dataAnalysisErr) throw dataAnalysisErr;
+ const largePromptErr = largePromptEmptyResponseError(
+ prompt,
+ resp.status,
+ raw.length,
+ largePromptEmptyResponseThreshold(cfg),
+ );
+ if (largePromptErr) throw largePromptErr;
+ const refreshedCfg = await refreshGeminiBuildLabelForRetry(
+ cfg,
+ activeCfg,
+ refreshedBL,
+ "stream without body",
+ );
+ if (refreshedCfg) {
+ refreshedBL = true;
+ activeCfg = refreshedCfg;
+ continue;
+ }
+ throw upstreamEmptyResponseError(
+ resp.status,
+ raw.length,
+ "stream without body",
+ );
+ }
+ return;
+ }
+ const reader = resp.body.getReader();
+ const decoder = new TextDecoder();
+ const extractor = createStreamTextExtractor();
+ const lineChunks: string[] = [];
+ let lineLength = 0;
+ let rawSnippet = "";
+ let rawLength = 0;
+ const takeLine = (piece: string): string => {
+ if (!lineChunks.length) return piece;
+ if (piece) {
+ lineChunks.push(piece);
+ lineLength += piece.length;
+ }
+ const line = lineChunks.join("");
+ lineChunks.length = 0;
+ lineLength = 0;
+ return line;
+ };
+ const appendLineRemainder = (piece: string): void => {
+ if (!piece) return;
+ lineChunks.push(piece);
+ lineLength += piece.length;
+ };
+ const consumeDecoded = function* (decoded: string): Generator {
+ let lineStart = 0;
+ let idx = decoded.indexOf("\n", lineStart);
+ while (idx >= 0) {
+ const line = takeLine(decoded.slice(lineStart, idx));
+ for (const delta of extractor.consumeLine(line)) yield delta;
+ lineStart = idx + 1;
+ idx = decoded.indexOf("\n", lineStart);
+ }
+ if (lineStart < decoded.length)
+ appendLineRemainder(decoded.slice(lineStart));
+ };
+ while (true) {
+ throwIfAborted(signal);
+ const { done, value } = await reader.read();
+ if (done) break;
+ const decoded = decoder.decode(value, { stream: true });
+ rawLength += decoded.length;
+ if (rawSnippet.length < 500)
+ rawSnippet += decoded.slice(0, 500 - rawSnippet.length);
+ for (const delta of consumeDecoded(decoded)) {
+ yielded = true;
+ yield delta;
+ }
+ }
+ const tail = decoder.decode();
+ if (tail) {
+ rawLength += tail.length;
+ if (rawSnippet.length < 500)
+ rawSnippet += tail.slice(0, 500 - rawSnippet.length);
+ for (const delta of consumeDecoded(tail)) {
+ yielded = true;
+ yield delta;
+ }
+ }
+ if (lineLength > 0) {
+ for (const delta of extractor.consumeLine(takeLine(""))) {
+ yielded = true;
+ yield delta;
+ }
+ }
+ if (!yielded) {
+ const shape = cfg.log_requests
+ ? ` ${wrbResponseShapeSummary(rawSnippet)}`
+ : "";
+ log(
+ cfg,
+ `stream upstream produced no text (status=${resp.status}) rawLen=${rawLength}${shape}`,
+ );
+ const dataAnalysisErr = dataAnalysisEmptyResponseError(
+ rawSnippet,
+ fileRefs,
+ );
+ if (dataAnalysisErr) throw dataAnalysisErr;
+ const largePromptErr = largePromptEmptyResponseError(
+ prompt,
+ resp.status,
+ null,
+ largePromptEmptyResponseThreshold(cfg),
+ );
+ if (largePromptErr) throw largePromptErr;
+ const refreshedCfg = await refreshGeminiBuildLabelForRetry(
+ cfg,
+ activeCfg,
+ refreshedBL,
+ "stream",
+ );
+ if (refreshedCfg) {
+ refreshedBL = true;
+ activeCfg = refreshedCfg;
+ continue;
+ }
+ throw upstreamEmptyResponseError(resp.status, rawLength, "stream");
+ }
+ return;
+ } catch (e) {
+ if (isAbortError(e) || signal?.aborted) throw abortError(signal);
+ if (isInvalidGeminiCookieError(e) && !yielded && !refreshedCookie) {
+ const rotated = await rotateGeminiCookieForRetryWithReason(activeCfg);
+ if (rotated.config) {
+ refreshedCookie = true;
+ activeCfg = await configWithCachedGeminiBuildLabel(rotated.config);
+ continue;
+ }
+ throw invalidCookieErrorWithRotationReason(cfg, e, rotated.reason);
+ }
+ if (isInvalidGeminiCookieError(e) && !yielded && refreshedCookie)
+ throw invalidCookieErrorWithRotationReason(cfg, e, "rotation_updated");
+ if (
+ isLargePromptEmptyResponseError(e) ||
+ isDataAnalysisEmptyResponseError(e) ||
+ isInvalidGeminiCookieError(e)
+ )
+ throw e;
+ lastErr = e;
+ if (
+ !yielded &&
+ (await waitBeforeRetry(cfg, attempt, e, "Stream retry", signal))
+ ) {
+ continue;
+ }
+ throw e;
+ }
+ }
+ if (lastErr) throw lastErr;
+}
+
+function invalidCookieErrorWithRotationReason(
+ cfg: RuntimeConfig,
+ err: unknown,
+ reason: unknown,
+): unknown {
+ const meta =
+ err && typeof err === "object" ? (err as Partial) : {};
+ return (
+ invalidGeminiCookieError(
+ cfg,
+ meta.upstreamStatus || meta.status || 401,
+ typeof meta.rawLength === "number" ? meta.rawLength : null,
+ reason,
+ ) || err
+ );
+}
diff --git a/src/gemini/client/parser.ts b/src/gemini/client/parser.ts
new file mode 100644
index 0000000000000000000000000000000000000000..cad074f2aeba9ce60933185529cc2bd7e909a18d
--- /dev/null
+++ b/src/gemini/client/parser.ts
@@ -0,0 +1,725 @@
+import { trimContinuationOverlap } from "../../shared/tokens";
+
+const STREAM_APPEND_PROBE_CHARS = 64;
+
+type WrbLineParseIssue =
+ | "ok"
+ | "not_wrb_line"
+ | "invalid_envelope_json"
+ | "invalid_envelope_shape"
+ | "missing_inner_payload"
+ | "invalid_inner_json"
+ | "invalid_inner_shape"
+ | "missing_text_parts"
+ | "empty_text_parts";
+
+type WrbLineParseResult = {
+ texts: string[];
+ issue: WrbLineParseIssue;
+ parsedEnvelope: boolean;
+ parsedInner: boolean;
+};
+
+export type GeminiParsedImage = {
+ url: string;
+ source: "generated" | "web";
+ title?: string;
+ alt?: string;
+ imageId?: string;
+ cid?: string;
+ rid?: string;
+ rcid?: string;
+};
+
+export type GeminiResponseParts = {
+ text: string;
+ images: GeminiParsedImage[];
+ fatalCode?: string;
+ candidateCount: number;
+ generatedImageCount: number;
+ webImageCount: number;
+};
+
+export function stripArtifacts(text: unknown): string {
+ let source = String(text || "");
+ if (!source) return "";
+ if (source.indexOf("```") >= 0 && source.indexOf("code_event_index=") >= 0) {
+ source = source.replace(
+ /```(?:python|javascript|text)\?code_(?:reference|stdout)&code_event_index=\d+\n[\s\S]*?```\n?/g,
+ "",
+ );
+ }
+ if (source.indexOf("http://googleusercontent.com/") >= 0) {
+ source = source.replace(
+ /http:\/\/googleusercontent\.com\/\w+\/\d+\n*/g,
+ "",
+ );
+ }
+ return source;
+}
+
+function hasArtifactMarkers(source: string): boolean {
+ return (
+ (source.indexOf("```") >= 0 && source.indexOf("code_event_index=") >= 0) ||
+ source.indexOf("http://googleusercontent.com/") >= 0
+ );
+}
+
+export function cleanText(text: unknown): string {
+ return stripArtifacts(text).trim();
+}
+
+export function extractTextsFromLine(line: unknown): string[] {
+ return parseWrbLine(line).texts;
+}
+
+export function wrbResponseShapeSummary(raw: unknown): string {
+ const source = String(raw || "");
+ let lines = 0;
+ let wrbLines = 0;
+ let parsedEnvelopes = 0;
+ let parsedInners = 0;
+ let textParts = 0;
+ const issues: Record = {};
+ for (const line of iterateLines(source)) {
+ if (!line) continue;
+ lines += 1;
+ const parsed = parseWrbLine(line);
+ if (parsed.issue === "not_wrb_line") continue;
+ wrbLines += 1;
+ if (parsed.parsedEnvelope) parsedEnvelopes += 1;
+ if (parsed.parsedInner) parsedInners += 1;
+ textParts += parsed.texts.length;
+ if (parsed.issue !== "ok")
+ issues[parsed.issue] = (issues[parsed.issue] || 0) + 1;
+ }
+ const topIssue = Object.entries(issues).sort((a, b) => b[1] - a[1])[0];
+ return [
+ `lines=${lines}`,
+ `wrbLines=${wrbLines}`,
+ `parsedEnvelopes=${parsedEnvelopes}`,
+ `parsedInnerPayloads=${parsedInners}`,
+ `textParts=${textParts}`,
+ topIssue ? `topIssue=${topIssue[0]}:${topIssue[1]}` : "",
+ ]
+ .filter(Boolean)
+ .join(" ");
+}
+
+export function richResponseShapeSummary(raw: unknown): string {
+ const parts = extractResponseParts(raw);
+ return [
+ `candidates=${parts.candidateCount}`,
+ `generatedImages=${parts.generatedImageCount}`,
+ `webImages=${parts.webImageCount}`,
+ parts.fatalCode ? `fatalCode=${parts.fatalCode}` : "",
+ wrbResponseShapeSummary(raw),
+ ]
+ .filter(Boolean)
+ .join(" ");
+}
+
+function parseWrbLine(line: unknown): WrbLineParseResult {
+ const source = String(line || "");
+ if (!isWrbResponseLineCandidate(source)) return wrbLineIssue("not_wrb_line");
+ let arr: unknown;
+ try {
+ arr = JSON.parse(source);
+ } catch (_) {
+ return wrbLineIssue("invalid_envelope_json");
+ }
+ if (!Array.isArray(arr) || !Array.isArray(arr[0]))
+ return wrbLineIssue("invalid_envelope_shape");
+ const innerStr = arr[0][2];
+ if (typeof innerStr !== "string")
+ return wrbLineIssue("missing_inner_payload", true);
+ let inner: unknown;
+ try {
+ inner = JSON.parse(innerStr);
+ } catch (_) {
+ return wrbLineIssue("invalid_inner_json", true);
+ }
+ if (!(Array.isArray(inner) && inner.length > 4))
+ return wrbLineIssue("invalid_inner_shape", true, true);
+ const textGroups = inner[4];
+ if (!Array.isArray(textGroups))
+ return wrbLineIssue("missing_text_parts", true, true);
+ const texts: string[] = [];
+ for (const part of textGroups) {
+ if (
+ Array.isArray(part) &&
+ part.length > 1 &&
+ part[1] &&
+ Array.isArray(part[1])
+ ) {
+ for (const t of part[1]) {
+ if (typeof t === "string" && t) texts.push(t);
+ }
+ }
+ }
+ return {
+ texts,
+ issue: texts.length ? "ok" : "empty_text_parts",
+ parsedEnvelope: true,
+ parsedInner: true,
+ };
+}
+
+function wrbLineIssue(
+ issue: WrbLineParseIssue,
+ parsedEnvelope = false,
+ parsedInner = false,
+): WrbLineParseResult {
+ return { texts: [], issue, parsedEnvelope, parsedInner };
+}
+
+function isWrbResponseLineCandidate(source: string): boolean {
+ let i = skipJsonWhitespace(source, 0);
+ if (source.charCodeAt(i) !== 91) return false; // [
+ i = skipJsonWhitespace(source, i + 1);
+ if (source.charCodeAt(i) !== 91) return false; // [
+ i = skipJsonWhitespace(source, i + 1);
+ return source.startsWith('"wrb.fr"', i);
+}
+
+function skipJsonWhitespace(source: string, index: number): number {
+ let cursor = index;
+ while (cursor < source.length) {
+ const c = source.charCodeAt(cursor);
+ if (c !== 32 && c !== 9 && c !== 10 && c !== 13) break;
+ cursor += 1;
+ }
+ return cursor;
+}
+
+export function extractResponseText(raw: unknown): string {
+ let lastText = "";
+ const source = String(raw || "");
+ for (const line of iterateLines(source)) {
+ for (const t of extractTextsFromLine(line)) {
+ if (t.length > lastText.length) lastText = t;
+ }
+ }
+ return cleanText(lastText);
+}
+
+export function extractResponseParts(raw: unknown): GeminiResponseParts {
+ const candidateStates = new Map();
+ let candidateCount = 0;
+ let fatalCode = "";
+ const source = String(raw || "");
+ for (const envelope of parseWrbEnvelopes(source)) {
+ fatalCode ||= fatalCodeFromEnvelope(envelope);
+ const inner = innerPayloadFromEnvelope(envelope);
+ if (!inner) continue;
+ fatalCode ||= fatalCodeFromInner(inner);
+ const candidates = Array.isArray(inner[4]) ? inner[4] : [];
+ const metadata = Array.isArray(inner[1]) ? inner[1] : [];
+ candidateCount += candidates.length;
+ for (let index = 0; index < candidates.length; index++) {
+ const candidate = candidates[index];
+ if (!Array.isArray(candidate)) continue;
+ const next = parseCandidateState(candidate, index, metadata);
+ const prev = candidateStates.get(index);
+ if (!prev || shouldReplaceCandidateState(prev, next))
+ candidateStates.set(index, next);
+ }
+ }
+
+ const selected = selectCandidateState([...candidateStates.values()]);
+ const images = selected ? dedupeImages(selected.images) : [];
+ const generatedImageCount = images.filter(
+ (image) => image.source === "generated",
+ ).length;
+ const webImageCount = images.filter((image) => image.source === "web").length;
+ const text = selected ? cleanText(selected.text) : extractResponseText(raw);
+ const out: GeminiResponseParts = {
+ text,
+ images,
+ candidateCount,
+ generatedImageCount,
+ webImageCount,
+ };
+ if (fatalCode) out.fatalCode = fatalCode;
+ return out;
+}
+
+function parseWrbEnvelopes(source: string): unknown[][] {
+ const framed = parseFramedWrbEnvelopes(source);
+ if (framed.length) return framed;
+ const out: unknown[][] = [];
+ for (const line of iterateLines(source))
+ out.push(...parseWrbEnvelopeJson(line));
+ return out;
+}
+
+function parseWrbEnvelopeJson(sourceValue: unknown): unknown[][] {
+ const source = String(sourceValue || "");
+ let arr: unknown;
+ try {
+ arr = JSON.parse(source);
+ } catch (_) {
+ return [];
+ }
+ return collectWrbEnvelopes(arr);
+}
+
+function innerPayloadFromEnvelope(envelope: unknown[]): unknown[] | null {
+ const innerStr = envelope[2];
+ if (typeof innerStr !== "string") return null;
+ let inner: unknown;
+ try {
+ inner = JSON.parse(innerStr);
+ } catch (_) {
+ return null;
+ }
+ return Array.isArray(inner) ? inner : null;
+}
+
+function parseFramedWrbEnvelopes(raw: string): unknown[][] {
+ let source = raw;
+ if (source.startsWith(")]}'")) source = source.slice(4).trimStart();
+ const out: unknown[][] = [];
+ let pos = 0;
+ while (pos < source.length) {
+ pos = skipFrameWhitespace(source, pos);
+ if (pos >= source.length) break;
+ const marker = readFrameLengthMarker(source, pos);
+ if (!marker) break;
+ const { frameLength, contentStart } = marker;
+ const contentEnd = contentStart + frameLength;
+ if (contentEnd > source.length) break;
+ const chunk = source.slice(contentStart, contentEnd).trim();
+ pos = contentEnd;
+ if (!chunk) continue;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(chunk);
+ } catch (_) {
+ continue;
+ }
+ out.push(...collectWrbEnvelopes(parsed));
+ }
+ return out;
+}
+
+function readFrameLengthMarker(
+ source: string,
+ pos: number,
+): { frameLength: number; contentStart: number } | null {
+ let i = pos;
+ let frameLength = 0;
+ while (i < source.length) {
+ const code = source.charCodeAt(i);
+ if (code === 10) {
+ if (i === pos || !Number.isSafeInteger(frameLength) || frameLength <= 0)
+ return null;
+ return { frameLength, contentStart: i + 1 };
+ }
+ if (code < 48 || code > 57) return null;
+ frameLength = frameLength * 10 + code - 48;
+ if (!Number.isSafeInteger(frameLength)) return null;
+ i += 1;
+ }
+ return null;
+}
+
+function skipFrameWhitespace(source: string, index: number): number {
+ let i = index;
+ while (i < source.length) {
+ const c = source.charCodeAt(i);
+ if (c !== 32 && c !== 9 && c !== 10 && c !== 13) break;
+ i += 1;
+ }
+ return i;
+}
+
+function collectWrbEnvelopes(value: unknown): unknown[][] {
+ const out: unknown[][] = [];
+ collectWrbEnvelopesInto(value, out, 0);
+ return out;
+}
+
+function collectWrbEnvelopesInto(
+ value: unknown,
+ out: unknown[][],
+ depth: number,
+): void {
+ if (!Array.isArray(value) || depth > 3) return;
+ if (isWrbEnvelope(value)) {
+ out.push(value);
+ return;
+ }
+ for (const item of value) collectWrbEnvelopesInto(item, out, depth + 1);
+}
+
+function isWrbEnvelope(value: unknown[]): value is unknown[] {
+ return value[0] === "wrb.fr" && typeof value[2] === "string";
+}
+
+type CandidateState = {
+ index: number;
+ text: string;
+ images: GeminiParsedImage[];
+ completed: boolean;
+};
+
+function parseCandidateState(
+ candidate: unknown[],
+ index: number,
+ metadata: unknown[],
+): CandidateState {
+ const texts: string[] = [];
+ const directText = stringAt(getNested(candidate, [1, 0]));
+ if (directText) texts.push(directText);
+ const cardText = stringAt(getNested(candidate, [22, 0]));
+ if (cardText) texts.push(cardText);
+ const legacyGroup = candidate[1];
+ if (!directText && Array.isArray(legacyGroup)) {
+ for (const item of legacyGroup) {
+ if (typeof item === "string" && item) texts.push(item);
+ }
+ }
+
+ const images: GeminiParsedImage[] = [];
+ const context = candidateContext(candidate, index, metadata);
+ appendGeneratedImages(images, getNested(candidate, [12, 7, 0]), context);
+ appendGeneratedImages(images, getNested(candidate, [12, 0, "8", 0]), context);
+ appendWebImages(images, getNested(candidate, [12, 1]), context);
+
+ return {
+ index,
+ text: texts.join("\n"),
+ images: dedupeImages(images),
+ completed: getNested(candidate, [8, 0]) === 2,
+ };
+}
+
+type CandidateImageContext = {
+ cid?: string;
+ rid?: string;
+ rcid: string;
+};
+
+function candidateContext(
+ candidate: unknown[],
+ index: number,
+ metadata: unknown[],
+): CandidateImageContext {
+ const context: CandidateImageContext = {
+ rcid: stringAt(candidate[0]) || stringAt(metadata[2]) || String(index),
+ };
+ const cid = stringAt(metadata[0]);
+ if (cid) context.cid = cid;
+ const rid = stringAt(metadata[1]);
+ if (rid) context.rid = rid;
+ return context;
+}
+
+function shouldReplaceCandidateState(
+ prev: CandidateState,
+ next: CandidateState,
+): boolean {
+ if (next.completed && !prev.completed) return true;
+ if (prev.completed && !next.completed) return false;
+ if (next.images.length > prev.images.length) return true;
+ return next.text.length >= prev.text.length;
+}
+
+function selectCandidateState(states: CandidateState[]): CandidateState | null {
+ const sorted = states.sort((a, b) => a.index - b.index);
+ return sorted[0] || null;
+}
+
+function appendGeneratedImages(
+ out: GeminiParsedImage[],
+ raw: unknown,
+ context: CandidateImageContext,
+): void {
+ for (const item of generatedImageItems(raw)) {
+ const url =
+ stringAt(getNested(item, [0, 3, 3])) ||
+ stringAt(getNested(item, [0, 0, 0]));
+ if (!url) continue;
+ const image: GeminiParsedImage = {
+ url,
+ source: "generated",
+ rcid: context.rcid,
+ };
+ const alt =
+ stringAt(getNested(item, [0, 3, 2])) ||
+ stringAt(getNested(item, [3, 5, 0]));
+ if (alt) image.alt = alt;
+ const imageId =
+ stringAt(getNested(item, [1, 0])) ||
+ `http://googleusercontent.com/image_generation_content/${out.length}`;
+ image.imageId = imageId;
+ if (context.cid) image.cid = context.cid;
+ if (context.rid) image.rid = context.rid;
+ out.push(image);
+ }
+}
+
+function appendWebImages(
+ out: GeminiParsedImage[],
+ raw: unknown,
+ context: CandidateImageContext,
+): void {
+ for (const item of webImageItems(raw)) {
+ const url = stringAt(getNested(item, [0, 0, 0]));
+ if (!url) continue;
+ const image: GeminiParsedImage = {
+ url,
+ source: "web",
+ rcid: context.rcid,
+ };
+ const alt = stringAt(getNested(item, [0, 4]));
+ if (alt) image.alt = alt;
+ const title = stringAt(getNested(item, [7, 0]));
+ if (title) image.title = title;
+ if (context.cid) image.cid = context.cid;
+ if (context.rid) image.rid = context.rid;
+ out.push(image);
+ }
+}
+
+function generatedImageItems(raw: unknown): unknown[] {
+ const out: unknown[] = [];
+ collectImageItems(raw, out, isGeneratedImageEntry, 0);
+ return out;
+}
+
+function webImageItems(raw: unknown): unknown[] {
+ const out: unknown[] = [];
+ collectImageItems(raw, out, isWebImageEntry, 0);
+ return out;
+}
+
+function collectImageItems(
+ raw: unknown,
+ out: unknown[],
+ isEntry: (value: unknown) => boolean,
+ depth: number,
+): void {
+ if (!Array.isArray(raw) || depth > 5) return;
+ if (isEntry(raw)) {
+ out.push(raw);
+ return;
+ }
+ for (const item of raw) collectImageItems(item, out, isEntry, depth + 1);
+}
+
+function isGeneratedImageEntry(value: unknown): boolean {
+ return !!(
+ stringAt(getNested(value, [0, 3, 3])) ||
+ stringAt(getNested(value, [0, 0, 0]))
+ );
+}
+
+function isWebImageEntry(value: unknown): boolean {
+ return !!stringAt(getNested(value, [0, 0, 0]));
+}
+
+function dedupeImages(images: GeminiParsedImage[]): GeminiParsedImage[] {
+ const out: GeminiParsedImage[] = [];
+ const seen = new Set();
+ for (const image of images) {
+ const key = image.imageId || image.url;
+ if (!key || seen.has(key)) continue;
+ seen.add(key);
+ out.push(image);
+ }
+ return out;
+}
+
+function fatalCodeFromInner(inner: unknown[]): string {
+ return stableFatalCode(getNested(inner, [5, 2, 0, 1, 0]));
+}
+
+function fatalCodeFromEnvelope(envelope: unknown[]): string {
+ return stableFatalCode(getNested(envelope, [5, 2, 0, 1, 0]));
+}
+
+function stableFatalCode(code: unknown): string {
+ const normalized =
+ typeof code === "string" || typeof code === "number"
+ ? String(code).trim()
+ : "";
+ switch (normalized) {
+ case "1013":
+ case "1037":
+ case "1050":
+ case "1052":
+ case "1060":
+ return normalized;
+ default:
+ return "";
+ }
+}
+
+function getNested(
+ value: unknown,
+ path: readonly (number | string)[],
+): unknown {
+ let cur = value;
+ for (const key of path) {
+ if (Array.isArray(cur) && typeof key === "number") {
+ cur = cur[key];
+ continue;
+ }
+ if (isObjectLike(cur) && typeof key === "string") {
+ cur = cur[key];
+ continue;
+ }
+ return undefined;
+ }
+ return cur;
+}
+
+function stringAt(value: unknown): string {
+ return typeof value === "string" && value.trim() ? value : "";
+}
+
+function isObjectLike(value: unknown): value is Record {
+ return !!value && typeof value === "object" && !Array.isArray(value);
+}
+
+function* iterateLines(source: string): Generator {
+ let start = 0;
+ while (start <= source.length) {
+ const idx = source.indexOf("\n", start);
+ if (idx < 0) {
+ yield source.slice(start);
+ return;
+ }
+ yield source.slice(start, idx);
+ start = idx + 1;
+ }
+}
+
+export function createStreamTextExtractor() {
+ let prevVisibleParts: string[] = [];
+ let prevVisibleMaterialized: string | null = "";
+ let prevVisibleLength = 0;
+ let prevVisibleHead = "";
+ let prevVisibleTail = "";
+ let prevRaw = "";
+ let prevRawLength = 0;
+ let prevRawHead = "";
+ let prevRawTail = "";
+ let prevRawHasArtifacts = false;
+ let started = false;
+ const rememberRaw = (raw: string) => {
+ prevRawLength = raw.length;
+ prevRaw = raw.length <= STREAM_APPEND_PROBE_CHARS * 2 ? raw : "";
+ prevRawHead = raw.slice(0, STREAM_APPEND_PROBE_CHARS);
+ prevRawTail = raw.slice(-STREAM_APPEND_PROBE_CHARS);
+ prevRawHasArtifacts = hasArtifactMarkers(raw);
+ };
+ const rememberVisible = (visible: string) => {
+ prevVisibleParts = visible ? [visible] : [];
+ prevVisibleMaterialized = visible;
+ prevVisibleLength = visible.length;
+ prevVisibleHead = visible.slice(0, STREAM_APPEND_PROBE_CHARS);
+ prevVisibleTail = visible.slice(-STREAM_APPEND_PROBE_CHARS);
+ };
+ const materializeVisible = () => {
+ if (prevVisibleMaterialized !== null) return prevVisibleMaterialized;
+ const visible = prevVisibleParts.join("");
+ prevVisibleParts = visible ? [visible] : [];
+ prevVisibleMaterialized = visible;
+ return visible;
+ };
+ const appendVisibleDelta = (delta: string) => {
+ if (!delta) return;
+ const oldLength = prevVisibleLength;
+ prevVisibleParts.push(delta);
+ prevVisibleMaterialized = null;
+ prevVisibleLength += delta.length;
+ if (oldLength < STREAM_APPEND_PROBE_CHARS) {
+ prevVisibleHead = `${prevVisibleHead}${delta}`.slice(
+ 0,
+ STREAM_APPEND_PROBE_CHARS,
+ );
+ }
+ prevVisibleTail = `${prevVisibleTail}${delta}`.slice(
+ -STREAM_APPEND_PROBE_CHARS,
+ );
+ };
+ const rawAppendDelta = (raw: string): string | null => {
+ if (!prevRawLength || raw.length <= prevRawLength || prevRawHasArtifacts)
+ return null;
+ if (prevRawLength <= STREAM_APPEND_PROBE_CHARS * 2) {
+ if (!raw.startsWith(prevRaw)) return null;
+ } else if (
+ raw.slice(0, prevRawHead.length) !== prevRawHead ||
+ raw.slice(prevRawLength - prevRawTail.length, prevRawLength) !==
+ prevRawTail
+ ) {
+ return null;
+ }
+ const delta = raw.slice(prevRawLength);
+ if (hasArtifactMarkers(prevRawTail + delta)) return null;
+ return delta;
+ };
+ const visibleAppendDelta = (visible: string): string | null => {
+ if (!prevVisibleLength || visible.length <= prevVisibleLength) return null;
+ if (prevVisibleLength <= STREAM_APPEND_PROBE_CHARS * 2) {
+ if (!visible.startsWith(materializeVisible())) return null;
+ } else if (
+ visible.slice(0, prevVisibleHead.length) !== prevVisibleHead ||
+ visible.slice(
+ prevVisibleLength - prevVisibleTail.length,
+ prevVisibleLength,
+ ) !== prevVisibleTail
+ ) {
+ return null;
+ }
+ return visible.slice(prevVisibleLength);
+ };
+ const consumeLine = function* (line: unknown): Generator {
+ for (const t of extractTextsFromLine(line)) {
+ const raw = String(t || "");
+ let delta = "";
+ const appendedRawDelta = rawAppendDelta(raw);
+ if (appendedRawDelta !== null) {
+ delta = appendedRawDelta;
+ appendVisibleDelta(delta);
+ rememberRaw(raw);
+ } else {
+ const visible = stripArtifacts(raw);
+ if (!prevVisibleLength) {
+ delta = visible;
+ rememberVisible(visible);
+ rememberRaw(raw);
+ } else {
+ const appendedVisibleDelta = visibleAppendDelta(visible);
+ if (appendedVisibleDelta !== null) {
+ delta = appendedVisibleDelta;
+ rememberVisible(visible);
+ rememberRaw(raw);
+ } else if (materializeVisible().startsWith(visible)) {
+ continue;
+ } else {
+ delta = trimContinuationOverlap(materializeVisible(), visible);
+ if (!delta) {
+ if (visible.length > prevVisibleLength) {
+ rememberVisible(visible);
+ rememberRaw(raw);
+ }
+ continue;
+ }
+ appendVisibleDelta(delta);
+ rememberRaw(raw);
+ }
+ }
+ }
+ if (!started) delta = delta.replace(/^\s+/, "");
+ if (delta) {
+ started = true;
+ yield delta;
+ }
+ }
+ };
+ return { consumeLine };
+}
diff --git a/src/gemini/client/protocol.ts b/src/gemini/client/protocol.ts
new file mode 100644
index 0000000000000000000000000000000000000000..7611448611ec6a69ba633a3650a8c890a2881a5b
--- /dev/null
+++ b/src/gemini/client/protocol.ts
@@ -0,0 +1,184 @@
+import { GEMINI_WEB_USER_AGENT } from "../constants";
+import { makeSapisidHash } from "../auth";
+import { accountPrefix, resinProxyUrl } from "../proxy";
+import { nowSec } from "../../shared/logging";
+import { uuid } from "../../shared/crypto";
+import type { RuntimeConfig } from "../../config";
+
+type PayloadFileRef =
+ | string
+ | {
+ ref?: unknown;
+ fileRef?: unknown;
+ id?: unknown;
+ name?: unknown;
+ filename?: unknown;
+ };
+
+const GEMINI_PAYLOAD_INNER_LENGTH = 102;
+const GEMINI_PAYLOAD_FIELD = {
+ request: 0,
+ language: 1,
+ clientContext: 2,
+ defaultGenerationFlags: 6,
+ requestKind: 7,
+ responseMode: 10,
+ toolMode: 11,
+ thinkingMode: 17,
+ responseSeed: 18,
+ conversationMode: 27,
+ responseOptions: 30,
+ enhancedMode: 31,
+ mediaMode: 41,
+ safetyMode: 53,
+ requestId: 59,
+ toolContext: 61,
+ clientFeature: 68,
+ modelFamily: 79,
+ enhancedRouting: 80,
+} as const;
+const MODEL_EXTRA_PAYLOAD_FIELDS = new Set([
+ GEMINI_PAYLOAD_FIELD.enhancedMode,
+ GEMINI_PAYLOAD_FIELD.enhancedRouting,
+]);
+
+export function buildPayload(
+ prompt: string,
+ modelId: number,
+ thinkMode: number,
+ fileRefs: readonly PayloadFileRef[] | null,
+ extra: Record | null,
+ requestId: string = uuid(),
+): string {
+ const inner = createGeminiPayloadInner(
+ prompt,
+ modelId,
+ thinkMode,
+ fileRefs,
+ requestId.toUpperCase(),
+ );
+ applyModelPayloadExtras(inner, extra);
+ const outer = [null, JSON.stringify(inner)];
+ return new URLSearchParams({ "f.req": JSON.stringify(outer) }).toString();
+}
+
+function createGeminiPayloadInner(
+ prompt: string,
+ modelId: number,
+ thinkMode: number,
+ fileRefs: readonly PayloadFileRef[] | null,
+ requestId: string,
+): unknown[] {
+ const inner = new Array(GEMINI_PAYLOAD_INNER_LENGTH);
+ if (fileRefs?.length) {
+ const files = fileRefs.map((item) => {
+ if (item && typeof item === "object" && !Array.isArray(item)) {
+ return [
+ [item.ref || item.fileRef || item.id || "", 1],
+ item.name || item.filename || "file.txt",
+ ];
+ }
+ return [[item, 1], "file.txt"];
+ });
+ inner[GEMINI_PAYLOAD_FIELD.request] = [
+ prompt,
+ 0,
+ null,
+ files,
+ null,
+ null,
+ 0,
+ ];
+ } else {
+ inner[GEMINI_PAYLOAD_FIELD.request] = [
+ prompt,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ 0,
+ ];
+ }
+ inner[GEMINI_PAYLOAD_FIELD.language] = ["en"];
+ inner[GEMINI_PAYLOAD_FIELD.clientContext] = [
+ "",
+ "",
+ "",
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ "",
+ ];
+ inner[GEMINI_PAYLOAD_FIELD.defaultGenerationFlags] = [0];
+ inner[GEMINI_PAYLOAD_FIELD.requestKind] = 1;
+ inner[GEMINI_PAYLOAD_FIELD.responseMode] = 1;
+ inner[GEMINI_PAYLOAD_FIELD.toolMode] = 0;
+ inner[GEMINI_PAYLOAD_FIELD.thinkingMode] = [[thinkMode]];
+ inner[GEMINI_PAYLOAD_FIELD.responseSeed] = 0;
+ inner[GEMINI_PAYLOAD_FIELD.conversationMode] = 1;
+ inner[GEMINI_PAYLOAD_FIELD.responseOptions] = [4];
+ inner[GEMINI_PAYLOAD_FIELD.mediaMode] = [2];
+ inner[GEMINI_PAYLOAD_FIELD.safetyMode] = 0;
+ inner[GEMINI_PAYLOAD_FIELD.requestId] = requestId;
+ inner[GEMINI_PAYLOAD_FIELD.toolContext] = [];
+ inner[GEMINI_PAYLOAD_FIELD.clientFeature] = 1;
+ inner[GEMINI_PAYLOAD_FIELD.modelFamily] = modelId;
+ return inner;
+}
+
+function applyModelPayloadExtras(
+ inner: unknown[],
+ extra: Record | null,
+): void {
+ if (extra) {
+ for (const k of Object.keys(extra)) {
+ const index = Number(k);
+ if (!Number.isInteger(index) || !MODEL_EXTRA_PAYLOAD_FIELDS.has(index)) {
+ throw new Error(`Unsupported Gemini model extra payload field: ${k}`);
+ }
+ inner[index] = extra[index];
+ }
+ }
+}
+
+export function getUrl(cfg: RuntimeConfig): string {
+ const reqid = nowSec() % 1000000;
+ const prefix = accountPrefix(cfg);
+ const path =
+ `${prefix}/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate` +
+ `?bl=${encodeURIComponent(cfg.gemini_bl)}&hl=en&_reqid=${reqid}&rt=c`;
+ if (cfg.resin_proxy)
+ return resinProxyUrl(cfg, `https://gemini.google.com${path}`);
+ const origin = (cfg.gemini_origin || "https://gemini.google.com").replace(
+ /\/$/,
+ "",
+ );
+ return origin + path;
+}
+
+export async function buildHeaders(
+ cfg: RuntimeConfig,
+ modelHeaders: Record | null = null,
+ requestId: string | null = null,
+): Promise> {
+ const prefix = accountPrefix(cfg);
+ const headers: Record = {
+ "Content-Type": "application/x-www-form-urlencoded",
+ Origin: "https://gemini.google.com",
+ Referer: `https://gemini.google.com${prefix}/app`,
+ "X-Same-Domain": "1",
+ "User-Agent": GEMINI_WEB_USER_AGENT,
+ "Accept-Language": "en-US,en;q=0.9",
+ };
+ if (modelHeaders) Object.assign(headers, modelHeaders);
+ if (requestId)
+ headers["x-goog-ext-525005358-jspb"] = `["${requestId.toUpperCase()}",1]`;
+ if (cfg.cookie) headers.Cookie = cfg.cookie;
+ if (cfg.sapisid) headers.Authorization = await makeSapisidHash(cfg.sapisid);
+ if (prefix) headers["X-Goog-AuthUser"] = cfg.auth_user;
+ return headers;
+}
diff --git a/src/gemini/client/retry.ts b/src/gemini/client/retry.ts
new file mode 100644
index 0000000000000000000000000000000000000000..8e3b902eae8b086b29bebf6f7876d5b936979389
--- /dev/null
+++ b/src/gemini/client/retry.ts
@@ -0,0 +1,99 @@
+import { GEMINI_WEB_USER_AGENT } from "../constants";
+import { httpFetch } from "../transport";
+import { extractGeminiBuildLabel } from "../app-page";
+import { geminiAppUrl } from "../proxy";
+import { createOriginScopedStringCache } from "../cache";
+import { errorLogSummary } from "../../shared/errors";
+import { log } from "../../shared/logging";
+import { sleep } from "../../shared/abort";
+import type { RuntimeConfig } from "../../config";
+
+export const GEMINI_BL_CACHE_TTL_SEC = 12 * 60 * 60;
+
+const buildLabelCache = createOriginScopedStringCache({
+ cachePrefix: "https://internal-cache/gemini-bl/",
+ ttlSec: GEMINI_BL_CACHE_TTL_SEC,
+ payloadKey: "gemini_bl",
+ logLabel: "Gemini BL",
+});
+
+export async function getCachedGeminiBuildLabel(
+ cfg: RuntimeConfig,
+): Promise {
+ return buildLabelCache.getCached(cfg);
+}
+
+export async function setCachedGeminiBuildLabel(
+ cfg: RuntimeConfig,
+ label: string,
+): Promise {
+ await buildLabelCache.setCached(cfg, label);
+}
+
+export async function configWithCachedGeminiBuildLabel(
+ cfg: RuntimeConfig,
+): Promise {
+ const cachedBL = await getCachedGeminiBuildLabel(cfg);
+ if (!cachedBL || cachedBL === cfg.gemini_bl) return cfg;
+ return { ...cfg, gemini_bl: cachedBL };
+}
+
+export async function getFreshGeminiBuildLabel(
+ cfg: RuntimeConfig,
+): Promise {
+ return buildLabelCache.getFresh(cfg, fetchFreshGeminiBuildLabel);
+}
+
+export function resetGeminiBuildLabelCacheForTest(): void {
+ buildLabelCache.reset();
+}
+
+async function fetchFreshGeminiBuildLabel(cfg: RuntimeConfig): Promise {
+ try {
+ const headers: Record = {
+ "User-Agent": GEMINI_WEB_USER_AGENT,
+ "Accept-Language": "en-US,en;q=0.9",
+ };
+ if (cfg.cookie) headers.Cookie = cfg.cookie;
+ const resp = await httpFetch(geminiAppUrl(cfg), {
+ headers,
+ timeoutMs: 30000,
+ socket: cfg.upstream_socket,
+ cfg,
+ });
+ return await extractGeminiBuildLabel(resp);
+ } catch (e) {
+ log(cfg, `failed to refresh Gemini BL ${errorLogSummary(e)}`);
+ return "";
+ }
+}
+
+export async function refreshGeminiBuildLabelForRetry(
+ cfg: RuntimeConfig,
+ activeCfg: RuntimeConfig,
+ alreadyRefreshed: boolean,
+ context: string,
+): Promise {
+ if (alreadyRefreshed) return null;
+ const freshBL = await getFreshGeminiBuildLabel(cfg);
+ if (!freshBL || freshBL === activeCfg.gemini_bl) return null;
+ const suffix = context ? ` ${context}` : "";
+ log(cfg, `retrying${suffix} with refreshed GEMINI_BL=${freshBL}`);
+ return { ...activeCfg, gemini_bl: freshBL };
+}
+
+export async function waitBeforeRetry(
+ cfg: RuntimeConfig,
+ attempt: number,
+ error: unknown,
+ label: string,
+ signal: AbortSignal | null | undefined = undefined,
+): Promise {
+ if (attempt >= Math.max(0, cfg.retry_attempts || 0) - 1) return false;
+ log(
+ cfg,
+ `${label} ${attempt + 1}/${cfg.retry_attempts} ${errorLogSummary(error)}`,
+ );
+ await sleep(cfg.retry_delay_sec * 1000, signal);
+ return true;
+}
diff --git a/src/gemini/completion-provider.ts b/src/gemini/completion-provider.ts
new file mode 100644
index 0000000000000000000000000000000000000000..99a9e830041ca71debcc17f59c313a6fa174b19c
--- /dev/null
+++ b/src/gemini/completion-provider.ts
@@ -0,0 +1,142 @@
+import type { AttachmentPlan } from "../attachments/types";
+import type {
+ CompletionProvider,
+ CompletionProviderOptions,
+ CompletionRichOptions,
+ CompletionTextInput,
+} from "../completion/ports";
+import type { RuntimeConfig } from "../config";
+import type { ResolvedModel } from "../models";
+import { logStage } from "../shared/logging";
+import {
+ generate,
+ generateRich as generateGeminiRich,
+ generateStream,
+} from "./client";
+import { resolveAttachments, uploadTextFile } from "./uploads";
+
+type ResolvedModelOK = Extract;
+type GeminiCompletionProviderDependencies = {
+ generate: typeof generate;
+ generateRich: typeof generateGeminiRich;
+ generateStream: typeof generateStream;
+ resolveAttachments: typeof resolveAttachments;
+ uploadTextFile: typeof uploadTextFile;
+ logStage: typeof logStage;
+};
+
+const defaultDependencies: GeminiCompletionProviderDependencies = {
+ generate,
+ generateRich: generateGeminiRich,
+ generateStream,
+ resolveAttachments,
+ uploadTextFile,
+ logStage,
+};
+
+export function createGeminiCompletionProvider(
+ cfg: RuntimeConfig,
+): CompletionProvider {
+ return createGeminiCompletionProviderWithDependencies(
+ cfg,
+ defaultDependencies,
+ );
+}
+
+export function createGeminiCompletionProviderWithDependenciesForTest(
+ cfg: RuntimeConfig,
+ dependencies: GeminiCompletionProviderDependencies,
+): CompletionProvider {
+ return createGeminiCompletionProviderWithDependencies(cfg, dependencies);
+}
+
+function createGeminiCompletionProviderWithDependencies(
+ cfg: RuntimeConfig,
+ dependencies: GeminiCompletionProviderDependencies,
+): CompletionProvider {
+ return {
+ supportsAuthenticatedSession: !!cfg.cookie,
+ generateText(input: CompletionTextInput) {
+ const model = requireResolvedModel(input.rm);
+ if (cfg.log_requests)
+ logGeminiRoute(dependencies.logStage, cfg, model, false);
+ return dependencies.generate(
+ cfg,
+ input.prompt,
+ model.modeId,
+ model.thinkMode,
+ model.extra,
+ input.fileRefs,
+ model.modelHeaders,
+ );
+ },
+ generateRich(
+ input: CompletionTextInput,
+ options: CompletionRichOptions = {},
+ ) {
+ const model = requireResolvedModel(input.rm);
+ if (cfg.log_requests)
+ logGeminiRoute(dependencies.logStage, cfg, model, false);
+ return dependencies.generateRich(
+ cfg,
+ input.prompt,
+ model.modeId,
+ model.thinkMode,
+ model.extra,
+ input.fileRefs,
+ model.modelHeaders,
+ options,
+ );
+ },
+ async *streamText(
+ input: CompletionTextInput,
+ options: CompletionProviderOptions = {},
+ ) {
+ const model = requireResolvedModel(input.rm);
+ if (cfg.log_requests)
+ logGeminiRoute(dependencies.logStage, cfg, model, true);
+ for await (const delta of dependencies.generateStream(
+ cfg,
+ input.prompt,
+ model.modeId,
+ model.thinkMode,
+ model.extra,
+ input.fileRefs,
+ options,
+ model.modelHeaders,
+ )) {
+ const text = String(delta || "");
+ if (text) yield text;
+ }
+ },
+ resolveAttachments(plan: AttachmentPlan) {
+ return dependencies.resolveAttachments(cfg, plan);
+ },
+ uploadTextFile(text: string, filename: string) {
+ return dependencies.uploadTextFile(cfg, text, filename);
+ },
+ };
+}
+
+function requireResolvedModel(rm: ResolvedModel): ResolvedModelOK {
+ if (rm.name === undefined)
+ throw new Error(rm.error || "model is not resolved");
+ return rm;
+}
+
+function logGeminiRoute(
+ writeLogStage: typeof logStage,
+ cfg: RuntimeConfig,
+ model: ResolvedModelOK,
+ stream: boolean,
+): void {
+ writeLogStage(cfg, "gemini_route", {
+ model: model.name,
+ modelFamily: model.modeId,
+ thinkingMode: model.thinkMode,
+ enhancedMode: model.extra ? model.extra[31] : undefined,
+ enhancedRouting: model.extra ? model.extra[80] : undefined,
+ webModelHeader: !!model.modelHeaders,
+ stream,
+ });
+}
diff --git a/src/gemini/concurrency.ts b/src/gemini/concurrency.ts
new file mode 100644
index 0000000000000000000000000000000000000000..225084c0e73e9573d7b96c589af8350aaa87eef8
--- /dev/null
+++ b/src/gemini/concurrency.ts
@@ -0,0 +1,76 @@
+export async function mapWithConcurrency(
+ items: readonly T[],
+ concurrency: number,
+ mapper: (item: T, index: number) => Promise,
+): Promise {
+ const results = new Array(items.length);
+ let nextIndex = 0;
+ const workerCount = Math.max(
+ 1,
+ Math.min(Math.floor(concurrency) || 1, items.length),
+ );
+ const workers = Array.from({ length: workerCount }, async () => {
+ while (true) {
+ const index = nextIndex;
+ nextIndex += 1;
+ if (index >= items.length) return;
+ results[index] = await mapper(items[index] as T, index);
+ }
+ });
+ await Promise.all(workers);
+ return results;
+}
+
+export async function mapWithConcurrencyAndWeight(
+ items: readonly T[],
+ concurrency: number,
+ maxWeight: number,
+ weightOf: (item: T, index: number) => number,
+ mapper: (item: T, index: number) => Promise,
+): Promise {
+ const limiter = createWeightLimiter(maxWeight);
+ return mapWithConcurrency(items, concurrency, async (item, index) => {
+ const release = await limiter.acquire(weightOf(item, index));
+ try {
+ return await mapper(item, index);
+ } finally {
+ release();
+ }
+ });
+}
+
+function createWeightLimiter(maxWeight: number) {
+ const limit = Math.max(1, Math.floor(maxWeight) || 1);
+ let activeWeight = 0;
+ const queue: Array<{ weight: number; start: () => void }> = [];
+ const drain = (): void => {
+ while (true) {
+ const next = queue[0];
+ if (!next) return;
+ if (activeWeight > 0 && activeWeight + next.weight > limit) return;
+ queue.shift();
+ activeWeight += next.weight;
+ next.start();
+ }
+ };
+ return {
+ acquire(rawWeight: number): Promise<() => void> {
+ const weight = Math.max(0, Math.floor(rawWeight) || 0);
+ return new Promise((resolve) => {
+ queue.push({
+ weight,
+ start: () => {
+ let released = false;
+ resolve(() => {
+ if (released) return;
+ released = true;
+ activeWeight -= weight;
+ drain();
+ });
+ },
+ });
+ drain();
+ });
+ },
+ };
+}
diff --git a/src/gemini/constants.ts b/src/gemini/constants.ts
new file mode 100644
index 0000000000000000000000000000000000000000..4469453b5cbb06c08be88c6ff8b5109d754a2b83
--- /dev/null
+++ b/src/gemini/constants.ts
@@ -0,0 +1,2 @@
+export const GEMINI_WEB_USER_AGENT =
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36";
diff --git a/src/gemini/cookies.ts b/src/gemini/cookies.ts
new file mode 100644
index 0000000000000000000000000000000000000000..12257ce686c87c709dec83a539d1310edd5a9114
--- /dev/null
+++ b/src/gemini/cookies.ts
@@ -0,0 +1,342 @@
+import type { RuntimeConfig } from "../config";
+import { errorLogSummary, log } from "../shared/runtime";
+import { GEMINI_WEB_USER_AGENT } from "./constants";
+import { httpFetch } from "./transport";
+
+export type ActiveCookieState = {
+ cookie: string;
+ sapisid: string;
+ secure1psid: string;
+ secure1psidts: string;
+ updatedAtMs: number;
+ lastRotateAtMs: number;
+ sourceKey: string;
+};
+
+export type CookieRotationReason =
+ | "missing_cookie"
+ | "missing_secure_1psid"
+ | "recent_rotation"
+ | "rotation_rejected"
+ | "rotation_failed"
+ | "rotation_no_update"
+ | "rotation_error"
+ | "rotation_updated";
+
+export type CookieRotationRetryResult = {
+ config: RuntimeConfig | null;
+ reason: CookieRotationReason;
+ upstreamStatus?: number;
+};
+
+export const COOKIE_ROTATE_MIN_INTERVAL_MS = 60 * 1000;
+export const COOKIE_ROTATE_STALE_MS = 10 * 60 * 1000;
+
+let activeCookieState: ActiveCookieState | null = null;
+let rotatePromise: Promise | null = null;
+let lastRotationReason: CookieRotationReason = "missing_cookie";
+let lastRotationUpstreamStatus = 0;
+
+export function parseCookieHeader(cookieHeader: unknown): Map {
+ const map = new Map();
+ const raw = String(cookieHeader || "");
+ for (const part of raw.split(";")) {
+ const trimmed = part.trim();
+ if (!trimmed) continue;
+ const eq = trimmed.indexOf("=");
+ if (eq <= 0) continue;
+ const name = trimmed.slice(0, eq).trim();
+ const value = trimmed.slice(eq + 1).trim();
+ if (name) map.set(name, value);
+ }
+ return map;
+}
+
+export function serializeCookieMap(cookies: Map): string {
+ return Array.from(cookies.entries())
+ .filter(([name]) => !!name)
+ .map(([name, value]) => `${name}=${value}`)
+ .join("; ");
+}
+
+export function extractCookieValue(
+ cookieHeader: unknown,
+ name: string,
+): string {
+ return parseCookieHeader(cookieHeader).get(name) || "";
+}
+
+export function splitSetCookieHeader(header: unknown): string[] {
+ const raw = String(header || "").trim();
+ if (!raw) return [];
+ const out: string[] = [];
+ let start = 0;
+ let inQuote = false;
+ for (let i = 0; i < raw.length; i++) {
+ const ch = raw[i];
+ if (ch === '"' && raw[i - 1] !== "\\") inQuote = !inQuote;
+ if (ch !== "," || inQuote || !looksLikeCookiePair(raw, i + 1)) continue;
+ const part = raw.slice(start, i).trim();
+ if (part) out.push(part);
+ start = i + 1;
+ }
+ const tail = raw.slice(start).trim();
+ if (tail) out.push(tail);
+ return out;
+}
+
+export function setCookieHeaders(headers: Headers): string[] {
+ return headers.getSetCookie();
+}
+
+export function mergeSetCookieHeaders(
+ cookieHeader: unknown,
+ setCookieValues: readonly string[],
+): string {
+ const cookies = parseCookieHeader(cookieHeader);
+ for (const setCookie of setCookieValues) {
+ const first =
+ String(setCookie || "")
+ .split(";")[0]
+ ?.trim() || "";
+ const eq = first.indexOf("=");
+ if (eq <= 0) continue;
+ const name = first.slice(0, eq).trim();
+ const value = first.slice(eq + 1).trim();
+ if (name) cookies.set(name, value);
+ }
+ return serializeCookieMap(cookies);
+}
+
+export function configWithActiveGeminiCookie(
+ cfg: RuntimeConfig,
+): RuntimeConfig {
+ const state = ensureActiveCookieState(cfg);
+ if (!state) return cfg;
+ return {
+ ...cfg,
+ cookie: state.cookie,
+ sapisid: state.sapisid || cfg.sapisid,
+ };
+}
+
+export async function configWithFreshGeminiCookie(
+ cfg: RuntimeConfig,
+): Promise {
+ const state = ensureActiveCookieState(cfg);
+ if (!state) return cfg;
+ if (Date.now() - state.updatedAtMs > COOKIE_ROTATE_STALE_MS) {
+ const refreshed = await rotateGeminiCookie(cfg, { force: false });
+ if (refreshed)
+ return {
+ ...cfg,
+ cookie: refreshed.cookie,
+ sapisid: refreshed.sapisid || cfg.sapisid,
+ };
+ }
+ return configWithActiveGeminiCookie(cfg);
+}
+
+export async function rotateGeminiCookieForRetry(
+ cfg: RuntimeConfig,
+): Promise {
+ return (await rotateGeminiCookieForRetryWithReason(cfg)).config;
+}
+
+export async function rotateGeminiCookieForRetryWithReason(
+ cfg: RuntimeConfig,
+): Promise {
+ const current = configWithActiveGeminiCookie(cfg);
+ const refreshed = await rotateGeminiCookie(current, { force: true });
+ if (!refreshed || refreshed.cookie === current.cookie) {
+ return rotationRetryResult(null);
+ }
+ return rotationRetryResult({
+ ...cfg,
+ cookie: refreshed.cookie,
+ sapisid: refreshed.sapisid || cfg.sapisid,
+ });
+}
+
+async function rotateGeminiCookie(
+ cfg: RuntimeConfig,
+ options: { force: boolean },
+): Promise {
+ const state = ensureActiveCookieState(cfg);
+ if (!state) {
+ setRotationReason("missing_cookie");
+ return null;
+ }
+ if (!state.secure1psid) {
+ setRotationReason("missing_secure_1psid");
+ log(cfg, "gemini cookie rotation skipped reason=missing_secure_1psid");
+ return state;
+ }
+ if (rotatePromise) return rotatePromise;
+
+ const now = Date.now();
+ if (
+ !options.force &&
+ now - state.lastRotateAtMs < COOKIE_ROTATE_MIN_INTERVAL_MS
+ )
+ return state;
+ if (
+ options.force &&
+ now - state.lastRotateAtMs < COOKIE_ROTATE_MIN_INTERVAL_MS
+ ) {
+ setRotationReason("recent_rotation");
+ log(cfg, "gemini cookie rotation skipped reason=recent_rotation");
+ return state;
+ }
+
+ state.lastRotateAtMs = now;
+ rotatePromise = rotateGeminiCookieOnce(cfg, state).finally(() => {
+ rotatePromise = null;
+ });
+ return rotatePromise;
+}
+
+async function rotateGeminiCookieOnce(
+ cfg: RuntimeConfig,
+ state: ActiveCookieState,
+): Promise {
+ try {
+ const resp = await httpFetch("https://accounts.google.com/RotateCookies", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Origin: "https://accounts.google.com",
+ Referer: "https://accounts.google.com/",
+ "User-Agent": GEMINI_WEB_USER_AGENT,
+ "Accept-Language": "en-US,en;q=0.9",
+ Cookie: state.cookie,
+ },
+ body: '[000,"-0000000000000000000"]',
+ timeoutMs: Math.min(
+ Math.max(Number(cfg.request_timeout_sec) || 30, 1) * 1000,
+ 30000,
+ ),
+ socket: cfg.upstream_socket,
+ socketFallback: "never",
+ cfg,
+ });
+ if (resp.status === 401 || resp.status === 403) {
+ setRotationReason("rotation_rejected", resp.status);
+ log(cfg, `gemini cookie rotation rejected upstreamStatus=${resp.status}`);
+ return state;
+ }
+ if (!resp.ok) {
+ setRotationReason("rotation_failed", resp.status);
+ log(cfg, `gemini cookie rotation failed upstreamStatus=${resp.status}`);
+ return state;
+ }
+
+ const mergedCookie = mergeSetCookieHeaders(
+ state.cookie,
+ setCookieHeaders(resp.headers),
+ );
+ const next = stateFromCookie(
+ mergedCookie,
+ state.sourceKey,
+ state.lastRotateAtMs,
+ cfg.sapisid,
+ );
+ if (!next || next.cookie === state.cookie) {
+ setRotationReason("rotation_no_update");
+ log(cfg, "gemini cookie rotation completed without cookie update");
+ return state;
+ }
+ activeCookieState = next;
+ setRotationReason("rotation_updated");
+ log(cfg, "gemini cookie rotation updated active cookie");
+ return next;
+ } catch (e) {
+ setRotationReason("rotation_error");
+ log(cfg, `gemini cookie rotation error ${errorLogSummary(e)}`);
+ return state;
+ }
+}
+
+function ensureActiveCookieState(cfg: RuntimeConfig): ActiveCookieState | null {
+ if (!cfg.cookie) {
+ activeCookieState = null;
+ return null;
+ }
+ const sourceKey = cookieSourceKey(cfg);
+ if (activeCookieState && activeCookieState.sourceKey === sourceKey)
+ return activeCookieState;
+ activeCookieState = stateFromCookie(cfg.cookie, sourceKey, 0, cfg.sapisid);
+ return activeCookieState;
+}
+
+function stateFromCookie(
+ cookie: string,
+ sourceKey: string,
+ lastRotateAtMs: number,
+ sapisidOverride?: unknown,
+): ActiveCookieState | null {
+ const cookies = parseCookieHeader(cookie);
+ const normalizedCookie = serializeCookieMap(cookies);
+ if (!normalizedCookie) return null;
+ const sapisid = String(sapisidOverride || cookies.get("SAPISID") || "");
+ return {
+ cookie: normalizedCookie,
+ sapisid,
+ secure1psid: cookies.get("__Secure-1PSID") || "",
+ secure1psidts: cookies.get("__Secure-1PSIDTS") || "",
+ updatedAtMs: Date.now(),
+ lastRotateAtMs,
+ sourceKey,
+ };
+}
+
+function cookieSourceKey(cfg: RuntimeConfig): string {
+ const secure1psid = extractCookieValue(cfg.cookie, "__Secure-1PSID");
+ const sapisid = String(
+ cfg.sapisid || extractCookieValue(cfg.cookie, "SAPISID") || "",
+ );
+ return `${secure1psid || cfg.cookie || ""}\x00${sapisid}`;
+}
+
+export function resetActiveGeminiCookieForTest(): void {
+ activeCookieState = null;
+ rotatePromise = null;
+ setRotationReason("missing_cookie");
+}
+
+function looksLikeCookiePair(raw: string, from: number): boolean {
+ let i = from;
+ while (i < raw.length && /\s/.test(raw[i] || "")) i++;
+ const nameStart = i;
+ while (i < raw.length) {
+ const ch = raw[i] || "";
+ if (ch === "=") return i > nameStart;
+ if (ch === ";" || ch === "," || /\s/.test(ch)) return false;
+ i++;
+ }
+ return false;
+}
+
+function setRotationReason(
+ reason: CookieRotationReason,
+ upstreamStatus = 0,
+): void {
+ lastRotationReason = reason;
+ lastRotationUpstreamStatus = upstreamStatus;
+}
+
+function rotationRetryResult(
+ config: RuntimeConfig | null,
+): CookieRotationRetryResult {
+ const result: CookieRotationRetryResult = {
+ config,
+ reason: lastRotationReason,
+ };
+ if (lastRotationUpstreamStatus)
+ result.upstreamStatus = lastRotationUpstreamStatus;
+ return result;
+}
+
+export function getLastGeminiCookieRotationReasonForTest(): CookieRotationRetryResult {
+ return rotationRetryResult(null);
+}
diff --git a/src/gemini/proxy.ts b/src/gemini/proxy.ts
new file mode 100644
index 0000000000000000000000000000000000000000..44eda84caa790e534c2c5b3f8ceab03aee2db241
--- /dev/null
+++ b/src/gemini/proxy.ts
@@ -0,0 +1,30 @@
+import type { RuntimeConfig } from "../config";
+
+// Resin 反向代理 URL 重写: https://host/path -> /host/path。
+// 未配置 resin_proxy 或非 https URL 时原样返回。
+export function resinProxyUrl(cfg: RuntimeConfig, url: string): string {
+ const prefix = String(cfg?.resin_proxy || "")
+ .trim()
+ .replace(/\/$/, "");
+ if (!prefix || typeof url !== "string" || !url.startsWith("https://"))
+ return url;
+ return `${prefix}/${url.slice("https://".length)}`;
+}
+
+// 登录账号路径前缀 (/u/{auth_user});未配置 auth_user 时返回空串。
+export function accountPrefix(cfg: RuntimeConfig): string {
+ const user = String(cfg?.auth_user || "").trim();
+ return user ? `/u/${user}` : "";
+}
+
+// Gemini app 页面 URL,用于抓取 page token 与刷新 BL(经 resin_proxy 重写)。
+export function geminiAppUrl(cfg: RuntimeConfig): string {
+ const prefix = accountPrefix(cfg);
+ const raw = `https://gemini.google.com${prefix}/app`;
+ if (cfg?.resin_proxy) return resinProxyUrl(cfg, raw);
+ const origin = (cfg?.gemini_origin || "https://gemini.google.com").replace(
+ /\/$/,
+ "",
+ );
+ return `${origin}${prefix}/app`;
+}
diff --git a/src/gemini/transport/body-stream.ts b/src/gemini/transport/body-stream.ts
new file mode 100644
index 0000000000000000000000000000000000000000..87d911b23d7566fd8f432a02c4b571d2ffe8e302
--- /dev/null
+++ b/src/gemini/transport/body-stream.ts
@@ -0,0 +1,150 @@
+import { createByteQueue } from "./byte-queue";
+import type { ByteChunk, SocketTimeoutScope } from "./socket-types";
+
+type SocketBodyStreamOptions = {
+ reader: ReadableStreamDefaultReader;
+ timeout: SocketTimeoutScope;
+ pending: ByteChunk;
+ noBody: boolean;
+ chunked: boolean;
+ contentLength: number | null;
+ keepAliveEligible: boolean;
+ cleanupBody: (reuse: boolean) => void;
+};
+
+export function createSocketBodyStream({
+ reader,
+ timeout,
+ pending,
+ noBody,
+ chunked,
+ contentLength,
+ keepAliveEligible,
+ cleanupBody,
+}: SocketBodyStreamOptions): ReadableStream {
+ const queue = createByteQueue(pending);
+ let fixedRemaining = contentLength == null ? null : contentLength;
+ let chunkRemaining = 0;
+ let bodyDone = false;
+
+ const pullToQueue = async () => {
+ const { done, value } = await timeout.wait(
+ reader.read(),
+ "response body idle",
+ );
+ if (done) return false;
+ queue.push(value);
+ return true;
+ };
+
+ const readAvailableLine = async () => {
+ let line = queue.readLineIfAvailable();
+ while (line === null) {
+ if (!(await pullToQueue())) return null;
+ line = queue.readLineIfAvailable();
+ }
+ return line;
+ };
+ const readAvailableChunkSize = async () => {
+ let parsed = queue.readHttpChunkSizeLineIfAvailable();
+ while (parsed === null) {
+ if (!(await pullToQueue())) return null;
+ parsed = queue.readHttpChunkSizeLineIfAvailable();
+ }
+ return parsed;
+ };
+
+ const closeController = (
+ controller: ReadableStreamDefaultController,
+ ) => {
+ if (bodyDone) return;
+ bodyDone = true;
+ cleanupBody(keepAliveEligible && queue.length === 0);
+ controller.close();
+ };
+
+ return new ReadableStream({
+ start(controller) {
+ if (noBody) closeController(controller);
+ },
+ async pull(controller) {
+ if (bodyDone) return;
+ try {
+ if (chunked) {
+ for (;;) {
+ if (chunkRemaining > 0) {
+ while (queue.length <= 0) {
+ if (!(await pullToQueue()))
+ throw new Error("socket: incomplete chunked body");
+ }
+ const take = Math.min(chunkRemaining, queue.length);
+ const out = queue.read(take);
+ chunkRemaining -= out.length;
+ controller.enqueue(out);
+ if (chunkRemaining === 0) {
+ while (queue.length < 2) {
+ if (!(await pullToQueue()))
+ throw new Error("socket: incomplete chunked body");
+ }
+ if (!queue.skipCRLF())
+ throw new Error("socket: invalid chunk terminator");
+ }
+ return;
+ }
+ const parsedSize = await readAvailableChunkSize();
+ if (parsedSize === null)
+ throw new Error("socket: incomplete chunked body");
+ chunkRemaining = parsedSize.size;
+ if (chunkRemaining < 0)
+ throw new Error(
+ `socket: invalid chunk size: ${parsedSize.errorLine}`,
+ );
+ if (chunkRemaining === 0) {
+ for (;;) {
+ const trailer = await readAvailableLine();
+ if (trailer === null || trailer.length === 0) {
+ closeController(controller);
+ return;
+ }
+ }
+ }
+ }
+ } else if (fixedRemaining != null) {
+ if (fixedRemaining <= 0) {
+ closeController(controller);
+ return;
+ }
+ while (queue.length <= 0) {
+ if (!(await pullToQueue()))
+ throw new Error("socket: incomplete fixed-length body");
+ }
+ const out = queue.read(Math.min(fixedRemaining, queue.length));
+ fixedRemaining -= out.length;
+ controller.enqueue(out);
+ if (fixedRemaining <= 0) closeController(controller);
+ } else {
+ if (queue.length) {
+ queue.drain(controller);
+ return;
+ }
+ const { done, value } = await timeout.wait(
+ reader.read(),
+ "response body idle",
+ );
+ if (done) {
+ closeController(controller);
+ return;
+ }
+ if (value?.length) controller.enqueue(value);
+ }
+ } catch (e) {
+ bodyDone = true;
+ cleanupBody(false);
+ controller.error(e);
+ }
+ },
+ cancel() {
+ cleanupBody(false);
+ },
+ });
+}
diff --git a/src/gemini/transport/byte-queue.ts b/src/gemini/transport/byte-queue.ts
new file mode 100644
index 0000000000000000000000000000000000000000..152c2ab4f02cacfa0a5aabc9f9f8cf0caac00eb4
--- /dev/null
+++ b/src/gemini/transport/byte-queue.ts
@@ -0,0 +1,340 @@
+import { TEXT_ENCODER } from "../../shared/encoding";
+import type { ByteChunk, ByteQueue } from "./socket-types";
+
+export function _joinByteChunks(
+ chunks: readonly ByteChunk[] | null | undefined,
+ totalLength: number,
+): ByteChunk {
+ if (!chunks?.length) return new Uint8Array(0);
+ if (chunks.length === 1) return chunks[0] || new Uint8Array(0);
+ const out = new Uint8Array(totalLength);
+ let offset = 0;
+ for (const chunk of chunks) {
+ out.set(chunk, offset);
+ offset += chunk.length;
+ }
+ return out;
+}
+
+export function bytesFromBody(body: unknown): ByteChunk | null {
+ if (body == null) return null;
+ if (typeof body === "string") return TEXT_ENCODER.encode(body);
+ if (body instanceof Uint8Array) return body;
+ if (body instanceof ArrayBuffer) return new Uint8Array(body);
+ if (ArrayBuffer.isView(body))
+ return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
+ return new Uint8Array(body as ArrayBufferLike);
+}
+
+export function createByteQueue(initial?: ByteChunk | null): ByteQueue {
+ const chunks: ByteChunk[] = [];
+ let headIndex = 0;
+ let headOffset = 0;
+ let length = 0;
+ let scanActive = false;
+ let scanChunkIndex = 0;
+ let scanOffset = 0;
+ let scanBytes = 0;
+ let scanPrev = -1;
+ let scanMode: "line" | "http-chunk-size" | null = null;
+ let scanHttpSize = 0;
+ let scanHttpDigits = 0;
+ let scanHttpInvalid = false;
+ let scanHttpAfterDigitWhitespace = false;
+ let scanHttpInExtension = false;
+ let scanHttpErrorLine = "";
+ if (initial?.length) {
+ chunks.push(initial);
+ length = initial.length;
+ }
+ const resetScan = () => {
+ scanActive = false;
+ scanChunkIndex = headIndex;
+ scanOffset = headOffset;
+ scanBytes = 0;
+ scanPrev = -1;
+ scanMode = null;
+ scanHttpSize = 0;
+ scanHttpDigits = 0;
+ scanHttpInvalid = false;
+ scanHttpAfterDigitWhitespace = false;
+ scanHttpInExtension = false;
+ scanHttpErrorLine = "";
+ };
+ const ensureScan = (mode: "line" | "http-chunk-size") => {
+ if (
+ scanActive &&
+ scanMode === mode &&
+ scanChunkIndex >= headIndex &&
+ (scanChunkIndex !== headIndex || scanOffset >= headOffset)
+ )
+ return;
+ scanActive = true;
+ scanChunkIndex = headIndex;
+ scanOffset = headOffset;
+ scanBytes = 0;
+ scanPrev = -1;
+ scanMode = mode;
+ scanHttpSize = 0;
+ scanHttpDigits = 0;
+ scanHttpInvalid = false;
+ scanHttpAfterDigitWhitespace = false;
+ scanHttpInExtension = false;
+ scanHttpErrorLine = "";
+ };
+ const compact = () => {
+ while (headIndex < chunks.length) {
+ const first = chunks[headIndex];
+ if (!first || headOffset < first.length) break;
+ headOffset -= first.length;
+ headIndex += 1;
+ }
+ if (headIndex >= chunks.length) {
+ chunks.length = 0;
+ headIndex = 0;
+ headOffset = 0;
+ resetScan();
+ } else if (headIndex > 32 && headIndex * 2 >= chunks.length) {
+ chunks.splice(0, headIndex);
+ if (scanActive) scanChunkIndex = Math.max(0, scanChunkIndex - headIndex);
+ headIndex = 0;
+ }
+ };
+ const readByte = (): number => {
+ compact();
+ if (headIndex >= chunks.length) return -1;
+ const first = chunks[headIndex];
+ if (!first) return -1;
+ const value = first[headOffset];
+ if (value === undefined) return -1;
+ headOffset += 1;
+ length -= 1;
+ compact();
+ resetScan();
+ return value;
+ };
+ const consumeLine = (
+ lineLength: number,
+ consumeLength: number,
+ ): ByteChunk => {
+ compact();
+ const out = lineLength > 0 ? new Uint8Array(lineLength) : new Uint8Array(0);
+ let copied = 0;
+ let remaining = consumeLength;
+ while (remaining > 0) {
+ compact();
+ const first = chunks[headIndex];
+ if (!first) break;
+ const take = Math.min(remaining, first.length - headOffset);
+ const copy = Math.min(take, lineLength - copied);
+ if (copy > 0) {
+ out.set(first.subarray(headOffset, headOffset + copy), copied);
+ copied += copy;
+ }
+ headOffset += take;
+ length -= take;
+ remaining -= take;
+ }
+ compact();
+ resetScan();
+ return out;
+ };
+ const consumeBytes = (consumeLength: number) => {
+ compact();
+ let remaining = consumeLength;
+ while (remaining > 0) {
+ const first = chunks[headIndex];
+ if (!first) break;
+ const take = Math.min(remaining, first.length - headOffset);
+ headOffset += take;
+ length -= take;
+ remaining -= take;
+ if (headOffset >= first.length) {
+ headIndex += 1;
+ headOffset = 0;
+ }
+ }
+ compact();
+ resetScan();
+ };
+ const scanHttpChunkSizeByte = (b: number) => {
+ if (scanHttpInExtension) return;
+ if (b === 59) {
+ if (scanHttpDigits <= 0 || scanHttpAfterDigitWhitespace)
+ scanHttpInvalid = true;
+ scanHttpInExtension = true;
+ return;
+ }
+ if (scanHttpErrorLine.length < 80)
+ scanHttpErrorLine += b >= 32 && b <= 126 ? String.fromCharCode(b) : "?";
+ if (isHttpWhitespaceByte(b)) {
+ if (scanHttpDigits > 0) scanHttpAfterDigitWhitespace = true;
+ return;
+ }
+ if (scanHttpAfterDigitWhitespace) {
+ scanHttpInvalid = true;
+ return;
+ }
+ const nibble = hexNibbleByte(b);
+ if (nibble < 0) {
+ scanHttpInvalid = true;
+ return;
+ }
+ scanHttpDigits += 1;
+ scanHttpSize = scanHttpSize * 16 + nibble;
+ if (!Number.isSafeInteger(scanHttpSize)) scanHttpInvalid = true;
+ };
+ const api: ByteQueue = {
+ get length() {
+ return length;
+ },
+ push(chunk: ByteChunk | null | undefined) {
+ if (!chunk?.length) return;
+ chunks.push(chunk);
+ length += chunk.length;
+ },
+ read(n: unknown) {
+ const count = Math.max(0, Math.min(Number(n) || 0, length));
+ if (!count) return new Uint8Array(0);
+ compact();
+ const first = chunks[headIndex];
+ if (first) {
+ const available = first.length - headOffset;
+ if (count <= available) {
+ const out = first.subarray(headOffset, headOffset + count);
+ headOffset += count;
+ length -= count;
+ compact();
+ resetScan();
+ return out;
+ }
+ }
+ const out = new Uint8Array(count);
+ let offset = 0;
+ while (offset < count) {
+ compact();
+ const nextChunk = chunks[headIndex];
+ if (!nextChunk) break;
+ const take = Math.min(count - offset, nextChunk.length - headOffset);
+ out.set(nextChunk.subarray(headOffset, headOffset + take), offset);
+ headOffset += take;
+ offset += take;
+ length -= take;
+ }
+ compact();
+ resetScan();
+ return out;
+ },
+ readLine() {
+ const out: number[] = [];
+ for (;;) {
+ const b = readByte();
+ if (b < 0) return null;
+ if (b === 13) {
+ const next = readByte();
+ if (next === 10) return new Uint8Array(out);
+ out.push(b);
+ if (next >= 0) out.push(next);
+ continue;
+ }
+ out.push(b);
+ }
+ },
+ readLineIfAvailable() {
+ compact();
+ ensureScan("line");
+ for (let c = scanChunkIndex; c < chunks.length; c++) {
+ const chunk = chunks[c];
+ if (!chunk) continue;
+ let start = 0;
+ if (c === scanChunkIndex) start = scanOffset;
+ else if (c === headIndex) start = headOffset;
+ for (let i = start; i < chunk.length; i++) {
+ const b = chunk[i];
+ if (b === undefined) continue;
+ if (scanPrev === 13 && b === 10) {
+ return consumeLine(scanBytes - 1, scanBytes + 1);
+ }
+ scanPrev = b;
+ scanBytes += 1;
+ scanChunkIndex = c;
+ scanOffset = i + 1;
+ }
+ scanChunkIndex = c + 1;
+ scanOffset = 0;
+ }
+ return null;
+ },
+ readHttpChunkSizeLineIfAvailable() {
+ compact();
+ ensureScan("http-chunk-size");
+ for (let c = scanChunkIndex; c < chunks.length; c++) {
+ const chunk = chunks[c];
+ if (!chunk) continue;
+ let start = 0;
+ if (c === scanChunkIndex) start = scanOffset;
+ else if (c === headIndex) start = headOffset;
+ for (let i = start; i < chunk.length; i++) {
+ const b = chunk[i];
+ if (b === undefined) continue;
+ if (scanPrev === 13 && b === 10) {
+ const result = {
+ size: scanHttpInvalid || scanHttpDigits <= 0 ? -1 : scanHttpSize,
+ errorLine: trimHttpChunkSizeErrorLine(scanHttpErrorLine),
+ };
+ consumeBytes(scanBytes + 1);
+ return result;
+ }
+ if (scanPrev >= 0 && !scanHttpInExtension)
+ scanHttpChunkSizeByte(scanPrev);
+ scanPrev = b;
+ scanBytes += 1;
+ scanChunkIndex = c;
+ scanOffset = i + 1;
+ }
+ scanChunkIndex = c + 1;
+ scanOffset = 0;
+ }
+ return null;
+ },
+ skipCRLF() {
+ const a = readByte();
+ const b = readByte();
+ return a === 13 && b === 10;
+ },
+ drain(controller: ReadableStreamDefaultController) {
+ compact();
+ if (!length) return;
+ while (headIndex < chunks.length) {
+ const first = chunks[headIndex];
+ if (!first) break;
+ const out = headOffset ? first.subarray(headOffset) : first;
+ if (out.length) controller.enqueue(out);
+ headIndex += 1;
+ headOffset = 0;
+ }
+ chunks.length = 0;
+ headIndex = 0;
+ length = 0;
+ resetScan();
+ },
+ };
+ return api;
+}
+
+function isHttpWhitespaceByte(value: number | undefined): boolean {
+ return value === 32 || value === 9;
+}
+
+function hexNibbleByte(value: number | undefined): number {
+ if (value === undefined) return -1;
+ if (value >= 48 && value <= 57) return value - 48;
+ if (value >= 65 && value <= 70) return value - 55;
+ if (value >= 97 && value <= 102) return value - 87;
+ return -1;
+}
+
+function trimHttpChunkSizeErrorLine(value: string): string {
+ const semi = value.indexOf(";");
+ return (semi >= 0 ? value.slice(0, semi) : value).trim();
+}
diff --git a/src/gemini/transport/decompression.ts b/src/gemini/transport/decompression.ts
new file mode 100644
index 0000000000000000000000000000000000000000..8485f99503449f40d090448c8984e63af7d7255c
--- /dev/null
+++ b/src/gemini/transport/decompression.ts
@@ -0,0 +1,36 @@
+type SupportedCompressionFormat = "gzip";
+
+export function socketAcceptEncoding(acceptCompressed: boolean): string {
+ if (!acceptCompressed) return "identity";
+ return "gzip";
+}
+
+export function contentDecompressionFormat(
+ raw: string | null,
+): SupportedCompressionFormat | null {
+ const value = String(raw || "")
+ .trim()
+ .toLowerCase();
+ if (value === "gzip" || value === "x-gzip") return "gzip";
+ return null;
+}
+
+export function maybeDecompressSocketBody(
+ stream: ReadableStream,
+ headers: Headers,
+ noBody: boolean,
+ contentLength: number | null,
+): ReadableStream {
+ const decompressionFormat =
+ noBody || contentLength === 0
+ ? null
+ : contentDecompressionFormat(headers.get("content-encoding"));
+ if (!decompressionFormat) return stream;
+ headers.delete("content-encoding");
+ headers.delete("content-length");
+ return stream.pipeThrough(
+ new DecompressionStream(
+ decompressionFormat,
+ ) as unknown as ReadableWritablePair,
+ );
+}
diff --git a/src/gemini/transport/http-parse.ts b/src/gemini/transport/http-parse.ts
new file mode 100644
index 0000000000000000000000000000000000000000..119d55066cc1972d9fee17b89d042eb9c0f45d7d
--- /dev/null
+++ b/src/gemini/transport/http-parse.ts
@@ -0,0 +1,223 @@
+import { TEXT_DECODER } from "../../shared/encoding";
+import { _joinByteChunks } from "./byte-queue";
+import type { ByteChunk, SocketTimeoutScope } from "./socket-types";
+
+export const MAX_SOCKET_HEADER_BYTES = 64 * 1024;
+
+export type ParsedSocketHeaderBlock = {
+ httpVersion: string;
+ status: number;
+ headers: Headers;
+};
+
+type ReadSocketHeaderBlockOptions = {
+ initial: ByteChunk;
+ reader: ReadableStreamDefaultReader;
+ timeout: SocketTimeoutScope;
+ failBeforeBody: (message: unknown) => never;
+};
+
+export async function readSocketHeaderBlock({
+ initial,
+ reader,
+ timeout,
+ failBeforeBody,
+}: ReadSocketHeaderBlockOptions): Promise<{
+ headerBytes: ByteChunk;
+ pending: ByteChunk;
+}> {
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ let matched = 0;
+ let headerEnd = -1;
+ const pattern = [13, 10, 13, 10];
+ const push = (value: ByteChunk | null | undefined) => {
+ if (!value?.length || headerEnd >= 0) return;
+ chunks.push(value);
+ const base = total;
+ for (let i = 0; i < value.length; i++) {
+ const b = value[i];
+ if (b === pattern[matched]) {
+ matched += 1;
+ if (matched === pattern.length) {
+ headerEnd = base + i - pattern.length + 1;
+ break;
+ }
+ } else {
+ matched = b === pattern[0] ? 1 : 0;
+ }
+ }
+ total += value.length;
+ };
+ push(initial);
+ while (headerEnd < 0) {
+ const { done, value } = await timeout.wait(
+ reader.read(),
+ "response headers",
+ );
+ if (done) break;
+ push(value);
+ if (headerEnd < 0 && total > MAX_SOCKET_HEADER_BYTES) {
+ failBeforeBody(
+ `socket: HTTP response headers exceed ${MAX_SOCKET_HEADER_BYTES} bytes`,
+ );
+ }
+ }
+ if (headerEnd < 0) failBeforeBody("socket: incomplete HTTP response headers");
+ const joined = _joinByteChunks(chunks, total);
+ return {
+ headerBytes: joined.subarray(0, headerEnd),
+ pending: joined.subarray(headerEnd + 4),
+ };
+}
+
+export function parseHttpChunkSizeLine(line: ByteChunk): number {
+ let start = 0;
+ let end = line.length;
+ while (start < end && isHttpWhitespace(line[start])) start += 1;
+ while (end > start && isHttpWhitespace(line[end - 1])) end -= 1;
+
+ let size = 0;
+ let digits = 0;
+ for (let i = start; i < end; i++) {
+ const b = line[i];
+ if (b === 59) break;
+ const nibble = hexNibble(b);
+ if (nibble < 0) return -1;
+ digits += 1;
+ size = size * 16 + nibble;
+ if (!Number.isSafeInteger(size)) return -1;
+ }
+ return digits > 0 ? size : -1;
+}
+
+export function chunkSizeLineForError(line: ByteChunk): string {
+ let start = 0;
+ let end = line.length;
+ while (start < end && isHttpWhitespace(line[start])) start += 1;
+ while (end > start && isHttpWhitespace(line[end - 1])) end -= 1;
+ const limit = Math.min(end, start + 80);
+ let out = "";
+ for (let i = start; i < limit; i++) {
+ const b = line[i];
+ if (b === 59) break;
+ out +=
+ b !== undefined && b >= 32 && b <= 126 ? String.fromCharCode(b) : "?";
+ }
+ return out;
+}
+
+export function parseSocketHeaderBlock(
+ headerBytes: ByteChunk,
+): ParsedSocketHeaderBlock {
+ let lineStart = 0;
+ let lineEnd = lineEndIndex(headerBytes, lineStart);
+ if (lineEnd < 0) lineEnd = headerBytes.length;
+ const statusLine = parseHttpStatusLine(headerBytes, lineStart, lineEnd);
+ const headers = new Headers();
+ lineStart = lineEnd + 2;
+
+ while (lineStart <= headerBytes.length) {
+ lineEnd = lineEndIndex(headerBytes, lineStart);
+ if (lineEnd < 0) lineEnd = headerBytes.length;
+ if (lineEnd <= lineStart) break;
+ let colon = -1;
+ for (let i = lineStart; i < lineEnd; i++) {
+ if (headerBytes[i] === 58) {
+ colon = i;
+ break;
+ }
+ }
+ if (colon > lineStart) {
+ const nameStart = trimHttpHeaderStart(headerBytes, lineStart, colon);
+ const nameEnd = trimHttpHeaderEnd(headerBytes, nameStart, colon);
+ const valueStart = trimHttpHeaderStart(headerBytes, colon + 1, lineEnd);
+ const valueEnd = trimHttpHeaderEnd(headerBytes, valueStart, lineEnd);
+ try {
+ headers.append(
+ decodeHttpHeaderSlice(headerBytes, nameStart, nameEnd),
+ decodeHttpHeaderSlice(headerBytes, valueStart, valueEnd),
+ );
+ } catch (_) {}
+ }
+ if (lineEnd === headerBytes.length) break;
+ lineStart = lineEnd + 2;
+ }
+
+ return {
+ httpVersion: statusLine.httpVersion,
+ status: statusLine.status,
+ headers,
+ };
+}
+
+function isHttpWhitespace(value: number | undefined): boolean {
+ return value === 32 || value === 9;
+}
+
+function hexNibble(value: number | undefined): number {
+ if (value === undefined) return -1;
+ if (value >= 48 && value <= 57) return value - 48;
+ if (value >= 65 && value <= 70) return value - 55;
+ if (value >= 97 && value <= 102) return value - 87;
+ return -1;
+}
+
+function trimHttpHeaderStart(
+ bytes: ByteChunk,
+ start: number,
+ end: number,
+): number {
+ let cursor = start;
+ while (cursor < end && isHttpWhitespace(bytes[cursor])) cursor += 1;
+ return cursor;
+}
+
+function trimHttpHeaderEnd(
+ bytes: ByteChunk,
+ start: number,
+ end: number,
+): number {
+ let cursor = end;
+ while (cursor > start && isHttpWhitespace(bytes[cursor - 1])) cursor -= 1;
+ return cursor;
+}
+
+function decodeHttpHeaderSlice(
+ bytes: ByteChunk,
+ start: number,
+ end: number,
+): string {
+ return start < end ? TEXT_DECODER.decode(bytes.subarray(start, end)) : "";
+}
+
+function lineEndIndex(bytes: ByteChunk, start: number): number {
+ for (let i = start; i + 1 < bytes.length; i++) {
+ if (bytes[i] === 13 && bytes[i + 1] === 10) return i;
+ }
+ return -1;
+}
+
+function parseHttpStatusLine(
+ bytes: ByteChunk,
+ start: number,
+ end: number,
+): { httpVersion: string; status: number } {
+ let versionEnd = start;
+ while (versionEnd < end && !isHttpWhitespace(bytes[versionEnd]))
+ versionEnd += 1;
+ let codeStart = trimHttpHeaderStart(bytes, versionEnd, end);
+ let status = 0;
+ let digits = 0;
+ while (codeStart < end) {
+ const b = bytes[codeStart];
+ if (b === undefined || b < 48 || b > 57) break;
+ status = status * 10 + (b - 48);
+ digits += 1;
+ codeStart += 1;
+ }
+ return {
+ httpVersion: decodeHttpHeaderSlice(bytes, start, versionEnd),
+ status: digits > 0 ? status : 0,
+ };
+}
diff --git a/src/gemini/transport/http.ts b/src/gemini/transport/http.ts
new file mode 100644
index 0000000000000000000000000000000000000000..3d8bab0a3f1d468eeed16a4e54f9cd24f51c9152
--- /dev/null
+++ b/src/gemini/transport/http.ts
@@ -0,0 +1,128 @@
+import {
+ abortError,
+ isAbortError,
+ throwIfAborted,
+ timeoutSignal,
+} from "../../shared/abort";
+import {
+ canFallbackAfterSocketError,
+ errorLogSummary,
+} from "../../shared/errors";
+import { log } from "../../shared/logging";
+import { getDefaultSocketPool, resolveConnect, socketHttp } from "./socket";
+import type { SocketHttpResponse } from "./socket";
+
+type HttpBodyInit = BodyInit | ArrayBufferView;
+
+type HttpFetchOptions = {
+ method?: string;
+ headers?: Record;
+ body?: HttpBodyInit | null | undefined;
+ bodyLength?: number | null | undefined;
+ timeoutMs?: number;
+ socket?: boolean;
+ socketFallback?: "pre-response" | "never";
+ signal?: AbortSignal | null | undefined;
+ cfg?: { log_requests?: unknown } | null;
+ acceptCompressed?: boolean;
+};
+
+// 统一上游入口:socket 优先,失败/不可用则回退 fetch。返回类 Response 对象。
+export async function httpFetch(
+ url: string,
+ {
+ method = "GET",
+ headers = {},
+ body,
+ bodyLength = null,
+ timeoutMs = 180000,
+ socket = true,
+ socketFallback = "pre-response",
+ signal,
+ cfg,
+ acceptCompressed,
+ }: HttpFetchOptions = {},
+): Promise {
+ throwIfAborted(signal);
+ if (socket) {
+ const connect = await resolveConnect();
+ if (connect) {
+ try {
+ const resp = await socketHttp(connect, url, {
+ method,
+ headers,
+ body,
+ bodyLength,
+ timeoutMs,
+ signal,
+ keepAlive: true,
+ pool: getDefaultSocketPool(),
+ acceptCompressed: acceptCompressed ?? method.toUpperCase() === "GET",
+ });
+ return resp;
+ } catch (e) {
+ if (isAbortError(e) || signal?.aborted) throw abortError(signal);
+ if (socketFallback === "never") {
+ log(
+ cfg,
+ `socket upstream failed; fallback disabled for ${method}: ${errorLogSummary(e)}`,
+ );
+ throw e;
+ }
+ if (
+ body instanceof ReadableStream &&
+ socketErrorConsumedRequestBody(e)
+ ) {
+ log(
+ cfg,
+ `socket upstream failed; not falling back with streaming request body for ${method}: ${errorLogSummary(e)}`,
+ );
+ throw e;
+ }
+ if (!canFallbackAfterSocketError(method, e)) {
+ log(
+ cfg,
+ `socket upstream failed; not falling back after upstream response for ${method}: ${errorLogSummary(e)}`,
+ );
+ throw e;
+ }
+ log(
+ cfg,
+ `socket upstream failed; falling back to fetch: ${errorLogSummary(e)}`,
+ );
+ }
+ }
+ }
+ const linked = linkedFetchSignal(signal, timeoutSignal(timeoutMs));
+ try {
+ const init: RequestInit = { method, headers };
+ if (body !== undefined) init.body = body as BodyInit;
+ if (body instanceof ReadableStream)
+ (init as RequestInit & { duplex?: "half" }).duplex = "half";
+ if (linked.signal) init.signal = linked.signal;
+ return await fetch(url, init);
+ } finally {
+ linked.cleanup();
+ }
+}
+
+function socketErrorConsumedRequestBody(error: unknown): boolean {
+ const err = error as
+ | { requestBodyStarted?: unknown; code?: unknown }
+ | null
+ | undefined;
+ return (
+ !!err &&
+ (err.requestBodyStarted === true ||
+ err.code === "socket_stream_body_length_required")
+ );
+}
+
+function linkedFetchSignal(
+ signal: AbortSignal | null | undefined,
+ timeout: AbortSignal | undefined,
+): { signal: AbortSignal | undefined; cleanup: () => void } {
+ if (!signal) return { signal: timeout, cleanup() {} };
+ if (!timeout) return { signal, cleanup() {} };
+ return { signal: AbortSignal.any([signal, timeout]), cleanup() {} };
+}
diff --git a/src/gemini/transport/index.ts b/src/gemini/transport/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..0c8fd7390ef5c6582dbd7e698b75fd43c8b4819b
--- /dev/null
+++ b/src/gemini/transport/index.ts
@@ -0,0 +1,14 @@
+export { httpFetch } from "./http";
+export {
+ _connect,
+ _joinByteChunks,
+ bytesFromBody,
+ closeIdleSocketPool,
+ closeSocketQuietly,
+ createByteQueue,
+ MAX_SOCKET_HEADER_BYTES,
+ resolveConnect,
+ socketHttp,
+ socketTimeoutError,
+ withSocketTimeout,
+} from "./socket";
diff --git a/src/gemini/transport/pool.ts b/src/gemini/transport/pool.ts
new file mode 100644
index 0000000000000000000000000000000000000000..f53d955d1cff075ae1f1827cfe1118953e16e65a
--- /dev/null
+++ b/src/gemini/transport/pool.ts
@@ -0,0 +1,61 @@
+import { closeSocketQuietly } from "./timeout";
+import type { SocketLike, SocketPool } from "./socket-types";
+
+export const SOCKET_KEEP_ALIVE_IDLE_MS = 30000;
+export const SOCKET_KEEP_ALIVE_MAX_IDLE_PER_ORIGIN = 2;
+
+export function createSocketPool(): SocketPool {
+ return { idle: new Map() };
+}
+
+const defaultSocketPool = createSocketPool();
+
+export function getDefaultSocketPool(): SocketPool {
+ return defaultSocketPool;
+}
+
+export function socketPoolKey(u: URL, secure: boolean, port: number): string {
+ return `${secure ? "https" : "http"}://${u.hostname}:${port}`;
+}
+
+export function takeIdleSocket(
+ pool: SocketPool,
+ key: string,
+): SocketLike | null {
+ const entries = pool.idle.get(key);
+ if (!entries) return null;
+ const now = Date.now();
+ for (;;) {
+ const entry = entries.pop();
+ if (!entry) {
+ pool.idle.delete(key);
+ return null;
+ }
+ if (!entries.length) pool.idle.delete(key);
+ if (entry.expiresAt > now) return entry.socket;
+ closeSocketQuietly(entry.socket);
+ }
+}
+
+export function putIdleSocket(
+ pool: SocketPool,
+ key: string,
+ socket: SocketLike,
+): void {
+ let entries = pool.idle.get(key);
+ if (!entries) {
+ entries = [];
+ pool.idle.set(key, entries);
+ }
+ while (entries.length >= SOCKET_KEEP_ALIVE_MAX_IDLE_PER_ORIGIN)
+ closeSocketQuietly(entries.shift()?.socket);
+ entries.push({ socket, expiresAt: Date.now() + SOCKET_KEEP_ALIVE_IDLE_MS });
+}
+
+export function closeIdleSocketPool(pool?: SocketPool | null): void {
+ const target = pool === undefined ? defaultSocketPool : pool;
+ if (!target) return;
+ const entries = Array.from(target.idle.values()).flat();
+ target.idle.clear();
+ for (const entry of entries) closeSocketQuietly(entry.socket);
+}
diff --git a/src/gemini/transport/socket-types.ts b/src/gemini/transport/socket-types.ts
new file mode 100644
index 0000000000000000000000000000000000000000..815bbf96d1f59b00a52f615163a7fc7c0d14b253
--- /dev/null
+++ b/src/gemini/transport/socket-types.ts
@@ -0,0 +1,67 @@
+export type ByteChunk = Uint8Array;
+
+export type SocketConnectOptions = {
+ secureTransport: "on" | "off";
+ allowHalfOpen: false;
+};
+
+export type SocketAddress = { hostname: string; port: number };
+
+export type SocketLike = {
+ readable: ReadableStream;
+ writable: WritableStream;
+ close?: () => void;
+};
+
+export type SocketConnect = (
+ address: SocketAddress,
+ options: SocketConnectOptions,
+) => SocketLike;
+
+export type SocketPool = {
+ idle: Map;
+};
+
+export type IdleSocket = {
+ socket: SocketLike;
+ expiresAt: number;
+};
+
+export type SocketHttpOptions = {
+ method?: string;
+ headers?: Record;
+ body?: unknown;
+ bodyLength?: number | null | undefined;
+ timeoutMs?: number;
+ signal?: AbortSignal | null | undefined;
+ keepAlive?: boolean;
+ pool?: SocketPool | null | undefined;
+ acceptCompressed?: boolean;
+};
+
+export type SocketHttpResponse = {
+ status: number;
+ ok: boolean;
+ headers: Headers;
+ body: ReadableStream;
+ text: () => Promise;
+};
+
+export type ByteQueue = {
+ readonly length: number;
+ push(chunk: ByteChunk | null | undefined): void;
+ read(n: unknown): ByteChunk;
+ readLine(): ByteChunk | null;
+ readLineIfAvailable(): ByteChunk | null;
+ readHttpChunkSizeLineIfAvailable(): {
+ size: number;
+ errorLine: string;
+ } | null;
+ skipCRLF(): boolean;
+ drain(controller: ReadableStreamDefaultController): void;
+};
+
+export type SocketTimeoutScope = {
+ wait(promise: PromiseLike | T, stage?: unknown): Promise;
+ clear(): void;
+};
diff --git a/src/gemini/transport/socket.ts b/src/gemini/transport/socket.ts
new file mode 100644
index 0000000000000000000000000000000000000000..2e7bbf8e2ee11cc3a560f4c04127227606221832
--- /dev/null
+++ b/src/gemini/transport/socket.ts
@@ -0,0 +1,321 @@
+import { TEXT_ENCODER } from "../../shared/encoding";
+import { throwIfAborted } from "../../shared/abort";
+import { bytesFromBody } from "./byte-queue";
+import { createSocketBodyStream } from "./body-stream";
+import {
+ maybeDecompressSocketBody,
+ socketAcceptEncoding,
+} from "./decompression";
+import { parseSocketHeaderBlock, readSocketHeaderBlock } from "./http-parse";
+import {
+ closeIdleSocketPool,
+ putIdleSocket,
+ socketPoolKey,
+ takeIdleSocket,
+} from "./pool";
+import { closeSocketQuietly, createSocketTimeoutScope } from "./timeout";
+import type {
+ ByteChunk,
+ SocketConnect,
+ SocketHttpOptions,
+ SocketHttpResponse,
+} from "./socket-types";
+import type { ErrorWithMetadata } from "../../shared/types";
+
+export type {
+ ByteChunk,
+ ByteQueue,
+ SocketConnect,
+ SocketHttpOptions,
+ SocketHttpResponse,
+ SocketPool,
+} from "./socket-types";
+export { _joinByteChunks, bytesFromBody, createByteQueue } from "./byte-queue";
+export { MAX_SOCKET_HEADER_BYTES, parseHttpChunkSizeLine } from "./http-parse";
+export {
+ closeIdleSocketPool,
+ createSocketPool,
+ getDefaultSocketPool,
+ putIdleSocket,
+ SOCKET_KEEP_ALIVE_IDLE_MS,
+ SOCKET_KEEP_ALIVE_MAX_IDLE_PER_ORIGIN,
+ socketPoolKey,
+ takeIdleSocket,
+} from "./pool";
+export {
+ closeSocketQuietly,
+ socketTimeoutError,
+ withSocketTimeout,
+} from "./timeout";
+
+export let _connect: SocketConnect | null | undefined = undefined;
+
+export function _setConnectForTest(
+ connect: SocketConnect | null | undefined,
+): void {
+ closeIdleSocketPool();
+ _connect = connect;
+}
+
+export async function resolveConnect(): Promise {
+ if (_connect !== undefined) return _connect;
+ try {
+ const mod = (await import("cloudflare:sockets")) as {
+ connect?: SocketConnect;
+ };
+ _connect = mod.connect || null;
+ } catch (_) {
+ _connect = null;
+ }
+ return _connect;
+}
+
+export async function socketHttp(
+ connect: SocketConnect,
+ url: string | URL,
+ {
+ method = "GET",
+ headers = {},
+ body,
+ bodyLength = null,
+ timeoutMs = 180000,
+ signal,
+ keepAlive = false,
+ pool = null,
+ acceptCompressed = false,
+ }: SocketHttpOptions = {},
+): Promise {
+ throwIfAborted(signal);
+ const u = new URL(url);
+ const bodyStream = readableByteStreamFromBody(body);
+ const bodyBytes = bodyStream ? null : bytesFromBody(body);
+ const declaredBodyLength = safeBodyLength(bodyLength);
+ if (bodyStream && declaredBodyLength == null)
+ throw socketStreamBodyLengthError();
+ const secure = u.protocol !== "http:";
+ const port = u.port ? Number(u.port) : defaultSocketPort(secure);
+ const poolKey = socketPoolKey(u, secure, port);
+ const useKeepAlive = keepAlive && !!pool;
+ const socket =
+ (useKeepAlive && takeIdleSocket(pool, poolKey)) ||
+ connect(
+ { hostname: u.hostname, port },
+ { secureTransport: secure ? "on" : "off", allowHalfOpen: false },
+ );
+
+ const onAbort = () => closeSocketQuietly(socket);
+ if (signal) signal.addEventListener("abort", onAbort, { once: true });
+ const timeout = createSocketTimeoutScope(timeoutMs, socket, signal);
+
+ const reqHeaders: Record = {
+ Host: u.host,
+ "Accept-Encoding": socketAcceptEncoding(acceptCompressed),
+ Connection: useKeepAlive ? "keep-alive" : "close",
+ };
+ for (const [k, v] of Object.entries(headers)) {
+ if (/^(host|connection|accept-encoding|content-length)$/i.test(k)) continue;
+ reqHeaders[k] = String(v);
+ }
+ if (bodyBytes) reqHeaders["Content-Length"] = String(bodyBytes.length);
+ else if (bodyStream)
+ reqHeaders["Content-Length"] = String(declaredBodyLength);
+ const headParts = [`${method} ${u.pathname}${u.search} HTTP/1.1`];
+ for (const [k, v] of Object.entries(reqHeaders)) headParts.push(`${k}: ${v}`);
+ const head = `${headParts.join("\r\n")}\r\n\r\n`;
+
+ const writer = socket.writable.getWriter();
+ try {
+ await timeout.wait(
+ writer.write(TEXT_ENCODER.encode(head)),
+ "request headers write",
+ );
+ if (bodyBytes)
+ await timeout.wait(writer.write(bodyBytes), "request body write");
+ else if (bodyStream) {
+ try {
+ await writeRequestBodyStream(writer, bodyStream, timeout);
+ } catch (e) {
+ throw markRequestBodyStarted(e);
+ }
+ }
+ } catch (e) {
+ timeout.clear();
+ if (signal) signal.removeEventListener("abort", onAbort);
+ closeSocketQuietly(socket);
+ throw e;
+ }
+ try {
+ writer.releaseLock();
+ } catch (_) {}
+
+ const reader = socket.readable.getReader();
+ const failBeforeBody = (message: unknown): never => {
+ timeout.clear();
+ if (signal) signal.removeEventListener("abort", onAbort);
+ try {
+ reader.releaseLock();
+ } catch (_) {}
+ closeSocketQuietly(socket);
+ throwIfAborted(signal);
+ throw new Error(String(message));
+ };
+ let pending: ByteChunk = new Uint8Array(0);
+ let status = 0;
+ let respHttpVersion = "";
+ let respHeaders = new Headers();
+ for (;;) {
+ const headerBlock = await readSocketHeaderBlock({
+ initial: pending,
+ reader,
+ timeout,
+ failBeforeBody,
+ });
+ pending = headerBlock.pending;
+ const parsedHeaders = parseSocketHeaderBlock(headerBlock.headerBytes);
+ respHttpVersion = parsedHeaders.httpVersion;
+ status = parsedHeaders.status;
+ respHeaders = parsedHeaders.headers;
+ if (status >= 100 && status < 200 && status !== 101) continue;
+ break;
+ }
+ const chunked = /chunked/i.test(respHeaders.get("transfer-encoding") || "");
+ let clen: number | null = null;
+ if (respHeaders.has("content-length")) {
+ const rawContentLength = String(
+ respHeaders.get("content-length") || "",
+ ).trim();
+ if (!/^(0|[1-9]\d*)$/.test(rawContentLength))
+ failBeforeBody(`socket: invalid Content-Length: ${rawContentLength}`);
+ clen = Number(rawContentLength);
+ if (!Number.isSafeInteger(clen))
+ failBeforeBody(`socket: invalid Content-Length: ${rawContentLength}`);
+ }
+ const noBody =
+ method.toUpperCase() === "HEAD" ||
+ status === 204 ||
+ status === 304 ||
+ (status >= 100 && status < 200);
+ const respConnection = respHeaders.get("connection") || "";
+ const serverAllowsKeepAlive =
+ respHttpVersion === "HTTP/1.1"
+ ? !/\bclose\b/i.test(respConnection)
+ : respHttpVersion === "HTTP/1.0" &&
+ /\bkeep-alive\b/i.test(respConnection);
+ const keepAliveEligible =
+ useKeepAlive &&
+ serverAllowsKeepAlive &&
+ (noBody || chunked || clen != null);
+
+ let cleanupDone = false;
+ const cleanupBody = (reuse: boolean) => {
+ if (cleanupDone) return;
+ cleanupDone = true;
+ timeout.clear();
+ if (signal) signal.removeEventListener("abort", onAbort);
+ try {
+ reader.releaseLock();
+ } catch (_) {}
+ if (reuse && pool) putIdleSocket(pool, poolKey, socket);
+ else closeSocketQuietly(socket);
+ };
+
+ const stream = createSocketBodyStream({
+ reader,
+ timeout,
+ pending,
+ noBody,
+ chunked,
+ contentLength: clen,
+ keepAliveEligible,
+ cleanupBody,
+ });
+
+ const responseBody = maybeDecompressSocketBody(
+ stream,
+ respHeaders,
+ noBody,
+ clen,
+ );
+ return {
+ status,
+ ok: status >= 200 && status < 300,
+ headers: respHeaders,
+ body: responseBody,
+ text: async () => {
+ const r = responseBody.getReader();
+ const decoder = new TextDecoder();
+ const chunks: string[] = [];
+ for (;;) {
+ const { done, value } = await r.read();
+ if (done) break;
+ if (!value?.length) continue;
+ chunks.push(decoder.decode(value, { stream: true }));
+ }
+ const tail = decoder.decode();
+ if (tail) chunks.push(tail);
+ return chunks.join("");
+ },
+ };
+}
+
+function defaultSocketPort(secure: boolean): number {
+ return secure ? 443 : 80;
+}
+
+function readableByteStreamFromBody(
+ body: unknown,
+): ReadableStream | null {
+ if (body instanceof ReadableStream) return body as ReadableStream;
+ return null;
+}
+
+function safeBodyLength(value: unknown): number | null {
+ if (value == null) return null;
+ const n = Number(value);
+ return Number.isSafeInteger(n) && n >= 0 ? n : null;
+}
+
+function socketStreamBodyLengthError(): ErrorWithMetadata {
+ const err: ErrorWithMetadata = new Error(
+ "socket: streaming request body requires a known content length",
+ );
+ err.code = "socket_stream_body_length_required";
+ return err;
+}
+
+function markRequestBodyStarted(error: unknown): unknown {
+ if (error && typeof error === "object") {
+ (
+ error as ErrorWithMetadata & { requestBodyStarted?: true }
+ ).requestBodyStarted = true;
+ return error;
+ }
+ const err: ErrorWithMetadata & { requestBodyStarted?: true } = new Error(
+ String(error),
+ );
+ err.requestBodyStarted = true;
+ return err;
+}
+
+async function writeRequestBodyStream(
+ writer: WritableStreamDefaultWriter,
+ stream: ReadableStream,
+ timeout: ReturnType,
+): Promise {
+ const reader = stream.getReader();
+ try {
+ for (;;) {
+ const { done, value } = await timeout.wait(
+ reader.read(),
+ "request body read",
+ );
+ if (done) break;
+ if (!value?.byteLength) continue;
+ await timeout.wait(writer.write(value), "request body write");
+ }
+ } finally {
+ try {
+ reader.releaseLock();
+ } catch (_) {}
+ }
+}
diff --git a/src/gemini/transport/timeout.ts b/src/gemini/transport/timeout.ts
new file mode 100644
index 0000000000000000000000000000000000000000..e49bc025c7bedf259215501feb2ee83b1d900b4b
--- /dev/null
+++ b/src/gemini/transport/timeout.ts
@@ -0,0 +1,121 @@
+import { throwIfAborted } from "../../shared/abort";
+import type { ErrorWithMetadata } from "../../shared/types";
+import type { SocketTimeoutScope } from "./socket-types";
+
+export function socketTimeoutError(
+ stage: unknown,
+ timeoutMs: unknown,
+): ErrorWithMetadata {
+ const err: ErrorWithMetadata = new Error(
+ `socket: ${stage} timed out after ${timeoutMs}ms`,
+ );
+ err.code = "socket_timeout";
+ return err;
+}
+
+export function closeSocketQuietly(socket: unknown): void {
+ const candidate = socket as { close?: unknown } | null | undefined;
+ if (typeof candidate?.close !== "function") return;
+ try {
+ candidate.close();
+ } catch (_) {}
+}
+
+export function withSocketTimeout(
+ promise: PromiseLike | T,
+ timeoutMs: unknown,
+ stage: unknown,
+ socket: unknown,
+ signal?: AbortSignal | null,
+): Promise {
+ throwIfAborted(signal);
+ const n = Number(timeoutMs);
+ if (!Number.isFinite(n) || n <= 0) {
+ return Promise.resolve(promise).then((value: T) => {
+ throwIfAborted(signal);
+ return value;
+ });
+ }
+ let timer: ReturnType | null = null;
+ return new Promise((resolve, reject) => {
+ timer = setTimeout(() => {
+ closeSocketQuietly(socket);
+ reject(socketTimeoutError(stage, n));
+ }, n);
+ Promise.resolve(promise).then(
+ (value: T) => {
+ if (timer) clearTimeout(timer);
+ try {
+ throwIfAborted(signal);
+ resolve(value);
+ } catch (e) {
+ reject(e);
+ }
+ },
+ (err: unknown) => {
+ if (timer) clearTimeout(timer);
+ try {
+ throwIfAborted(signal);
+ reject(err);
+ } catch (e) {
+ reject(e);
+ }
+ },
+ );
+ });
+}
+
+export function createSocketTimeoutScope(
+ timeoutMs: unknown,
+ socket: unknown,
+ signal?: AbortSignal | null,
+): SocketTimeoutScope {
+ const n = Number(timeoutMs);
+ if (!Number.isFinite(n) || n <= 0) {
+ return {
+ wait(promise: PromiseLike | T): Promise {
+ return Promise.resolve(promise).then((value: T) => {
+ throwIfAborted(signal);
+ return value;
+ });
+ },
+ clear() {},
+ };
+ }
+ let timer: ReturnType | null = null;
+ let rejectIdle: ((reason?: unknown) => void) | null = null;
+ const idle = new Promise((_, reject) => {
+ rejectIdle = reject;
+ });
+ const clear = () => {
+ if (timer) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ };
+ const arm = (stage: unknown) => {
+ clear();
+ timer = setTimeout(() => {
+ timer = null;
+ closeSocketQuietly(socket);
+ rejectIdle?.(socketTimeoutError(stage, n));
+ }, n);
+ };
+ return {
+ async wait(promise: PromiseLike | T, stage: unknown): Promise {
+ throwIfAborted(signal);
+ arm(stage);
+ try {
+ const value = await Promise.race([Promise.resolve(promise), idle]);
+ clear();
+ throwIfAborted(signal);
+ return value;
+ } catch (e) {
+ clear();
+ throwIfAborted(signal);
+ throw e;
+ }
+ },
+ clear,
+ };
+}
diff --git a/src/gemini/uploads/errors.ts b/src/gemini/uploads/errors.ts
new file mode 100644
index 0000000000000000000000000000000000000000..bc121dabc00f14e51b2fb8128f3dfc9c33b67fdb
--- /dev/null
+++ b/src/gemini/uploads/errors.ts
@@ -0,0 +1,37 @@
+export type ContentPushUploadErrorCode =
+ | "content_push_http_status"
+ | "content_push_invalid_ref"
+ | "content_push_missing_page_token";
+
+export type ContentPushUploadError = Error & {
+ code: ContentPushUploadErrorCode;
+ status?: number;
+ protocol?: string;
+};
+
+export function contentPushUploadError(
+ code: ContentPushUploadErrorCode,
+ message: string,
+ meta: { status?: number; protocol?: string } = {},
+): ContentPushUploadError {
+ const err = new Error(message) as ContentPushUploadError;
+ err.code = code;
+ if (meta.status !== undefined) err.status = meta.status;
+ if (meta.protocol) err.protocol = meta.protocol;
+ return err;
+}
+
+export function validateContentPushFileRef(
+ raw: unknown,
+ protocol: string,
+): string {
+ const fileRef = String(raw || "").trim();
+ if (!fileRef.startsWith("/")) {
+ throw contentPushUploadError(
+ "content_push_invalid_ref",
+ `invalid ${protocol} file ref: ${fileRef.slice(0, 120)}`,
+ { protocol },
+ );
+ }
+ return fileRef;
+}
diff --git a/src/gemini/uploads/execute.ts b/src/gemini/uploads/execute.ts
new file mode 100644
index 0000000000000000000000000000000000000000..bfa115e9c30f1b3be75209b21554579e67b2e9cf
--- /dev/null
+++ b/src/gemini/uploads/execute.ts
@@ -0,0 +1,525 @@
+import {
+ type AttachmentLimits,
+ DEFAULT_ATTACHMENT_MAX_BYTES,
+ type MaterializedAttachment,
+ materializeAttachment,
+} from "../../attachments/materialize";
+import {
+ chooseUploadMime,
+ firstNonEmptyString,
+ genericFilenameFromMime,
+ imageFilenameFromMime,
+ normalizeMimeType,
+} from "../../attachments/mime";
+import { attachmentDrop, droppedAttachmentNote } from "../../attachments/notes";
+import { createAttachmentPlan } from "../../attachments/plan";
+import type {
+ AttachmentCandidate,
+ AttachmentDrop,
+ AttachmentFileRef,
+ AttachmentPlan,
+ AttachmentUploadResult,
+ AttachmentUsage,
+} from "../../attachments/types";
+import type { RuntimeConfig } from "../../config";
+import { bytesToHex } from "../../shared/crypto";
+import { TEXT_ENCODER, UTF8_FATAL_DECODER } from "../../shared/encoding";
+import { errorLogSummary } from "../../shared/errors";
+import { log, logStage } from "../../shared/logging";
+import { mapWithConcurrencyAndWeight } from "../concurrency";
+import { configWithFreshGeminiCookie } from "../cookies";
+import { type UploadBytesInput, uploadMultipartFile } from "./multipart";
+
+const MAX_PARALLEL_UPLOADS = 4;
+const MAX_IN_FLIGHT_ATTACHMENT_BYTES = 32 * 1024 * 1024;
+
+type UploadOneResult = {
+ candidate: AttachmentCandidate;
+ fileRef: AttachmentFileRef | null;
+ promptText: string;
+ drop: AttachmentDrop | null;
+ bytesLength: number;
+ deduped: boolean;
+};
+
+type UploadState = {
+ uploadedByKey: Map;
+ pendingByKey: Map>;
+ inlinedByKey: Map;
+ uploadedFiles: number;
+ dedupedFiles: number;
+ uploadedBytes: number;
+ inlinedFiles: number;
+ inlinedBytes: number;
+ multipartUploads: number;
+};
+
+type UploadProtocol = "multipart";
+
+type UploadBytesResult = {
+ ref: string;
+ protocol: UploadProtocol;
+};
+
+type UploadedAttachmentRef = {
+ fileRef: AttachmentFileRef;
+ protocol: UploadProtocol;
+};
+
+export async function resolveAttachments(
+ cfg: RuntimeConfig,
+ plan: AttachmentPlan,
+): Promise {
+ const activeCfg = await configWithFreshGeminiCookie(cfg);
+ const supportsFileRefs = !!activeCfg.cookie;
+ const state: UploadState = {
+ uploadedByKey: new Map(),
+ pendingByKey: new Map(),
+ inlinedByKey: new Map(),
+ uploadedFiles: 0,
+ dedupedFiles: 0,
+ uploadedBytes: 0,
+ inlinedFiles: 0,
+ inlinedBytes: 0,
+ multipartUploads: 0,
+ };
+ const limits = attachmentLimitsFromConfig(activeCfg);
+ const uploadResults = await mapWithConcurrencyAndWeight(
+ plan.candidates,
+ MAX_PARALLEL_UPLOADS,
+ MAX_IN_FLIGHT_ATTACHMENT_BYTES,
+ estimatedMaterializedBytes,
+ (candidate) =>
+ resolveOneRequestAttachment(
+ activeCfg,
+ candidate,
+ limits,
+ state,
+ supportsFileRefs,
+ ),
+ );
+ const fileRefs: AttachmentFileRef[] = [];
+ const imageFileRefs: AttachmentFileRef[] = [];
+ const genericFileRefs: AttachmentFileRef[] = [];
+ const promptParts: string[] = [];
+ const drops = [...plan.dropped];
+ let fileRefBytes = 0;
+ for (const result of uploadResults) {
+ if (result.drop) {
+ drops.push(result.drop);
+ log(
+ activeCfg,
+ `attachment upload dropped kind=${result.candidate.kind} bytes=${result.bytesLength || "unknown"} ${errorLogSummary(result.drop.message)}`,
+ );
+ continue;
+ }
+ if (result.promptText) promptParts.push(result.promptText);
+ if (!result.fileRef) continue;
+ fileRefBytes += result.bytesLength;
+ fileRefs.push(result.fileRef);
+ if (result.candidate.kind === "image") imageFileRefs.push(result.fileRef);
+ else genericFileRefs.push(result.fileRef);
+ }
+ const usage: AttachmentUsage = {
+ uploadedFiles: state.uploadedFiles,
+ dedupedFiles: state.dedupedFiles,
+ uploadedBytes: state.uploadedBytes,
+ fileRefBytes,
+ inlinedFiles: state.inlinedFiles,
+ inlinedBytes: state.inlinedBytes,
+ droppedFiles: drops.length,
+ multipartUploads: state.multipartUploads,
+ };
+ if (activeCfg.log_requests) {
+ logStage(activeCfg, "attachment_upload", {
+ candidates: plan.candidates.length,
+ existingRefs: plan.existingFileRefs ? plan.existingFileRefs.length : 0,
+ uploadedFiles: usage.uploadedFiles,
+ dedupedFiles: usage.dedupedFiles,
+ uploadedBytes: usage.uploadedBytes,
+ fileRefBytes: usage.fileRefBytes,
+ inlinedFiles: usage.inlinedFiles,
+ inlinedBytes: usage.inlinedBytes,
+ droppedFiles: usage.droppedFiles,
+ multipartUploads: usage.multipartUploads,
+ supportsFileRefs,
+ });
+ }
+ return {
+ fileRefs: fileRefs.length ? fileRefs : null,
+ imageFileRefs: imageFileRefs.length ? imageFileRefs : null,
+ genericFileRefs: genericFileRefs.length ? genericFileRefs : null,
+ promptText: promptParts.join(""),
+ droppedNote: droppedAttachmentNote(drops),
+ supportsFileRefs,
+ usage,
+ };
+}
+
+export async function uploadTextFile(
+ cfg: RuntimeConfig,
+ text: unknown,
+ filename: unknown,
+): Promise {
+ const activeCfg = await configWithFreshGeminiCookie(cfg);
+ const name = String(filename || "context.txt").trim() || "context.txt";
+ const bytes = TEXT_ENCODER.encode(String(text || ""));
+ const { ref } = await uploadBytesWithFallbackResult(activeCfg, {
+ bytes,
+ mime: "text/plain; charset=utf-8",
+ filename: name,
+ });
+ return { ref, name };
+}
+
+export async function uploadImage(
+ cfg: RuntimeConfig,
+ bytes: Uint8Array,
+ mime: string,
+): Promise {
+ const activeCfg = await configWithFreshGeminiCookie(cfg);
+ const result = await uploadBytesWithFallbackResult(activeCfg, {
+ bytes,
+ mime: chooseUploadMime(mime, "image/png"),
+ filename: imageFilenameFromMime(mime, 1),
+ });
+ return result.ref;
+}
+
+export async function uploadFile(
+ cfg: RuntimeConfig,
+ bytes: Uint8Array,
+ mime: string,
+): Promise {
+ const activeCfg = await configWithFreshGeminiCookie(cfg);
+ const result = await uploadBytesWithFallbackResult(activeCfg, {
+ bytes,
+ mime: chooseUploadMime(mime),
+ filename: genericFilenameFromMime(mime, 1),
+ });
+ return result.ref;
+}
+
+export async function resolveImages(
+ cfg: RuntimeConfig,
+ images: unknown,
+): Promise {
+ return resolveAttachments(cfg, createAttachmentPlan({ images }));
+}
+
+export async function resolveFiles(
+ cfg: RuntimeConfig,
+ files: unknown,
+): Promise {
+ return resolveAttachments(cfg, createAttachmentPlan({ files }));
+}
+
+export async function uploadBytesWithFallback(
+ cfg: RuntimeConfig,
+ input: UploadBytesInput,
+): Promise {
+ const result = await uploadBytesWithFallbackResult(cfg, input);
+ return result.ref;
+}
+
+async function uploadBytesWithFallbackResult(
+ cfg: RuntimeConfig,
+ input: UploadBytesInput,
+): Promise {
+ try {
+ return {
+ ref: await uploadMultipartFile(cfg, input),
+ protocol: "multipart",
+ };
+ } catch (e) {
+ log(cfg, `multipart upload failed ${errorLogSummary(e)}`);
+ throw e;
+ }
+}
+
+function attachmentLimitsFromConfig(cfg: RuntimeConfig): AttachmentLimits {
+ const n = Number(cfg.generic_file_upload_max_bytes);
+ const maxBytes = Number.isFinite(n)
+ ? Math.max(0, Math.floor(n))
+ : DEFAULT_ATTACHMENT_MAX_BYTES;
+ return {
+ maxFileBytes: maxBytes,
+ maxImageBytes: maxBytes,
+ };
+}
+
+async function resolveOneRequestAttachment(
+ cfg: RuntimeConfig,
+ candidate: AttachmentCandidate,
+ limits: AttachmentLimits,
+ state: UploadState,
+ supportsFileRefs: boolean,
+): Promise {
+ if (!supportsFileRefs)
+ return inlineOrDropAnonymousAttachment(cfg, candidate, limits, state);
+ return uploadOneRequestAttachment(cfg, candidate, limits, state);
+}
+
+async function uploadOneRequestAttachment(
+ cfg: RuntimeConfig,
+ candidate: AttachmentCandidate,
+ limits: AttachmentLimits,
+ state: UploadState,
+): Promise {
+ let materialized: MaterializedAttachment | null = null;
+ try {
+ materialized = await materializeAttachment(candidate, limits);
+ const key = await dedupeKey(materialized);
+ const existing = state.uploadedByKey.get(key);
+ if (existing) {
+ state.dedupedFiles += 1;
+ return {
+ candidate,
+ fileRef: existing,
+ promptText: "",
+ drop: null,
+ bytesLength: materialized.bytes.byteLength,
+ deduped: true,
+ };
+ }
+ const pending = state.pendingByKey.get(key);
+ if (pending) {
+ const { fileRef } = await pending;
+ state.dedupedFiles += 1;
+ return {
+ candidate,
+ fileRef,
+ promptText: "",
+ drop: null,
+ bytesLength: materialized.bytes.byteLength,
+ deduped: true,
+ };
+ }
+ const uploadPromise = uploadMaterializedAttachment(cfg, materialized);
+ state.pendingByKey.set(key, uploadPromise);
+ const uploaded = await uploadPromise.finally(() => {
+ state.pendingByKey.delete(key);
+ });
+ const fileRef = uploaded.fileRef;
+ state.uploadedByKey.set(key, fileRef);
+ state.uploadedFiles += 1;
+ state.uploadedBytes += materialized.bytes.byteLength;
+ state.multipartUploads += 1;
+ return {
+ candidate,
+ fileRef,
+ promptText: "",
+ drop: null,
+ bytesLength: materialized.bytes.byteLength,
+ deduped: false,
+ };
+ } catch (e) {
+ const code = dropCodeFromError(candidate, e);
+ const message = dropMessageFromError(code, e);
+ return {
+ candidate,
+ fileRef: null,
+ promptText: "",
+ drop: attachmentDrop(candidate.kind, code, message, candidate.filename),
+ bytesLength: materialized ? materialized.bytes.byteLength : 0,
+ deduped: false,
+ };
+ }
+}
+
+async function inlineOrDropAnonymousAttachment(
+ cfg: RuntimeConfig,
+ candidate: AttachmentCandidate,
+ limits: AttachmentLimits,
+ state: UploadState,
+): Promise {
+ let materialized: MaterializedAttachment | null = null;
+ try {
+ materialized = await materializeAttachment(candidate, limits);
+ if (candidate.kind !== "file") {
+ return droppedAnonymousAttachment(
+ cfg,
+ candidate,
+ materialized,
+ "image input requires GEMINI_COOKIE",
+ );
+ }
+ const inlineText = anonymousInlineTextFor(materialized);
+ if (inlineText == null) {
+ return droppedAnonymousAttachment(
+ cfg,
+ candidate,
+ materialized,
+ "file attachment requires GEMINI_COOKIE",
+ );
+ }
+ const key = await dedupeKey(materialized);
+ const existingInlineText = state.inlinedByKey.get(key);
+ if (existingInlineText != null) {
+ state.dedupedFiles += 1;
+ return {
+ candidate,
+ fileRef: null,
+ promptText: "",
+ drop: null,
+ bytesLength: materialized.bytes.byteLength,
+ deduped: true,
+ };
+ }
+ const promptText = formatInlineAttachmentText(
+ materialized.filename,
+ inlineText,
+ );
+ state.inlinedByKey.set(key, promptText);
+ state.inlinedFiles += 1;
+ state.inlinedBytes += materialized.bytes.byteLength;
+ return {
+ candidate,
+ fileRef: null,
+ promptText,
+ drop: null,
+ bytesLength: materialized.bytes.byteLength,
+ deduped: false,
+ };
+ } catch (e) {
+ const code = dropCodeFromError(candidate, e);
+ const message = dropMessageFromError(code, e);
+ return {
+ candidate,
+ fileRef: null,
+ promptText: "",
+ drop: attachmentDrop(candidate.kind, code, message, candidate.filename),
+ bytesLength: materialized ? materialized.bytes.byteLength : 0,
+ deduped: false,
+ };
+ }
+}
+
+function droppedAnonymousAttachment(
+ cfg: RuntimeConfig,
+ candidate: AttachmentCandidate,
+ materialized: MaterializedAttachment,
+ message: string,
+): UploadOneResult {
+ log(
+ cfg,
+ `attachment upload skipped kind=${candidate.kind} bytes=${materialized.bytes.byteLength} reason=anonymous_file_refs_unavailable`,
+ );
+ return {
+ candidate,
+ fileRef: null,
+ promptText: "",
+ drop: attachmentDrop(
+ candidate.kind,
+ "upload_failed",
+ message,
+ materialized.filename,
+ ),
+ bytesLength: materialized.bytes.byteLength,
+ deduped: false,
+ };
+}
+
+function anonymousInlineTextFor(
+ materialized: MaterializedAttachment,
+): string | null {
+ const mime = normalizeMimeType(materialized.mime);
+ if (!isInlineTextMime(mime)) return null;
+ try {
+ return UTF8_FATAL_DECODER.decode(materialized.bytes);
+ } catch (_) {
+ return null;
+ }
+}
+
+function isInlineTextMime(mime: string): boolean {
+ return (
+ mime.startsWith("text/") ||
+ mime === "application/json" ||
+ mime === "application/x-ndjson" ||
+ mime === "application/xml"
+ );
+}
+
+function formatInlineAttachmentText(filename: string, text: string): string {
+ return `\n\n[File attachment: ${filename}]\n${text}\n[/File attachment]`;
+}
+
+async function uploadMaterializedAttachment(
+ cfg: RuntimeConfig,
+ materialized: MaterializedAttachment,
+): Promise {
+ const result = await uploadBytesWithFallbackResult(cfg, {
+ bytes: materialized.bytes,
+ mime: materialized.mime,
+ filename: materialized.filename,
+ });
+ return {
+ fileRef: { ref: result.ref, name: materialized.filename },
+ protocol: result.protocol,
+ };
+}
+
+async function dedupeKey(
+ materialized: MaterializedAttachment,
+): Promise {
+ const digest = await crypto.subtle.digest("SHA-256", materialized.bytes);
+ return `${materialized.mime}\x00${materialized.filename}\x00${bytesToHex(new Uint8Array(digest))}`;
+}
+
+export const attachmentDedupeKeyForTest = dedupeKey;
+
+function estimatedMaterializedBytes(candidate: AttachmentCandidate): number {
+ if (candidate.source.type === "bytes")
+ return candidate.source.bytes.byteLength;
+ return Math.floor((String(candidate.source.data || "").length * 3) / 4);
+}
+
+function dropCodeFromError(
+ candidate: AttachmentCandidate,
+ error: unknown,
+): AttachmentDrop["code"] {
+ const code =
+ error && typeof error === "object"
+ ? String((error as { code?: unknown }).code || "")
+ : "";
+ switch (code) {
+ case "invalid_base64":
+ case "invalid_remote_url":
+ case "file_too_large":
+ case "image_too_large":
+ return code;
+ default:
+ return candidate.kind === "image" && code === "invalid_image_input"
+ ? "invalid_image_input"
+ : "upload_failed";
+ }
+}
+
+function dropMessageFromError(
+ code: AttachmentDrop["code"],
+ error: unknown,
+): string {
+ const message =
+ error && typeof error === "object" && "message" in error
+ ? firstNonEmptyString((error as { message?: unknown }).message)
+ : "";
+ switch (code) {
+ case "invalid_base64":
+ return "invalid base64 payload";
+ case "invalid_remote_url":
+ return "invalid remote URL";
+ case "file_too_large":
+ return message || "file attachment is too large";
+ case "image_too_large":
+ return message || "image attachment is too large";
+ case "invalid_image_input":
+ return "invalid image input";
+ case "invalid_file_input":
+ return "invalid file input";
+ case "too_many_files":
+ return "too many attachments";
+ case "upload_failed":
+ return "attachment upload failed";
+ }
+}
diff --git a/src/gemini/uploads/index.ts b/src/gemini/uploads/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..f4495ffb276ae7615afaabe0f91b3527b5336176
--- /dev/null
+++ b/src/gemini/uploads/index.ts
@@ -0,0 +1,2 @@
+export { resolveAttachments, uploadTextFile } from "./execute";
+export { getPageTokens, resetGeminiUploadCachesForTest } from "./tokens";
diff --git a/src/gemini/uploads/multipart.ts b/src/gemini/uploads/multipart.ts
new file mode 100644
index 0000000000000000000000000000000000000000..85380ec88996a15e8d542101cadca6908073fe8f
--- /dev/null
+++ b/src/gemini/uploads/multipart.ts
@@ -0,0 +1,172 @@
+import type { RuntimeConfig } from "../../config";
+import { sanitizeUploadFilename } from "../../attachments/mime";
+import { TEXT_ENCODER } from "../../shared/encoding";
+import { bytesToHex } from "../../shared/crypto";
+import { GEMINI_WEB_USER_AGENT } from "../constants";
+import { httpFetch } from "../transport";
+import { resinProxyUrl } from "../proxy";
+import { contentPushUploadError, validateContentPushFileRef } from "./errors";
+import {
+ contentPushUploadTokens,
+ getGeminiPushId,
+ refreshGeminiPushId,
+} from "./tokens";
+
+export type UploadBytesInput = {
+ bytes: Uint8Array;
+ mime: string;
+ filename: string;
+};
+
+const MULTIPART_UPLOAD_ENDPOINT = "https://content-push.googleapis.com/upload";
+
+type MultipartFileBody = {
+ body: BodyInit;
+ contentType: string;
+ boundary: string;
+ contentLength: number;
+};
+
+export async function uploadMultipartFile(
+ cfg: RuntimeConfig,
+ input: UploadBytesInput,
+): Promise {
+ return uploadMultipartFileWithPushId(
+ cfg,
+ input,
+ await getGeminiPushId(cfg),
+ false,
+ );
+}
+
+async function uploadMultipartFileWithPushId(
+ cfg: RuntimeConfig,
+ input: UploadBytesInput,
+ pushId: string,
+ retriedAfterRefresh: boolean,
+): Promise {
+ const tokens = contentPushUploadTokens(pushId, "multipart");
+ const multipart = buildMultipartFileBody(input);
+ const headers: Record = {
+ Origin: "https://gemini.google.com",
+ Referer: "https://gemini.google.com/",
+ "X-Tenant-Id": "bard-storage",
+ "Push-ID": tokens.pushId,
+ "User-Agent": GEMINI_WEB_USER_AGENT,
+ "Content-Type": multipart.contentType,
+ };
+ const response = await httpFetch(resinProxyUrl(cfg, MULTIPART_UPLOAD_ENDPOINT), {
+ method: "POST",
+ headers,
+ body: multipart.body,
+ bodyLength: multipart.contentLength,
+ timeoutMs: 60000,
+ socket: cfg.upstream_socket,
+ cfg,
+ });
+ if (!response.ok) {
+ if (
+ !retriedAfterRefresh &&
+ shouldRefreshPushIdAfterStatus(response.status)
+ ) {
+ const refreshedPushId = await refreshGeminiPushId(cfg);
+ if (refreshedPushId && refreshedPushId !== tokens.pushId) {
+ return uploadMultipartFileWithPushId(cfg, input, refreshedPushId, true);
+ }
+ }
+ throw contentPushUploadError(
+ "content_push_http_status",
+ `multipart upload failed with HTTP ${response.status}`,
+ {
+ status: response.status,
+ protocol: "multipart",
+ },
+ );
+ }
+ return validateContentPushFileRef(await response.text(), "multipart");
+}
+
+function shouldRefreshPushIdAfterStatus(status: unknown): boolean {
+ const code = Number(status);
+ return code === 401 || code === 403 || code === 415;
+}
+
+export function buildMultipartFileBody(
+ input: UploadBytesInput,
+): MultipartFileBody {
+ const boundary = `----web2gem-${randomBoundarySuffix()}`;
+ const filename = escapeMultipartFilename(input.filename || "upload.bin");
+ const mime =
+ String(input.mime || "application/octet-stream")
+ .replace(/[\r\n]/g, "")
+ .trim() || "application/octet-stream";
+ const head = TEXT_ENCODER.encode(
+ [
+ `--${boundary}`,
+ `Content-Disposition: form-data; name="file"; filename="${filename}"`,
+ `Content-Type: ${mime}`,
+ "",
+ "",
+ ].join("\r\n"),
+ );
+ const tail = TEXT_ENCODER.encode(`\r\n--${boundary}--\r\n`);
+ const contentLength =
+ head.byteLength + input.bytes.byteLength + tail.byteLength;
+ return {
+ body: multipartByteStream([head, input.bytes, tail], contentLength),
+ contentType: `multipart/form-data; boundary=${boundary}`,
+ boundary,
+ contentLength,
+ };
+}
+
+function multipartByteStream(
+ chunks: readonly Uint8Array[],
+ contentLength: number,
+): BodyInit {
+ if (typeof FixedLengthStream === "function") {
+ const stream = new FixedLengthStream(contentLength);
+ void writeMultipartChunks(stream.writable, chunks);
+ return stream.readable;
+ }
+ return new ReadableStream({
+ start(controller) {
+ for (const chunk of chunks) {
+ if (chunk.byteLength) controller.enqueue(chunk);
+ }
+ controller.close();
+ },
+ });
+}
+
+async function writeMultipartChunks(
+ writable: WritableStream,
+ chunks: readonly Uint8Array[],
+): Promise {
+ const writer = writable.getWriter();
+ try {
+ for (const chunk of chunks) {
+ if (chunk.byteLength) await writer.write(chunk);
+ }
+ await writer.close();
+ } catch (e) {
+ try {
+ await writer.abort(e);
+ } catch (_) {}
+ } finally {
+ try {
+ writer.releaseLock();
+ } catch (_) {}
+ }
+}
+
+function escapeMultipartFilename(filename: string): string {
+ const safe = sanitizeUploadFilename(filename) || "upload.bin";
+ return safe.replace(/\\/g, "_").replace(/"/g, "_");
+}
+
+function randomBoundarySuffix(): string {
+ const bytes = new Uint8Array(8);
+ crypto.getRandomValues(bytes);
+ return bytesToHex(bytes);
+}
diff --git a/src/gemini/uploads/tokens.ts b/src/gemini/uploads/tokens.ts
new file mode 100644
index 0000000000000000000000000000000000000000..70ebd65baacccf527770c09889e50e9c665e1aba
--- /dev/null
+++ b/src/gemini/uploads/tokens.ts
@@ -0,0 +1,188 @@
+import {
+ extractGeminiAppPageTokens,
+ extractGeminiPushId,
+ type GeminiAppPageTokens,
+} from "../app-page";
+import { GEMINI_WEB_USER_AGENT } from "../constants";
+import { httpFetch } from "../transport";
+import { createOriginScopedStringCache } from "../cache";
+import { accountPrefix, geminiAppUrl } from "../proxy";
+import type { RuntimeConfig } from "../../config";
+import { configWithFreshGeminiCookie } from "../cookies";
+import { errorLogSummary, log } from "../../shared/runtime";
+import { contentPushUploadError } from "./errors";
+
+type PageTokens = GeminiAppPageTokens;
+type PageTokenCache = { key: string; tokens: PageTokens | null; ts: number };
+type PageTokenPending = { key: string; promise: Promise | null };
+type ContentPushUploadTokens = {
+ pushId: string;
+};
+
+const GEMINI_UPLOAD_USER_AGENT = GEMINI_WEB_USER_AGENT;
+const GEMINI_PUSH_ID_CACHE_TTL_SEC = 12 * 60 * 60;
+export let _pageTokens: PageTokenCache = { key: "", tokens: null, ts: 0 };
+export let _pageTokensPending: PageTokenPending = { key: "", promise: null };
+
+const PAGE_TOKEN_CACHE_TTL_MS = 600000;
+const EMPTY_PAGE_TOKEN_CACHE_TTL_MS = 30000;
+const pushIdCache = createOriginScopedStringCache({
+ cachePrefix: "https://internal-cache/gemini-push-id/",
+ ttlSec: GEMINI_PUSH_ID_CACHE_TTL_SEC,
+ payloadKey: "push_id",
+ logLabel: "Gemini push_id",
+});
+
+export function resetGeminiUploadCachesForTest(): void {
+ _pageTokens = { key: "", tokens: null, ts: 0 };
+ _pageTokensPending = { key: "", promise: null };
+ pushIdCache.reset();
+}
+
+export async function getPageTokens(cfg: RuntimeConfig): Promise {
+ const activeCfg = await configWithFreshGeminiCookie(cfg);
+ return getPageTokensForConfig(activeCfg);
+}
+
+export async function getPageTokensForConfig(
+ activeCfg: RuntimeConfig,
+): Promise {
+ const now = Date.now();
+ const cacheKey = `${activeCfg.gemini_origin || "https://gemini.google.com"}\x00${activeCfg.resin_proxy || ""}\x00${accountPrefix(activeCfg)}\x00${activeCfg.cookie || ""}`;
+ if (
+ _pageTokens.tokens &&
+ _pageTokens.key === cacheKey &&
+ now - _pageTokens.ts < pageTokenCacheTtl(_pageTokens.tokens)
+ )
+ return _pageTokens.tokens;
+ if (_pageTokensPending.promise && _pageTokensPending.key === cacheKey)
+ return _pageTokensPending.promise;
+ const promise = (async () => {
+ const headers: Record = {
+ "User-Agent": GEMINI_UPLOAD_USER_AGENT,
+ "Accept-Language": "en-US,en;q=0.9",
+ };
+ if (activeCfg.cookie) headers["Cookie"] = activeCfg.cookie;
+ const tokens: PageTokens = {};
+ let shouldCache = true;
+ try {
+ const resp = await httpFetch(geminiAppUrl(activeCfg), {
+ headers,
+ timeoutMs: 30000,
+ socket: activeCfg.upstream_socket,
+ cfg: activeCfg,
+ });
+ Object.assign(tokens, await extractGeminiAppPageTokens(resp));
+ if (!hasAnyPageToken(tokens)) {
+ log(
+ activeCfg,
+ "gemini app page token markers missing; content-push upload unavailable",
+ );
+ }
+ } catch (e) {
+ shouldCache = false;
+ log(
+ activeCfg,
+ `gemini app page token fetch failed; content-push upload unavailable ${errorLogSummary(e)}`,
+ );
+ }
+ if (shouldCache) _pageTokens = { key: cacheKey, tokens, ts: now };
+ return tokens;
+ })();
+ _pageTokensPending = { key: cacheKey, promise };
+ try {
+ return await promise;
+ } finally {
+ if (_pageTokensPending.promise === promise)
+ _pageTokensPending = { key: "", promise: null };
+ }
+}
+
+export async function getGeminiPushId(cfg: RuntimeConfig): Promise {
+ const cachedPushId = await getCachedGeminiPushId(cfg);
+ if (cachedPushId) return cachedPushId;
+ return getFreshGeminiPushId(cfg);
+}
+
+export async function getCachedGeminiPushId(
+ cfg: RuntimeConfig,
+): Promise {
+ return pushIdCache.getCached(cfg);
+}
+
+export async function setCachedGeminiPushId(
+ cfg: RuntimeConfig,
+ value: string,
+): Promise {
+ await pushIdCache.setCached(cfg, value);
+}
+
+export async function refreshGeminiPushId(cfg: RuntimeConfig): Promise {
+ await pushIdCache.deleteCached(cfg);
+ return getFreshGeminiPushId(cfg);
+}
+
+async function getFreshGeminiPushId(cfg: RuntimeConfig): Promise {
+ return pushIdCache.getFresh(cfg, fetchFreshGeminiPushId);
+}
+
+export function contentPushUploadTokens(
+ pushId: string | null | undefined,
+ protocol: string,
+): ContentPushUploadTokens {
+ const value = validGeminiPushId(pushId);
+ if (!value) {
+ throw contentPushUploadError(
+ "content_push_missing_page_token",
+ `content-push ${protocol} upload missing Gemini page token: push_id`,
+ { protocol },
+ );
+ }
+ return { pushId: value };
+}
+
+function pageTokenCacheTtl(tokens: PageTokens): number {
+ return hasAnyPageToken(tokens)
+ ? PAGE_TOKEN_CACHE_TTL_MS
+ : EMPTY_PAGE_TOKEN_CACHE_TTL_MS;
+}
+
+function hasAnyPageToken(tokens: PageTokens): boolean {
+ return !!(tokens.at || tokens.push_id);
+}
+
+function validGeminiPushId(value: unknown): string {
+ const pushId = typeof value === "string" ? value.trim() : "";
+ return pushId ? pushId : "";
+}
+
+async function fetchFreshGeminiPushId(cfg: RuntimeConfig): Promise {
+ const activeCfg = await configWithFreshGeminiCookie(cfg);
+ try {
+ const headers: Record = {
+ "User-Agent": GEMINI_UPLOAD_USER_AGENT,
+ "Accept-Language": "en-US,en;q=0.9",
+ };
+ if (activeCfg.cookie) headers["Cookie"] = activeCfg.cookie;
+ const resp = await httpFetch(geminiAppUrl(activeCfg), {
+ headers,
+ timeoutMs: 30000,
+ socket: activeCfg.upstream_socket,
+ cfg: activeCfg,
+ });
+ const pushId = validGeminiPushId(await extractGeminiPushId(resp));
+ if (!pushId) {
+ log(
+ activeCfg,
+ "gemini app page push_id marker missing; content-push upload unavailable",
+ );
+ }
+ return pushId;
+ } catch (e) {
+ log(
+ activeCfg,
+ `gemini app page push_id fetch failed; content-push upload unavailable ${errorLogSummary(e)}`,
+ );
+ return "";
+ }
+}
diff --git a/src/http/core/auth.ts b/src/http/core/auth.ts
new file mode 100644
index 0000000000000000000000000000000000000000..209a552d5f09d3d84b6d2149d5a9a4f3f1747ff5
--- /dev/null
+++ b/src/http/core/auth.ts
@@ -0,0 +1,33 @@
+import { timingSafeStringEqual } from "../../shared/crypto";
+
+type AuthConfig = { api_keys?: readonly string[] | null | undefined };
+
+// Accept the caller key from Bearer, x-api-key, x-goog-api-key, or ?key=.
+export function authorized(
+ request: Request,
+ url: URL,
+ cfg: AuthConfig,
+): boolean {
+ const keys = cfg.api_keys || [];
+ if (!keys.length) return true;
+ const h = request.headers;
+ const auth = h.get("authorization") || "";
+ const bearer = /^\s*Bearer\s+(.+?)\s*$/i.exec(auth);
+ const candidates = [
+ bearer?.[1] ? bearer[1] : null,
+ h.get("x-api-key"),
+ h.get("x-goog-api-key"),
+ url.searchParams.get("key"),
+ ];
+ for (const raw of candidates) {
+ const candidate = String(raw || "").trim();
+ if (!candidate) continue;
+ let matched = false;
+ for (const configured of keys) {
+ matched =
+ timingSafeStringEqual(candidate, String(configured || "")) || matched;
+ }
+ if (matched) return true;
+ }
+ return false;
+}
diff --git a/src/http/core/cors.ts b/src/http/core/cors.ts
new file mode 100644
index 0000000000000000000000000000000000000000..e26d811855fce38a8503d7ac5d4b20dbd603d141
--- /dev/null
+++ b/src/http/core/cors.ts
@@ -0,0 +1,94 @@
+export const DEFAULT_CORS_ALLOW_HEADERS = [
+ "Content-Type",
+ "Authorization",
+ "OpenAI-Organization",
+ "OpenAI-Project",
+ "OpenAI-Beta",
+ "X-API-Key",
+ "X-Goog-Api-Key",
+ "Anthropic-Version",
+ "Anthropic-Beta",
+ "X-Stainless-OS",
+ "X-Stainless-Arch",
+ "X-Stainless-Lang",
+ "X-Stainless-Package-Version",
+ "X-Stainless-Runtime",
+ "X-Stainless-Runtime-Version",
+ "X-Client-Version",
+ "X-Requested-With",
+ "HTTP-Referer",
+ "X-Title",
+];
+
+export const BLOCKED_CORS_REQUEST_HEADERS = new Set(["x-ds2-internal-token"]);
+const DEFAULT_CORS_ALLOW_HEADERS_VALUE = DEFAULT_CORS_ALLOW_HEADERS.join(", ");
+
+export function corsHeaders(request: Request): Record {
+ const origin = String(request.headers.get("Origin") || "").trim();
+ const headers: Record = {
+ "Access-Control-Allow-Origin": origin || "*",
+ "Access-Control-Allow-Headers": buildCORSAllowHeaders(request),
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
+ "Access-Control-Max-Age": "600",
+ Vary: "Origin, Access-Control-Request-Headers, Access-Control-Request-Private-Network",
+ };
+ if (
+ /^true$/i.test(
+ String(
+ request.headers.get("Access-Control-Request-Private-Network") || "",
+ ).trim(),
+ )
+ ) {
+ headers["Access-Control-Allow-Private-Network"] = "true";
+ }
+ return headers;
+}
+
+export function buildCORSAllowHeaders(request: Request): string {
+ const requested = request.headers.get("Access-Control-Request-Headers") || "";
+ if (!String(requested || "").trim()) return DEFAULT_CORS_ALLOW_HEADERS_VALUE;
+ const names: string[] = [];
+ const seen = new Set();
+ const append = (name: unknown) => {
+ const headerName = String(name || "").trim();
+ if (!isValidCORSHeaderToken(headerName)) return;
+ const key = headerName.toLowerCase();
+ if (BLOCKED_CORS_REQUEST_HEADERS.has(key) || seen.has(key)) return;
+ seen.add(key);
+ names.push(headerName);
+ };
+ for (const name of DEFAULT_CORS_ALLOW_HEADERS) append(name);
+ for (const name of splitCORSRequestHeaders(requested)) append(name);
+ return names.join(", ");
+}
+
+export function splitCORSRequestHeaders(raw: unknown): string[] {
+ if (!String(raw || "").trim()) return [];
+ return String(raw)
+ .split(",")
+ .map((s) => s.trim())
+ .filter(Boolean);
+}
+
+export function isValidCORSHeaderToken(v: unknown): boolean {
+ return /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(String(v || ""));
+}
+
+export function withCORS(response: Response, request: Request): Response {
+ const cors = corsHeaders(request);
+ try {
+ for (const [key, value] of Object.entries(cors))
+ response.headers.set(key, value);
+ return response;
+ } catch (_) {
+ // Some platform-created responses expose immutable headers; keep the old
+ // wrapping path for those rare cases.
+ }
+ const headers = new Headers(response.headers);
+ for (const [key, value] of Object.entries(cors)) headers.set(key, value);
+ return new Response(response.body, {
+ status: response.status,
+ statusText: response.statusText,
+ headers,
+ });
+}
diff --git a/src/http/core/json.ts b/src/http/core/json.ts
new file mode 100644
index 0000000000000000000000000000000000000000..991e5b9264f1904c7fc397c99c70c427007f236f
--- /dev/null
+++ b/src/http/core/json.ts
@@ -0,0 +1,225 @@
+import { UTF8_FATAL_DECODER } from "../../shared/encoding";
+import { tryParseJson } from "../../shared/json";
+import type { UnknownRecord } from "../../shared/types";
+
+export { parseJson, parseJsonObject, tryParseJson } from "../../shared/json";
+
+export type ReadJsonRequestResult =
+ | {
+ value: UnknownRecord;
+ bytes: number;
+ error?: undefined;
+ status?: undefined;
+ code?: undefined;
+ }
+ | {
+ error: string;
+ status: number;
+ code?: string;
+ value?: undefined;
+ text?: undefined;
+ bytes?: undefined;
+ };
+
+export type ReadRequestBodyBytesResult =
+ | {
+ value: Uint8Array;
+ bytes: number;
+ error?: undefined;
+ status?: undefined;
+ code?: undefined;
+ }
+ | {
+ error: string;
+ status: number;
+ code?: string;
+ value?: undefined;
+ bytes?: undefined;
+ };
+
+export type ReadJsonRequestOptions = {
+ maxBodyBytes?: number | null;
+ oversizedError?: {
+ message: string;
+ status: number;
+ code?: string;
+ };
+};
+
+export function jsonResponse(
+ data: unknown,
+ status = 200,
+ extra: HeadersInit = {},
+): Response {
+ return jsonTextResponse(JSON.stringify(data), status, extra);
+}
+
+export function jsonTextResponse(
+ body: string,
+ status = 200,
+ extra: HeadersInit = {},
+): Response {
+ return new Response(body, {
+ status,
+ headers: { "Content-Type": "application/json", ...extra },
+ });
+}
+
+export async function readJsonRequest(
+ request: Request,
+ options: ReadJsonRequestOptions = {},
+): Promise {
+ const read = await readRequestBodyBytes(request, options);
+ if (read.error !== undefined) return read;
+ const buf = read.value;
+ let bodyText: string;
+ try {
+ bodyText = UTF8_FATAL_DECODER.decode(buf);
+ } catch (_) {
+ return { error: "invalid UTF-8 request body", status: 400 };
+ }
+ const parsed = tryParseJson(bodyText);
+ if (!parsed.ok) return { error: "invalid JSON", status: 400 };
+ if (
+ !parsed.value ||
+ typeof parsed.value !== "object" ||
+ Array.isArray(parsed.value)
+ ) {
+ return { error: "request body must be a JSON object", status: 400 };
+ }
+ return { value: parsed.value as UnknownRecord, bytes: buf.byteLength };
+}
+
+export async function readRequestBodyBytes(
+ request: Request,
+ options: ReadJsonRequestOptions = {},
+): Promise {
+ try {
+ const maxBodyBytes = boundedMaxBodyBytes(options.maxBodyBytes);
+ const value = await readRequestBodyBounded(
+ request,
+ maxBodyBytes,
+ options.oversizedError,
+ );
+ return { value, bytes: value.byteLength };
+ } catch (e) {
+ if (isReadJsonRequestError(e)) {
+ return e.result;
+ }
+ const err = e as { message?: unknown } | null | undefined;
+ return {
+ error: `failed to read request body: ${err?.message || e}`,
+ status: 400,
+ };
+ }
+}
+
+type ReadJsonRequestError = Error & {
+ result: Extract;
+};
+
+function boundedMaxBodyBytes(value: number | null | undefined): number | null {
+ if (value == null) return null;
+ const n = Math.floor(Number(value));
+ return Number.isFinite(n) && n >= 0 ? n : null;
+}
+
+async function readRequestBodyBounded(
+ request: Request,
+ maxBodyBytes: number | null,
+ oversizedError?: ReadJsonRequestOptions["oversizedError"],
+): Promise {
+ if (maxBodyBytes == null) return request.bytes();
+ const contentLength = requestContentLength(request);
+ if (contentLength != null && contentLength > maxBodyBytes) {
+ throw readJsonRequestError(
+ oversizedError || oversizedBodyError(contentLength, maxBodyBytes),
+ );
+ }
+ if (!request.body) return request.bytes();
+ const reader = request.body.getReader();
+ let out = contentLength != null ? new Uint8Array(contentLength) : null;
+ let chunks: Uint8Array[] | null = out ? null : [];
+ let total = 0;
+ try {
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ if (!value?.byteLength) continue;
+ const nextTotal = total + value.byteLength;
+ if (nextTotal > maxBodyBytes) {
+ try {
+ await reader.cancel();
+ } catch (_) {}
+ throw readJsonRequestError(
+ oversizedError || {
+ message: `request body is too large (${nextTotal} bytes > ${maxBodyBytes})`,
+ status: 413,
+ },
+ );
+ }
+ if (out && nextTotal <= out.byteLength) {
+ out.set(value, total);
+ } else {
+ if (!chunks) {
+ chunks = [];
+ if (out && total > 0) chunks.push(out.subarray(0, total));
+ out = null;
+ }
+ chunks.push(value);
+ }
+ total = nextTotal;
+ }
+ } finally {
+ try {
+ reader.releaseLock();
+ } catch (_) {}
+ }
+ if (out) return total === out.byteLength ? out : out.subarray(0, total);
+ if (!chunks) return new Uint8Array(0);
+ const merged = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) {
+ merged.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return merged;
+}
+
+export function requestContentLength(request: Request): number | null {
+ const raw = request.headers.get("content-length");
+ if (!raw) return null;
+ const trimmed = raw.trim();
+ if (!/^(0|[1-9]\d*)$/.test(trimmed)) return null;
+ const n = Number(trimmed);
+ return Number.isSafeInteger(n) ? n : null;
+}
+
+function oversizedBodyError(
+ total: number,
+ maxBodyBytes: number,
+): NonNullable {
+ return {
+ message: `request body is too large (${total} bytes > ${maxBodyBytes})`,
+ status: 413,
+ };
+}
+
+function readJsonRequestError(
+ result: ReadJsonRequestOptions["oversizedError"],
+): ReadJsonRequestError {
+ const err = new Error(
+ result?.message || "failed to read request body",
+ ) as ReadJsonRequestError;
+ const responseError: Extract = {
+ error: result?.message || "failed to read request body",
+ status: result?.status || 400,
+ };
+ if (result?.code) responseError.code = result.code;
+ err.result = responseError;
+ return err;
+}
+
+function isReadJsonRequestError(error: unknown): error is ReadJsonRequestError {
+ return !!error && typeof error === "object" && "result" in error;
+}
diff --git a/src/http/core/model-routes.ts b/src/http/core/model-routes.ts
new file mode 100644
index 0000000000000000000000000000000000000000..6ce9aa7a4693baa566b316aefc379daec9c6ac39
--- /dev/null
+++ b/src/http/core/model-routes.ts
@@ -0,0 +1,46 @@
+import { VERSION } from "../../config";
+import { MODELS } from "../../models";
+
+const OPENAI_MODEL_LIST = Object.entries(MODELS).map(([n, c]) => ({
+ id: n,
+ object: "model",
+ created: 1700000000,
+ owned_by: "google",
+ description: c.desc,
+}));
+const GOOGLE_MODEL_LIST = Object.entries(MODELS).map(([n, c]) => ({
+ name: `models/${n}`,
+ displayName: n,
+ description: c.desc,
+ supportedGenerationMethods: ["generateContent", "streamGenerateContent"],
+}));
+const HEALTH_MODEL_IDS = Object.keys(MODELS);
+
+export const OPENAI_MODEL_LIST_JSON = JSON.stringify({
+ object: "list",
+ data: OPENAI_MODEL_LIST,
+});
+export const OPENAI_MODEL_JSON_BY_ID = new Map(
+ Object.entries(MODELS).map(([id, cfg]) => [
+ id,
+ JSON.stringify({
+ id,
+ object: "model",
+ created: 1700000000,
+ owned_by: "google",
+ description: cfg.desc,
+ }),
+ ]),
+);
+export const GOOGLE_MODEL_LIST_JSON = JSON.stringify({
+ models: GOOGLE_MODEL_LIST,
+});
+export const GOOGLE_MODEL_JSON_BY_ID = new Map(
+ GOOGLE_MODEL_LIST.map((model) => [model.displayName, JSON.stringify(model)]),
+);
+export const HEALTH_JSON = JSON.stringify({
+ status: "ok",
+ version: VERSION,
+ models: HEALTH_MODEL_IDS,
+});
+export const NOT_FOUND_JSON = JSON.stringify({ error: "not found" });
diff --git a/src/http/core/route-json.ts b/src/http/core/route-json.ts
new file mode 100644
index 0000000000000000000000000000000000000000..e5e61e87ea1b2eee79d04cb5eef097fe1edb6532
--- /dev/null
+++ b/src/http/core/route-json.ts
@@ -0,0 +1,169 @@
+import { contextFileThreshold } from "../../completion/context-files";
+import { elapsedMs, logStage, nowMs } from "../../shared/logging";
+import type { UnknownRecord } from "../../shared/types";
+import { readJsonRequest, requestContentLength } from "./json";
+import type { ReadJsonRequestOptions } from "./json";
+
+const LARGE_CONTEXT_INLINE_UNSUPPORTED = "large_context_inline_unsupported";
+
+type RouteJsonConfig = {
+ current_input_file_enabled?: unknown;
+ current_input_file_min_bytes?: unknown;
+ generic_file_upload_max_bytes?: unknown;
+ request_body_max_bytes?: unknown;
+ supports_authenticated_session?: unknown;
+ cookie?: unknown;
+ log_requests?: unknown;
+};
+
+const JSON_ATTACHMENT_OVERHEAD_BYTES = 1024 * 1024;
+
+export type RouteJsonPostResult =
+ | {
+ value: UnknownRecord;
+ error?: undefined;
+ status?: undefined;
+ code?: undefined;
+ }
+ | { error: string; status: number; code?: string; value?: undefined };
+
+export async function readRouteJsonPost(
+ request: Request,
+ cfg: RouteJsonConfig,
+ path: string,
+): Promise {
+ const rejection = oversizedInlineBodyRejection(request, cfg, path);
+ if (rejection) return rejection;
+ const parsed = await readJsonForRoute(request, cfg, path);
+ if (parsed.error !== undefined) {
+ const errorResult: Extract = {
+ error: parsed.error,
+ status: parsed.status || 400,
+ };
+ if (parsed.code) errorResult.code = parsed.code;
+ return errorResult;
+ }
+ return { value: parsed.value };
+}
+
+export function googleJsonError(
+ message: string,
+ code?: string,
+): { error: { message: string; code?: string } } {
+ const error: { message: string; code?: string } = { message };
+ if (code) error.code = code;
+ return { error };
+}
+
+function oversizedInlineBodyRejection(
+ request: Request,
+ cfg: RouteJsonConfig,
+ path: string,
+): { message: string; error: string; status: number; code: string } | null {
+ const unavailable = inlineContextUnavailableReason(cfg);
+ if (!unavailable) return null;
+ const contentLength = requestContentLength(request);
+ if (contentLength == null) return null;
+ const threshold = contextFileThreshold(cfg);
+ const bodyLimit = inlineContextBodyReadLimit(cfg, threshold);
+ const requestBodyLimit = positiveIntegerOrNull(cfg.request_body_max_bytes);
+ if (requestBodyLimit != null && requestBodyLimit < bodyLimit) return null;
+ if (contentLength <= bodyLimit) return null;
+ logStage(cfg, "request_json_reject", {
+ path,
+ status: 413,
+ code: LARGE_CONTEXT_INLINE_UNSUPPORTED,
+ bodyBytes: contentLength,
+ threshold,
+ bodyLimit,
+ });
+ const message = `request body is too large to parse without Gemini text attachments (${contentLength} bytes > ${bodyLimit}; inline prompt threshold ${threshold}) and ${unavailable}; configure GEMINI_COOKIE with CURRENT_INPUT_FILE_ENABLED=true so this worker can use text attachments, or reduce the request size`;
+ return {
+ status: 413,
+ code: LARGE_CONTEXT_INLINE_UNSUPPORTED,
+ message,
+ error: message,
+ };
+}
+
+async function readJsonForRoute(
+ request: Request,
+ cfg: RouteJsonConfig,
+ path: string,
+) {
+ const options = oversizedInlineBodyReadOptions(cfg);
+ const start = cfg.log_requests ? nowMs() : 0;
+ const parsed = await readJsonRequest(request, options);
+ if (cfg.log_requests) {
+ logStage(cfg, "request_json", {
+ path,
+ ms: elapsedMs(start),
+ status: parsed.error !== undefined ? parsed.status : 200,
+ code: parsed.code,
+ bodyBytes: parsed.bytes ?? requestContentLength(request) ?? "unknown",
+ bodyLimit: options?.maxBodyBytes,
+ });
+ }
+ return parsed;
+}
+
+function oversizedInlineBodyReadOptions(
+ cfg: RouteJsonConfig,
+): ReadJsonRequestOptions | undefined {
+ const requestBodyLimit = positiveIntegerOrNull(cfg.request_body_max_bytes);
+ const unavailable = inlineContextUnavailableReason(cfg);
+ if (!unavailable) return requestBodyReadOptions(requestBodyLimit);
+ const threshold = contextFileThreshold(cfg);
+ const bodyLimit = inlineContextBodyReadLimit(cfg, threshold);
+ if (requestBodyLimit != null && requestBodyLimit < bodyLimit)
+ return requestBodyReadOptions(requestBodyLimit);
+ return {
+ maxBodyBytes: bodyLimit,
+ oversizedError: {
+ status: 413,
+ code: LARGE_CONTEXT_INLINE_UNSUPPORTED,
+ message: `request body is too large to parse without Gemini text attachments (at least ${bodyLimit + 1} UTF-8 bytes > ${bodyLimit}; inline prompt threshold ${threshold}) and ${unavailable}; configure GEMINI_COOKIE with CURRENT_INPUT_FILE_ENABLED=true so this worker can use text attachments, or reduce the request size`,
+ },
+ };
+}
+
+function requestBodyReadOptions(
+ requestBodyLimit: number | null,
+): ReadJsonRequestOptions | undefined {
+ if (requestBodyLimit == null) return undefined;
+ return {
+ maxBodyBytes: requestBodyLimit,
+ oversizedError: {
+ status: 413,
+ code: "request_body_too_large",
+ message: `request body exceeds configured JSON limit (${requestBodyLimit} bytes)`,
+ },
+ };
+}
+
+function positiveIntegerOrNull(value: unknown): number | null {
+ const numberValue = Number(value);
+ if (!Number.isSafeInteger(numberValue) || numberValue <= 0) return null;
+ return numberValue;
+}
+
+export function inlineContextBodyReadLimit(
+ cfg: RouteJsonConfig,
+ threshold: number = contextFileThreshold(cfg),
+): number {
+ const attachmentMaxBytes = Number(cfg.generic_file_upload_max_bytes);
+ if (!Number.isFinite(attachmentMaxBytes) || attachmentMaxBytes <= 0)
+ return threshold;
+ const encodedAttachmentBytes = Math.ceil(
+ (Math.floor(attachmentMaxBytes) * 4) / 3,
+ );
+ return threshold + encodedAttachmentBytes + JSON_ATTACHMENT_OVERHEAD_BYTES;
+}
+
+function inlineContextUnavailableReason(cfg: RouteJsonConfig): string {
+ if (!cfg.current_input_file_enabled)
+ return "CURRENT_INPUT_FILE_ENABLED is disabled";
+ if (!(cfg.supports_authenticated_session ?? !!cfg.cookie))
+ return "GEMINI_COOKIE is not configured";
+ return "";
+}
diff --git a/src/http/core/sse.ts b/src/http/core/sse.ts
new file mode 100644
index 0000000000000000000000000000000000000000..3ebb84691ac07d12a4d4b81d6f85dd679248a511
--- /dev/null
+++ b/src/http/core/sse.ts
@@ -0,0 +1,124 @@
+import { TEXT_ENCODER } from "../../shared/encoding";
+import { isAbortError, sleep } from "../../shared/abort";
+import { upstreamErrorCode, upstreamErrorMessage } from "../../shared/errors";
+
+export type SSEWrite = (chunk: string) => void | Promise;
+export type SSEProducer = (
+ write: SSEWrite,
+ signal: AbortSignal,
+) => unknown | Promise;
+export type SSEOptions = {
+ onError?: (write: SSEWrite, error: unknown) => unknown | Promise;
+};
+
+const SSE_DONE_FRAME = "data: [DONE]\n\n";
+const SSE_KEEP_ALIVE_FRAME = ": keep-alive\n\n";
+const SSE_DONE_CHUNK = TEXT_ENCODER.encode(SSE_DONE_FRAME);
+const SSE_KEEP_ALIVE_CHUNK = TEXT_ENCODER.encode(SSE_KEEP_ALIVE_FRAME);
+
+export function sseResponse(
+ producer: SSEProducer,
+ options: SSEOptions = {},
+): Response {
+ const ac = new AbortController();
+ const { readable, writable } = createSSETransform();
+ const writer = writable.getWriter();
+ let closed = false;
+ let keepAliveWrite: Promise | null = null;
+
+ const abort = (reason: unknown) => {
+ try {
+ if (!ac.signal.aborted) ac.abort(reason);
+ } catch (_) {}
+ };
+
+ const write: SSEWrite = (chunk) => {
+ if (closed || ac.signal.aborted) return;
+ const bytes = sseFrameBytes(chunk);
+ try {
+ return writer.write(bytes).catch(() => {
+ closed = true;
+ abort("stream closed");
+ });
+ } catch (_) {
+ closed = true;
+ abort("stream closed");
+ return;
+ }
+ };
+
+ writer.closed.catch(() => abort("client disconnected"));
+
+ const runKeepAlive = async () => {
+ while (!closed && !ac.signal.aborted) {
+ try {
+ await sleep(15000, ac.signal);
+ } catch (_) {
+ return;
+ }
+ if (closed || ac.signal.aborted || keepAliveWrite) return;
+ keepAliveWrite = Promise.resolve(write(SSE_KEEP_ALIVE_FRAME)).then(
+ () => undefined,
+ () => undefined,
+ );
+ await keepAliveWrite;
+ keepAliveWrite = null;
+ }
+ };
+
+ const run = async () => {
+ void runKeepAlive();
+ try {
+ await producer(write, ac.signal);
+ } catch (e) {
+ if (isAbortError(e) || ac.signal.aborted) return;
+ if (typeof options.onError === "function") {
+ try {
+ await options.onError(write, e);
+ } catch (_) {}
+ } else {
+ await write(
+ `event: error\ndata: ${JSON.stringify({ error: { message: upstreamErrorMessage(e), code: upstreamErrorCode(e) || "stream_error" } })}\n\n`,
+ );
+ }
+ } finally {
+ closed = true;
+ abort("stream finished");
+ try {
+ await writer.close();
+ } catch (_) {}
+ try {
+ writer.releaseLock();
+ } catch (_) {}
+ }
+ };
+ void run();
+
+ return new Response(readable, {
+ headers: {
+ "Content-Type": "text/event-stream",
+ "Cache-Control": "no-cache, no-transform",
+ Connection: "keep-alive",
+ "X-Accel-Buffering": "no",
+ },
+ });
+}
+
+function sseFrameBytes(chunk: string): Uint8Array {
+ if (chunk === SSE_DONE_FRAME) return SSE_DONE_CHUNK;
+ if (chunk === SSE_KEEP_ALIVE_FRAME) return SSE_KEEP_ALIVE_CHUNK;
+ return TEXT_ENCODER.encode(chunk);
+}
+
+function createSSETransform(): TransformStream {
+ const Ctor =
+ (
+ globalThis as typeof globalThis & {
+ IdentityTransformStream?: new () => TransformStream<
+ Uint8Array,
+ Uint8Array
+ >;
+ }
+ ).IdentityTransformStream || TransformStream;
+ return new Ctor();
+}
diff --git a/src/http/core/stream-errors.ts b/src/http/core/stream-errors.ts
new file mode 100644
index 0000000000000000000000000000000000000000..ba1b3774a0dfc9cb25fb7d83e18bc662f7c61c54
--- /dev/null
+++ b/src/http/core/stream-errors.ts
@@ -0,0 +1,33 @@
+import { upstreamErrorCode, upstreamErrorMessage } from "../../shared/errors";
+import type { SSEWrite } from "./sse";
+
+export function streamErrorText(e: unknown, prefix = "upstream error"): string {
+ const code = upstreamErrorCode(e);
+ return `⚠️ ${prefix}: ${upstreamErrorMessage(e)}${code ? ` [${code}]` : ""}`;
+}
+
+export function streamInterruptedWarningText(e: unknown): string {
+ return streamErrorText(e, "stream interrupted after partial output");
+}
+
+export function streamWarningObject(
+ e: unknown,
+ message: unknown = undefined,
+): { code: string; message: unknown } {
+ return {
+ code: upstreamErrorCode(e) || "stream_interrupted",
+ message: message || streamInterruptedWarningText(e),
+ };
+}
+
+export async function writeStreamWarningEvent(
+ write: SSEWrite,
+ e: unknown,
+ message: unknown = undefined,
+): Promise {
+ const result = write(
+ `event: warning\ndata: ${JSON.stringify({ warning: streamWarningObject(e, message) })}\n\n`,
+ );
+ if (result && typeof (result as Promise).then === "function")
+ await result;
+}
diff --git a/src/http/google/format.ts b/src/http/google/format.ts
new file mode 100644
index 0000000000000000000000000000000000000000..7ae28de198f88ea4d8ab8fbafdbfe3952496775b
--- /dev/null
+++ b/src/http/google/format.ts
@@ -0,0 +1,113 @@
+import type { GoogleResponsePart } from "../../completion/google-turn";
+import { upstreamErrorCode, upstreamErrorMessage } from "../../shared/errors";
+import type { SSEWrite } from "../core/sse";
+import { streamWarningObject } from "../core/stream-errors";
+import { isPromiseLike } from "../stream/promise";
+
+export function googleErrorResponseBody(
+ message: unknown,
+ code: unknown = undefined,
+) {
+ const error: Record = { message };
+ if (code) error.code = code;
+ return { error };
+}
+
+export async function writeGoogleStreamError(
+ write: SSEWrite,
+ model: unknown,
+ e: unknown,
+): Promise {
+ const result = write(
+ `data: ${JSON.stringify({
+ error: {
+ message: upstreamErrorMessage(e),
+ code: upstreamErrorCode(e) || "upstream_error",
+ },
+ modelVersion: model,
+ })}\n\n`,
+ );
+ if (isPromiseLike(result)) await result;
+}
+
+export async function writeGoogleCandidate(
+ write: SSEWrite,
+ model: unknown,
+ parts: GoogleResponsePart[] | null,
+ finishReason: string | null,
+): Promise {
+ const candidate: Record = { index: 0 };
+ if (Array.isArray(parts) && parts.length)
+ candidate.content = { parts, role: "model" };
+ if (finishReason) candidate.finishReason = finishReason;
+ const result = write(
+ `data: ${JSON.stringify({ candidates: [candidate], modelVersion: model })}\n\n`,
+ );
+ if (isPromiseLike(result)) await result;
+}
+
+export async function writeGoogleDone(
+ write: SSEWrite,
+ model: unknown,
+ usageMetadata: unknown,
+): Promise {
+ const result = write(
+ `data: ${JSON.stringify({
+ candidates: [{ finishReason: "STOP", index: 0 }],
+ usageMetadata,
+ modelVersion: model,
+ })}\n\n`,
+ );
+ if (isPromiseLike(result)) await result;
+}
+
+export function googleGenerateContentResponse(params: {
+ model: string;
+ responseParts: GoogleResponsePart[];
+ promptTokens: number;
+ candidateTokens: number;
+ upstreamEmpty: boolean;
+ warning?: unknown;
+}) {
+ const responseObj: Record = {
+ candidates: [
+ {
+ content: { parts: params.responseParts, role: "model" },
+ finishReason: "STOP",
+ index: 0,
+ },
+ ],
+ usageMetadata: {
+ promptTokenCount: params.promptTokens,
+ candidatesTokenCount: params.candidateTokens,
+ totalTokenCount: params.promptTokens + params.candidateTokens,
+ },
+ modelVersion: params.model,
+ };
+ if (params.upstreamEmpty)
+ responseObj.promptFeedback = {
+ blockReason: "OTHER",
+ warning: params.warning,
+ };
+ return responseObj;
+}
+
+export function googleStreamDonePayload(
+ model: string,
+ promptTokens: number,
+ candidateTokens: number,
+ streamErr: unknown = null,
+) {
+ const donePayload: Record = {
+ candidates: [{ finishReason: "STOP", index: 0 }],
+ usageMetadata: {
+ promptTokenCount: promptTokens,
+ candidatesTokenCount: candidateTokens,
+ totalTokenCount: promptTokens + candidateTokens,
+ },
+ modelVersion: model,
+ };
+ if (streamErr)
+ donePayload.promptFeedback = { warning: streamWarningObject(streamErr) };
+ return donePayload;
+}
diff --git a/src/http/google/handlers.ts b/src/http/google/handlers.ts
new file mode 100644
index 0000000000000000000000000000000000000000..7298457dec26f7bfe46332898d90175c3d302477
--- /dev/null
+++ b/src/http/google/handlers.ts
@@ -0,0 +1,189 @@
+import { jsonResponse } from "../core/json";
+import { sseResponse } from "../core/sse";
+import { EMPTY_UPSTREAM_MSG } from "../../completion";
+import type { CompletionProvider } from "../../completion";
+import type { RuntimeConfig } from "../../config";
+import { prepareGoogleCompletion } from "../../completion/google-request";
+import { finalizeGoogleCompletionResult } from "../../completion/google-turn";
+import { elapsedMs, log, logStage, nowMs } from "../../shared/logging";
+import {
+ errorLogSummary,
+ upstreamErrorCode,
+ upstreamErrorMessage,
+ upstreamErrorStatus,
+} from "../../shared/errors";
+import { tokenEst } from "../../shared/tokens";
+import type { UnknownRecord } from "../../shared/types";
+import {
+ googleErrorResponseBody,
+ googleGenerateContentResponse,
+ writeGoogleStreamError,
+} from "./format";
+import { streamGooglePlain, streamGoogleTools } from "./stream";
+
+export async function handleGoogleGenerate(
+ req: UnknownRecord,
+ cfg: RuntimeConfig,
+ provider: CompletionProvider,
+ path: string,
+ stream: boolean,
+) {
+ const logRequests = !!cfg.log_requests;
+ const prepareStart = logRequests ? nowMs() : 0;
+ const prepared = await prepareGoogleCompletion(cfg, provider, req, path);
+ if ("error" in prepared) {
+ await provider.dispose?.();
+ if (logRequests)
+ logStage(cfg, "google_prepare", {
+ ms: elapsedMs(prepareStart),
+ status: prepared.error.status,
+ code: prepared.error.code,
+ });
+ return jsonResponse(
+ googleErrorResponseBody(prepared.error.message, prepared.error.code),
+ prepared.error.status,
+ );
+ }
+ const {
+ rm,
+ effectiveReq,
+ effectiveGoogleTools,
+ hasTools,
+ prompt,
+ fileRefs,
+ promptTokens,
+ contextFiles,
+ } = prepared;
+
+ if (logRequests) {
+ logStage(cfg, "google_prepare", {
+ ms: elapsedMs(prepareStart),
+ status: 200,
+ model: rm.name,
+ stream,
+ tools: hasTools,
+ promptChars: prompt.length,
+ promptTokens,
+ fileRefs: fileRefs ? fileRefs.length : 0,
+ contextFiles: !!contextFiles,
+ contextRefs: contextFiles ? contextFiles.fileRefs.length : 0,
+ });
+ }
+
+ if (stream && !hasTools) {
+ return sseResponse(
+ async (write, signal) => {
+ const generationStart = logRequests ? nowMs() : 0;
+ await streamGooglePlain(write, cfg, {
+ provider,
+ prompt,
+ rm,
+ fileRefs,
+ promptTokens,
+ signal,
+ });
+ if (logRequests)
+ logStage(cfg, "google_stream_generate", {
+ ms: elapsedMs(generationStart),
+ model: rm.name,
+ promptTokens,
+ fileRefs: fileRefs ? fileRefs.length : 0,
+ });
+ },
+ { onError: (write, e) => writeGoogleStreamError(write, rm.name, e) },
+ );
+ }
+
+ if (stream && hasTools) {
+ return sseResponse(
+ async (write, signal) => {
+ const generationStart = logRequests ? nowMs() : 0;
+ await streamGoogleTools(write, cfg, {
+ provider,
+ prompt,
+ rm,
+ fileRefs,
+ tools: effectiveGoogleTools,
+ effectiveReq,
+ promptTokens,
+ signal,
+ });
+ if (logRequests)
+ logStage(cfg, "google_stream_generate", {
+ ms: elapsedMs(generationStart),
+ model: rm.name,
+ promptTokens,
+ fileRefs: fileRefs ? fileRefs.length : 0,
+ tools: effectiveGoogleTools ? effectiveGoogleTools.length : 0,
+ });
+ },
+ { onError: (write, e) => writeGoogleStreamError(write, rm.name, e) },
+ );
+ }
+
+ let text: string;
+ const generationStart = logRequests ? nowMs() : 0;
+ try {
+ text = await provider.generateText({ prompt, rm, fileRefs });
+ } catch (e) {
+ if (logRequests)
+ logStage(cfg, "google_generate", {
+ ms: elapsedMs(generationStart),
+ status: "error",
+ model: rm.name,
+ code: upstreamErrorCode(e) || "upstream_error",
+ });
+ log(
+ cfg,
+ `google generate failed model=${rm.name} code=${upstreamErrorCode(e) || "upstream_error"} error=${errorLogSummary(e)}`,
+ );
+ return jsonResponse(
+ {
+ error: {
+ message: `upstream error: ${upstreamErrorMessage(e)}`,
+ code: upstreamErrorCode(e) || "upstream_error",
+ },
+ },
+ upstreamErrorStatus(e) || 502,
+ );
+ }
+ if (logRequests)
+ logStage(cfg, "google_generate", {
+ ms: elapsedMs(generationStart),
+ status: "ok",
+ model: rm.name,
+ completionChars: text.length,
+ promptTokens,
+ fileRefs: fileRefs ? fileRefs.length : 0,
+ });
+ const upstreamEmpty = !text;
+ if (upstreamEmpty) {
+ log(cfg, `google generate produced no content model=${rm.name}`);
+ return jsonResponse(
+ googleErrorResponseBody(EMPTY_UPSTREAM_MSG, "upstream_empty"),
+ 502,
+ );
+ }
+
+ const finalized = finalizeGoogleCompletionResult(text, {
+ effectiveReq,
+ effectiveGoogleTools,
+ hasTools,
+ });
+ if (finalized.error)
+ return jsonResponse(
+ googleErrorResponseBody(finalized.error.message, finalized.error.code),
+ finalized.error.status,
+ );
+
+ const candidateTokens = tokenEst(text);
+ const responseObj = googleGenerateContentResponse({
+ model: rm.name,
+ responseParts: finalized.responseParts,
+ promptTokens,
+ candidateTokens,
+ upstreamEmpty,
+ });
+
+ return jsonResponse(responseObj);
+}
diff --git a/src/http/google/stream.ts b/src/http/google/stream.ts
new file mode 100644
index 0000000000000000000000000000000000000000..57419e9eaadbe690fe4a19954e64ee0b35a294cc
--- /dev/null
+++ b/src/http/google/stream.ts
@@ -0,0 +1,152 @@
+import {
+ createCompletionStreamLifecycle,
+ recordCompletionStreamEvent,
+ streamPlainCompletionEvents,
+} from "../../completion";
+import type { CompletionProvider } from "../../completion";
+import type { RuntimeConfig } from "../../config";
+import type { ResolvedModel } from "../../models";
+import type { FileRef, LooseRequest } from "../../completion/types";
+import { streamGoogleToolCompletionEvents } from "../../completion/google";
+import { tokenCountFromCounts } from "../../shared/tokens";
+import { errorLogSummary, upstreamErrorCode } from "../../shared/errors";
+import { log } from "../../shared/logging";
+import type { SSEWrite } from "../core/sse";
+import {
+ streamInterruptedWarningText,
+ writeStreamWarningEvent,
+} from "../core/stream-errors";
+import { createDeltaCoalescer } from "../stream/coalescer";
+import {
+ googleStreamDonePayload,
+ writeGoogleCandidate,
+ writeGoogleDone,
+ writeGoogleStreamError,
+} from "./format";
+
+type ResolvedCompletionModel = Extract;
+type GooglePlainStreamParams = {
+ provider: CompletionProvider;
+ prompt: string;
+ rm: ResolvedCompletionModel;
+ fileRefs: FileRef[] | null;
+ promptTokens: number;
+ signal: AbortSignal;
+};
+type GoogleToolStreamParams = GooglePlainStreamParams & {
+ tools: LooseRequest[] | null;
+ effectiveReq: LooseRequest;
+};
+
+export async function streamGooglePlain(
+ write: SSEWrite,
+ cfg: RuntimeConfig,
+ params: GooglePlainStreamParams,
+) {
+ const { provider, prompt, rm, fileRefs, promptTokens, signal } = params;
+ const lifecycle = createCompletionStreamLifecycle();
+ const textCoalescer = createDeltaCoalescer(
+ (delta) => {
+ const text = delta.text || "";
+ return write(
+ `data: ${JSON.stringify({ candidates: [{ content: { parts: [{ text }], role: "model" }, index: 0 }], modelVersion: rm.name })}\n\n`,
+ );
+ },
+ undefined,
+ undefined,
+ { emitFirstImmediately: true },
+ );
+ for await (const event of streamPlainCompletionEvents(
+ provider,
+ { prompt, rm, fileRefs },
+ { signal, coalesceTextDeltas: true },
+ )) {
+ recordCompletionStreamEvent(lifecycle, event);
+ if (event.type === "text_delta") {
+ const appended = textCoalescer.append("text", event.text);
+ if (appended) await appended;
+ }
+ }
+ const flushed = textCoalescer.flush();
+ if (flushed) await flushed;
+ if (lifecycle.issue) {
+ if (!lifecycle.emittedText) {
+ log(
+ cfg,
+ `google stream failed before output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "upstream_error"} error=${errorLogSummary(lifecycle.issue.error)}`,
+ );
+ await writeGoogleStreamError(write, rm.name, lifecycle.issue.error);
+ return;
+ }
+ const warning = `\n\n${streamInterruptedWarningText(lifecycle.issue.error)}`;
+ log(
+ cfg,
+ `google stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "stream_interrupted"} error=${errorLogSummary(lifecycle.issue.error)}`,
+ );
+ await writeStreamWarningEvent(write, lifecycle.issue.error, warning.trim());
+ }
+ const candidateTokens = tokenCountFromCounts(lifecycle.completionCounts);
+ await write(
+ `data: ${JSON.stringify(googleStreamDonePayload(rm.name, promptTokens, candidateTokens, lifecycle.issue ? lifecycle.issue.error : null))}\n\n`,
+ );
+}
+
+export async function streamGoogleTools(
+ write: SSEWrite,
+ cfg: RuntimeConfig,
+ params: GoogleToolStreamParams,
+) {
+ const {
+ provider,
+ prompt,
+ rm,
+ fileRefs,
+ tools,
+ effectiveReq,
+ promptTokens,
+ signal,
+ } = params;
+ for await (const event of streamGoogleToolCompletionEvents(provider, {
+ prompt,
+ rm,
+ fileRefs,
+ tools,
+ effectiveReq,
+ promptTokens,
+ signal,
+ })) {
+ if (event.type === "candidate") {
+ await writeGoogleCandidate(
+ write,
+ rm.name,
+ event.parts,
+ event.finishReason,
+ );
+ } else if (event.type === "error") {
+ log(
+ cfg,
+ `google tool stream failed before output model=${rm.name} code=${upstreamErrorCode(event.error) || "upstream_error"} error=${errorLogSummary(event.error)}`,
+ );
+ await writeGoogleStreamError(write, rm.name, event.error);
+ return;
+ } else if (event.type === "warning") {
+ log(
+ cfg,
+ `google tool stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(event.error) || "stream_interrupted"} error=${errorLogSummary(event.error)}`,
+ );
+ await writeStreamWarningEvent(write, event.error, event.message);
+ } else if (event.type === "tool_policy_violation") {
+ log(
+ cfg,
+ `google tool stream policy violation model=${rm.name} code=${event.violation.code}`,
+ );
+ await writeGoogleStreamError(write, rm.name, {
+ message: event.violation.message,
+ code: event.violation.code,
+ });
+ return;
+ } else if (event.type === "done") {
+ await writeGoogleDone(write, rm.name, event.usageMetadata);
+ }
+ }
+}
diff --git a/src/http/index.ts b/src/http/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..1651f2361d6ec0fbf2645184015ab038d7f9c9b7
--- /dev/null
+++ b/src/http/index.ts
@@ -0,0 +1,41 @@
+export { authorized } from "./core/auth";
+export {
+ BLOCKED_CORS_REQUEST_HEADERS,
+ DEFAULT_CORS_ALLOW_HEADERS,
+ buildCORSAllowHeaders,
+ corsHeaders,
+ isValidCORSHeaderToken,
+ splitCORSRequestHeaders,
+ withCORS,
+} from "./core/cors";
+export {
+ jsonResponse,
+ jsonTextResponse,
+ parseJson,
+ parseJsonObject,
+ readJsonRequest,
+ requestContentLength,
+ tryParseJson,
+} from "./core/json";
+export type {
+ ReadJsonRequestOptions,
+ ReadJsonRequestResult,
+} from "./core/json";
+export { sseResponse } from "./core/sse";
+export type { SSEOptions, SSEProducer, SSEWrite } from "./core/sse";
+export {
+ openAIErrorResponse,
+ openAIErrorType,
+ openAIUpstreamErrorResponse,
+} from "./openai/errors";
+export {
+ streamErrorText,
+ streamInterruptedWarningText,
+ streamWarningObject,
+ writeStreamWarningEvent,
+} from "./core/stream-errors";
+export {
+ MAX_DELTA_FLUSH_WAIT_MS,
+ MIN_DELTA_FLUSH_CHARS,
+ createDeltaCoalescer,
+} from "./stream/coalescer";
diff --git a/src/http/openai/chat-stream.ts b/src/http/openai/chat-stream.ts
new file mode 100644
index 0000000000000000000000000000000000000000..b23b9e2874ecf3389da799423bcd3a51b62f11df
--- /dev/null
+++ b/src/http/openai/chat-stream.ts
@@ -0,0 +1,283 @@
+import { parseJsonObject } from "../core/json";
+import type { SSEWrite } from "../core/sse";
+import {
+ streamInterruptedWarningText,
+ writeStreamWarningEvent,
+} from "../core/stream-errors";
+import { createDeltaCoalescer } from "../stream/coalescer";
+import {
+ EMPTY_UPSTREAM_MSG,
+ createCompletionStreamLifecycle,
+ recordCompletionStreamEvent,
+ streamPlainCompletionEvents,
+ streamToolSieveCompletionEvents,
+} from "../../completion";
+import type {
+ CompletionProvider,
+ CompletionStreamEvent,
+} from "../../completion";
+import type { RuntimeConfig } from "../../config";
+import type { ResolvedModel } from "../../models";
+import type { FileRef } from "../../completion/types";
+import { errorLogSummary, upstreamErrorCode } from "../../shared/errors";
+import { log } from "../../shared/logging";
+import {
+ combinedTokenCount,
+ createTokenCounter,
+ tokenCountFromCounts,
+} from "../../shared/tokens";
+import { formatOpenAIStreamToolCalls } from "../../toolcall/openai-format";
+import type { OpenAIToolCall } from "../../toolcall/openai-format";
+import type { ToolChoicePolicy } from "../../toolcall/policy-openai";
+import { openAIChatChunk, writeOpenAIChatUsageTokenChunk } from "./format";
+import { writeOpenAIChatStreamError } from "./format";
+
+type StreamIssue = Extract<
+ CompletionStreamEvent,
+ { type: "warning" } | { type: "stream_error" }
+>;
+type ResolvedCompletionModel = Extract;
+type OpenAIChatChunkWriter = (
+ delta: Record,
+ finish: string | null,
+) => void | Promise;
+type OpenAIChatDeltaCoalescer = ReturnType