xjackkx commited on
Commit
e81f4e4
·
verified ·
1 Parent(s): 113b9f6

Upload 151 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +28 -0
  2. .gitattributes +49 -0
  3. .gitignore +25 -0
  4. Dockerfile +30 -0
  5. LICENSE +21 -0
  6. biome.json +119 -0
  7. compose.yaml +30 -0
  8. package.json +41 -0
  9. pnpm-lock.yaml +2045 -0
  10. pnpm-workspace.yaml +40 -0
  11. scripts/bench.mjs +1150 -0
  12. scripts/build.mjs +49 -0
  13. scripts/check-architecture.mjs +372 -0
  14. scripts/check-benchmark.mjs +161 -0
  15. scripts/check-bundle-size.mjs +51 -0
  16. scripts/check-coverage.mjs +141 -0
  17. scripts/check-release.mjs +16 -0
  18. scripts/ci-change-risk.mjs +18 -0
  19. scripts/classify-ci-changes.mjs +21 -0
  20. scripts/coverage.mjs +25 -0
  21. scripts/docker-server.mjs +129 -0
  22. scripts/docker-smoke.mjs +115 -0
  23. scripts/ensure-test-bundle-fresh.mjs +29 -0
  24. scripts/io.mjs +25 -0
  25. scripts/process.mjs +88 -0
  26. scripts/smoke.mjs +225 -0
  27. scripts/unit.mjs +10 -0
  28. src/app.ts +301 -0
  29. src/attachments/base64.ts +65 -0
  30. src/attachments/collect-openai.ts +161 -0
  31. src/attachments/input.ts +303 -0
  32. src/attachments/materialize.ts +140 -0
  33. src/attachments/media.ts +3 -0
  34. src/attachments/mime.ts +173 -0
  35. src/attachments/notes.ts +61 -0
  36. src/attachments/plan.ts +215 -0
  37. src/attachments/refs.ts +133 -0
  38. src/attachments/types.ts +71 -0
  39. src/completion/context-files.ts +361 -0
  40. src/completion/context.ts +581 -0
  41. src/completion/google-request.ts +130 -0
  42. src/completion/google-turn.ts +82 -0
  43. src/completion/google.ts +124 -0
  44. src/completion/image-generation.ts +681 -0
  45. src/completion/index.ts +23 -0
  46. src/completion/openai.ts +158 -0
  47. src/completion/ports.ts +51 -0
  48. src/completion/runtime.ts +13 -0
  49. src/completion/stream-coalesce.ts +135 -0
  50. src/completion/stream-events.ts +237 -0
.dockerignore ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .git
2
+ .github
3
+ .claude
4
+ .agents
5
+ .codex
6
+ .cursor
7
+ .trellis
8
+ .wrangler
9
+ node_modules
10
+ dist
11
+ dist-coverage
12
+ coverage
13
+ release-assets
14
+ reports
15
+ tests
16
+ docs
17
+ *.log
18
+ .env
19
+ .env.*
20
+ !.env.example
21
+ .dev.vars
22
+ .dev.vars.*
23
+ !.dev.vars.example
24
+ README*
25
+ LICENSE
26
+ compose.yaml
27
+ worker-configuration.d.ts
28
+ AGENTS.md
.gitattributes ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Normalize text files to LF in both the repository and working tree.
2
+ * text=auto eol=lf
3
+
4
+ # Windows command scripts require CRLF.
5
+ *.bat text eol=crlf
6
+ *.cmd text eol=crlf
7
+
8
+ # Trellis framework tooling is not application source. Keep it visible in
9
+ # diffs while excluding it from GitHub language statistics.
10
+ .trellis/scripts/** linguist-vendored=true
11
+
12
+ # Generated sources should not skew language statistics. The embedded admin
13
+ # bundle is a single generated line, so suppress its unreviewable text diff.
14
+ src/generated/** linguist-generated=true
15
+ src/generated/admin-ui.ts -diff
16
+ worker-configuration.d.ts linguist-generated=true
17
+
18
+ # Images and documents.
19
+ *.avif binary
20
+ *.bmp binary
21
+ *.gif binary
22
+ *.ico binary
23
+ *.jpeg binary
24
+ *.jpg binary
25
+ *.pdf binary
26
+ *.png binary
27
+ *.webp binary
28
+
29
+ # Fonts and compiled web assets.
30
+ *.eot binary
31
+ *.otf binary
32
+ *.ttf binary
33
+ *.wasm binary
34
+ *.woff binary
35
+ *.woff2 binary
36
+
37
+ # Audio and video.
38
+ *.mp3 binary
39
+ *.mp4 binary
40
+ *.ogg binary
41
+ *.wav binary
42
+ *.webm binary
43
+
44
+ # Archives and compressed assets.
45
+ *.7z binary
46
+ *.gz binary
47
+ *.tar binary
48
+ *.tgz binary
49
+ *.zip binary
.gitignore ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ node_modules/
2
+ dist/
3
+ dist-coverage/
4
+ coverage/
5
+ .wrangler/
6
+ *.log
7
+ AGENTS.md
8
+ .env
9
+ .env.*
10
+ !.env.example
11
+ .dev.vars
12
+ .dev.vars.*
13
+ !.dev.vars.example
14
+
15
+ # Local agent and workspace state
16
+ .claude/
17
+ .codex/
18
+ .cursor/
19
+ .trellis/.backup-*
20
+ .trellis/.cache/
21
+ .trellis/.runtime/
22
+ .trellis/.template-hashes.json
23
+ .trellis/worktrees/
24
+ .trellis/tasks/
25
+ .trellis/workspace/
Dockerfile ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM node:26-alpine AS deps
2
+
3
+ WORKDIR /app
4
+ ARG PNPM_VERSION=11.10.0
5
+ RUN npm install -g pnpm@${PNPM_VERSION}
6
+
7
+ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
8
+ RUN pnpm install --frozen-lockfile
9
+
10
+ FROM deps AS build
11
+
12
+ COPY tsconfig.json vitest.config.mjs wrangler.jsonc ./
13
+ COPY scripts ./scripts
14
+ COPY src ./src
15
+ RUN pnpm build
16
+
17
+ FROM node:26-alpine AS runtime
18
+
19
+ WORKDIR /app
20
+ # HuggingFace Space 默认路由到 7860 端口;docker-server 读 PORT 环境变量。
21
+ ENV NODE_ENV=production \
22
+ HOST=0.0.0.0 \
23
+ PORT=7860 \
24
+ UPSTREAM_SOCKET=false
25
+
26
+ COPY --from=build /app/dist/worker.js ./dist/worker.js
27
+ COPY --from=build /app/scripts/docker-server.mjs ./scripts/docker-server.mjs
28
+
29
+ EXPOSE 7860
30
+ CMD ["node", "scripts/docker-server.mjs"]
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Guardinary
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
biome.json ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "https://biomejs.dev/schemas/2.5.3/schema.json",
3
+ "vcs": {
4
+ "enabled": true,
5
+ "clientKind": "git",
6
+ "useIgnoreFile": true
7
+ },
8
+ "files": {
9
+ "includes": [
10
+ "src/**/*.ts",
11
+ "src/**/*.tsx",
12
+ "scripts/**/*.mjs",
13
+ "tests/**/*.js",
14
+ "tests/**/*.mjs",
15
+ "src/**/*.css",
16
+ "*.json",
17
+ "*.jsonc",
18
+ "*.mjs"
19
+ ]
20
+ },
21
+ "javascript": {
22
+ "globals": ["FixedLengthStream"]
23
+ },
24
+ "formatter": {
25
+ "enabled": true,
26
+ "lineEnding": "lf"
27
+ },
28
+ "overrides": [
29
+ {
30
+ "includes": ["src/generated/**"],
31
+ "formatter": {
32
+ "enabled": false
33
+ },
34
+ "linter": {
35
+ "rules": {
36
+ "suspicious": {
37
+ "noTemplateCurlyInString": "off"
38
+ }
39
+ }
40
+ }
41
+ },
42
+ {
43
+ "includes": ["src/index.ts", "src/test-index.ts", "vitest.config.mjs"],
44
+ "linter": {
45
+ "rules": {
46
+ "style": {
47
+ "noDefaultExport": "off"
48
+ }
49
+ }
50
+ }
51
+ },
52
+ {
53
+ "includes": ["scripts/**/*.mjs"],
54
+ "linter": {
55
+ "rules": {
56
+ "suspicious": {
57
+ "noConsole": "off"
58
+ }
59
+ }
60
+ }
61
+ }
62
+ ],
63
+ "linter": {
64
+ "enabled": true,
65
+ "rules": {
66
+ "preset": "recommended",
67
+ "a11y": {
68
+ "preset": "all"
69
+ },
70
+ "correctness": {
71
+ "preset": "all",
72
+ "noNodejsModules": "off",
73
+ "noProcessGlobal": "off",
74
+ "noUnresolvedImports": "off",
75
+ "useImportExtensions": "off",
76
+ "useQwikValidLexicalScope": "off",
77
+ "useUniqueElementIds": "off"
78
+ },
79
+ "security": {
80
+ "preset": "all"
81
+ },
82
+ "performance": {
83
+ "recommended": true
84
+ },
85
+ "complexity": {
86
+ "recommended": true,
87
+ "noUselessStringConcat": "info"
88
+ },
89
+ "style": {
90
+ "recommended": true,
91
+ "noCommonJs": "warn",
92
+ "noDefaultExport": "warn",
93
+ "noEnum": "warn",
94
+ "noNamespace": "warn",
95
+ "noNestedTernary": "info",
96
+ "noParameterAssign": "warn",
97
+ "useAsConstAssertion": "info",
98
+ "useConsistentArrayType": "info",
99
+ "useThrowNewError": "info",
100
+ "useThrowOnlyError": "warn"
101
+ },
102
+ "suspicious": {
103
+ "preset": "all",
104
+ "noAlert": "off",
105
+ "noBitwiseOperators": "off",
106
+ "noControlCharactersInRegex": "off",
107
+ "noDeprecatedImports": "off",
108
+ "noEmptyBlockStatements": "off",
109
+ "noEqualsToNull": "off",
110
+ "noMisplacedAssertion": "off",
111
+ "noUnknownAttribute": "off",
112
+ "noUnnecessaryConditions": "off",
113
+ "useArraySortCompare": "off",
114
+ "useAwait": "off",
115
+ "useStaticResponseMethods": "off"
116
+ }
117
+ }
118
+ }
119
+ }
compose.yaml ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ web2gem:
3
+ image: "${WEB2GEM_IMAGE:-ghcr.io/guardinary/web2gem:latest}"
4
+ pull_policy: always
5
+ restart: unless-stopped
6
+ ports:
7
+ - "${PORT:-52389}:${PORT:-52389}"
8
+ environment:
9
+ HOST: "0.0.0.0"
10
+ PORT: "${PORT:-52389}"
11
+ UPSTREAM_SOCKET: "${UPSTREAM_SOCKET:-false}"
12
+ API_KEYS: "${API_KEYS:-}"
13
+ GEMINI_COOKIE: "${GEMINI_COOKIE:-}"
14
+ SAPISID: "${SAPISID:-}"
15
+ GEMINI_BL: "${GEMINI_BL:-}"
16
+ GEMINI_ORIGIN: "${GEMINI_ORIGIN:-}"
17
+ RESIN_PROXY: "${RESIN_PROXY:-}"
18
+ AUTH_USER: "${AUTH_USER:-}"
19
+ XSRF_TOKEN: "${XSRF_TOKEN:-}"
20
+ DEFAULT_MODEL: "${DEFAULT_MODEL:-}"
21
+ RETRY_ATTEMPTS: "${RETRY_ATTEMPTS:-}"
22
+ RETRY_DELAY_SEC: "${RETRY_DELAY_SEC:-}"
23
+ REQUEST_TIMEOUT_SEC: "${REQUEST_TIMEOUT_SEC:-}"
24
+ REQUEST_BODY_MAX_BYTES: "${REQUEST_BODY_MAX_BYTES:-16777216}"
25
+ LOG_REQUESTS: "${LOG_REQUESTS:-}"
26
+ CURRENT_INPUT_FILE_ENABLED: "${CURRENT_INPUT_FILE_ENABLED:-}"
27
+ CURRENT_INPUT_FILE_MIN_BYTES: "${CURRENT_INPUT_FILE_MIN_BYTES:-}"
28
+ CURRENT_INPUT_FILE_NAME: "${CURRENT_INPUT_FILE_NAME:-}"
29
+ CURRENT_TOOLS_FILE_NAME: "${CURRENT_TOOLS_FILE_NAME:-}"
30
+ GENERIC_FILE_UPLOAD_MAX_BYTES: "${GENERIC_FILE_UPLOAD_MAX_BYTES:-}"
package.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "web2gem",
3
+ "version": "1.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=22"
8
+ },
9
+ "packageManager": "pnpm@11.10.0",
10
+ "scripts": {
11
+ "build": "node scripts/build.mjs",
12
+ "check:static": "biome check --assist-enabled=false --diagnostic-level=warn --error-on-warnings",
13
+ "worker:types": "pnpm build && wrangler types worker-configuration.d.ts --env-interface WorkerBindings --include-runtime false --strict-vars false --env-file .dev.vars.example",
14
+ "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",
15
+ "format": "biome format --write",
16
+ "typecheck": "tsc --noEmit",
17
+ "check:arch": "node scripts/check-architecture.mjs",
18
+ "check:size": "pnpm build && node scripts/check-bundle-size.mjs",
19
+ "check:bench": "node scripts/build.mjs --test-bundle && node scripts/check-benchmark.mjs",
20
+ "check:release": "node scripts/check-release.mjs",
21
+ "unit:quick": "node scripts/ensure-test-bundle-fresh.mjs && vitest run",
22
+ "unit": "node scripts/unit.mjs",
23
+ "coverage": "node scripts/coverage.mjs",
24
+ "coverage:ci": "node scripts/coverage.mjs --ci",
25
+ "smoke": "node scripts/build.mjs --test-bundle && node scripts/smoke.mjs",
26
+ "docker:smoke": "node scripts/docker-smoke.mjs",
27
+ "bench": "node scripts/build.mjs --test-bundle && node scripts/bench.mjs",
28
+ "docker:start": "node scripts/docker-server.mjs",
29
+ "dev": "pnpm build && wrangler dev",
30
+ "deploy": "pnpm build && wrangler deploy"
31
+ },
32
+ "devDependencies": {
33
+ "@biomejs/biome": "^2.5.3",
34
+ "@cloudflare/workers-types": "^5.20260712.1",
35
+ "@vitest/coverage-v8": "^4.1.10",
36
+ "esbuild": "^0.28.1",
37
+ "typescript": "^7.0.2",
38
+ "vitest": "^4.1.10",
39
+ "wrangler": "^4.110.0"
40
+ }
41
+ }
pnpm-lock.yaml ADDED
@@ -0,0 +1,2045 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ lockfileVersion: '9.0'
2
+
3
+ settings:
4
+ autoInstallPeers: true
5
+ excludeLinksFromLockfile: false
6
+
7
+ importers:
8
+
9
+ .:
10
+ devDependencies:
11
+ '@biomejs/biome':
12
+ specifier: ^2.5.3
13
+ version: 2.5.3
14
+ '@cloudflare/workers-types':
15
+ specifier: ^5.20260712.1
16
+ version: 5.20260712.1
17
+ '@vitest/coverage-v8':
18
+ specifier: ^4.1.10
19
+ version: 4.1.10(vitest@4.1.10)
20
+ esbuild:
21
+ specifier: ^0.28.1
22
+ version: 0.28.1
23
+ typescript:
24
+ specifier: ^7.0.2
25
+ version: 7.0.2
26
+ vitest:
27
+ specifier: ^4.1.10
28
+ version: 4.1.10(@vitest/coverage-v8@4.1.10)(vite@8.0.16(esbuild@0.28.1))
29
+ wrangler:
30
+ specifier: ^4.110.0
31
+ version: 4.110.0(@cloudflare/workers-types@5.20260712.1)
32
+
33
+ packages:
34
+
35
+ '@babel/helper-string-parser@7.29.7':
36
+ resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==}
37
+ engines: {node: '>=6.9.0'}
38
+
39
+ '@babel/helper-validator-identifier@7.29.7':
40
+ resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==}
41
+ engines: {node: '>=6.9.0'}
42
+
43
+ '@babel/parser@7.29.7':
44
+ resolution: {integrity: sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==}
45
+ engines: {node: '>=6.0.0'}
46
+ hasBin: true
47
+
48
+ '@babel/types@7.29.7':
49
+ resolution: {integrity: sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==}
50
+ engines: {node: '>=6.9.0'}
51
+
52
+ '@bcoe/v8-coverage@1.0.2':
53
+ resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
54
+ engines: {node: '>=18'}
55
+
56
+ '@biomejs/biome@2.5.3':
57
+ resolution: {integrity: sha512-MrJswFdei9EfDwwUy2tQrPDpK0AO+RmMFvBoaaJ6ayBc3sUbHdCE+XG5N8vp+5So41ZupZJQm0roHFFhMGVD7A==}
58
+ engines: {node: '>=14.21.3'}
59
+ hasBin: true
60
+
61
+ '@biomejs/cli-darwin-arm64@2.5.3':
62
+ resolution: {integrity: sha512-QhYP9muVQ0nUO5zztFuPbEwi4+94sJWVjaZds9aMi1l/KNZBiUjdiSUrGHsTaMGDXrYl+r4AS2sUKfgH3w+V3g==}
63
+ engines: {node: '>=14.21.3'}
64
+ cpu: [arm64]
65
+ os: [darwin]
66
+
67
+ '@biomejs/cli-darwin-x64@2.5.3':
68
+ resolution: {integrity: sha512-NC1Ss13UaW7QZX+y8j44bF7AP0jSJdBl6iRhe0MAkvaSqZy+mWg3GaXsrb+eSoHoGDBtaXWEbMVV0iVN2cZ7cQ==}
69
+ engines: {node: '>=14.21.3'}
70
+ cpu: [x64]
71
+ os: [darwin]
72
+
73
+ '@biomejs/cli-linux-arm64-musl@2.5.3':
74
+ resolution: {integrity: sha512-fccix0w6xp6csCXgxeC0dU/3ecgRQal0y+cv2SP9ajNlhe7Yrk2Ug7UDe2j9AT9ZDYitkXpvUKgZjjuoYeP4Vg==}
75
+ engines: {node: '>=14.21.3'}
76
+ cpu: [arm64]
77
+ os: [linux]
78
+ libc: [musl]
79
+
80
+ '@biomejs/cli-linux-arm64@2.5.3':
81
+ resolution: {integrity: sha512-ksx1KWeyYW18ILL04msF/J4ZBtBDN33znYK8Z/aNv/vlBVxL9/g3mGP+omgHJKy4+KWbK87vcmmpmurfNjSgiA==}
82
+ engines: {node: '>=14.21.3'}
83
+ cpu: [arm64]
84
+ os: [linux]
85
+ libc: [glibc]
86
+
87
+ '@biomejs/cli-linux-x64-musl@2.5.3':
88
+ resolution: {integrity: sha512-O/yU9YKRUiHhmcjF2f38PSjseVk3G4VLWYc0G2HWpzdBVREV6G8IGWIVEFf7MFPfWIzNUIvPsEjeAZQIOgnLcQ==}
89
+ engines: {node: '>=14.21.3'}
90
+ cpu: [x64]
91
+ os: [linux]
92
+ libc: [musl]
93
+
94
+ '@biomejs/cli-linux-x64@2.5.3':
95
+ resolution: {integrity: sha512-yMkJtilsgvILDcVkh187aVLTb64xYsrxYajx5kym+r1ULkO5HUOfu9AYKLGQbOVLwJtT2utNw7hhFNg+17mUYA==}
96
+ engines: {node: '>=14.21.3'}
97
+ cpu: [x64]
98
+ os: [linux]
99
+ libc: [glibc]
100
+
101
+ '@biomejs/cli-win32-arm64@2.5.3':
102
+ resolution: {integrity: sha512-cX5z+GYwRcqEok0AH3KSfQGgqYd0Nomfp6Fbe1uiTtELE38hdH2k842wQ9wLNaF/JJ7r4rjJQ4VR+ce+fRmQbw==}
103
+ engines: {node: '>=14.21.3'}
104
+ cpu: [arm64]
105
+ os: [win32]
106
+
107
+ '@biomejs/cli-win32-x64@2.5.3':
108
+ resolution: {integrity: sha512-ExSaJWi4/u6+GXCszlSKpWSjKNbDseAYqqkCznsCsZ/4uidZ/BEqsCc5/3ctlq6dfIubdIIRSVLC/PG9xPl70Q==}
109
+ engines: {node: '>=14.21.3'}
110
+ cpu: [x64]
111
+ os: [win32]
112
+
113
+ '@cloudflare/kv-asset-handler@0.5.0':
114
+ resolution: {integrity: sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==}
115
+ engines: {node: '>=22.0.0'}
116
+
117
+ '@cloudflare/unenv-preset@2.16.1':
118
+ resolution: {integrity: sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw==}
119
+ peerDependencies:
120
+ unenv: 2.0.0-rc.24
121
+ workerd: '>1.20260305.0 <2.0.0-0'
122
+ peerDependenciesMeta:
123
+ workerd:
124
+ optional: true
125
+
126
+ '@cloudflare/workerd-darwin-64@1.20260708.1':
127
+ resolution: {integrity: sha512-HXFCvhS1wpg3uXO0CLUwmwC41i2loM5FSK69EUchOBpmYBAXxT1oHLm6EOA5lqhTk5Mu9kjRiQYxa1GwKPwfJg==}
128
+ engines: {node: '>=16'}
129
+ cpu: [x64]
130
+ os: [darwin]
131
+
132
+ '@cloudflare/workerd-darwin-arm64@1.20260708.1':
133
+ resolution: {integrity: sha512-JVlJaKDoRTVKSroHIlf8g3UCPjKj4iDbMZE2CNYht5qQ+2rL0FAUiVlV82G3BqKnnw9kHYnnsMzC08b9zVtdzA==}
134
+ engines: {node: '>=16'}
135
+ cpu: [arm64]
136
+ os: [darwin]
137
+
138
+ '@cloudflare/workerd-linux-64@1.20260708.1':
139
+ resolution: {integrity: sha512-3daE60YdD7YX0Jtuzc9DE/r/qMkmx8ZvHTkF8Mzmp3F5tbzlV0DAzmu5PFUPF2WuvtKbAhZKbvC2cHmWpQYxnA==}
140
+ engines: {node: '>=16'}
141
+ cpu: [x64]
142
+ os: [linux]
143
+
144
+ '@cloudflare/workerd-linux-arm64@1.20260708.1':
145
+ resolution: {integrity: sha512-VLdNYOx5Hj+9C6isy0ACWZsbMtSxex2DIJWEe7cZxUdlphZ58ZT8zxNXK8yunFiowd34hn3VwGMopdvdj8lvmA==}
146
+ engines: {node: '>=16'}
147
+ cpu: [arm64]
148
+ os: [linux]
149
+
150
+ '@cloudflare/workerd-windows-64@1.20260708.1':
151
+ resolution: {integrity: sha512-bC/aSAwLy16Vjo24i9XU3aWH+eRgz7NeR5xPKavGbembO18ZywYTQbXh14eXtY6fAqN3RzRG8psijTdhX4xydA==}
152
+ engines: {node: '>=16'}
153
+ cpu: [x64]
154
+ os: [win32]
155
+
156
+ '@cloudflare/workers-types@5.20260712.1':
157
+ resolution: {integrity: sha512-tkQ18Lz41EPXLzh4cSuIGQzztDVueuGfTcjlP4M7Qa0rfHpVBNItf3GRkd9O0JgiXs9csAwz/kVv7sjYXSoF2w==}
158
+
159
+ '@cspotcode/source-map-support@0.8.1':
160
+ resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==}
161
+ engines: {node: '>=12'}
162
+
163
+ '@emnapi/core@1.10.0':
164
+ resolution: {integrity: sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==}
165
+
166
+ '@emnapi/runtime@1.10.0':
167
+ resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==}
168
+
169
+ '@emnapi/runtime@1.11.2':
170
+ resolution: {integrity: sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==}
171
+
172
+ '@emnapi/wasi-threads@1.2.1':
173
+ resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==}
174
+
175
+ '@esbuild/aix-ppc64@0.28.1':
176
+ resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==}
177
+ engines: {node: '>=18'}
178
+ cpu: [ppc64]
179
+ os: [aix]
180
+
181
+ '@esbuild/android-arm64@0.28.1':
182
+ resolution: {integrity: sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==}
183
+ engines: {node: '>=18'}
184
+ cpu: [arm64]
185
+ os: [android]
186
+
187
+ '@esbuild/android-arm@0.28.1':
188
+ resolution: {integrity: sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==}
189
+ engines: {node: '>=18'}
190
+ cpu: [arm]
191
+ os: [android]
192
+
193
+ '@esbuild/android-x64@0.28.1':
194
+ resolution: {integrity: sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==}
195
+ engines: {node: '>=18'}
196
+ cpu: [x64]
197
+ os: [android]
198
+
199
+ '@esbuild/darwin-arm64@0.28.1':
200
+ resolution: {integrity: sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==}
201
+ engines: {node: '>=18'}
202
+ cpu: [arm64]
203
+ os: [darwin]
204
+
205
+ '@esbuild/darwin-x64@0.28.1':
206
+ resolution: {integrity: sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==}
207
+ engines: {node: '>=18'}
208
+ cpu: [x64]
209
+ os: [darwin]
210
+
211
+ '@esbuild/freebsd-arm64@0.28.1':
212
+ resolution: {integrity: sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==}
213
+ engines: {node: '>=18'}
214
+ cpu: [arm64]
215
+ os: [freebsd]
216
+
217
+ '@esbuild/freebsd-x64@0.28.1':
218
+ resolution: {integrity: sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==}
219
+ engines: {node: '>=18'}
220
+ cpu: [x64]
221
+ os: [freebsd]
222
+
223
+ '@esbuild/linux-arm64@0.28.1':
224
+ resolution: {integrity: sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==}
225
+ engines: {node: '>=18'}
226
+ cpu: [arm64]
227
+ os: [linux]
228
+
229
+ '@esbuild/linux-arm@0.28.1':
230
+ resolution: {integrity: sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==}
231
+ engines: {node: '>=18'}
232
+ cpu: [arm]
233
+ os: [linux]
234
+
235
+ '@esbuild/linux-ia32@0.28.1':
236
+ resolution: {integrity: sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==}
237
+ engines: {node: '>=18'}
238
+ cpu: [ia32]
239
+ os: [linux]
240
+
241
+ '@esbuild/linux-loong64@0.28.1':
242
+ resolution: {integrity: sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==}
243
+ engines: {node: '>=18'}
244
+ cpu: [loong64]
245
+ os: [linux]
246
+
247
+ '@esbuild/linux-mips64el@0.28.1':
248
+ resolution: {integrity: sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==}
249
+ engines: {node: '>=18'}
250
+ cpu: [mips64el]
251
+ os: [linux]
252
+
253
+ '@esbuild/linux-ppc64@0.28.1':
254
+ resolution: {integrity: sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==}
255
+ engines: {node: '>=18'}
256
+ cpu: [ppc64]
257
+ os: [linux]
258
+
259
+ '@esbuild/linux-riscv64@0.28.1':
260
+ resolution: {integrity: sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==}
261
+ engines: {node: '>=18'}
262
+ cpu: [riscv64]
263
+ os: [linux]
264
+
265
+ '@esbuild/linux-s390x@0.28.1':
266
+ resolution: {integrity: sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==}
267
+ engines: {node: '>=18'}
268
+ cpu: [s390x]
269
+ os: [linux]
270
+
271
+ '@esbuild/linux-x64@0.28.1':
272
+ resolution: {integrity: sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==}
273
+ engines: {node: '>=18'}
274
+ cpu: [x64]
275
+ os: [linux]
276
+
277
+ '@esbuild/netbsd-arm64@0.28.1':
278
+ resolution: {integrity: sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==}
279
+ engines: {node: '>=18'}
280
+ cpu: [arm64]
281
+ os: [netbsd]
282
+
283
+ '@esbuild/netbsd-x64@0.28.1':
284
+ resolution: {integrity: sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==}
285
+ engines: {node: '>=18'}
286
+ cpu: [x64]
287
+ os: [netbsd]
288
+
289
+ '@esbuild/openbsd-arm64@0.28.1':
290
+ resolution: {integrity: sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==}
291
+ engines: {node: '>=18'}
292
+ cpu: [arm64]
293
+ os: [openbsd]
294
+
295
+ '@esbuild/openbsd-x64@0.28.1':
296
+ resolution: {integrity: sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==}
297
+ engines: {node: '>=18'}
298
+ cpu: [x64]
299
+ os: [openbsd]
300
+
301
+ '@esbuild/openharmony-arm64@0.28.1':
302
+ resolution: {integrity: sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==}
303
+ engines: {node: '>=18'}
304
+ cpu: [arm64]
305
+ os: [openharmony]
306
+
307
+ '@esbuild/sunos-x64@0.28.1':
308
+ resolution: {integrity: sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==}
309
+ engines: {node: '>=18'}
310
+ cpu: [x64]
311
+ os: [sunos]
312
+
313
+ '@esbuild/win32-arm64@0.28.1':
314
+ resolution: {integrity: sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==}
315
+ engines: {node: '>=18'}
316
+ cpu: [arm64]
317
+ os: [win32]
318
+
319
+ '@esbuild/win32-ia32@0.28.1':
320
+ resolution: {integrity: sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==}
321
+ engines: {node: '>=18'}
322
+ cpu: [ia32]
323
+ os: [win32]
324
+
325
+ '@esbuild/win32-x64@0.28.1':
326
+ resolution: {integrity: sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==}
327
+ engines: {node: '>=18'}
328
+ cpu: [x64]
329
+ os: [win32]
330
+
331
+ '@img/colour@1.1.0':
332
+ resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==}
333
+ engines: {node: '>=18'}
334
+
335
+ '@img/sharp-darwin-arm64@0.34.5':
336
+ resolution: {integrity: sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==}
337
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
338
+ cpu: [arm64]
339
+ os: [darwin]
340
+
341
+ '@img/sharp-darwin-x64@0.34.5':
342
+ resolution: {integrity: sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==}
343
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
344
+ cpu: [x64]
345
+ os: [darwin]
346
+
347
+ '@img/sharp-libvips-darwin-arm64@1.2.4':
348
+ resolution: {integrity: sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==}
349
+ cpu: [arm64]
350
+ os: [darwin]
351
+
352
+ '@img/sharp-libvips-darwin-x64@1.2.4':
353
+ resolution: {integrity: sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==}
354
+ cpu: [x64]
355
+ os: [darwin]
356
+
357
+ '@img/sharp-libvips-linux-arm64@1.2.4':
358
+ resolution: {integrity: sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==}
359
+ cpu: [arm64]
360
+ os: [linux]
361
+ libc: [glibc]
362
+
363
+ '@img/sharp-libvips-linux-arm@1.2.4':
364
+ resolution: {integrity: sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==}
365
+ cpu: [arm]
366
+ os: [linux]
367
+ libc: [glibc]
368
+
369
+ '@img/sharp-libvips-linux-ppc64@1.2.4':
370
+ resolution: {integrity: sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==}
371
+ cpu: [ppc64]
372
+ os: [linux]
373
+ libc: [glibc]
374
+
375
+ '@img/sharp-libvips-linux-riscv64@1.2.4':
376
+ resolution: {integrity: sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==}
377
+ cpu: [riscv64]
378
+ os: [linux]
379
+ libc: [glibc]
380
+
381
+ '@img/sharp-libvips-linux-s390x@1.2.4':
382
+ resolution: {integrity: sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==}
383
+ cpu: [s390x]
384
+ os: [linux]
385
+ libc: [glibc]
386
+
387
+ '@img/sharp-libvips-linux-x64@1.2.4':
388
+ resolution: {integrity: sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==}
389
+ cpu: [x64]
390
+ os: [linux]
391
+ libc: [glibc]
392
+
393
+ '@img/sharp-libvips-linuxmusl-arm64@1.2.4':
394
+ resolution: {integrity: sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==}
395
+ cpu: [arm64]
396
+ os: [linux]
397
+ libc: [musl]
398
+
399
+ '@img/sharp-libvips-linuxmusl-x64@1.2.4':
400
+ resolution: {integrity: sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==}
401
+ cpu: [x64]
402
+ os: [linux]
403
+ libc: [musl]
404
+
405
+ '@img/sharp-linux-arm64@0.34.5':
406
+ resolution: {integrity: sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==}
407
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
408
+ cpu: [arm64]
409
+ os: [linux]
410
+ libc: [glibc]
411
+
412
+ '@img/sharp-linux-arm@0.34.5':
413
+ resolution: {integrity: sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==}
414
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
415
+ cpu: [arm]
416
+ os: [linux]
417
+ libc: [glibc]
418
+
419
+ '@img/sharp-linux-ppc64@0.34.5':
420
+ resolution: {integrity: sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==}
421
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
422
+ cpu: [ppc64]
423
+ os: [linux]
424
+ libc: [glibc]
425
+
426
+ '@img/sharp-linux-riscv64@0.34.5':
427
+ resolution: {integrity: sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==}
428
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
429
+ cpu: [riscv64]
430
+ os: [linux]
431
+ libc: [glibc]
432
+
433
+ '@img/sharp-linux-s390x@0.34.5':
434
+ resolution: {integrity: sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==}
435
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
436
+ cpu: [s390x]
437
+ os: [linux]
438
+ libc: [glibc]
439
+
440
+ '@img/sharp-linux-x64@0.34.5':
441
+ resolution: {integrity: sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==}
442
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
443
+ cpu: [x64]
444
+ os: [linux]
445
+ libc: [glibc]
446
+
447
+ '@img/sharp-linuxmusl-arm64@0.34.5':
448
+ resolution: {integrity: sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==}
449
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
450
+ cpu: [arm64]
451
+ os: [linux]
452
+ libc: [musl]
453
+
454
+ '@img/sharp-linuxmusl-x64@0.34.5':
455
+ resolution: {integrity: sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==}
456
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
457
+ cpu: [x64]
458
+ os: [linux]
459
+ libc: [musl]
460
+
461
+ '@img/sharp-wasm32@0.34.5':
462
+ resolution: {integrity: sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==}
463
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
464
+ cpu: [wasm32]
465
+
466
+ '@img/sharp-win32-arm64@0.34.5':
467
+ resolution: {integrity: sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==}
468
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
469
+ cpu: [arm64]
470
+ os: [win32]
471
+
472
+ '@img/sharp-win32-ia32@0.34.5':
473
+ resolution: {integrity: sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==}
474
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
475
+ cpu: [ia32]
476
+ os: [win32]
477
+
478
+ '@img/sharp-win32-x64@0.34.5':
479
+ resolution: {integrity: sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==}
480
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
481
+ cpu: [x64]
482
+ os: [win32]
483
+
484
+ '@jridgewell/resolve-uri@3.1.2':
485
+ resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}
486
+ engines: {node: '>=6.0.0'}
487
+
488
+ '@jridgewell/sourcemap-codec@1.5.5':
489
+ resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==}
490
+
491
+ '@jridgewell/trace-mapping@0.3.31':
492
+ resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
493
+
494
+ '@jridgewell/trace-mapping@0.3.9':
495
+ resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==}
496
+
497
+ '@napi-rs/wasm-runtime@1.1.5':
498
+ resolution: {integrity: sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==}
499
+ peerDependencies:
500
+ '@emnapi/core': ^1.7.1
501
+ '@emnapi/runtime': ^1.7.1
502
+
503
+ '@oxc-project/types@0.133.0':
504
+ resolution: {integrity: sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==}
505
+
506
+ '@poppinss/colors@4.1.6':
507
+ resolution: {integrity: sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==}
508
+
509
+ '@poppinss/dumper@0.6.5':
510
+ resolution: {integrity: sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==}
511
+
512
+ '@poppinss/exception@1.2.3':
513
+ resolution: {integrity: sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==}
514
+
515
+ '@rolldown/binding-android-arm64@1.0.3':
516
+ resolution: {integrity: sha512-454rs7jHngixp/NMxd5srYD57OnzSlZ/eFTETjORQHLwJG1lRtmNOJcBerZlfu4GjKqeq8aCCIQrMdHyhI51Hw==}
517
+ engines: {node: ^20.19.0 || >=22.12.0}
518
+ cpu: [arm64]
519
+ os: [android]
520
+
521
+ '@rolldown/binding-darwin-arm64@1.0.3':
522
+ resolution: {integrity: sha512-PcAhP+ynjURNyy8SKGl5DQP94aGuB/7JrXJb/t7P+hanXvQVMWzUvRRhBAcg/lNRadBhoUPqSoP4xw5tR/KBEA==}
523
+ engines: {node: ^20.19.0 || >=22.12.0}
524
+ cpu: [arm64]
525
+ os: [darwin]
526
+
527
+ '@rolldown/binding-darwin-x64@1.0.3':
528
+ resolution: {integrity: sha512-9YpfeUvSE2RS7wysJ81uOZkXJz7f7Q55H2Gvp3VEw/EsahqDtrphrZ0EwDLK5vvKOzaCrBsjF8JmnMLcUt78Gg==}
529
+ engines: {node: ^20.19.0 || >=22.12.0}
530
+ cpu: [x64]
531
+ os: [darwin]
532
+
533
+ '@rolldown/binding-freebsd-x64@1.0.3':
534
+ resolution: {integrity: sha512-yB1IlAsSNHncV6SCTL27/MVGR5htvQsoGxIv5KMGXALp+Ll1wYsn+x98M9MW7qa+NdSbvrrY7ANI4wLJ0n1e6g==}
535
+ engines: {node: ^20.19.0 || >=22.12.0}
536
+ cpu: [x64]
537
+ os: [freebsd]
538
+
539
+ '@rolldown/binding-linux-arm-gnueabihf@1.0.3':
540
+ resolution: {integrity: sha512-Yi30IVAAfLUCy2MseFjbB1jAMDl1VMCAas5StnYp8da9+CKvMd2H2cbEjWcw5NPaPqzvYkVIaF1nNUG+b7u/sw==}
541
+ engines: {node: ^20.19.0 || >=22.12.0}
542
+ cpu: [arm]
543
+ os: [linux]
544
+
545
+ '@rolldown/binding-linux-arm64-gnu@1.0.3':
546
+ resolution: {integrity: sha512-jsO7R8To+AdlYgUmN5sHSCZbfhtMBkO0WUx8iORQnPcMMdgr7qM2DQmMwgabs3GhNztdmoKkMKQFHD6DTMCIQw==}
547
+ engines: {node: ^20.19.0 || >=22.12.0}
548
+ cpu: [arm64]
549
+ os: [linux]
550
+ libc: [glibc]
551
+
552
+ '@rolldown/binding-linux-arm64-musl@1.0.3':
553
+ resolution: {integrity: sha512-VWkUHwWriDciit80wleYwKILoR/KMvxh/IdwS/paX+ZgpuRpCrKLUdadJbc0NpBEiyhpYawsJ73j9aCvOH+f7Q==}
554
+ engines: {node: ^20.19.0 || >=22.12.0}
555
+ cpu: [arm64]
556
+ os: [linux]
557
+ libc: [musl]
558
+
559
+ '@rolldown/binding-linux-ppc64-gnu@1.0.3':
560
+ resolution: {integrity: sha512-5f1laC0SlIR0yDbFCd8acUhvJIag6N3zC5P7oUPN6wX0aOma+uKJ0wBDH5aq7I1PVI2ttTlhJwzwRIBnLiSGEg==}
561
+ engines: {node: ^20.19.0 || >=22.12.0}
562
+ cpu: [ppc64]
563
+ os: [linux]
564
+ libc: [glibc]
565
+
566
+ '@rolldown/binding-linux-s390x-gnu@1.0.3':
567
+ resolution: {integrity: sha512-Iq4ko0r4XsgbrF/LunNgHtAGLRRVE2kXonAXQ/MV0mC6jQpMOhW1SvtZja2EhC/kd05++bP78dsqBeIQyYJ6Yg==}
568
+ engines: {node: ^20.19.0 || >=22.12.0}
569
+ cpu: [s390x]
570
+ os: [linux]
571
+ libc: [glibc]
572
+
573
+ '@rolldown/binding-linux-x64-gnu@1.0.3':
574
+ resolution: {integrity: sha512-B8m6tD5+/N5FeNQFbKlLA/2yVq9ycQP1SeedyEYYKWBNR3ZQbkvIUcNnDNM03lO1l5F2roiiFJGgvoLLyZXtSg==}
575
+ engines: {node: ^20.19.0 || >=22.12.0}
576
+ cpu: [x64]
577
+ os: [linux]
578
+ libc: [glibc]
579
+
580
+ '@rolldown/binding-linux-x64-musl@1.0.3':
581
+ resolution: {integrity: sha512-pSdpdUJHkuCxun9LE7jvgUB9qsRgaiyNNCX7m/AvHTcq67AiT/Yhoxvw5zPfhrM8k/BfP8ce/hMOpthKDpEUow==}
582
+ engines: {node: ^20.19.0 || >=22.12.0}
583
+ cpu: [x64]
584
+ os: [linux]
585
+ libc: [musl]
586
+
587
+ '@rolldown/binding-openharmony-arm64@1.0.3':
588
+ resolution: {integrity: sha512-OXXS3RKJgX2uLwM+gYyuH5omcH8fL1LJs96pZGgtetVCahON57+d4SJHzTgZiOjxgGkSnpXpOsWuPDGAKAigEg==}
589
+ engines: {node: ^20.19.0 || >=22.12.0}
590
+ cpu: [arm64]
591
+ os: [openharmony]
592
+
593
+ '@rolldown/binding-wasm32-wasi@1.0.3':
594
+ resolution: {integrity: sha512-JTtb8BWFynicNSoPrehsCzBtOKjZ6jhMiPFEmOiuXg1Fl8dn2KHQob+GuPSGR0dryQa1PQJbzjF3dqO/whhjLg==}
595
+ engines: {node: ^20.19.0 || >=22.12.0}
596
+ cpu: [wasm32]
597
+
598
+ '@rolldown/binding-win32-arm64-msvc@1.0.3':
599
+ resolution: {integrity: sha512-gEdFFEN70A/jxb2svrWsN3aDL7OUtmvlOy+6fa2jxG8K0wQ1ZbdeLGnidov6Yu5/733dI5ySfzFlQ/cb0bSz1g==}
600
+ engines: {node: ^20.19.0 || >=22.12.0}
601
+ cpu: [arm64]
602
+ os: [win32]
603
+
604
+ '@rolldown/binding-win32-x64-msvc@1.0.3':
605
+ resolution: {integrity: sha512-eXB7CHuaQdqmJcc3koCNtNPmT/bj2gc999kUFgBxG8Ac0NdgXc4rkCHhqrgrhN3zddvvvrgzj1e90SuSfmyIXA==}
606
+ engines: {node: ^20.19.0 || >=22.12.0}
607
+ cpu: [x64]
608
+ os: [win32]
609
+
610
+ '@rolldown/pluginutils@1.0.1':
611
+ resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}
612
+
613
+ '@sindresorhus/is@7.2.0':
614
+ resolution: {integrity: sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==}
615
+ engines: {node: '>=18'}
616
+
617
+ '@speed-highlight/core@1.2.17':
618
+ resolution: {integrity: sha512-Z92FwKpCtfaW1V0jTU/fh3QzYEZN8wDwrzRIBoADCJfn4mJCNcJN/XegifX7BDrQ8/h9Xh/JnbyMchL0FqXrkg==}
619
+
620
+ '@standard-schema/spec@1.1.0':
621
+ resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
622
+
623
+ '@tybys/wasm-util@0.10.2':
624
+ resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==}
625
+
626
+ '@types/chai@5.2.3':
627
+ resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
628
+
629
+ '@types/deep-eql@4.0.2':
630
+ resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
631
+
632
+ '@types/estree@1.0.9':
633
+ resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}
634
+
635
+ '@typescript/typescript-aix-ppc64@7.0.2':
636
+ resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==}
637
+ engines: {node: '>=16.20.0'}
638
+ cpu: [ppc64]
639
+ os: [aix]
640
+
641
+ '@typescript/typescript-darwin-arm64@7.0.2':
642
+ resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==}
643
+ engines: {node: '>=16.20.0'}
644
+ cpu: [arm64]
645
+ os: [darwin]
646
+
647
+ '@typescript/typescript-darwin-x64@7.0.2':
648
+ resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==}
649
+ engines: {node: '>=16.20.0'}
650
+ cpu: [x64]
651
+ os: [darwin]
652
+
653
+ '@typescript/typescript-freebsd-arm64@7.0.2':
654
+ resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==}
655
+ engines: {node: '>=16.20.0'}
656
+ cpu: [arm64]
657
+ os: [freebsd]
658
+
659
+ '@typescript/typescript-freebsd-x64@7.0.2':
660
+ resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==}
661
+ engines: {node: '>=16.20.0'}
662
+ cpu: [x64]
663
+ os: [freebsd]
664
+
665
+ '@typescript/typescript-linux-arm64@7.0.2':
666
+ resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==}
667
+ engines: {node: '>=16.20.0'}
668
+ cpu: [arm64]
669
+ os: [linux]
670
+
671
+ '@typescript/typescript-linux-arm@7.0.2':
672
+ resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==}
673
+ engines: {node: '>=16.20.0'}
674
+ cpu: [arm]
675
+ os: [linux]
676
+
677
+ '@typescript/typescript-linux-loong64@7.0.2':
678
+ resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==}
679
+ engines: {node: '>=16.20.0'}
680
+ cpu: [loong64]
681
+ os: [linux]
682
+
683
+ '@typescript/typescript-linux-mips64el@7.0.2':
684
+ resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==}
685
+ engines: {node: '>=16.20.0'}
686
+ cpu: [mips64el]
687
+ os: [linux]
688
+
689
+ '@typescript/typescript-linux-ppc64@7.0.2':
690
+ resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==}
691
+ engines: {node: '>=16.20.0'}
692
+ cpu: [ppc64]
693
+ os: [linux]
694
+
695
+ '@typescript/typescript-linux-riscv64@7.0.2':
696
+ resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==}
697
+ engines: {node: '>=16.20.0'}
698
+ cpu: [riscv64]
699
+ os: [linux]
700
+
701
+ '@typescript/typescript-linux-s390x@7.0.2':
702
+ resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==}
703
+ engines: {node: '>=16.20.0'}
704
+ cpu: [s390x]
705
+ os: [linux]
706
+
707
+ '@typescript/typescript-linux-x64@7.0.2':
708
+ resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==}
709
+ engines: {node: '>=16.20.0'}
710
+ cpu: [x64]
711
+ os: [linux]
712
+
713
+ '@typescript/typescript-netbsd-arm64@7.0.2':
714
+ resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==}
715
+ engines: {node: '>=16.20.0'}
716
+ cpu: [arm64]
717
+ os: [netbsd]
718
+
719
+ '@typescript/typescript-netbsd-x64@7.0.2':
720
+ resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==}
721
+ engines: {node: '>=16.20.0'}
722
+ cpu: [x64]
723
+ os: [netbsd]
724
+
725
+ '@typescript/typescript-openbsd-arm64@7.0.2':
726
+ resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==}
727
+ engines: {node: '>=16.20.0'}
728
+ cpu: [arm64]
729
+ os: [openbsd]
730
+
731
+ '@typescript/typescript-openbsd-x64@7.0.2':
732
+ resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==}
733
+ engines: {node: '>=16.20.0'}
734
+ cpu: [x64]
735
+ os: [openbsd]
736
+
737
+ '@typescript/typescript-sunos-x64@7.0.2':
738
+ resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==}
739
+ engines: {node: '>=16.20.0'}
740
+ cpu: [x64]
741
+ os: [sunos]
742
+
743
+ '@typescript/typescript-win32-arm64@7.0.2':
744
+ resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==}
745
+ engines: {node: '>=16.20.0'}
746
+ cpu: [arm64]
747
+ os: [win32]
748
+
749
+ '@typescript/typescript-win32-x64@7.0.2':
750
+ resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==}
751
+ engines: {node: '>=16.20.0'}
752
+ cpu: [x64]
753
+ os: [win32]
754
+
755
+ '@vitest/coverage-v8@4.1.10':
756
+ resolution: {integrity: sha512-IM49HmthevbgAO4anp1hwtoT9wYe59w0LR00gr+eagHE+ZJ5lK4sLPeO0ubgoJcwLk6dehU3R24N+FbEEKDc8g==}
757
+ peerDependencies:
758
+ '@vitest/browser': 4.1.10
759
+ vitest: 4.1.10
760
+ peerDependenciesMeta:
761
+ '@vitest/browser':
762
+ optional: true
763
+
764
+ '@vitest/expect@4.1.10':
765
+ resolution: {integrity: sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==}
766
+
767
+ '@vitest/mocker@4.1.10':
768
+ resolution: {integrity: sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==}
769
+ peerDependencies:
770
+ msw: ^2.4.9
771
+ vite: ^6.0.0 || ^7.0.0 || ^8.0.0
772
+ peerDependenciesMeta:
773
+ msw:
774
+ optional: true
775
+ vite:
776
+ optional: true
777
+
778
+ '@vitest/pretty-format@4.1.10':
779
+ resolution: {integrity: sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==}
780
+
781
+ '@vitest/runner@4.1.10':
782
+ resolution: {integrity: sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==}
783
+
784
+ '@vitest/snapshot@4.1.10':
785
+ resolution: {integrity: sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==}
786
+
787
+ '@vitest/spy@4.1.10':
788
+ resolution: {integrity: sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==}
789
+
790
+ '@vitest/utils@4.1.10':
791
+ resolution: {integrity: sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==}
792
+
793
+ assertion-error@2.0.1:
794
+ resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
795
+ engines: {node: '>=12'}
796
+
797
+ ast-v8-to-istanbul@1.0.4:
798
+ resolution: {integrity: sha512-0bC0/4bTSrnwdhU3IsZDwEdojvuPrSg59OYZfKsLRtJZ0u8VBx9DebfqqG8bRdCC0I7vjgxmPi41P0lpkhJHtA==}
799
+
800
+ blake3-wasm@2.1.5:
801
+ resolution: {integrity: sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==}
802
+
803
+ chai@6.2.2:
804
+ resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}
805
+ engines: {node: '>=18'}
806
+
807
+ convert-source-map@2.0.0:
808
+ resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
809
+
810
+ cookie@1.1.1:
811
+ resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
812
+ engines: {node: '>=18'}
813
+
814
+ detect-libc@2.1.2:
815
+ resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
816
+ engines: {node: '>=8'}
817
+
818
+ error-stack-parser-es@1.0.5:
819
+ resolution: {integrity: sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==}
820
+
821
+ es-module-lexer@2.3.0:
822
+ resolution: {integrity: sha512-KLdwQm2NvGLDkQDCGvmiQrhkd0JbMzXthwQAUgWjQuQdBLFa3eiBP5arXZyA+f8x+x7OXgud6bq2rxjGtHV2tw==}
823
+
824
+ esbuild@0.28.1:
825
+ resolution: {integrity: sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==}
826
+ engines: {node: '>=18'}
827
+ hasBin: true
828
+
829
+ estree-walker@3.0.3:
830
+ resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
831
+
832
+ expect-type@1.4.0:
833
+ resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}
834
+ engines: {node: '>=12.0.0'}
835
+
836
+ fdir@6.5.0:
837
+ resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
838
+ engines: {node: '>=12.0.0'}
839
+ peerDependencies:
840
+ picomatch: ^3 || ^4
841
+ peerDependenciesMeta:
842
+ picomatch:
843
+ optional: true
844
+
845
+ fsevents@2.3.3:
846
+ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
847
+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
848
+ os: [darwin]
849
+
850
+ has-flag@4.0.0:
851
+ resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==}
852
+ engines: {node: '>=8'}
853
+
854
+ html-escaper@2.0.2:
855
+ resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}
856
+
857
+ istanbul-lib-coverage@3.2.2:
858
+ resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}
859
+ engines: {node: '>=8'}
860
+
861
+ istanbul-lib-report@3.0.1:
862
+ resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==}
863
+ engines: {node: '>=10'}
864
+
865
+ istanbul-reports@3.2.0:
866
+ resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==}
867
+ engines: {node: '>=8'}
868
+
869
+ js-tokens@10.0.0:
870
+ resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==}
871
+
872
+ kleur@4.1.5:
873
+ resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==}
874
+ engines: {node: '>=6'}
875
+
876
+ lightningcss-android-arm64@1.32.0:
877
+ resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==}
878
+ engines: {node: '>= 12.0.0'}
879
+ cpu: [arm64]
880
+ os: [android]
881
+
882
+ lightningcss-darwin-arm64@1.32.0:
883
+ resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==}
884
+ engines: {node: '>= 12.0.0'}
885
+ cpu: [arm64]
886
+ os: [darwin]
887
+
888
+ lightningcss-darwin-x64@1.32.0:
889
+ resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==}
890
+ engines: {node: '>= 12.0.0'}
891
+ cpu: [x64]
892
+ os: [darwin]
893
+
894
+ lightningcss-freebsd-x64@1.32.0:
895
+ resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==}
896
+ engines: {node: '>= 12.0.0'}
897
+ cpu: [x64]
898
+ os: [freebsd]
899
+
900
+ lightningcss-linux-arm-gnueabihf@1.32.0:
901
+ resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==}
902
+ engines: {node: '>= 12.0.0'}
903
+ cpu: [arm]
904
+ os: [linux]
905
+
906
+ lightningcss-linux-arm64-gnu@1.32.0:
907
+ resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==}
908
+ engines: {node: '>= 12.0.0'}
909
+ cpu: [arm64]
910
+ os: [linux]
911
+ libc: [glibc]
912
+
913
+ lightningcss-linux-arm64-musl@1.32.0:
914
+ resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}
915
+ engines: {node: '>= 12.0.0'}
916
+ cpu: [arm64]
917
+ os: [linux]
918
+ libc: [musl]
919
+
920
+ lightningcss-linux-x64-gnu@1.32.0:
921
+ resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}
922
+ engines: {node: '>= 12.0.0'}
923
+ cpu: [x64]
924
+ os: [linux]
925
+ libc: [glibc]
926
+
927
+ lightningcss-linux-x64-musl@1.32.0:
928
+ resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}
929
+ engines: {node: '>= 12.0.0'}
930
+ cpu: [x64]
931
+ os: [linux]
932
+ libc: [musl]
933
+
934
+ lightningcss-win32-arm64-msvc@1.32.0:
935
+ resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==}
936
+ engines: {node: '>= 12.0.0'}
937
+ cpu: [arm64]
938
+ os: [win32]
939
+
940
+ lightningcss-win32-x64-msvc@1.32.0:
941
+ resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==}
942
+ engines: {node: '>= 12.0.0'}
943
+ cpu: [x64]
944
+ os: [win32]
945
+
946
+ lightningcss@1.32.0:
947
+ resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==}
948
+ engines: {node: '>= 12.0.0'}
949
+
950
+ magic-string@0.30.21:
951
+ resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
952
+
953
+ magicast@0.5.3:
954
+ resolution: {integrity: sha512-pVKE4UdSQ7DvHzivsCIFx2BJn1mHG6KsyrFcaxFx6tONdneEuThrDx0Cj3AMg58KyN4pzYT+LHOotxDQDjNvkw==}
955
+
956
+ make-dir@4.0.0:
957
+ resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}
958
+ engines: {node: '>=10'}
959
+
960
+ miniflare@4.20260708.1:
961
+ resolution: {integrity: sha512-c94O9zRDISdqO18EHt6l0iF/fWgWt8p18PJvRsA/L/NJZ9Cfke3s/F5Blg1XXF7WDutVRzWVWy8Vy4LaT5ifsA==}
962
+ engines: {node: '>=22.0.0'}
963
+ hasBin: true
964
+
965
+ nanoid@3.3.13:
966
+ resolution: {integrity: sha512-sPdqC6ByMVVGvF1ynvvMo0/o+oD1VX7DaHhijt1bFgjvBkHBib4t49GoNDhf2NDta4oeUNlaGbSt5K7qjZ955Q==}
967
+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
968
+ hasBin: true
969
+
970
+ obug@2.1.3:
971
+ resolution: {integrity: sha512-9miFgM2OFba7hB+pRgvtV84pYTBaoTHohvmIgiRt6dRIzbwEOIaNaP+dIlGs2fNFoB0SeISs0Jz5WFVRid6Xyg==}
972
+ engines: {node: '>=12.20.0'}
973
+
974
+ path-to-regexp@6.3.0:
975
+ resolution: {integrity: sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==}
976
+
977
+ pathe@2.0.3:
978
+ resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
979
+
980
+ picocolors@1.1.1:
981
+ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
982
+
983
+ picomatch@4.0.5:
984
+ resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==}
985
+ engines: {node: '>=12'}
986
+
987
+ postcss@8.5.15:
988
+ resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==}
989
+ engines: {node: ^10 || ^12 || >=14}
990
+
991
+ rolldown@1.0.3:
992
+ resolution: {integrity: sha512-i00lAJ2ks1BYr7rjNjKC7BcqAS7nVfiT3QX1SI5aY+AFHblCmaUf9OE9dbdzDvW6dJxbi2ZCZiy9v3CcwOiX3g==}
993
+ engines: {node: ^20.19.0 || >=22.12.0}
994
+ hasBin: true
995
+
996
+ semver@7.8.5:
997
+ resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==}
998
+ engines: {node: '>=10'}
999
+ hasBin: true
1000
+
1001
+ sharp@0.34.5:
1002
+ resolution: {integrity: sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==}
1003
+ engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
1004
+
1005
+ siginfo@2.0.0:
1006
+ resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
1007
+
1008
+ source-map-js@1.2.1:
1009
+ resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
1010
+ engines: {node: '>=0.10.0'}
1011
+
1012
+ stackback@0.0.2:
1013
+ resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
1014
+
1015
+ std-env@4.2.0:
1016
+ resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==}
1017
+
1018
+ supports-color@10.2.2:
1019
+ resolution: {integrity: sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==}
1020
+ engines: {node: '>=18'}
1021
+
1022
+ supports-color@7.2.0:
1023
+ resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}
1024
+ engines: {node: '>=8'}
1025
+
1026
+ tinybench@2.9.0:
1027
+ resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
1028
+
1029
+ tinyexec@1.2.4:
1030
+ resolution: {integrity: sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==}
1031
+ engines: {node: '>=18'}
1032
+
1033
+ tinyglobby@0.2.17:
1034
+ resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
1035
+ engines: {node: '>=12.0.0'}
1036
+
1037
+ tinyrainbow@3.1.0:
1038
+ resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==}
1039
+ engines: {node: '>=14.0.0'}
1040
+
1041
+ tslib@2.8.1:
1042
+ resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
1043
+
1044
+ typescript@7.0.2:
1045
+ resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==}
1046
+ engines: {node: '>=16.20.0'}
1047
+ hasBin: true
1048
+
1049
+ undici@7.28.0:
1050
+ resolution: {integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==}
1051
+ engines: {node: '>=20.18.1'}
1052
+
1053
+ unenv@2.0.0-rc.24:
1054
+ resolution: {integrity: sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==}
1055
+
1056
+ vite@8.0.16:
1057
+ resolution: {integrity: sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==}
1058
+ engines: {node: ^20.19.0 || >=22.12.0}
1059
+ hasBin: true
1060
+ peerDependencies:
1061
+ '@types/node': ^20.19.0 || >=22.12.0
1062
+ '@vitejs/devtools': ^0.1.18
1063
+ esbuild: ^0.27.0 || ^0.28.0
1064
+ jiti: '>=1.21.0'
1065
+ less: ^4.0.0
1066
+ sass: ^1.70.0
1067
+ sass-embedded: ^1.70.0
1068
+ stylus: '>=0.54.8'
1069
+ sugarss: ^5.0.0
1070
+ terser: ^5.16.0
1071
+ tsx: ^4.8.1
1072
+ yaml: ^2.4.2
1073
+ peerDependenciesMeta:
1074
+ '@types/node':
1075
+ optional: true
1076
+ '@vitejs/devtools':
1077
+ optional: true
1078
+ esbuild:
1079
+ optional: true
1080
+ jiti:
1081
+ optional: true
1082
+ less:
1083
+ optional: true
1084
+ sass:
1085
+ optional: true
1086
+ sass-embedded:
1087
+ optional: true
1088
+ stylus:
1089
+ optional: true
1090
+ sugarss:
1091
+ optional: true
1092
+ terser:
1093
+ optional: true
1094
+ tsx:
1095
+ optional: true
1096
+ yaml:
1097
+ optional: true
1098
+
1099
+ vitest@4.1.10:
1100
+ resolution: {integrity: sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==}
1101
+ engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0}
1102
+ hasBin: true
1103
+ peerDependencies:
1104
+ '@edge-runtime/vm': '*'
1105
+ '@opentelemetry/api': ^1.9.0
1106
+ '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0
1107
+ '@vitest/browser-playwright': 4.1.10
1108
+ '@vitest/browser-preview': 4.1.10
1109
+ '@vitest/browser-webdriverio': 4.1.10
1110
+ '@vitest/coverage-istanbul': 4.1.10
1111
+ '@vitest/coverage-v8': 4.1.10
1112
+ '@vitest/ui': 4.1.10
1113
+ happy-dom: '*'
1114
+ jsdom: '*'
1115
+ vite: ^6.0.0 || ^7.0.0 || ^8.0.0
1116
+ peerDependenciesMeta:
1117
+ '@edge-runtime/vm':
1118
+ optional: true
1119
+ '@opentelemetry/api':
1120
+ optional: true
1121
+ '@types/node':
1122
+ optional: true
1123
+ '@vitest/browser-playwright':
1124
+ optional: true
1125
+ '@vitest/browser-preview':
1126
+ optional: true
1127
+ '@vitest/browser-webdriverio':
1128
+ optional: true
1129
+ '@vitest/coverage-istanbul':
1130
+ optional: true
1131
+ '@vitest/coverage-v8':
1132
+ optional: true
1133
+ '@vitest/ui':
1134
+ optional: true
1135
+ happy-dom:
1136
+ optional: true
1137
+ jsdom:
1138
+ optional: true
1139
+
1140
+ why-is-node-running@2.3.0:
1141
+ resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
1142
+ engines: {node: '>=8'}
1143
+ hasBin: true
1144
+
1145
+ workerd@1.20260708.1:
1146
+ resolution: {integrity: sha512-WAK+Kt/VVCSldH2qSr8lx46XCJ4Q+bdlHNaFqUtOHthBEIB8C1N8HVW+VOLrxDoTCk0NGNv0zajnBeQK4JOB9w==}
1147
+ engines: {node: '>=16'}
1148
+ hasBin: true
1149
+
1150
+ wrangler@4.110.0:
1151
+ resolution: {integrity: sha512-xZeXKYi7hxQRF5anL+v77RkufJNpF9f3Eqeyqq2QBsETpLZgh0Agj0jJ6JPtkbgn6ukZdh8OK5egsGPWIditgg==}
1152
+ engines: {node: '>=22.0.0'}
1153
+ hasBin: true
1154
+ peerDependencies:
1155
+ '@cloudflare/workers-types': ^5.20260708.1
1156
+ peerDependenciesMeta:
1157
+ '@cloudflare/workers-types':
1158
+ optional: true
1159
+
1160
+ ws@8.21.0:
1161
+ resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==}
1162
+ engines: {node: '>=10.0.0'}
1163
+ peerDependencies:
1164
+ bufferutil: ^4.0.1
1165
+ utf-8-validate: '>=5.0.2'
1166
+ peerDependenciesMeta:
1167
+ bufferutil:
1168
+ optional: true
1169
+ utf-8-validate:
1170
+ optional: true
1171
+
1172
+ youch-core@0.3.3:
1173
+ resolution: {integrity: sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==}
1174
+
1175
+ youch@4.1.0-beta.10:
1176
+ resolution: {integrity: sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==}
1177
+
1178
+ snapshots:
1179
+
1180
+ '@babel/helper-string-parser@7.29.7': {}
1181
+
1182
+ '@babel/helper-validator-identifier@7.29.7': {}
1183
+
1184
+ '@babel/parser@7.29.7':
1185
+ dependencies:
1186
+ '@babel/types': 7.29.7
1187
+
1188
+ '@babel/types@7.29.7':
1189
+ dependencies:
1190
+ '@babel/helper-string-parser': 7.29.7
1191
+ '@babel/helper-validator-identifier': 7.29.7
1192
+
1193
+ '@bcoe/v8-coverage@1.0.2': {}
1194
+
1195
+ '@biomejs/biome@2.5.3':
1196
+ optionalDependencies:
1197
+ '@biomejs/cli-darwin-arm64': 2.5.3
1198
+ '@biomejs/cli-darwin-x64': 2.5.3
1199
+ '@biomejs/cli-linux-arm64': 2.5.3
1200
+ '@biomejs/cli-linux-arm64-musl': 2.5.3
1201
+ '@biomejs/cli-linux-x64': 2.5.3
1202
+ '@biomejs/cli-linux-x64-musl': 2.5.3
1203
+ '@biomejs/cli-win32-arm64': 2.5.3
1204
+ '@biomejs/cli-win32-x64': 2.5.3
1205
+
1206
+ '@biomejs/cli-darwin-arm64@2.5.3':
1207
+ optional: true
1208
+
1209
+ '@biomejs/cli-darwin-x64@2.5.3':
1210
+ optional: true
1211
+
1212
+ '@biomejs/cli-linux-arm64-musl@2.5.3':
1213
+ optional: true
1214
+
1215
+ '@biomejs/cli-linux-arm64@2.5.3':
1216
+ optional: true
1217
+
1218
+ '@biomejs/cli-linux-x64-musl@2.5.3':
1219
+ optional: true
1220
+
1221
+ '@biomejs/cli-linux-x64@2.5.3':
1222
+ optional: true
1223
+
1224
+ '@biomejs/cli-win32-arm64@2.5.3':
1225
+ optional: true
1226
+
1227
+ '@biomejs/cli-win32-x64@2.5.3':
1228
+ optional: true
1229
+
1230
+ '@cloudflare/kv-asset-handler@0.5.0': {}
1231
+
1232
+ '@cloudflare/unenv-preset@2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260708.1)':
1233
+ dependencies:
1234
+ unenv: 2.0.0-rc.24
1235
+ optionalDependencies:
1236
+ workerd: 1.20260708.1
1237
+
1238
+ '@cloudflare/workerd-darwin-64@1.20260708.1':
1239
+ optional: true
1240
+
1241
+ '@cloudflare/workerd-darwin-arm64@1.20260708.1':
1242
+ optional: true
1243
+
1244
+ '@cloudflare/workerd-linux-64@1.20260708.1':
1245
+ optional: true
1246
+
1247
+ '@cloudflare/workerd-linux-arm64@1.20260708.1':
1248
+ optional: true
1249
+
1250
+ '@cloudflare/workerd-windows-64@1.20260708.1':
1251
+ optional: true
1252
+
1253
+ '@cloudflare/workers-types@5.20260712.1': {}
1254
+
1255
+ '@cspotcode/source-map-support@0.8.1':
1256
+ dependencies:
1257
+ '@jridgewell/trace-mapping': 0.3.9
1258
+
1259
+ '@emnapi/core@1.10.0':
1260
+ dependencies:
1261
+ '@emnapi/wasi-threads': 1.2.1
1262
+ tslib: 2.8.1
1263
+ optional: true
1264
+
1265
+ '@emnapi/runtime@1.10.0':
1266
+ dependencies:
1267
+ tslib: 2.8.1
1268
+ optional: true
1269
+
1270
+ '@emnapi/runtime@1.11.2':
1271
+ dependencies:
1272
+ tslib: 2.8.1
1273
+ optional: true
1274
+
1275
+ '@emnapi/wasi-threads@1.2.1':
1276
+ dependencies:
1277
+ tslib: 2.8.1
1278
+ optional: true
1279
+
1280
+ '@esbuild/aix-ppc64@0.28.1':
1281
+ optional: true
1282
+
1283
+ '@esbuild/android-arm64@0.28.1':
1284
+ optional: true
1285
+
1286
+ '@esbuild/android-arm@0.28.1':
1287
+ optional: true
1288
+
1289
+ '@esbuild/android-x64@0.28.1':
1290
+ optional: true
1291
+
1292
+ '@esbuild/darwin-arm64@0.28.1':
1293
+ optional: true
1294
+
1295
+ '@esbuild/darwin-x64@0.28.1':
1296
+ optional: true
1297
+
1298
+ '@esbuild/freebsd-arm64@0.28.1':
1299
+ optional: true
1300
+
1301
+ '@esbuild/freebsd-x64@0.28.1':
1302
+ optional: true
1303
+
1304
+ '@esbuild/linux-arm64@0.28.1':
1305
+ optional: true
1306
+
1307
+ '@esbuild/linux-arm@0.28.1':
1308
+ optional: true
1309
+
1310
+ '@esbuild/linux-ia32@0.28.1':
1311
+ optional: true
1312
+
1313
+ '@esbuild/linux-loong64@0.28.1':
1314
+ optional: true
1315
+
1316
+ '@esbuild/linux-mips64el@0.28.1':
1317
+ optional: true
1318
+
1319
+ '@esbuild/linux-ppc64@0.28.1':
1320
+ optional: true
1321
+
1322
+ '@esbuild/linux-riscv64@0.28.1':
1323
+ optional: true
1324
+
1325
+ '@esbuild/linux-s390x@0.28.1':
1326
+ optional: true
1327
+
1328
+ '@esbuild/linux-x64@0.28.1':
1329
+ optional: true
1330
+
1331
+ '@esbuild/netbsd-arm64@0.28.1':
1332
+ optional: true
1333
+
1334
+ '@esbuild/netbsd-x64@0.28.1':
1335
+ optional: true
1336
+
1337
+ '@esbuild/openbsd-arm64@0.28.1':
1338
+ optional: true
1339
+
1340
+ '@esbuild/openbsd-x64@0.28.1':
1341
+ optional: true
1342
+
1343
+ '@esbuild/openharmony-arm64@0.28.1':
1344
+ optional: true
1345
+
1346
+ '@esbuild/sunos-x64@0.28.1':
1347
+ optional: true
1348
+
1349
+ '@esbuild/win32-arm64@0.28.1':
1350
+ optional: true
1351
+
1352
+ '@esbuild/win32-ia32@0.28.1':
1353
+ optional: true
1354
+
1355
+ '@esbuild/win32-x64@0.28.1':
1356
+ optional: true
1357
+
1358
+ '@img/colour@1.1.0': {}
1359
+
1360
+ '@img/sharp-darwin-arm64@0.34.5':
1361
+ optionalDependencies:
1362
+ '@img/sharp-libvips-darwin-arm64': 1.2.4
1363
+ optional: true
1364
+
1365
+ '@img/sharp-darwin-x64@0.34.5':
1366
+ optionalDependencies:
1367
+ '@img/sharp-libvips-darwin-x64': 1.2.4
1368
+ optional: true
1369
+
1370
+ '@img/sharp-libvips-darwin-arm64@1.2.4':
1371
+ optional: true
1372
+
1373
+ '@img/sharp-libvips-darwin-x64@1.2.4':
1374
+ optional: true
1375
+
1376
+ '@img/sharp-libvips-linux-arm64@1.2.4':
1377
+ optional: true
1378
+
1379
+ '@img/sharp-libvips-linux-arm@1.2.4':
1380
+ optional: true
1381
+
1382
+ '@img/sharp-libvips-linux-ppc64@1.2.4':
1383
+ optional: true
1384
+
1385
+ '@img/sharp-libvips-linux-riscv64@1.2.4':
1386
+ optional: true
1387
+
1388
+ '@img/sharp-libvips-linux-s390x@1.2.4':
1389
+ optional: true
1390
+
1391
+ '@img/sharp-libvips-linux-x64@1.2.4':
1392
+ optional: true
1393
+
1394
+ '@img/sharp-libvips-linuxmusl-arm64@1.2.4':
1395
+ optional: true
1396
+
1397
+ '@img/sharp-libvips-linuxmusl-x64@1.2.4':
1398
+ optional: true
1399
+
1400
+ '@img/sharp-linux-arm64@0.34.5':
1401
+ optionalDependencies:
1402
+ '@img/sharp-libvips-linux-arm64': 1.2.4
1403
+ optional: true
1404
+
1405
+ '@img/sharp-linux-arm@0.34.5':
1406
+ optionalDependencies:
1407
+ '@img/sharp-libvips-linux-arm': 1.2.4
1408
+ optional: true
1409
+
1410
+ '@img/sharp-linux-ppc64@0.34.5':
1411
+ optionalDependencies:
1412
+ '@img/sharp-libvips-linux-ppc64': 1.2.4
1413
+ optional: true
1414
+
1415
+ '@img/sharp-linux-riscv64@0.34.5':
1416
+ optionalDependencies:
1417
+ '@img/sharp-libvips-linux-riscv64': 1.2.4
1418
+ optional: true
1419
+
1420
+ '@img/sharp-linux-s390x@0.34.5':
1421
+ optionalDependencies:
1422
+ '@img/sharp-libvips-linux-s390x': 1.2.4
1423
+ optional: true
1424
+
1425
+ '@img/sharp-linux-x64@0.34.5':
1426
+ optionalDependencies:
1427
+ '@img/sharp-libvips-linux-x64': 1.2.4
1428
+ optional: true
1429
+
1430
+ '@img/sharp-linuxmusl-arm64@0.34.5':
1431
+ optionalDependencies:
1432
+ '@img/sharp-libvips-linuxmusl-arm64': 1.2.4
1433
+ optional: true
1434
+
1435
+ '@img/sharp-linuxmusl-x64@0.34.5':
1436
+ optionalDependencies:
1437
+ '@img/sharp-libvips-linuxmusl-x64': 1.2.4
1438
+ optional: true
1439
+
1440
+ '@img/sharp-wasm32@0.34.5':
1441
+ dependencies:
1442
+ '@emnapi/runtime': 1.11.2
1443
+ optional: true
1444
+
1445
+ '@img/sharp-win32-arm64@0.34.5':
1446
+ optional: true
1447
+
1448
+ '@img/sharp-win32-ia32@0.34.5':
1449
+ optional: true
1450
+
1451
+ '@img/sharp-win32-x64@0.34.5':
1452
+ optional: true
1453
+
1454
+ '@jridgewell/resolve-uri@3.1.2': {}
1455
+
1456
+ '@jridgewell/sourcemap-codec@1.5.5': {}
1457
+
1458
+ '@jridgewell/trace-mapping@0.3.31':
1459
+ dependencies:
1460
+ '@jridgewell/resolve-uri': 3.1.2
1461
+ '@jridgewell/sourcemap-codec': 1.5.5
1462
+
1463
+ '@jridgewell/trace-mapping@0.3.9':
1464
+ dependencies:
1465
+ '@jridgewell/resolve-uri': 3.1.2
1466
+ '@jridgewell/sourcemap-codec': 1.5.5
1467
+
1468
+ '@napi-rs/wasm-runtime@1.1.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)':
1469
+ dependencies:
1470
+ '@emnapi/core': 1.10.0
1471
+ '@emnapi/runtime': 1.10.0
1472
+ '@tybys/wasm-util': 0.10.2
1473
+ optional: true
1474
+
1475
+ '@oxc-project/types@0.133.0': {}
1476
+
1477
+ '@poppinss/colors@4.1.6':
1478
+ dependencies:
1479
+ kleur: 4.1.5
1480
+
1481
+ '@poppinss/dumper@0.6.5':
1482
+ dependencies:
1483
+ '@poppinss/colors': 4.1.6
1484
+ '@sindresorhus/is': 7.2.0
1485
+ supports-color: 10.2.2
1486
+
1487
+ '@poppinss/exception@1.2.3': {}
1488
+
1489
+ '@rolldown/binding-android-arm64@1.0.3':
1490
+ optional: true
1491
+
1492
+ '@rolldown/binding-darwin-arm64@1.0.3':
1493
+ optional: true
1494
+
1495
+ '@rolldown/binding-darwin-x64@1.0.3':
1496
+ optional: true
1497
+
1498
+ '@rolldown/binding-freebsd-x64@1.0.3':
1499
+ optional: true
1500
+
1501
+ '@rolldown/binding-linux-arm-gnueabihf@1.0.3':
1502
+ optional: true
1503
+
1504
+ '@rolldown/binding-linux-arm64-gnu@1.0.3':
1505
+ optional: true
1506
+
1507
+ '@rolldown/binding-linux-arm64-musl@1.0.3':
1508
+ optional: true
1509
+
1510
+ '@rolldown/binding-linux-ppc64-gnu@1.0.3':
1511
+ optional: true
1512
+
1513
+ '@rolldown/binding-linux-s390x-gnu@1.0.3':
1514
+ optional: true
1515
+
1516
+ '@rolldown/binding-linux-x64-gnu@1.0.3':
1517
+ optional: true
1518
+
1519
+ '@rolldown/binding-linux-x64-musl@1.0.3':
1520
+ optional: true
1521
+
1522
+ '@rolldown/binding-openharmony-arm64@1.0.3':
1523
+ optional: true
1524
+
1525
+ '@rolldown/binding-wasm32-wasi@1.0.3':
1526
+ dependencies:
1527
+ '@emnapi/core': 1.10.0
1528
+ '@emnapi/runtime': 1.10.0
1529
+ '@napi-rs/wasm-runtime': 1.1.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)
1530
+ optional: true
1531
+
1532
+ '@rolldown/binding-win32-arm64-msvc@1.0.3':
1533
+ optional: true
1534
+
1535
+ '@rolldown/binding-win32-x64-msvc@1.0.3':
1536
+ optional: true
1537
+
1538
+ '@rolldown/pluginutils@1.0.1': {}
1539
+
1540
+ '@sindresorhus/is@7.2.0': {}
1541
+
1542
+ '@speed-highlight/core@1.2.17': {}
1543
+
1544
+ '@standard-schema/spec@1.1.0': {}
1545
+
1546
+ '@tybys/wasm-util@0.10.2':
1547
+ dependencies:
1548
+ tslib: 2.8.1
1549
+ optional: true
1550
+
1551
+ '@types/chai@5.2.3':
1552
+ dependencies:
1553
+ '@types/deep-eql': 4.0.2
1554
+ assertion-error: 2.0.1
1555
+
1556
+ '@types/deep-eql@4.0.2': {}
1557
+
1558
+ '@types/estree@1.0.9': {}
1559
+
1560
+ '@typescript/typescript-aix-ppc64@7.0.2':
1561
+ optional: true
1562
+
1563
+ '@typescript/typescript-darwin-arm64@7.0.2':
1564
+ optional: true
1565
+
1566
+ '@typescript/typescript-darwin-x64@7.0.2':
1567
+ optional: true
1568
+
1569
+ '@typescript/typescript-freebsd-arm64@7.0.2':
1570
+ optional: true
1571
+
1572
+ '@typescript/typescript-freebsd-x64@7.0.2':
1573
+ optional: true
1574
+
1575
+ '@typescript/typescript-linux-arm64@7.0.2':
1576
+ optional: true
1577
+
1578
+ '@typescript/typescript-linux-arm@7.0.2':
1579
+ optional: true
1580
+
1581
+ '@typescript/typescript-linux-loong64@7.0.2':
1582
+ optional: true
1583
+
1584
+ '@typescript/typescript-linux-mips64el@7.0.2':
1585
+ optional: true
1586
+
1587
+ '@typescript/typescript-linux-ppc64@7.0.2':
1588
+ optional: true
1589
+
1590
+ '@typescript/typescript-linux-riscv64@7.0.2':
1591
+ optional: true
1592
+
1593
+ '@typescript/typescript-linux-s390x@7.0.2':
1594
+ optional: true
1595
+
1596
+ '@typescript/typescript-linux-x64@7.0.2':
1597
+ optional: true
1598
+
1599
+ '@typescript/typescript-netbsd-arm64@7.0.2':
1600
+ optional: true
1601
+
1602
+ '@typescript/typescript-netbsd-x64@7.0.2':
1603
+ optional: true
1604
+
1605
+ '@typescript/typescript-openbsd-arm64@7.0.2':
1606
+ optional: true
1607
+
1608
+ '@typescript/typescript-openbsd-x64@7.0.2':
1609
+ optional: true
1610
+
1611
+ '@typescript/typescript-sunos-x64@7.0.2':
1612
+ optional: true
1613
+
1614
+ '@typescript/typescript-win32-arm64@7.0.2':
1615
+ optional: true
1616
+
1617
+ '@typescript/typescript-win32-x64@7.0.2':
1618
+ optional: true
1619
+
1620
+ '@vitest/coverage-v8@4.1.10(vitest@4.1.10)':
1621
+ dependencies:
1622
+ '@bcoe/v8-coverage': 1.0.2
1623
+ '@vitest/utils': 4.1.10
1624
+ ast-v8-to-istanbul: 1.0.4
1625
+ istanbul-lib-coverage: 3.2.2
1626
+ istanbul-lib-report: 3.0.1
1627
+ istanbul-reports: 3.2.0
1628
+ magicast: 0.5.3
1629
+ obug: 2.1.3
1630
+ std-env: 4.2.0
1631
+ tinyrainbow: 3.1.0
1632
+ vitest: 4.1.10(@vitest/coverage-v8@4.1.10)(vite@8.0.16(esbuild@0.28.1))
1633
+
1634
+ '@vitest/expect@4.1.10':
1635
+ dependencies:
1636
+ '@standard-schema/spec': 1.1.0
1637
+ '@types/chai': 5.2.3
1638
+ '@vitest/spy': 4.1.10
1639
+ '@vitest/utils': 4.1.10
1640
+ chai: 6.2.2
1641
+ tinyrainbow: 3.1.0
1642
+
1643
+ '@vitest/mocker@4.1.10(vite@8.0.16(esbuild@0.28.1))':
1644
+ dependencies:
1645
+ '@vitest/spy': 4.1.10
1646
+ estree-walker: 3.0.3
1647
+ magic-string: 0.30.21
1648
+ optionalDependencies:
1649
+ vite: 8.0.16(esbuild@0.28.1)
1650
+
1651
+ '@vitest/pretty-format@4.1.10':
1652
+ dependencies:
1653
+ tinyrainbow: 3.1.0
1654
+
1655
+ '@vitest/runner@4.1.10':
1656
+ dependencies:
1657
+ '@vitest/utils': 4.1.10
1658
+ pathe: 2.0.3
1659
+
1660
+ '@vitest/snapshot@4.1.10':
1661
+ dependencies:
1662
+ '@vitest/pretty-format': 4.1.10
1663
+ '@vitest/utils': 4.1.10
1664
+ magic-string: 0.30.21
1665
+ pathe: 2.0.3
1666
+
1667
+ '@vitest/spy@4.1.10': {}
1668
+
1669
+ '@vitest/utils@4.1.10':
1670
+ dependencies:
1671
+ '@vitest/pretty-format': 4.1.10
1672
+ convert-source-map: 2.0.0
1673
+ tinyrainbow: 3.1.0
1674
+
1675
+ assertion-error@2.0.1: {}
1676
+
1677
+ ast-v8-to-istanbul@1.0.4:
1678
+ dependencies:
1679
+ '@jridgewell/trace-mapping': 0.3.31
1680
+ estree-walker: 3.0.3
1681
+ js-tokens: 10.0.0
1682
+
1683
+ blake3-wasm@2.1.5: {}
1684
+
1685
+ chai@6.2.2: {}
1686
+
1687
+ convert-source-map@2.0.0: {}
1688
+
1689
+ cookie@1.1.1: {}
1690
+
1691
+ detect-libc@2.1.2: {}
1692
+
1693
+ error-stack-parser-es@1.0.5: {}
1694
+
1695
+ es-module-lexer@2.3.0: {}
1696
+
1697
+ esbuild@0.28.1:
1698
+ optionalDependencies:
1699
+ '@esbuild/aix-ppc64': 0.28.1
1700
+ '@esbuild/android-arm': 0.28.1
1701
+ '@esbuild/android-arm64': 0.28.1
1702
+ '@esbuild/android-x64': 0.28.1
1703
+ '@esbuild/darwin-arm64': 0.28.1
1704
+ '@esbuild/darwin-x64': 0.28.1
1705
+ '@esbuild/freebsd-arm64': 0.28.1
1706
+ '@esbuild/freebsd-x64': 0.28.1
1707
+ '@esbuild/linux-arm': 0.28.1
1708
+ '@esbuild/linux-arm64': 0.28.1
1709
+ '@esbuild/linux-ia32': 0.28.1
1710
+ '@esbuild/linux-loong64': 0.28.1
1711
+ '@esbuild/linux-mips64el': 0.28.1
1712
+ '@esbuild/linux-ppc64': 0.28.1
1713
+ '@esbuild/linux-riscv64': 0.28.1
1714
+ '@esbuild/linux-s390x': 0.28.1
1715
+ '@esbuild/linux-x64': 0.28.1
1716
+ '@esbuild/netbsd-arm64': 0.28.1
1717
+ '@esbuild/netbsd-x64': 0.28.1
1718
+ '@esbuild/openbsd-arm64': 0.28.1
1719
+ '@esbuild/openbsd-x64': 0.28.1
1720
+ '@esbuild/openharmony-arm64': 0.28.1
1721
+ '@esbuild/sunos-x64': 0.28.1
1722
+ '@esbuild/win32-arm64': 0.28.1
1723
+ '@esbuild/win32-ia32': 0.28.1
1724
+ '@esbuild/win32-x64': 0.28.1
1725
+
1726
+ estree-walker@3.0.3:
1727
+ dependencies:
1728
+ '@types/estree': 1.0.9
1729
+
1730
+ expect-type@1.4.0: {}
1731
+
1732
+ fdir@6.5.0(picomatch@4.0.5):
1733
+ optionalDependencies:
1734
+ picomatch: 4.0.5
1735
+
1736
+ fsevents@2.3.3:
1737
+ optional: true
1738
+
1739
+ has-flag@4.0.0: {}
1740
+
1741
+ html-escaper@2.0.2: {}
1742
+
1743
+ istanbul-lib-coverage@3.2.2: {}
1744
+
1745
+ istanbul-lib-report@3.0.1:
1746
+ dependencies:
1747
+ istanbul-lib-coverage: 3.2.2
1748
+ make-dir: 4.0.0
1749
+ supports-color: 7.2.0
1750
+
1751
+ istanbul-reports@3.2.0:
1752
+ dependencies:
1753
+ html-escaper: 2.0.2
1754
+ istanbul-lib-report: 3.0.1
1755
+
1756
+ js-tokens@10.0.0: {}
1757
+
1758
+ kleur@4.1.5: {}
1759
+
1760
+ lightningcss-android-arm64@1.32.0:
1761
+ optional: true
1762
+
1763
+ lightningcss-darwin-arm64@1.32.0:
1764
+ optional: true
1765
+
1766
+ lightningcss-darwin-x64@1.32.0:
1767
+ optional: true
1768
+
1769
+ lightningcss-freebsd-x64@1.32.0:
1770
+ optional: true
1771
+
1772
+ lightningcss-linux-arm-gnueabihf@1.32.0:
1773
+ optional: true
1774
+
1775
+ lightningcss-linux-arm64-gnu@1.32.0:
1776
+ optional: true
1777
+
1778
+ lightningcss-linux-arm64-musl@1.32.0:
1779
+ optional: true
1780
+
1781
+ lightningcss-linux-x64-gnu@1.32.0:
1782
+ optional: true
1783
+
1784
+ lightningcss-linux-x64-musl@1.32.0:
1785
+ optional: true
1786
+
1787
+ lightningcss-win32-arm64-msvc@1.32.0:
1788
+ optional: true
1789
+
1790
+ lightningcss-win32-x64-msvc@1.32.0:
1791
+ optional: true
1792
+
1793
+ lightningcss@1.32.0:
1794
+ dependencies:
1795
+ detect-libc: 2.1.2
1796
+ optionalDependencies:
1797
+ lightningcss-android-arm64: 1.32.0
1798
+ lightningcss-darwin-arm64: 1.32.0
1799
+ lightningcss-darwin-x64: 1.32.0
1800
+ lightningcss-freebsd-x64: 1.32.0
1801
+ lightningcss-linux-arm-gnueabihf: 1.32.0
1802
+ lightningcss-linux-arm64-gnu: 1.32.0
1803
+ lightningcss-linux-arm64-musl: 1.32.0
1804
+ lightningcss-linux-x64-gnu: 1.32.0
1805
+ lightningcss-linux-x64-musl: 1.32.0
1806
+ lightningcss-win32-arm64-msvc: 1.32.0
1807
+ lightningcss-win32-x64-msvc: 1.32.0
1808
+
1809
+ magic-string@0.30.21:
1810
+ dependencies:
1811
+ '@jridgewell/sourcemap-codec': 1.5.5
1812
+
1813
+ magicast@0.5.3:
1814
+ dependencies:
1815
+ '@babel/parser': 7.29.7
1816
+ '@babel/types': 7.29.7
1817
+ source-map-js: 1.2.1
1818
+
1819
+ make-dir@4.0.0:
1820
+ dependencies:
1821
+ semver: 7.8.5
1822
+
1823
+ miniflare@4.20260708.1:
1824
+ dependencies:
1825
+ '@cspotcode/source-map-support': 0.8.1
1826
+ sharp: 0.34.5
1827
+ undici: 7.28.0
1828
+ workerd: 1.20260708.1
1829
+ ws: 8.21.0
1830
+ youch: 4.1.0-beta.10
1831
+ transitivePeerDependencies:
1832
+ - bufferutil
1833
+ - utf-8-validate
1834
+
1835
+ nanoid@3.3.13: {}
1836
+
1837
+ obug@2.1.3: {}
1838
+
1839
+ path-to-regexp@6.3.0: {}
1840
+
1841
+ pathe@2.0.3: {}
1842
+
1843
+ picocolors@1.1.1: {}
1844
+
1845
+ picomatch@4.0.5: {}
1846
+
1847
+ postcss@8.5.15:
1848
+ dependencies:
1849
+ nanoid: 3.3.13
1850
+ picocolors: 1.1.1
1851
+ source-map-js: 1.2.1
1852
+
1853
+ rolldown@1.0.3:
1854
+ dependencies:
1855
+ '@oxc-project/types': 0.133.0
1856
+ '@rolldown/pluginutils': 1.0.1
1857
+ optionalDependencies:
1858
+ '@rolldown/binding-android-arm64': 1.0.3
1859
+ '@rolldown/binding-darwin-arm64': 1.0.3
1860
+ '@rolldown/binding-darwin-x64': 1.0.3
1861
+ '@rolldown/binding-freebsd-x64': 1.0.3
1862
+ '@rolldown/binding-linux-arm-gnueabihf': 1.0.3
1863
+ '@rolldown/binding-linux-arm64-gnu': 1.0.3
1864
+ '@rolldown/binding-linux-arm64-musl': 1.0.3
1865
+ '@rolldown/binding-linux-ppc64-gnu': 1.0.3
1866
+ '@rolldown/binding-linux-s390x-gnu': 1.0.3
1867
+ '@rolldown/binding-linux-x64-gnu': 1.0.3
1868
+ '@rolldown/binding-linux-x64-musl': 1.0.3
1869
+ '@rolldown/binding-openharmony-arm64': 1.0.3
1870
+ '@rolldown/binding-wasm32-wasi': 1.0.3
1871
+ '@rolldown/binding-win32-arm64-msvc': 1.0.3
1872
+ '@rolldown/binding-win32-x64-msvc': 1.0.3
1873
+
1874
+ semver@7.8.5: {}
1875
+
1876
+ sharp@0.34.5:
1877
+ dependencies:
1878
+ '@img/colour': 1.1.0
1879
+ detect-libc: 2.1.2
1880
+ semver: 7.8.5
1881
+ optionalDependencies:
1882
+ '@img/sharp-darwin-arm64': 0.34.5
1883
+ '@img/sharp-darwin-x64': 0.34.5
1884
+ '@img/sharp-libvips-darwin-arm64': 1.2.4
1885
+ '@img/sharp-libvips-darwin-x64': 1.2.4
1886
+ '@img/sharp-libvips-linux-arm': 1.2.4
1887
+ '@img/sharp-libvips-linux-arm64': 1.2.4
1888
+ '@img/sharp-libvips-linux-ppc64': 1.2.4
1889
+ '@img/sharp-libvips-linux-riscv64': 1.2.4
1890
+ '@img/sharp-libvips-linux-s390x': 1.2.4
1891
+ '@img/sharp-libvips-linux-x64': 1.2.4
1892
+ '@img/sharp-libvips-linuxmusl-arm64': 1.2.4
1893
+ '@img/sharp-libvips-linuxmusl-x64': 1.2.4
1894
+ '@img/sharp-linux-arm': 0.34.5
1895
+ '@img/sharp-linux-arm64': 0.34.5
1896
+ '@img/sharp-linux-ppc64': 0.34.5
1897
+ '@img/sharp-linux-riscv64': 0.34.5
1898
+ '@img/sharp-linux-s390x': 0.34.5
1899
+ '@img/sharp-linux-x64': 0.34.5
1900
+ '@img/sharp-linuxmusl-arm64': 0.34.5
1901
+ '@img/sharp-linuxmusl-x64': 0.34.5
1902
+ '@img/sharp-wasm32': 0.34.5
1903
+ '@img/sharp-win32-arm64': 0.34.5
1904
+ '@img/sharp-win32-ia32': 0.34.5
1905
+ '@img/sharp-win32-x64': 0.34.5
1906
+
1907
+ siginfo@2.0.0: {}
1908
+
1909
+ source-map-js@1.2.1: {}
1910
+
1911
+ stackback@0.0.2: {}
1912
+
1913
+ std-env@4.2.0: {}
1914
+
1915
+ supports-color@10.2.2: {}
1916
+
1917
+ supports-color@7.2.0:
1918
+ dependencies:
1919
+ has-flag: 4.0.0
1920
+
1921
+ tinybench@2.9.0: {}
1922
+
1923
+ tinyexec@1.2.4: {}
1924
+
1925
+ tinyglobby@0.2.17:
1926
+ dependencies:
1927
+ fdir: 6.5.0(picomatch@4.0.5)
1928
+ picomatch: 4.0.5
1929
+
1930
+ tinyrainbow@3.1.0: {}
1931
+
1932
+ tslib@2.8.1:
1933
+ optional: true
1934
+
1935
+ typescript@7.0.2:
1936
+ optionalDependencies:
1937
+ '@typescript/typescript-aix-ppc64': 7.0.2
1938
+ '@typescript/typescript-darwin-arm64': 7.0.2
1939
+ '@typescript/typescript-darwin-x64': 7.0.2
1940
+ '@typescript/typescript-freebsd-arm64': 7.0.2
1941
+ '@typescript/typescript-freebsd-x64': 7.0.2
1942
+ '@typescript/typescript-linux-arm': 7.0.2
1943
+ '@typescript/typescript-linux-arm64': 7.0.2
1944
+ '@typescript/typescript-linux-loong64': 7.0.2
1945
+ '@typescript/typescript-linux-mips64el': 7.0.2
1946
+ '@typescript/typescript-linux-ppc64': 7.0.2
1947
+ '@typescript/typescript-linux-riscv64': 7.0.2
1948
+ '@typescript/typescript-linux-s390x': 7.0.2
1949
+ '@typescript/typescript-linux-x64': 7.0.2
1950
+ '@typescript/typescript-netbsd-arm64': 7.0.2
1951
+ '@typescript/typescript-netbsd-x64': 7.0.2
1952
+ '@typescript/typescript-openbsd-arm64': 7.0.2
1953
+ '@typescript/typescript-openbsd-x64': 7.0.2
1954
+ '@typescript/typescript-sunos-x64': 7.0.2
1955
+ '@typescript/typescript-win32-arm64': 7.0.2
1956
+ '@typescript/typescript-win32-x64': 7.0.2
1957
+
1958
+ undici@7.28.0: {}
1959
+
1960
+ unenv@2.0.0-rc.24:
1961
+ dependencies:
1962
+ pathe: 2.0.3
1963
+
1964
+ vite@8.0.16(esbuild@0.28.1):
1965
+ dependencies:
1966
+ lightningcss: 1.32.0
1967
+ picomatch: 4.0.5
1968
+ postcss: 8.5.15
1969
+ rolldown: 1.0.3
1970
+ tinyglobby: 0.2.17
1971
+ optionalDependencies:
1972
+ esbuild: 0.28.1
1973
+ fsevents: 2.3.3
1974
+
1975
+ vitest@4.1.10(@vitest/coverage-v8@4.1.10)(vite@8.0.16(esbuild@0.28.1)):
1976
+ dependencies:
1977
+ '@vitest/expect': 4.1.10
1978
+ '@vitest/mocker': 4.1.10(vite@8.0.16(esbuild@0.28.1))
1979
+ '@vitest/pretty-format': 4.1.10
1980
+ '@vitest/runner': 4.1.10
1981
+ '@vitest/snapshot': 4.1.10
1982
+ '@vitest/spy': 4.1.10
1983
+ '@vitest/utils': 4.1.10
1984
+ es-module-lexer: 2.3.0
1985
+ expect-type: 1.4.0
1986
+ magic-string: 0.30.21
1987
+ obug: 2.1.3
1988
+ pathe: 2.0.3
1989
+ picomatch: 4.0.5
1990
+ std-env: 4.2.0
1991
+ tinybench: 2.9.0
1992
+ tinyexec: 1.2.4
1993
+ tinyglobby: 0.2.17
1994
+ tinyrainbow: 3.1.0
1995
+ vite: 8.0.16(esbuild@0.28.1)
1996
+ why-is-node-running: 2.3.0
1997
+ optionalDependencies:
1998
+ '@vitest/coverage-v8': 4.1.10(vitest@4.1.10)
1999
+ transitivePeerDependencies:
2000
+ - msw
2001
+
2002
+ why-is-node-running@2.3.0:
2003
+ dependencies:
2004
+ siginfo: 2.0.0
2005
+ stackback: 0.0.2
2006
+
2007
+ workerd@1.20260708.1:
2008
+ optionalDependencies:
2009
+ '@cloudflare/workerd-darwin-64': 1.20260708.1
2010
+ '@cloudflare/workerd-darwin-arm64': 1.20260708.1
2011
+ '@cloudflare/workerd-linux-64': 1.20260708.1
2012
+ '@cloudflare/workerd-linux-arm64': 1.20260708.1
2013
+ '@cloudflare/workerd-windows-64': 1.20260708.1
2014
+
2015
+ wrangler@4.110.0(@cloudflare/workers-types@5.20260712.1):
2016
+ dependencies:
2017
+ '@cloudflare/kv-asset-handler': 0.5.0
2018
+ '@cloudflare/unenv-preset': 2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260708.1)
2019
+ blake3-wasm: 2.1.5
2020
+ esbuild: 0.28.1
2021
+ miniflare: 4.20260708.1
2022
+ path-to-regexp: 6.3.0
2023
+ unenv: 2.0.0-rc.24
2024
+ workerd: 1.20260708.1
2025
+ optionalDependencies:
2026
+ '@cloudflare/workers-types': 5.20260712.1
2027
+ fsevents: 2.3.3
2028
+ transitivePeerDependencies:
2029
+ - bufferutil
2030
+ - utf-8-validate
2031
+
2032
+ ws@8.21.0: {}
2033
+
2034
+ youch-core@0.3.3:
2035
+ dependencies:
2036
+ '@poppinss/exception': 1.2.3
2037
+ error-stack-parser-es: 1.0.5
2038
+
2039
+ youch@4.1.0-beta.10:
2040
+ dependencies:
2041
+ '@poppinss/colors': 4.1.6
2042
+ '@poppinss/dumper': 0.6.5
2043
+ '@speed-highlight/core': 1.2.17
2044
+ cookie: 1.1.1
2045
+ youch-core: 0.3.3
pnpm-workspace.yaml ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ packageImportMethod: copy
2
+ allowBuilds:
3
+ esbuild: true
4
+ sharp: true
5
+ workerd: true
6
+ minimumReleaseAgeExclude:
7
+ - '@cloudflare/workers-types@5.20260712.1'
8
+ - '@biomejs/biome@2.5.3'
9
+ - '@biomejs/cli-darwin-arm64@2.5.3'
10
+ - '@biomejs/cli-darwin-x64@2.5.3'
11
+ - '@biomejs/cli-linux-arm64-musl@2.5.3'
12
+ - '@biomejs/cli-linux-arm64@2.5.3'
13
+ - '@biomejs/cli-linux-x64-musl@2.5.3'
14
+ - '@biomejs/cli-linux-x64@2.5.3'
15
+ - '@biomejs/cli-win32-arm64@2.5.3'
16
+ - '@biomejs/cli-win32-x64@2.5.3'
17
+ - '@typescript/typescript-aix-ppc64@7.0.2'
18
+ - '@typescript/typescript-darwin-arm64@7.0.2'
19
+ - '@typescript/typescript-darwin-x64@7.0.2'
20
+ - '@typescript/typescript-freebsd-arm64@7.0.2'
21
+ - '@typescript/typescript-freebsd-x64@7.0.2'
22
+ - '@typescript/typescript-linux-arm64@7.0.2'
23
+ - '@typescript/typescript-linux-arm@7.0.2'
24
+ - '@typescript/typescript-linux-loong64@7.0.2'
25
+ - '@typescript/typescript-linux-mips64el@7.0.2'
26
+ - '@typescript/typescript-linux-ppc64@7.0.2'
27
+ - '@typescript/typescript-linux-riscv64@7.0.2'
28
+ - '@typescript/typescript-linux-s390x@7.0.2'
29
+ - '@typescript/typescript-linux-x64@7.0.2'
30
+ - '@typescript/typescript-netbsd-arm64@7.0.2'
31
+ - '@typescript/typescript-netbsd-x64@7.0.2'
32
+ - '@typescript/typescript-openbsd-arm64@7.0.2'
33
+ - '@typescript/typescript-openbsd-x64@7.0.2'
34
+ - '@typescript/typescript-sunos-x64@7.0.2'
35
+ - '@typescript/typescript-win32-arm64@7.0.2'
36
+ - '@typescript/typescript-win32-x64@7.0.2'
37
+ - typescript@7.0.2
38
+ peerDependencyRules:
39
+ allowedVersions:
40
+ '@cloudflare/workers-types': '>=4.20260702.1 <6'
scripts/bench.mjs ADDED
@@ -0,0 +1,1150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { resolve } from "node:path";
2
+ import { performance } from "node:perf_hooks";
3
+ import { pathToFileURL } from "node:url";
4
+ import { errorLine, outputLine } from "./io.mjs";
5
+
6
+ const benchmarkBundlePath = resolve(
7
+ process.cwd(),
8
+ process.env.BENCH_TEST_BUNDLE || "dist/worker.test.js",
9
+ );
10
+ let mod;
11
+ try {
12
+ mod = await import(pathToFileURL(benchmarkBundlePath).href);
13
+ } catch (error) {
14
+ errorLine(
15
+ `Benchmark bundle load failed: ${benchmarkBundlePath}: ${error instanceof Error ? error.message : String(error)}`,
16
+ );
17
+ process.exit(1);
18
+ }
19
+
20
+ const ITERATIONS = positiveInt(process.env.BENCH_ITERS, 2000);
21
+ const JSON_OUTPUT = /^(1|true|yes|on)$/i.test(
22
+ String(process.env.BENCH_JSON || ""),
23
+ );
24
+ const WARMUP = positiveInt(
25
+ process.env.BENCH_WARMUP,
26
+ Math.min(500, Math.floor(ITERATIONS / 4)),
27
+ );
28
+ const SSE_CHUNKS = positiveInt(process.env.BENCH_SSE_CHUNKS, 512);
29
+ const SSE_SLOW_CHUNKS = positiveInt(process.env.BENCH_SSE_SLOW_CHUNKS, 128);
30
+ const SSE_SLOW_DELAY_MS = positiveInt(process.env.BENCH_SSE_SLOW_DELAY_MS, 1);
31
+ const SOCKET_BODY_BYTES = positiveInt(
32
+ process.env.BENCH_SOCKET_BODY_BYTES,
33
+ 64 * 1024,
34
+ );
35
+ const SOCKET_CHUNK_BYTES = positiveInt(
36
+ process.env.BENCH_SOCKET_CHUNK_BYTES,
37
+ 1024,
38
+ );
39
+ const UNIQUE_ITEMS_COUNT = positiveInt(
40
+ process.env.BENCH_UNIQUE_ITEMS_COUNT,
41
+ 240,
42
+ );
43
+ const BASE64_BYTES = positiveInt(process.env.BENCH_BASE64_BYTES, 64 * 1024);
44
+ const MULTIPART_BYTES = positiveInt(
45
+ process.env.BENCH_MULTIPART_BYTES,
46
+ 8 * 1024 * 1024,
47
+ );
48
+ const APP_HTML_BYTES = positiveInt(
49
+ process.env.BENCH_APP_HTML_BYTES,
50
+ 512 * 1024,
51
+ );
52
+ const APP_HTML_CHUNK_BYTES = positiveInt(
53
+ process.env.BENCH_APP_HTML_CHUNK_BYTES,
54
+ 4096,
55
+ );
56
+ const STRUCTURED_JSON_NOISE_BYTES = positiveInt(
57
+ process.env.BENCH_STRUCTURED_JSON_NOISE_BYTES,
58
+ 16 * 1024,
59
+ );
60
+ const STREAM_CUMULATIVE_STEPS = positiveInt(
61
+ process.env.BENCH_STREAM_CUMULATIVE_STEPS,
62
+ 160,
63
+ );
64
+ const STREAM_CUMULATIVE_STEP_CHARS = positiveInt(
65
+ process.env.BENCH_STREAM_CUMULATIVE_STEP_CHARS,
66
+ 256,
67
+ );
68
+ const STREAM_LONG_LINE_BYTES = positiveInt(
69
+ process.env.BENCH_STREAM_LONG_LINE_BYTES,
70
+ 64 * 1024,
71
+ );
72
+ const STREAM_LONG_LINE_CHUNK_BYTES = positiveInt(
73
+ process.env.BENCH_STREAM_LONG_LINE_CHUNK_BYTES,
74
+ 128,
75
+ );
76
+ const SOCKET_LONG_CHUNK_LINE_BYTES = positiveInt(
77
+ process.env.BENCH_SOCKET_LONG_CHUNK_LINE_BYTES,
78
+ 4096,
79
+ );
80
+ const CONFIG_CACHE_BENCH_ENVS = {
81
+ empty: {},
82
+ realistic: {
83
+ GEMINI_COOKIE: "__Secure-1PSID=bench-session; SAPISID=bench-sapisid",
84
+ SAPISID: "bench-sapisid",
85
+ API_KEYS: ["sk-bench-primary", "sk-bench-secondary"],
86
+ DEFAULT_MODEL: "gemini-3.5-flash",
87
+ },
88
+ large: {
89
+ GEMINI_COOKIE: `SID=${"x".repeat(64 * 1024)}`,
90
+ SAPISID: "s".repeat(4096),
91
+ API_KEYS: ["a".repeat(4096), "b".repeat(4096)],
92
+ },
93
+ maximum: {
94
+ GEMINI_COOKIE: `SID=${"x".repeat(1024 * 1024 - 4)}`,
95
+ SAPISID: "s".repeat(4096),
96
+ API_KEYS: ["a".repeat(4096), "b".repeat(4096)],
97
+ },
98
+ };
99
+ const ATTACHMENT_DEDUPE_BYTES = new Uint8Array(8 * 1024 * 1024);
100
+ ATTACHMENT_DEDUPE_BYTES.fill(0x61);
101
+ const ATTACHMENT_DEDUPE_INPUT = {
102
+ candidate: {},
103
+ bytes: ATTACHMENT_DEDUPE_BYTES,
104
+ mime: "application/octet-stream",
105
+ filename: "benchmark.bin",
106
+ };
107
+ const TOOL = {
108
+ type: "function",
109
+ function: {
110
+ name: "Read",
111
+ parameters: { type: "object", properties: { path: { type: "string" } } },
112
+ },
113
+ };
114
+ const CFG = {
115
+ gemini_bl: "bench",
116
+ gemini_origin: "https://gemini.google.com",
117
+ upstream_socket: false,
118
+ default_model: "gemini-3.5-flash",
119
+ retry_attempts: 1,
120
+ retry_delay_sec: 0,
121
+ request_timeout_sec: 1,
122
+ log_requests: false,
123
+ current_input_file_enabled: true,
124
+ current_input_file_min_bytes: 95000,
125
+ current_input_file_name: "message.txt",
126
+ current_tools_file_name: "tools.txt",
127
+ api_keys: [],
128
+ cookie: "",
129
+ sapisid: "",
130
+ };
131
+ const FAKE_PROVIDER = {
132
+ async generateText() {
133
+ return "ok";
134
+ },
135
+ async *streamText() {
136
+ yield "ok";
137
+ },
138
+ async resolveAttachments() {
139
+ return emptyAttachmentResult();
140
+ },
141
+ async uploadTextFile(_text, filename) {
142
+ return { ref: `/uploaded/${filename}`, name: filename };
143
+ },
144
+ };
145
+
146
+ const longFalsePositive = makeLongFalsePositiveText(96_000);
147
+ const validDsml = [
148
+ "before",
149
+ '<tool_calls><invoke name="Read"><parameter name="path">/tmp/a.txt</parameter></invoke></tool_calls>',
150
+ "after",
151
+ ].join("\n");
152
+ const messages = [
153
+ { role: "system", content: "You are concise." },
154
+ { role: "user", content: "Read the file and summarize it." },
155
+ ];
156
+ const tools = [TOOL];
157
+ const toolBundle = mod.createToolBundle(tools);
158
+ const socketSingleBody = makeBytes(SOCKET_BODY_BYTES);
159
+ const socketChunks = makeSocketChunks(SOCKET_BODY_BYTES, SOCKET_CHUNK_BYTES);
160
+ const socketTextSingleResponse = makeHttpResponseChunks(
161
+ socketSingleBody,
162
+ SOCKET_BODY_BYTES,
163
+ );
164
+ const socketTextMultiResponse = makeHttpResponseChunks(
165
+ socketChunks,
166
+ SOCKET_BODY_BYTES,
167
+ );
168
+ const uniqueItemsValue = makeUniqueCompositeValues(UNIQUE_ITEMS_COUNT);
169
+ const uniqueItemsRequirement = {
170
+ type: "json_schema",
171
+ schema: { type: "array", uniqueItems: true },
172
+ };
173
+ const structuredPatternValue = {
174
+ tag: "ok-ready",
175
+ slug: "item-123",
176
+ note: "alpha",
177
+ };
178
+ const structuredPatternRequirement = {
179
+ type: "json_schema",
180
+ schema: {
181
+ type: "object",
182
+ required: ["tag", "slug"],
183
+ properties: {
184
+ tag: { type: "string", pattern: "^ok-[a-z0-9-]{2,32}$" },
185
+ slug: { type: "string", pattern: "^[a-z]+-[0-9]{3}$" },
186
+ note: { type: "string", pattern: "^[a-z]+$" },
187
+ },
188
+ },
189
+ };
190
+ const base64Input = bytesToBase64(makeBytes(BASE64_BYTES));
191
+ const multipartBytes = makeBytes(MULTIPART_BYTES);
192
+ const appPageTokensHtml = makeAppHtml(
193
+ APP_HTML_BYTES,
194
+ '{"qKIAYe":"push-bench","SNlM0e":"at-bench"}',
195
+ );
196
+ const appBuildLabelHtml = makeAppHtml(
197
+ APP_HTML_BYTES,
198
+ '<script>{"cfb2h":"bench-bl"}</script>',
199
+ );
200
+ const structuredJsonNoise = "{".repeat(STRUCTURED_JSON_NOISE_BYTES);
201
+ const markdownRestoreMasked = mod.maskMarkdownProtectedSpans(
202
+ makeMarkdownProtectedText(300),
203
+ );
204
+ const markdownRestorePlaceholderCount = countOccurrences(
205
+ markdownRestoreMasked.text,
206
+ "GEMINI_MD_PROTECTED_",
207
+ );
208
+ const largeJsonBody = JSON.stringify({
209
+ message: "x".repeat(128 * 1024),
210
+ ok: true,
211
+ });
212
+ const longHeldToolCandidate = makeLongHeldToolCandidate(240 * 1024);
213
+ const cumulativeWrbLines = makeCumulativeWrbLines(
214
+ STREAM_CUMULATIVE_STEPS,
215
+ STREAM_CUMULATIVE_STEP_CHARS,
216
+ );
217
+ const longLineResponseChunks = makeLongLineStreamResponseChunks(
218
+ STREAM_LONG_LINE_BYTES,
219
+ STREAM_LONG_LINE_CHUNK_BYTES,
220
+ );
221
+ const socketLongChunkedLineResponse = makeSocketLongChunkedLineResponse(
222
+ SOCKET_LONG_CHUNK_LINE_BYTES,
223
+ );
224
+ const smallDeltaProvider = {
225
+ async generateText() {
226
+ return "ok";
227
+ },
228
+ async *streamText() {
229
+ for (let i = 0; i < SSE_CHUNKS; i++) yield "x";
230
+ },
231
+ async resolveAttachments() {
232
+ return emptyAttachmentResult();
233
+ },
234
+ async uploadTextFile(_text, filename) {
235
+ return { ref: `/uploaded/${filename}`, name: filename };
236
+ },
237
+ };
238
+ function emptyAttachmentResult() {
239
+ return {
240
+ fileRefs: null,
241
+ imageFileRefs: null,
242
+ genericFileRefs: null,
243
+ droppedNote: "",
244
+ usage: {
245
+ uploadedFiles: 0,
246
+ dedupedFiles: 0,
247
+ uploadedBytes: 0,
248
+ droppedFiles: 0,
249
+ },
250
+ };
251
+ }
252
+
253
+ const cases = [
254
+ {
255
+ name: "config_cache_empty",
256
+ fn: () => mod.getConfig(CONFIG_CACHE_BENCH_ENVS.empty),
257
+ },
258
+ {
259
+ name: "config_cache_realistic",
260
+ fn: () => mod.getConfig(CONFIG_CACHE_BENCH_ENVS.realistic),
261
+ },
262
+ {
263
+ name: "config_cache_large_secrets",
264
+ fn: () => mod.getConfig(CONFIG_CACHE_BENCH_ENVS.large),
265
+ iterations: Math.min(ITERATIONS, 1000),
266
+ warmup: Math.min(WARMUP, 100),
267
+ },
268
+ {
269
+ name: "config_cache_maximum_secrets",
270
+ fn: () => mod.getConfig(CONFIG_CACHE_BENCH_ENVS.maximum),
271
+ iterations: Math.min(ITERATIONS, 200),
272
+ warmup: Math.min(WARMUP, 20),
273
+ },
274
+ {
275
+ name: "attachment_dedupe_large",
276
+ fn: () => mod.attachmentDedupeKeyForTest(ATTACHMENT_DEDUPE_INPUT),
277
+ iterations: Math.min(ITERATIONS, 30),
278
+ warmup: Math.min(WARMUP, 5),
279
+ },
280
+ {
281
+ name: "route_options",
282
+ fn: () =>
283
+ mod.default.fetch(
284
+ new Request("https://worker.example/v1/models", { method: "OPTIONS" }),
285
+ {},
286
+ {},
287
+ ),
288
+ },
289
+ {
290
+ name: "route_health",
291
+ fn: () => mod.default.fetch(new Request("https://worker.example/"), {}, {}),
292
+ },
293
+ {
294
+ name: "route_models",
295
+ fn: () =>
296
+ mod.default.fetch(
297
+ new Request("https://worker.example/v1/models"),
298
+ {},
299
+ {},
300
+ ),
301
+ },
302
+ {
303
+ name: "json_invalid",
304
+ fn: () =>
305
+ mod.default.fetch(
306
+ new Request("https://worker.example/v1/chat/completions", {
307
+ method: "POST",
308
+ body: "{",
309
+ }),
310
+ {},
311
+ {},
312
+ ),
313
+ },
314
+ {
315
+ name: "json_large_strict",
316
+ fn: () => runReadLargeJsonStrict(),
317
+ iterations: Math.min(ITERATIONS, 500),
318
+ warmup: Math.min(WARMUP, 100),
319
+ },
320
+ {
321
+ name: "json_oversized_reject",
322
+ fn: () =>
323
+ mod.default.fetch(
324
+ new Request("https://worker.example/v1/chat/completions", {
325
+ method: "POST",
326
+ headers: { "content-length": "95001" },
327
+ body: "{}",
328
+ }),
329
+ {},
330
+ {},
331
+ ),
332
+ },
333
+ {
334
+ name: "messages_to_prompt",
335
+ fn: () =>
336
+ mod.messagesToPrompt(
337
+ messages,
338
+ toolBundle,
339
+ "auto",
340
+ toolBundle.defs,
341
+ "",
342
+ 1_000_000,
343
+ ),
344
+ },
345
+ {
346
+ name: "prepare_openai_context",
347
+ fn: () =>
348
+ mod.prepareOpenAIGeminiContext(
349
+ CFG,
350
+ FAKE_PROVIDER,
351
+ { model: "gemini-3.5-flash" },
352
+ messages,
353
+ toolBundle,
354
+ "auto",
355
+ null,
356
+ null,
357
+ ),
358
+ },
359
+ {
360
+ name: "parse_plain_long_false_positive",
361
+ fn: () => mod.parseToolCalls(longFalsePositive, tools),
362
+ },
363
+ { name: "parse_valid_dsml", fn: () => mod.parseToolCalls(validDsml, tools) },
364
+ {
365
+ name: "stream_sieve_plain_chunks",
366
+ fn: () => runPlainSieveChunks(longFalsePositive),
367
+ },
368
+ {
369
+ name: "stream_sieve_held_tool",
370
+ fn: () => runHeldToolCandidateChunks(longHeldToolCandidate),
371
+ iterations: Math.min(ITERATIONS, 300),
372
+ warmup: Math.min(WARMUP, 50),
373
+ },
374
+ {
375
+ name: "stream_text_cumulative_deltas",
376
+ fn: () => runStreamTextCumulativeDeltas(),
377
+ iterations: Math.min(ITERATIONS, 120),
378
+ warmup: Math.min(WARMUP, 20),
379
+ },
380
+ {
381
+ name: "gemini_stream_long_line_chunks",
382
+ fn: () => runGeminiStreamLongLineChunks(),
383
+ iterations: Math.min(ITERATIONS, 80),
384
+ warmup: Math.min(WARMUP, 10),
385
+ },
386
+ {
387
+ name: "responses_small_delta_stream",
388
+ fn: () => runResponsesSmallDeltaStream(),
389
+ iterations: Math.min(ITERATIONS, 60),
390
+ warmup: Math.min(WARMUP, 10),
391
+ },
392
+ {
393
+ name: "google_small_delta_stream",
394
+ fn: () => runGoogleSmallDeltaStream(),
395
+ iterations: Math.min(ITERATIONS, 60),
396
+ warmup: Math.min(WARMUP, 10),
397
+ },
398
+ {
399
+ name: "sse_many_small_delta",
400
+ fn: () => runSseChunks({ chunks: SSE_CHUNKS, delayMs: 0 }),
401
+ iterations: Math.min(ITERATIONS, 400),
402
+ warmup: Math.min(WARMUP, 100),
403
+ },
404
+ {
405
+ name: "sse_slow_consumer",
406
+ fn: () =>
407
+ runSseChunks({ chunks: SSE_SLOW_CHUNKS, delayMs: SSE_SLOW_DELAY_MS }),
408
+ iterations: Math.min(ITERATIONS, 30),
409
+ warmup: Math.min(WARMUP, 5),
410
+ },
411
+ {
412
+ name: "socket_single_chunk_body",
413
+ fn: () => runSocketSingleChunkBody(),
414
+ iterations: Math.min(ITERATIONS, 1000),
415
+ warmup: Math.min(WARMUP, 200),
416
+ },
417
+ {
418
+ name: "socket_multi_chunk_body",
419
+ fn: () => runSocketMultiChunkBody(),
420
+ iterations: Math.min(ITERATIONS, 1000),
421
+ warmup: Math.min(WARMUP, 200),
422
+ },
423
+ {
424
+ name: "socket_text_single_chunk",
425
+ fn: () => runSocketText(socketTextSingleResponse),
426
+ iterations: Math.min(ITERATIONS, 400),
427
+ warmup: Math.min(WARMUP, 100),
428
+ },
429
+ {
430
+ name: "socket_text_multi_chunk",
431
+ fn: () => runSocketText(socketTextMultiResponse),
432
+ iterations: Math.min(ITERATIONS, 400),
433
+ warmup: Math.min(WARMUP, 100),
434
+ },
435
+ {
436
+ name: "socket_chunked_long_split_line",
437
+ fn: () => runSocketText(socketLongChunkedLineResponse),
438
+ iterations: Math.min(ITERATIONS, 80),
439
+ warmup: Math.min(WARMUP, 10),
440
+ },
441
+ {
442
+ name: "structured_unique_items",
443
+ fn: () => runUniqueItemsValidation(),
444
+ iterations: Math.min(ITERATIONS, 200),
445
+ warmup: Math.min(WARMUP, 50),
446
+ },
447
+ {
448
+ name: "structured_pattern_schema",
449
+ fn: () => runStructuredPatternValidation(),
450
+ iterations: Math.min(ITERATIONS, 1000),
451
+ warmup: Math.min(WARMUP, 200),
452
+ },
453
+ {
454
+ name: "base64_decode_large",
455
+ fn: () => runBase64Decode(),
456
+ iterations: Math.min(ITERATIONS, 1000),
457
+ warmup: Math.min(WARMUP, 200),
458
+ },
459
+ {
460
+ name: "multipart_body_large",
461
+ fn: () => runMultipartBodyLarge(),
462
+ iterations: Math.min(ITERATIONS, 1000),
463
+ warmup: Math.min(WARMUP, 200),
464
+ },
465
+ {
466
+ name: "app_page_tokens_large",
467
+ fn: () => runAppPageTokensLarge(),
468
+ iterations: Math.min(ITERATIONS, 200),
469
+ warmup: Math.min(WARMUP, 50),
470
+ },
471
+ {
472
+ name: "app_build_label_large",
473
+ fn: () => runAppBuildLabelLarge(),
474
+ iterations: Math.min(ITERATIONS, 200),
475
+ warmup: Math.min(WARMUP, 50),
476
+ },
477
+ {
478
+ name: "structured_json_unclosed",
479
+ fn: () => runStructuredJsonUnclosed(),
480
+ iterations: Math.min(ITERATIONS, 100),
481
+ warmup: Math.min(WARMUP, 20),
482
+ },
483
+ { name: "rand_hex_32", fn: () => runRandHex32() },
484
+ {
485
+ name: "markdown_restore_many",
486
+ fn: () => runMarkdownRestoreMany(),
487
+ iterations: Math.min(ITERATIONS, 1000),
488
+ warmup: Math.min(WARMUP, 200),
489
+ },
490
+ ];
491
+
492
+ const caseFilters = String(process.env.BENCH_CASES || "")
493
+ .split(",")
494
+ .map((value) => value.trim())
495
+ .filter(Boolean);
496
+ const selectedCases = caseFilters.length
497
+ ? cases.filter((item) =>
498
+ caseFilters.some((filter) => item.name.includes(filter)),
499
+ )
500
+ : cases;
501
+ if (!selectedCases.length) {
502
+ errorLine(`No benchmark cases matched BENCH_CASES=${caseFilters.join(",")}`);
503
+ process.exit(1);
504
+ }
505
+
506
+ const results = [];
507
+ for (const item of selectedCases) {
508
+ const result = await bench(item.fn, item);
509
+ results.push({ name: item.name, ...result });
510
+ }
511
+ if (JSON_OUTPUT) {
512
+ outputLine(
513
+ JSON.stringify({
514
+ iterations: ITERATIONS,
515
+ warmup: WARMUP,
516
+ filters: caseFilters,
517
+ results,
518
+ }),
519
+ );
520
+ } else {
521
+ outputLine(`Benchmark iterations=${ITERATIONS} warmup=${WARMUP}`);
522
+ if (caseFilters.length)
523
+ outputLine(`Benchmark filters=${caseFilters.join(",")}`);
524
+ for (const result of results) outputLine(formatResult(result.name, result));
525
+ }
526
+
527
+ async function bench(fn, options = {}) {
528
+ const iterations = positiveInt(options.iterations, ITERATIONS);
529
+ const warmup = positiveInt(options.warmup, WARMUP);
530
+ for (let i = 0; i < warmup; i++) await fn();
531
+ const samples = new Array(iterations);
532
+ let lastValue;
533
+ const totalStart = performance.now();
534
+ for (let i = 0; i < iterations; i++) {
535
+ const start = performance.now();
536
+ lastValue = await fn();
537
+ samples[i] = performance.now() - start;
538
+ }
539
+ const totalMs = performance.now() - totalStart;
540
+ samples.sort((a, b) => a - b);
541
+ return {
542
+ iterations,
543
+ warmup,
544
+ medianMs: percentile(samples, 0.5),
545
+ p95Ms: percentile(samples, 0.95),
546
+ p99Ms: percentile(samples, 0.99),
547
+ meanMs: totalMs / iterations,
548
+ opsPerSec: iterations / (totalMs / 1000),
549
+ details: benchmarkDetails(lastValue),
550
+ };
551
+ }
552
+
553
+ function formatResult(name, result) {
554
+ const fields = [
555
+ name.padEnd(30),
556
+ `n=${result.iterations}`,
557
+ `median=${formatMs(result.medianMs)}`,
558
+ `p95=${formatMs(result.p95Ms)}`,
559
+ `p99=${formatMs(result.p99Ms)}`,
560
+ `mean=${formatMs(result.meanMs)}`,
561
+ `ops/s=${Math.round(result.opsPerSec)}`,
562
+ ];
563
+ const details = formatDetails(result.details);
564
+ if (details) fields.push(details);
565
+ return fields.join(" ");
566
+ }
567
+
568
+ function benchmarkDetails(value) {
569
+ if (!value || typeof value !== "object" || !value.__benchDetails) return null;
570
+ return value.__benchDetails;
571
+ }
572
+
573
+ function formatDetails(details) {
574
+ if (!details || typeof details !== "object") return "";
575
+ return Object.entries(details)
576
+ .map(
577
+ ([key, val]) =>
578
+ `${key}=${typeof val === "number" ? Math.round(val) : String(val)}`,
579
+ )
580
+ .join(" ");
581
+ }
582
+
583
+ function percentile(sorted, p) {
584
+ if (!sorted.length) return 0;
585
+ const index = Math.min(
586
+ sorted.length - 1,
587
+ Math.max(0, Math.floor((sorted.length - 1) * p)),
588
+ );
589
+ return sorted[index] || 0;
590
+ }
591
+
592
+ function formatMs(ms) {
593
+ if (ms < 1) return `${(ms * 1000).toFixed(1)}us`;
594
+ return `${ms.toFixed(3)}ms`;
595
+ }
596
+
597
+ function positiveInt(value, fallback) {
598
+ const n = Number.parseInt(String(value ?? ""), 10);
599
+ return Number.isFinite(n) && n > 0 ? n : fallback;
600
+ }
601
+
602
+ function makeLongFalsePositiveText(bytes) {
603
+ const line =
604
+ "ordinary prose: a < b, parameterless discussion, invoke is just a word, tool_calls appears as text.\n";
605
+ let out = "";
606
+ while (out.length < bytes) out += line;
607
+ return out.slice(0, bytes);
608
+ }
609
+
610
+ function makeLongHeldToolCandidate(bytes) {
611
+ const prefix = '<tool_calls><invoke name="Read"><parameter name="path">';
612
+ const suffix = "</parameter></invoke></tool_calls>";
613
+ return (
614
+ prefix +
615
+ "x".repeat(Math.max(0, bytes - prefix.length - suffix.length)) +
616
+ suffix
617
+ );
618
+ }
619
+
620
+ function wrbLine(texts) {
621
+ const inner = [null, null, null, null, [[null, texts]], "x".repeat(160)];
622
+ return JSON.stringify([["wrb.fr", null, JSON.stringify(inner)]]);
623
+ }
624
+
625
+ function makeCumulativeWrbLines(steps, stepChars) {
626
+ const lines = [];
627
+ let text = "";
628
+ const piece = "x".repeat(stepChars);
629
+ for (let i = 0; i < steps; i++) {
630
+ text += piece;
631
+ lines.push(wrbLine([text]));
632
+ }
633
+ return lines;
634
+ }
635
+
636
+ function runStreamTextCumulativeDeltas() {
637
+ const extractor = mod.createStreamTextExtractor();
638
+ let deltas = 0;
639
+ let chars = 0;
640
+ for (const line of cumulativeWrbLines) {
641
+ for (const delta of extractor.consumeLine(line)) {
642
+ deltas += 1;
643
+ chars += delta.length;
644
+ }
645
+ }
646
+ return {
647
+ __benchDetails: {
648
+ lines: cumulativeWrbLines.length,
649
+ chars,
650
+ deltas,
651
+ },
652
+ };
653
+ }
654
+
655
+ async function runGeminiStreamLongLineChunks() {
656
+ const stats = installFetchChunks(longLineResponseChunks);
657
+ let chunks = 0;
658
+ let chars = 0;
659
+ try {
660
+ for await (const delta of mod.generateStream(
661
+ CFG,
662
+ "bench",
663
+ 1,
664
+ 0,
665
+ null,
666
+ null,
667
+ )) {
668
+ chunks += 1;
669
+ chars += delta.length;
670
+ }
671
+ } finally {
672
+ stats.restore();
673
+ }
674
+ return {
675
+ __benchDetails: {
676
+ responseChunks: stats.chunks,
677
+ chars,
678
+ chunks,
679
+ },
680
+ };
681
+ }
682
+
683
+ function makeLongLineStreamResponseChunks(totalBytes, chunkBytes) {
684
+ const text = "x".repeat(totalBytes);
685
+ const line = new TextEncoder().encode(`${wrbLine([text])}\n`);
686
+ const chunks = [];
687
+ for (let i = 0; i < line.length; i += chunkBytes) {
688
+ chunks.push(line.subarray(i, i + chunkBytes));
689
+ }
690
+ return chunks;
691
+ }
692
+
693
+ async function runReadLargeJsonStrict() {
694
+ const parsed = await mod.readJsonRequest(
695
+ new Request("https://worker.example/", {
696
+ method: "POST",
697
+ headers: { "content-length": String(largeJsonBody.length) },
698
+ body: largeJsonBody,
699
+ }),
700
+ );
701
+ return {
702
+ __benchDetails: {
703
+ bytes: parsed.bytes || 0,
704
+ ok: parsed.value?.ok ? 1 : 0,
705
+ },
706
+ };
707
+ }
708
+
709
+ function runPlainSieveChunks(text) {
710
+ const state = mod.createToolSieveState();
711
+ for (let i = 0; i < text.length; i += 1024) {
712
+ mod.processToolSieveChunk(state, text.slice(i, i + 1024));
713
+ }
714
+ return mod.flushToolSieve(state, tools);
715
+ }
716
+
717
+ function runHeldToolCandidateChunks(text) {
718
+ const state = mod.createToolSieveState();
719
+ for (let i = 0; i < text.length; i += 1024) {
720
+ mod.processToolSieveChunk(state, text.slice(i, i + 1024));
721
+ }
722
+ return mod.flushToolSieve(state, tools);
723
+ }
724
+
725
+ async function runResponsesSmallDeltaStream() {
726
+ let writes = 0;
727
+ await mod.streamResponsesWithToolSieve(
728
+ () => {
729
+ writes += 1;
730
+ },
731
+ CFG,
732
+ {
733
+ provider: smallDeltaProvider,
734
+ rid: "resp_bench",
735
+ rm: { name: "gemini-3.5-flash" },
736
+ prompt: "bench",
737
+ fileRefs: null,
738
+ tools: null,
739
+ toolPolicy: null,
740
+ promptTokens: 1,
741
+ signal: new AbortController().signal,
742
+ },
743
+ );
744
+ return {
745
+ __benchDetails: {
746
+ inputDeltas: SSE_CHUNKS,
747
+ writes,
748
+ },
749
+ };
750
+ }
751
+
752
+ async function runGoogleSmallDeltaStream() {
753
+ let writes = 0;
754
+ await mod.streamGooglePlain(
755
+ () => {
756
+ writes += 1;
757
+ },
758
+ CFG,
759
+ {
760
+ provider: smallDeltaProvider,
761
+ prompt: "bench",
762
+ rm: { name: "gemini-3.5-flash" },
763
+ fileRefs: null,
764
+ promptTokens: 1,
765
+ signal: new AbortController().signal,
766
+ },
767
+ );
768
+ return {
769
+ __benchDetails: {
770
+ inputDeltas: SSE_CHUNKS,
771
+ writes,
772
+ },
773
+ };
774
+ }
775
+
776
+ async function runSseChunks({ chunks, delayMs }) {
777
+ const frame = "data: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n";
778
+ let producedBytes = 0;
779
+ let consumedBytes = 0;
780
+ let peakBufferedBytes = 0;
781
+ const resp = mod.sseResponse(async (write) => {
782
+ for (let i = 0; i < chunks; i++) {
783
+ producedBytes += frame.length;
784
+ peakBufferedBytes = Math.max(
785
+ peakBufferedBytes,
786
+ producedBytes - consumedBytes,
787
+ );
788
+ await write(frame);
789
+ peakBufferedBytes = Math.max(
790
+ peakBufferedBytes,
791
+ producedBytes - consumedBytes,
792
+ );
793
+ }
794
+ });
795
+ const reader = resp.body.getReader();
796
+ for (;;) {
797
+ const { done, value } = await reader.read();
798
+ if (done) break;
799
+ consumedBytes += value ? value.length : 0;
800
+ peakBufferedBytes = Math.max(
801
+ peakBufferedBytes,
802
+ producedBytes - consumedBytes,
803
+ );
804
+ if (delayMs > 0) await delay(delayMs);
805
+ }
806
+ return {
807
+ __benchDetails: {
808
+ totalBytes: producedBytes,
809
+ peakBufferedBytes,
810
+ },
811
+ };
812
+ }
813
+
814
+ function delay(ms) {
815
+ return new Promise((done) => setTimeout(done, ms));
816
+ }
817
+
818
+ function runSocketSingleChunkBody() {
819
+ const queue = mod.createByteQueue(socketSingleBody);
820
+ const out = queue.read(socketSingleBody.length);
821
+ return {
822
+ __benchDetails: {
823
+ totalBytes: out.length,
824
+ sameBuffer:
825
+ out.buffer === socketSingleBody.buffer &&
826
+ out.byteOffset === socketSingleBody.byteOffset
827
+ ? 1
828
+ : 0,
829
+ },
830
+ };
831
+ }
832
+
833
+ function runSocketMultiChunkBody() {
834
+ const queue = mod.createByteQueue();
835
+ for (const chunk of socketChunks) queue.push(chunk);
836
+ const out = queue.read(SOCKET_BODY_BYTES);
837
+ return {
838
+ __benchDetails: {
839
+ totalBytes: out.length,
840
+ sameBuffer: socketChunks.some((chunk) => out.buffer === chunk.buffer)
841
+ ? 1
842
+ : 0,
843
+ },
844
+ };
845
+ }
846
+
847
+ function makeBytes(length) {
848
+ const out = new Uint8Array(length);
849
+ for (let i = 0; i < out.length; i++) out[i] = i & 255;
850
+ return out;
851
+ }
852
+
853
+ function bytesToBase64(bytes) {
854
+ const native = bytes.toBase64;
855
+ if (typeof native === "function") return native.call(bytes);
856
+ let binary = "";
857
+ const chunkSize = 0x8000;
858
+ for (let offset = 0; offset < bytes.byteLength; offset += chunkSize) {
859
+ const chunk = bytes.subarray(offset, offset + chunkSize);
860
+ binary += String.fromCharCode(...chunk);
861
+ }
862
+ return btoa(binary);
863
+ }
864
+
865
+ function makeSocketChunks(totalBytes, chunkBytes) {
866
+ const chunks = [];
867
+ let remaining = totalBytes;
868
+ let seed = 0;
869
+ while (remaining > 0) {
870
+ const size = Math.min(chunkBytes, remaining);
871
+ const chunk = new Uint8Array(size);
872
+ for (let i = 0; i < chunk.length; i++) chunk[i] = (seed + i) & 255;
873
+ chunks.push(chunk);
874
+ seed += size;
875
+ remaining -= size;
876
+ }
877
+ return chunks;
878
+ }
879
+
880
+ async function runSocketText(responseChunks) {
881
+ const resp = await mod.socketHttp(
882
+ fakeSocketConnect(responseChunks),
883
+ "https://example.test/text",
884
+ { timeoutMs: 0 },
885
+ );
886
+ const text = await resp.text();
887
+ return {
888
+ __benchDetails: {
889
+ totalChars: text.length,
890
+ chunks: responseChunks.length,
891
+ },
892
+ };
893
+ }
894
+
895
+ function makeHttpResponseChunks(bodyOrChunks, totalBytes) {
896
+ const head = new TextEncoder().encode(
897
+ `HTTP/1.1 200 OK\r\nContent-Length: ${totalBytes}\r\n\r\n`,
898
+ );
899
+ if (bodyOrChunks instanceof Uint8Array)
900
+ return [concatBytes(head, bodyOrChunks)];
901
+ return [head, ...bodyOrChunks];
902
+ }
903
+
904
+ function makeSocketLongChunkedLineResponse(lineBytes) {
905
+ const encoder = new TextEncoder();
906
+ const head = encoder.encode(
907
+ "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n",
908
+ );
909
+ const line = encoder.encode(`1;${"x".repeat(lineBytes)}\r\n`);
910
+ const tail = encoder.encode("a\r\n0\r\n\r\n");
911
+ const chunks = [head];
912
+ for (let i = 0; i < line.length; i++) chunks.push(line.subarray(i, i + 1));
913
+ chunks.push(tail);
914
+ return chunks;
915
+ }
916
+
917
+ function fakeSocketConnect(responseChunks) {
918
+ return () => ({
919
+ readable: new ReadableStream({
920
+ start(controller) {
921
+ for (const chunk of responseChunks) controller.enqueue(chunk);
922
+ controller.close();
923
+ },
924
+ }),
925
+ writable: new WritableStream({
926
+ write() {},
927
+ }),
928
+ close() {},
929
+ });
930
+ }
931
+
932
+ function concatBytes(a, b) {
933
+ const out = new Uint8Array(a.length + b.length);
934
+ out.set(a, 0);
935
+ out.set(b, a.length);
936
+ return out;
937
+ }
938
+
939
+ function runUniqueItemsValidation() {
940
+ const error = mod.validateStructuredOutputValue(
941
+ uniqueItemsValue,
942
+ uniqueItemsRequirement,
943
+ );
944
+ return {
945
+ __benchDetails: {
946
+ items: uniqueItemsValue.length,
947
+ ok: error ? 0 : 1,
948
+ },
949
+ };
950
+ }
951
+
952
+ function runStructuredPatternValidation() {
953
+ let error = "";
954
+ for (let i = 0; i < 100; i++) {
955
+ error = mod.validateStructuredOutputValue(
956
+ structuredPatternValue,
957
+ structuredPatternRequirement,
958
+ );
959
+ }
960
+ return {
961
+ __benchDetails: {
962
+ checks: 100,
963
+ ok: error ? 0 : 1,
964
+ },
965
+ };
966
+ }
967
+
968
+ function makeUniqueCompositeValues(count) {
969
+ const out = [];
970
+ for (let i = 0; i < count; i++) {
971
+ out.push({
972
+ id: i,
973
+ tags: [`tag-${i % 17}`, `group-${Math.floor(i / 17)}`],
974
+ nested: {
975
+ left: { value: i * 3, ok: (i & 1) === 0 },
976
+ right: [i, { label: `item-${i}` }],
977
+ },
978
+ });
979
+ }
980
+ return out;
981
+ }
982
+
983
+ function runBase64Decode() {
984
+ const bytes = mod.base64ToBytes(base64Input);
985
+ return {
986
+ __benchDetails: {
987
+ bytes: bytes.length,
988
+ },
989
+ };
990
+ }
991
+
992
+ function runMultipartBodyLarge() {
993
+ const multipart = mod.buildMultipartFileBody({
994
+ bytes: multipartBytes,
995
+ mime: "application/octet-stream",
996
+ filename: "large.bin",
997
+ });
998
+ return {
999
+ __benchDetails: {
1000
+ bytes: multipart.contentLength,
1001
+ },
1002
+ };
1003
+ }
1004
+
1005
+ async function runAppPageTokensLarge() {
1006
+ mod.resetGeminiUploadCachesForTest();
1007
+ const stats = installFetchResponse(appPageTokensHtml);
1008
+ try {
1009
+ const tokens = await mod.getPageTokens(CFG);
1010
+ return {
1011
+ __benchDetails: {
1012
+ htmlBytes: stats.bytes,
1013
+ pulls: stats.pulls,
1014
+ canceled: stats.canceled,
1015
+ ok: tokens.push_id === "push-bench" && tokens.at === "at-bench" ? 1 : 0,
1016
+ },
1017
+ };
1018
+ } finally {
1019
+ stats.restore();
1020
+ }
1021
+ }
1022
+
1023
+ async function runAppBuildLabelLarge() {
1024
+ const stats = installFetchResponse(appBuildLabelHtml);
1025
+ try {
1026
+ const label = await mod.getFreshGeminiBuildLabel(CFG);
1027
+ return {
1028
+ __benchDetails: {
1029
+ htmlBytes: stats.bytes,
1030
+ pulls: stats.pulls,
1031
+ canceled: stats.canceled,
1032
+ ok: label === "bench-bl" ? 1 : 0,
1033
+ },
1034
+ };
1035
+ } finally {
1036
+ stats.restore();
1037
+ }
1038
+ }
1039
+
1040
+ function makeAppHtml(totalBytes, tokenBlock) {
1041
+ const prefix = `<!doctype html><html><head>${tokenBlock}</head><body>`;
1042
+ const suffix = "</body></html>";
1043
+ const fillerUnit =
1044
+ "app bootstrap payload: boq_assistant placeholder config data;\n";
1045
+ let filler = "";
1046
+ const target = Math.max(0, totalBytes - prefix.length - suffix.length);
1047
+ while (filler.length < target) filler += fillerUnit;
1048
+ return prefix + filler.slice(0, target) + suffix;
1049
+ }
1050
+
1051
+ function installFetchResponse(text) {
1052
+ const originalFetch = globalThis.fetch;
1053
+ const encoded = new TextEncoder().encode(text);
1054
+ const stats = {
1055
+ bytes: encoded.length,
1056
+ pulls: 0,
1057
+ canceled: 0,
1058
+ restore() {
1059
+ globalThis.fetch = originalFetch;
1060
+ },
1061
+ };
1062
+ globalThis.fetch = async () =>
1063
+ new Response(
1064
+ new ReadableStream({
1065
+ pull(controller) {
1066
+ const start = stats.pulls * APP_HTML_CHUNK_BYTES;
1067
+ if (start >= encoded.length) {
1068
+ controller.close();
1069
+ return;
1070
+ }
1071
+ stats.pulls += 1;
1072
+ controller.enqueue(
1073
+ encoded.subarray(start, start + APP_HTML_CHUNK_BYTES),
1074
+ );
1075
+ },
1076
+ cancel() {
1077
+ stats.canceled += 1;
1078
+ },
1079
+ }),
1080
+ );
1081
+ return stats;
1082
+ }
1083
+
1084
+ function installFetchChunks(chunks) {
1085
+ const originalFetch = globalThis.fetch;
1086
+ const stats = {
1087
+ chunks: chunks.length,
1088
+ restore() {
1089
+ globalThis.fetch = originalFetch;
1090
+ },
1091
+ };
1092
+ globalThis.fetch = async () =>
1093
+ new Response(
1094
+ new ReadableStream({
1095
+ start(controller) {
1096
+ for (const chunk of chunks) controller.enqueue(chunk);
1097
+ controller.close();
1098
+ },
1099
+ }),
1100
+ { status: 200 },
1101
+ );
1102
+ return stats;
1103
+ }
1104
+
1105
+ function runStructuredJsonUnclosed() {
1106
+ const candidate = mod.extractFirstJsonDocument(structuredJsonNoise);
1107
+ return {
1108
+ __benchDetails: {
1109
+ bytes: structuredJsonNoise.length,
1110
+ found: candidate ? 1 : 0,
1111
+ },
1112
+ };
1113
+ }
1114
+
1115
+ function runRandHex32() {
1116
+ const value = mod.randHex(32);
1117
+ return {
1118
+ __benchDetails: {
1119
+ chars: value.length,
1120
+ },
1121
+ };
1122
+ }
1123
+
1124
+ function runMarkdownRestoreMany() {
1125
+ const restored = markdownRestoreMasked.restore(markdownRestoreMasked.text);
1126
+ return {
1127
+ __benchDetails: {
1128
+ chars: restored.length,
1129
+ placeholders: markdownRestorePlaceholderCount,
1130
+ },
1131
+ };
1132
+ }
1133
+
1134
+ function makeMarkdownProtectedText(count) {
1135
+ const parts = [];
1136
+ for (let i = 0; i < count; i++) {
1137
+ parts.push(`plain ${i} \`<tool_calls>${i}</tool_calls>\` tail`);
1138
+ }
1139
+ return parts.join("\n");
1140
+ }
1141
+
1142
+ function countOccurrences(text, needle) {
1143
+ let count = 0;
1144
+ let index = String(text || "").indexOf(needle);
1145
+ while (index >= 0) {
1146
+ count += 1;
1147
+ index = String(text || "").indexOf(needle, index + needle.length);
1148
+ }
1149
+ return count;
1150
+ }
scripts/build.mjs ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import esbuild from "esbuild";
2
+ import { mkdir, rm } from "node:fs/promises";
3
+
4
+ const coverageBuild = /^(1|true|yes|on)$/i.test(process.env.COVERAGE || "");
5
+ const includeTestBundle =
6
+ process.argv.includes("--test-bundle") ||
7
+ /^(1|true|yes|on)$/i.test(process.env.BUILD_TEST_BUNDLE || "");
8
+ const outDir =
9
+ process.env.BUILD_DIR || (coverageBuild ? "dist-coverage" : "dist");
10
+
11
+ if (coverageBuild) {
12
+ await rm(outDir, { recursive: true, force: true });
13
+ }
14
+
15
+ await mkdir(outDir, { recursive: true });
16
+
17
+ if (!coverageBuild) {
18
+ await Promise.all([
19
+ rm(`${outDir}/worker.js.map`, { force: true }),
20
+ rm(`${outDir}/worker.test.js`, { force: true }),
21
+ rm(`${outDir}/worker.test.js.map`, { force: true }),
22
+ ]);
23
+ }
24
+
25
+ const common = {
26
+ bundle: true,
27
+ format: "esm",
28
+ target: "es2025",
29
+ platform: "browser",
30
+ sourcemap: coverageBuild ? "linked" : false,
31
+ sourcesContent: coverageBuild,
32
+ legalComments: "none",
33
+ external: ["cloudflare:sockets"],
34
+ logLevel: "info",
35
+ };
36
+
37
+ await esbuild.build({
38
+ ...common,
39
+ entryPoints: ["src/index.ts"],
40
+ outfile: `${outDir}/worker.js`,
41
+ });
42
+
43
+ if (includeTestBundle || coverageBuild) {
44
+ await esbuild.build({
45
+ ...common,
46
+ entryPoints: ["src/test-index.ts"],
47
+ outfile: `${outDir}/worker.test.js`,
48
+ });
49
+ }
scripts/check-architecture.mjs ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join, normalize, relative, resolve } from "node:path";
4
+ import { globSync } from "node:fs";
5
+ import { errorLine, outputLine } from "./io.mjs";
6
+
7
+ const root = process.cwd();
8
+ const rules = [
9
+ {
10
+ label: "attachment modules must stay provider-neutral",
11
+ files: "src/attachments/**/*.{ts,tsx}",
12
+ disallowed: ["../"],
13
+ allowed: ["../shared"],
14
+ },
15
+ {
16
+ label: "shared modules must stay leaf-level",
17
+ files: "src/shared/**/*.ts",
18
+ disallowed: [
19
+ "../gemini/",
20
+ "../http/",
21
+ "../promptcompat/",
22
+ "../toolcall/",
23
+ "../toolstream/",
24
+ "./gemini/",
25
+ "./http/",
26
+ "./promptcompat/",
27
+ "./toolcall/",
28
+ "./toolstream/",
29
+ ],
30
+ },
31
+ {
32
+ label: "gemini client must not depend on prompt compatibility",
33
+ files: "src/gemini/client/**/*.ts",
34
+ disallowed: ["../../promptcompat/", "../promptcompat/"],
35
+ },
36
+ {
37
+ label: "prompt compatibility must not depend on HTTP adapters",
38
+ files: "src/promptcompat/**/*.ts",
39
+ disallowed: ["../http/", "../../http/"],
40
+ },
41
+ {
42
+ label: "completion modules must not depend on HTTP adapters",
43
+ files: "src/completion/**/*.ts",
44
+ disallowed: ["../http/", "../../http/"],
45
+ },
46
+ {
47
+ label:
48
+ "completion modules must depend on provider ports instead of Gemini implementation packages",
49
+ files: "src/completion/**/*.ts",
50
+ disallowed: ["../gemini/", "../../gemini/"],
51
+ },
52
+ {
53
+ label:
54
+ "completion modules must import prompt compatibility owner modules instead of the compatibility barrel",
55
+ files: "src/completion/**/*.ts",
56
+ disallowed: [
57
+ "../promptcompat",
58
+ "../promptcompat/",
59
+ "../../promptcompat",
60
+ "../../promptcompat/",
61
+ ],
62
+ allowed: [
63
+ "../promptcompat/file-refs",
64
+ "../promptcompat/google",
65
+ "../promptcompat/history",
66
+ "../promptcompat/messages",
67
+ "../promptcompat/prompt-build",
68
+ "../promptcompat/responses-input",
69
+ "../../promptcompat/file-refs",
70
+ "../../promptcompat/google",
71
+ "../../promptcompat/history",
72
+ "../../promptcompat/messages",
73
+ "../../promptcompat/prompt-build",
74
+ "../../promptcompat/responses-input",
75
+ ],
76
+ },
77
+ {
78
+ label: "HTTP adapters must not call Gemini client directly",
79
+ files: "src/http/**/*.ts",
80
+ disallowed: [
81
+ "../gemini/client",
82
+ "../gemini/client/",
83
+ "../../gemini/client",
84
+ "../../gemini/client/",
85
+ ],
86
+ },
87
+ {
88
+ label:
89
+ "Gemini implementation must only depend on completion ports through its provider adapter",
90
+ files: "src/gemini/**/*.ts",
91
+ disallowed: [
92
+ "../completion",
93
+ "../completion/",
94
+ "../../completion",
95
+ "../../completion/",
96
+ ],
97
+ allowed: ["../completion/ports", "../../completion/ports"],
98
+ },
99
+ {
100
+ label:
101
+ "HTTP protocol adapters must import core helpers directly instead of the HTTP barrel",
102
+ files: "src/http/{openai,google}/**/*.ts",
103
+ disallowed: ["../index", "../index.ts", "../../http", "../../http/"],
104
+ },
105
+ {
106
+ label: "HTTP adapters must not consume tool stream state directly",
107
+ files: "src/http/**/*.ts",
108
+ disallowed: [
109
+ "../toolstream",
110
+ "../toolstream/",
111
+ "../../toolstream",
112
+ "../../toolstream/",
113
+ ],
114
+ },
115
+ {
116
+ label: "HTTP adapter barrels must not re-export lower-layer internals",
117
+ files: "src/http/**/index.ts",
118
+ disallowed: [
119
+ "../../completion",
120
+ "../../completion/",
121
+ "../../promptcompat",
122
+ "../../promptcompat/",
123
+ "../../toolcall",
124
+ "../../toolcall/",
125
+ "../../gemini",
126
+ "../../gemini/",
127
+ ],
128
+ },
129
+ {
130
+ label: "prompt compatibility must not perform Gemini uploads",
131
+ files: "src/promptcompat/**/*.ts",
132
+ disallowed: [
133
+ "../gemini/uploads",
134
+ "../gemini/uploads/",
135
+ "../../gemini/uploads",
136
+ "../../gemini/uploads/",
137
+ ],
138
+ },
139
+ {
140
+ label:
141
+ "prompt compatibility internals must not depend on completion modules",
142
+ files: "src/promptcompat/**/*.ts",
143
+ disallowed: [
144
+ "../completion",
145
+ "../completion/",
146
+ "../../completion",
147
+ "../../completion/",
148
+ ],
149
+ },
150
+ {
151
+ label: "google HTTP adapter must not depend on openai HTTP adapter",
152
+ files: "src/http/google/**/*.ts",
153
+ disallowed: ["../openai/", "../../http/openai/"],
154
+ },
155
+ {
156
+ label: "openai HTTP adapter must not depend on google HTTP adapter",
157
+ files: "src/http/openai/**/*.ts",
158
+ disallowed: ["../google/", "../../http/google/"],
159
+ },
160
+ {
161
+ label: "toolcall must not depend on prompt compatibility",
162
+ files: "src/toolcall/**/*.ts",
163
+ disallowed: ["../promptcompat/", "../../promptcompat/"],
164
+ },
165
+ {
166
+ label: "toolcall must not depend on HTTP adapters or stream state",
167
+ files: "src/toolcall/**/*.ts",
168
+ disallowed: [
169
+ "../http/",
170
+ "../../http/",
171
+ "../toolstream/",
172
+ "../../toolstream/",
173
+ ],
174
+ },
175
+ {
176
+ label: "toolcall must not depend on Gemini upload modules",
177
+ files: "src/toolcall/**/*.ts",
178
+ disallowed: [
179
+ "../gemini/uploads",
180
+ "../gemini/uploads/",
181
+ "../../gemini/uploads",
182
+ "../../gemini/uploads/",
183
+ ],
184
+ },
185
+ {
186
+ label:
187
+ "implementation modules must import toolcall owner modules instead of the compatibility barrel",
188
+ files: "src/{completion,promptcompat,toolstream,http}/**/*.ts",
189
+ disallowedExact: [
190
+ "../toolcall",
191
+ "../toolcall/index",
192
+ "../toolcall/index.ts",
193
+ "../../toolcall",
194
+ "../../toolcall/index",
195
+ "../../toolcall/index.ts",
196
+ ],
197
+ },
198
+ {
199
+ label:
200
+ "implementation modules must import attachment media owner modules instead of the shared media compatibility shim",
201
+ files:
202
+ "src/{completion,promptcompat,toolcall,toolstream,http,gemini}/**/*.ts",
203
+ disallowed: ["../shared/media", "../../shared/media"],
204
+ },
205
+ ];
206
+
207
+ const importPattern =
208
+ /(?:import|export)\s+(?:[^"']*?\s+from\s+)?["']([^"']+)["']/g;
209
+ const violations = [];
210
+
211
+ for (const rule of rules) {
212
+ for (const file of globSync(rule.files, { cwd: root })) {
213
+ if (rule.exceptFiles?.includes(normalizeSourcePath(file))) continue;
214
+ const text = await readFile(resolve(root, file), "utf8");
215
+ for (const match of text.matchAll(importPattern)) {
216
+ const specifier = match[1];
217
+ if (
218
+ rule.allowed?.some(
219
+ (prefix) =>
220
+ specifier === prefix || specifier.startsWith(`${prefix}/`),
221
+ )
222
+ )
223
+ continue;
224
+ if (rule.disallowedExact?.includes(specifier)) {
225
+ violations.push(
226
+ `${normalizeSourcePath(relative(root, resolve(root, file)))}: ${specifier} (${rule.label})`,
227
+ );
228
+ continue;
229
+ }
230
+ if (
231
+ rule.disallowed?.some(
232
+ (prefix) => specifier === prefix || specifier.startsWith(prefix),
233
+ )
234
+ ) {
235
+ violations.push(
236
+ `${normalizeSourcePath(relative(root, resolve(root, file)))}: ${specifier} (${rule.label})`,
237
+ );
238
+ }
239
+ }
240
+ }
241
+ }
242
+
243
+ const sourceFiles = globSync("src/**/*.{ts,tsx}", { cwd: root }).map(
244
+ normalizeSourcePath,
245
+ );
246
+ const sourceFileSet = new Set(sourceFiles);
247
+ const importGraph = new Map();
248
+
249
+ for (const file of sourceFiles) {
250
+ const text = await readFile(resolve(root, file), "utf8");
251
+ const deps = [];
252
+ for (const match of text.matchAll(importPattern)) {
253
+ const specifier = match[1];
254
+ if (!specifier.startsWith(".")) continue;
255
+ const dep = resolveSourceImport(file, specifier);
256
+ if (dep && sourceFileSet.has(dep)) deps.push(dep);
257
+ }
258
+ importGraph.set(file, deps);
259
+ }
260
+
261
+ for (const cycle of findImportCycles(importGraph)) {
262
+ violations.push(
263
+ `${cycle.join(" -> ")} (source modules must not form import cycles)`,
264
+ );
265
+ }
266
+
267
+ const packageGraph = buildPackageGraph(sourceFiles, sourceFileSet);
268
+ for (const cycle of findImportCycles(packageGraph)) {
269
+ violations.push(
270
+ `${cycle.join(" -> ")} (source directories must not form dependency cycles)`,
271
+ );
272
+ }
273
+
274
+ if (violations.length) {
275
+ errorLine("Architecture check failed:");
276
+ for (const violation of violations) errorLine(`- ${violation}`);
277
+ process.exit(1);
278
+ }
279
+
280
+ outputLine("Architecture check passed");
281
+
282
+ function resolveSourceImport(fromFile, specifier) {
283
+ const base = normalizeSourcePath(join(dirname(fromFile), specifier));
284
+ const candidates = [
285
+ base,
286
+ `${base}.ts`,
287
+ `${base}.tsx`,
288
+ normalizeSourcePath(join(base, "index.ts")),
289
+ normalizeSourcePath(join(base, "index.tsx")),
290
+ ];
291
+ for (const candidate of candidates) {
292
+ const absolute = resolve(root, candidate);
293
+ if (existsSync(absolute) && statSync(absolute).isFile())
294
+ return normalizeSourcePath(candidate);
295
+ }
296
+ return null;
297
+ }
298
+
299
+ function findImportCycles(graph) {
300
+ const cycles = [];
301
+ const seen = new Set();
302
+ const active = new Set();
303
+ const stack = [];
304
+ const cycleKeys = new Set();
305
+
306
+ function visit(node) {
307
+ seen.add(node);
308
+ active.add(node);
309
+ stack.push(node);
310
+ for (const dep of graph.get(node) || []) {
311
+ if (!graph.has(dep)) continue;
312
+ if (!seen.has(dep)) {
313
+ visit(dep);
314
+ continue;
315
+ }
316
+ if (!active.has(dep)) continue;
317
+ const start = stack.indexOf(dep);
318
+ const cycle = stack.slice(start).concat(dep);
319
+ const key = cycle.slice(0, -1).sort().join("|");
320
+ if (!cycleKeys.has(key)) {
321
+ cycleKeys.add(key);
322
+ cycles.push(cycle);
323
+ }
324
+ }
325
+ stack.pop();
326
+ active.delete(node);
327
+ }
328
+
329
+ for (const node of graph.keys()) {
330
+ if (!seen.has(node)) visit(node);
331
+ }
332
+ return cycles;
333
+ }
334
+
335
+ function buildPackageGraph(files, fileSet) {
336
+ const graph = new Map();
337
+ const packageOwners = new Set(
338
+ files.map(sourcePackage).filter((owner) => owner && owner !== "generated"),
339
+ );
340
+ for (const owner of packageOwners) graph.set(owner, []);
341
+
342
+ for (const file of files) {
343
+ const fromOwner = sourcePackage(file);
344
+ if (!packageOwners.has(fromOwner)) continue;
345
+ const text = readSourceFileSync(file);
346
+ for (const match of text.matchAll(importPattern)) {
347
+ const specifier = match[1];
348
+ if (!specifier.startsWith(".")) continue;
349
+ const dep = resolveSourceImport(file, specifier);
350
+ if (!dep || !fileSet.has(dep)) continue;
351
+ const toOwner = sourcePackage(dep);
352
+ if (!packageOwners.has(toOwner) || toOwner === fromOwner) continue;
353
+ const deps = graph.get(fromOwner);
354
+ if (deps && !deps.includes(toOwner)) deps.push(toOwner);
355
+ }
356
+ }
357
+
358
+ return graph;
359
+ }
360
+
361
+ function sourcePackage(file) {
362
+ const match = /^src\/([^/]+)\//.exec(file);
363
+ return match?.[1] ? match[1] : "";
364
+ }
365
+
366
+ function readSourceFileSync(file) {
367
+ return readFileSync(resolve(root, file), "utf8");
368
+ }
369
+
370
+ function normalizeSourcePath(file) {
371
+ return normalize(file).replaceAll("\\", "/");
372
+ }
scripts/check-benchmark.mjs ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { readFile } from "node:fs/promises";
2
+ import { errorLine, outputLine } from "./io.mjs";
3
+ import { outputCommand } from "./process.mjs";
4
+
5
+ const DEFAULT_CASE = "stream_sieve_held_tool";
6
+ const DEFAULT_MAX_MEDIAN_MS = 20;
7
+ const DEFAULT_ITERS = "80";
8
+ const DEFAULT_WARMUP = "10";
9
+ const DEFAULT_BUDGETS = Object.freeze({
10
+ stream_sieve_held_tool: 8,
11
+ stream_text_cumulative_deltas: 12,
12
+ socket_chunked_long_split_line: 8,
13
+ structured_unique_items: 4,
14
+ });
15
+
16
+ const outputPath = process.argv[2] || "";
17
+
18
+ try {
19
+ const budgets = benchmarkBudgets(outputPath);
20
+ const output = outputPath
21
+ ? await readFile(outputPath, "utf8")
22
+ : await runBenchmark(Object.keys(budgets));
23
+ const results = parseBenchmarkResults(output);
24
+ for (const [caseName, maxMedianMs] of Object.entries(budgets)) {
25
+ const medianMs = results.get(caseName)?.medianMs ?? null;
26
+ if (medianMs == null) fail(`missing benchmark median for ${caseName}`);
27
+ if (medianMs > maxMedianMs) {
28
+ fail(
29
+ `${caseName} median ${formatMs(medianMs)} exceeds ${formatMs(maxMedianMs)}`,
30
+ );
31
+ }
32
+ outputLine(
33
+ `benchmark gate ok: ${caseName} median ${formatMs(medianMs)} <= ${formatMs(maxMedianMs)}`,
34
+ );
35
+ }
36
+ } catch (err) {
37
+ const message = err instanceof Error ? err.message : String(err);
38
+ fail(message);
39
+ }
40
+
41
+ function benchmarkBudgets(inputPath) {
42
+ const rawBudgets = String(process.env.BENCH_GATE_BUDGETS || "").trim();
43
+ if (rawBudgets) {
44
+ let parsed;
45
+ try {
46
+ parsed = JSON.parse(rawBudgets);
47
+ } catch (_) {
48
+ throw new Error("BENCH_GATE_BUDGETS must be a JSON object");
49
+ }
50
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
51
+ throw new Error("BENCH_GATE_BUDGETS must be a JSON object");
52
+ const out = {};
53
+ for (const [name, value] of Object.entries(parsed)) {
54
+ const budget = positiveNumber(value, 0);
55
+ if (!name.trim() || budget <= 0)
56
+ throw new Error(`invalid benchmark budget for ${name || "<empty>"}`);
57
+ out[name] = budget;
58
+ }
59
+ if (!Object.keys(out).length)
60
+ throw new Error("BENCH_GATE_BUDGETS must not be empty");
61
+ return out;
62
+ }
63
+
64
+ const explicitCase = String(process.env.BENCH_GATE_CASE || "").trim();
65
+ if (explicitCase || inputPath) {
66
+ return {
67
+ [explicitCase || DEFAULT_CASE]: positiveNumber(
68
+ process.env.BENCH_MAX_MEDIAN_MS,
69
+ DEFAULT_MAX_MEDIAN_MS,
70
+ ),
71
+ };
72
+ }
73
+ return { ...DEFAULT_BUDGETS };
74
+ }
75
+
76
+ function runBenchmark(targetCases) {
77
+ return outputCommand(process.execPath, ["scripts/bench.mjs"], {
78
+ env: {
79
+ ...process.env,
80
+ BENCH_CASES: targetCases.join(","),
81
+ BENCH_ITERS: process.env.BENCH_ITERS || DEFAULT_ITERS,
82
+ BENCH_WARMUP: process.env.BENCH_WARMUP || DEFAULT_WARMUP,
83
+ BENCH_JSON: "1",
84
+ },
85
+ });
86
+ }
87
+
88
+ export function parseBenchmarkResults(output) {
89
+ const raw = String(output || "").trim();
90
+ if (raw.startsWith("{")) {
91
+ let parsed;
92
+ try {
93
+ parsed = JSON.parse(raw);
94
+ } catch (_) {
95
+ throw new Error("invalid benchmark JSON output");
96
+ }
97
+ if (!Array.isArray(parsed?.results))
98
+ throw new Error("benchmark JSON output is missing results");
99
+ const out = new Map();
100
+ for (const result of parsed.results) {
101
+ const name = String(result?.name || "").trim();
102
+ const medianMs = result?.medianMs;
103
+ if (name && typeof medianMs === "number" && Number.isFinite(medianMs))
104
+ out.set(name, { medianMs });
105
+ }
106
+ return out;
107
+ }
108
+
109
+ const out = new Map();
110
+ for (const line of raw.split(/\r?\n/)) {
111
+ const name = /^\s*([^\s]+)\s+/.exec(line)?.[1] || "";
112
+ if (!name) continue;
113
+ const medianMs = parseBenchmarkMetric(line, name, "median");
114
+ if (medianMs != null) out.set(name, { medianMs });
115
+ }
116
+ return out;
117
+ }
118
+
119
+ export function parseBenchmarkMetric(output, benchmarkCaseName, metricName) {
120
+ const line = String(output || "")
121
+ .split(/\r?\n/)
122
+ .find((candidate) =>
123
+ candidate.trimStart().startsWith(`${benchmarkCaseName} `),
124
+ );
125
+ if (!line) return null;
126
+ const match = new RegExp(
127
+ `\\b${escapeRegex(metricName)}=([0-9]+(?:\\.[0-9]+)?)(us|ms|s)\\b`,
128
+ ).exec(line);
129
+ if (!match) return null;
130
+ const value = Number(match[1]);
131
+ if (!Number.isFinite(value)) return null;
132
+ switch (match[2]) {
133
+ case "us":
134
+ return value / 1000;
135
+ case "ms":
136
+ return value;
137
+ case "s":
138
+ return value * 1000;
139
+ default:
140
+ return null;
141
+ }
142
+ }
143
+
144
+ function positiveNumber(value, fallback) {
145
+ const n = Number(value);
146
+ return Number.isFinite(n) && n > 0 ? n : fallback;
147
+ }
148
+
149
+ function formatMs(ms) {
150
+ if (ms < 1) return `${(ms * 1000).toFixed(1)}us`;
151
+ return `${ms.toFixed(3)}ms`;
152
+ }
153
+
154
+ function escapeRegex(value) {
155
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
156
+ }
157
+
158
+ function fail(message) {
159
+ errorLine(`Benchmark gate failed: ${message}`);
160
+ process.exit(1);
161
+ }
scripts/check-bundle-size.mjs ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { readFile } from "node:fs/promises";
2
+ import { gzipSync } from "node:zlib";
3
+ import { errorLine, outputLine } from "./io.mjs";
4
+
5
+ const bundlePath = process.argv[2] || "dist/worker.js";
6
+ const defaultLimitBytes = 3 * 1024 * 1024;
7
+ const limitBytes = parseLimit(
8
+ process.env.BUNDLE_GZIP_SIZE_LIMIT_BYTES,
9
+ defaultLimitBytes,
10
+ );
11
+
12
+ try {
13
+ const bundle = await readFile(bundlePath);
14
+ if (bundle.length <= 0) {
15
+ fail(`${bundlePath} is missing or empty`);
16
+ }
17
+ const gzipBytes = gzipSync(bundle, { level: 9 }).length;
18
+ if (gzipBytes > limitBytes) {
19
+ fail(
20
+ `${bundlePath} gzip size is ${formatBytes(gzipBytes)}, limit ${formatBytes(limitBytes)}`,
21
+ );
22
+ }
23
+ outputLine(
24
+ `bundle size ok: ${bundlePath} raw ${formatBytes(bundle.length)}, gzip ${formatBytes(gzipBytes)} <= ${formatBytes(limitBytes)}, headroom ${formatBytes(limitBytes - gzipBytes)}`,
25
+ );
26
+ } catch (error) {
27
+ if (
28
+ error &&
29
+ typeof error === "object" &&
30
+ "code" in error &&
31
+ error.code === "ENOENT"
32
+ ) {
33
+ fail(`${bundlePath} does not exist; run pnpm build first`);
34
+ }
35
+ throw error;
36
+ }
37
+
38
+ function parseLimit(value, fallback) {
39
+ if (value == null || value === "") return fallback;
40
+ const n = Number(value);
41
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback;
42
+ }
43
+
44
+ function formatBytes(bytes) {
45
+ return `${bytes} bytes`;
46
+ }
47
+
48
+ function fail(message) {
49
+ errorLine(`Bundle size gate failed: ${message}`);
50
+ process.exit(1);
51
+ }
scripts/check-coverage.mjs ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { readFile } from "node:fs/promises";
2
+ import { relative } from "node:path";
3
+ import { errorLine, outputLine } from "./io.mjs";
4
+
5
+ const summaryPath = process.argv[2] || "coverage/coverage-summary.json";
6
+
7
+ const sourceGates = [
8
+ ["statements", 69],
9
+ ["branches", 55],
10
+ ["functions", 82],
11
+ ["lines", 75],
12
+ ];
13
+
14
+ const lineGates = [
15
+ ["src/attachments", 88],
16
+ ["src/completion", 92],
17
+ ["src/config", 95],
18
+ ["src/gemini", 88],
19
+ ["src/gemini/completion-provider.ts", 95],
20
+ ["src/gemini/client", 88],
21
+ ["src/gemini/transport", 90],
22
+ ["src/gemini/uploads", 90],
23
+ ["src/http/core", 92],
24
+ ["src/http/google", 92],
25
+ ["src/http/openai", 92],
26
+ ["src/http/stream", 94],
27
+ ["src/models", 95],
28
+ ["src/promptcompat", 94],
29
+ ["src/shared", 85],
30
+ ["src/toolcall", 90],
31
+ ["src/toolstream", 85],
32
+ ];
33
+
34
+ const branchGates = [
35
+ ["src/attachments", 75],
36
+ ["src/gemini/client", 75],
37
+ ["src/gemini/client/parser.ts", 75],
38
+ ["src/gemini/transport", 78],
39
+ ["src/gemini/app-page.ts", 70],
40
+ ["src/gemini/completion-provider.ts", 85],
41
+ ["src/http/google/handlers.ts", 65],
42
+ ["src/http/openai/chat.ts", 65],
43
+ ["src/http/openai", 78],
44
+ ["src/http/openai/responses.ts", 72],
45
+ ["src/http/openai/responses-stream.ts", 72],
46
+ ["src/promptcompat", 78],
47
+ ["src/promptcompat/history.ts", 75],
48
+ ["src/promptcompat/responses-input.ts", 78],
49
+ ["src/shared/tokens.ts", 70],
50
+ ["src/toolcall/markdown.ts", 68],
51
+ ["src/toolcall/structured.ts", 75],
52
+ ["src/toolstream/index.ts", 65],
53
+ ];
54
+
55
+ const summary = JSON.parse(await readFile(summaryPath, "utf8"));
56
+ const cwd = process.cwd();
57
+
58
+ function normalizePath(path) {
59
+ const rel = path.startsWith(cwd) ? relative(cwd, path) : path;
60
+ return rel.split("\\").join("/");
61
+ }
62
+
63
+ function statsForDir(dir, metric) {
64
+ let covered = 0;
65
+ let total = 0;
66
+
67
+ for (const [key, entry] of Object.entries(summary)) {
68
+ if (key === "total") continue;
69
+ const rel = normalizePath(key);
70
+ if (!rel.startsWith(`${dir}/`)) continue;
71
+ if (!entry || typeof entry !== "object" || !entry[metric]) continue;
72
+ const stats = entry[metric];
73
+ covered += Number(stats.covered || 0);
74
+ total += Number(stats.total || 0);
75
+ }
76
+
77
+ return { covered, total, pct: total > 0 ? (covered / total) * 100 : 0 };
78
+ }
79
+
80
+ function statsForPath(path, metric) {
81
+ let covered = 0;
82
+ let total = 0;
83
+ const normalizedPath = path.split("\\").join("/");
84
+
85
+ for (const [key, entry] of Object.entries(summary)) {
86
+ if (key === "total") continue;
87
+ const rel = normalizePath(key);
88
+ if (rel !== normalizedPath) continue;
89
+ if (!entry || typeof entry !== "object" || !entry[metric]) continue;
90
+ const stats = entry[metric];
91
+ covered += Number(stats.covered || 0);
92
+ total += Number(stats.total || 0);
93
+ }
94
+
95
+ return { covered, total, pct: total > 0 ? (covered / total) * 100 : 0 };
96
+ }
97
+
98
+ function statsForTarget(target, metric) {
99
+ if (/\.tsx?$/.test(target)) return statsForPath(target, metric);
100
+ return statsForDir(target, metric);
101
+ }
102
+
103
+ const failures = [];
104
+
105
+ for (const [metric, threshold] of sourceGates) {
106
+ checkGate("src", threshold, metric);
107
+ }
108
+
109
+ for (const [target, threshold] of lineGates) {
110
+ checkGate(target, threshold, "lines");
111
+ }
112
+
113
+ for (const [target, threshold] of branchGates) {
114
+ checkGate(target, threshold, "branches");
115
+ }
116
+
117
+ function checkGate(target, threshold, metric) {
118
+ const stats = statsForTarget(target, metric);
119
+ const pct = Number(stats.pct.toFixed(2));
120
+ const rendered = `${target}: ${pct.toFixed(2)}% ${metric} (${stats.covered}/${stats.total}), required ${threshold.toFixed(2)}%`;
121
+
122
+ if (stats.total === 0) {
123
+ failures.push(`${target}: missing ${metric} coverage data`);
124
+ return;
125
+ }
126
+
127
+ if (pct + 0.001 < threshold) {
128
+ failures.push(rendered);
129
+ return;
130
+ }
131
+
132
+ outputLine(`coverage ok: ${rendered}`);
133
+ }
134
+
135
+ if (failures.length) {
136
+ errorLine("Coverage gate failed:");
137
+ for (const failure of failures) errorLine(`- ${failure}`);
138
+ process.exit(1);
139
+ }
140
+
141
+ outputLine("Coverage gates passed");
scripts/check-release.mjs ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { runPnpm } from "./process.mjs";
2
+
3
+ export const RELEASE_CHECKS = [
4
+ "check:static",
5
+ "check:worker-types",
6
+ "typecheck",
7
+ "check:arch",
8
+ "coverage:ci",
9
+ "smoke",
10
+ "check:bench",
11
+ "check:size",
12
+ ];
13
+
14
+ for (const check of RELEASE_CHECKS) {
15
+ await runPnpm([check]);
16
+ }
scripts/ci-change-risk.mjs ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const DOC_ONLY_ROOT_FILES = new Set(["LICENSE", "README.md", "README.zh.md"]);
2
+
3
+ export function classifyChangedFiles(files) {
4
+ const normalized = files
5
+ .map((file) =>
6
+ String(file || "")
7
+ .replaceAll("\\", "/")
8
+ .trim(),
9
+ )
10
+ .filter(Boolean);
11
+ if (!normalized.length) return "runtime";
12
+ return normalized.every(isDocumentationOnlyPath) ? "docs" : "runtime";
13
+ }
14
+
15
+ function isDocumentationOnlyPath(path) {
16
+ if (DOC_ONLY_ROOT_FILES.has(path)) return true;
17
+ return path.startsWith("docs/");
18
+ }
scripts/classify-ci-changes.mjs ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { classifyChangedFiles } from "./ci-change-risk.mjs";
2
+ import { outputLine } from "./io.mjs";
3
+
4
+ const files = process.env.CI_CHANGED_FILES_JSON
5
+ ? JSON.parse(process.env.CI_CHANGED_FILES_JSON)
6
+ : await readNullSeparatedStdin();
7
+ const risk = classifyChangedFiles(Array.isArray(files) ? files : []);
8
+ outputLine(risk);
9
+ if (process.env.GITHUB_OUTPUT) {
10
+ const { appendFile } = await import("node:fs/promises");
11
+ await appendFile(
12
+ process.env.GITHUB_OUTPUT,
13
+ `risk=${risk}\nruntime=${risk === "runtime"}\n`,
14
+ );
15
+ }
16
+
17
+ async function readNullSeparatedStdin() {
18
+ const chunks = [];
19
+ for await (const chunk of process.stdin) chunks.push(chunk);
20
+ return Buffer.concat(chunks).toString("utf8").split("\0");
21
+ }
scripts/coverage.mjs ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { runCommand, runPnpm } from "./process.mjs";
2
+
3
+ const ci = process.argv.includes("--ci");
4
+ const coverageBuildDir = "dist-coverage";
5
+
6
+ await runPnpm(["build"], {
7
+ env: {
8
+ ...process.env,
9
+ BUILD_DIR: coverageBuildDir,
10
+ BUILD_TEST_BUNDLE: "1",
11
+ COVERAGE: "1",
12
+ },
13
+ });
14
+
15
+ await runPnpm(["exec", "vitest", "run", "--coverage"], {
16
+ env: {
17
+ ...process.env,
18
+ TEST_BUNDLE: `../../${coverageBuildDir}/worker.test.js`,
19
+ BENCH_TEST_BUNDLE: `${coverageBuildDir}/worker.test.js`,
20
+ },
21
+ });
22
+
23
+ if (ci) {
24
+ await runCommand(process.execPath, ["scripts/check-coverage.mjs"]);
25
+ }
scripts/docker-server.mjs ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import http from "node:http";
2
+ import { Readable } from "node:stream";
3
+ import { finished } from "node:stream/promises";
4
+ import { pathToFileURL } from "node:url";
5
+
6
+ const port = Number(process.env.PORT || 52389);
7
+ const host = process.env.HOST || "0.0.0.0";
8
+ const env = { ...process.env };
9
+ let defaultWorkerPromise = null;
10
+
11
+ export function requestHeaders(rawHeaders) {
12
+ const headers = new Headers();
13
+ for (let i = 0; i < rawHeaders.length; i += 2) {
14
+ const name = rawHeaders[i];
15
+ const value = rawHeaders[i + 1];
16
+ if (name && value !== undefined) headers.append(name, value);
17
+ }
18
+ return headers;
19
+ }
20
+
21
+ export function requestUrl(req, fallbackPort = port) {
22
+ const scheme =
23
+ firstForwardedHeaderValue(req.headers["x-forwarded-proto"]) || "http";
24
+ const forwardedHost = firstForwardedHeaderValue(
25
+ req.headers["x-forwarded-host"],
26
+ );
27
+ const authority =
28
+ forwardedHost ||
29
+ firstForwardedHeaderValue(req.headers.host) ||
30
+ `localhost:${fallbackPort}`;
31
+ return `${scheme}://${authority}${req.url || "/"}`;
32
+ }
33
+
34
+ function firstForwardedHeaderValue(value) {
35
+ const raw = Array.isArray(value) ? value[0] : value;
36
+ return String(raw || "")
37
+ .split(",")[0]
38
+ .trim();
39
+ }
40
+
41
+ export function executionContext() {
42
+ const pending = new Set();
43
+ return {
44
+ waitUntil(promise) {
45
+ const p = Promise.resolve(promise).catch((err) => {
46
+ console.error("waitUntil failed:", err);
47
+ });
48
+ pending.add(p);
49
+ p.finally(() => pending.delete(p));
50
+ },
51
+ passThroughOnException() {},
52
+ };
53
+ }
54
+
55
+ export async function handleDockerRequest(req, res, options = {}) {
56
+ const workerImpl = options.worker || (await defaultWorker());
57
+ const requestEnv = options.env || env;
58
+ const fallbackPort = Number(options.port || port);
59
+ const method = req.method || "GET";
60
+ const init = {
61
+ method,
62
+ headers: requestHeaders(req.rawHeaders),
63
+ };
64
+
65
+ if (method !== "GET" && method !== "HEAD") {
66
+ init.body = Readable.toWeb(req);
67
+ init.duplex = "half";
68
+ }
69
+
70
+ const request = new Request(requestUrl(req, fallbackPort), init);
71
+ const response = await workerImpl.fetch(
72
+ request,
73
+ requestEnv,
74
+ executionContext(),
75
+ );
76
+
77
+ res.statusCode = response.status;
78
+ response.headers.forEach((value, key) => {
79
+ res.setHeader(key, value);
80
+ });
81
+
82
+ if (!response.body || method === "HEAD") {
83
+ res.end();
84
+ return;
85
+ }
86
+
87
+ const body = Readable.fromWeb(response.body);
88
+ body.pipe(res);
89
+ await finished(res);
90
+ }
91
+
92
+ async function defaultWorker() {
93
+ if (!defaultWorkerPromise) {
94
+ defaultWorkerPromise = import("../dist/worker.js").then(
95
+ (mod) => mod.default || mod,
96
+ );
97
+ }
98
+ return defaultWorkerPromise;
99
+ }
100
+
101
+ export function createDockerServer(options = {}) {
102
+ return http.createServer((req, res) => {
103
+ handleDockerRequest(req, res, options).catch((err) => {
104
+ console.error("request failed:", err);
105
+ if (!res.headersSent) {
106
+ res.statusCode = 500;
107
+ res.setHeader("content-type", "application/json; charset=utf-8");
108
+ }
109
+ res.end(JSON.stringify({ error: { message: "internal server error" } }));
110
+ });
111
+ });
112
+ }
113
+
114
+ export function startDockerServer(options = {}) {
115
+ const server = createDockerServer(options);
116
+ const listenPort = Number(options.port || port);
117
+ const listenHost = options.host || host;
118
+ server.listen(listenPort, listenHost, () => {
119
+ console.log(`web2gem listening on http://${listenHost}:${listenPort}`);
120
+ });
121
+ return server;
122
+ }
123
+
124
+ if (
125
+ process.argv[1] &&
126
+ import.meta.url === pathToFileURL(process.argv[1]).href
127
+ ) {
128
+ startDockerServer();
129
+ }
scripts/docker-smoke.mjs ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { outputLine } from "./io.mjs";
2
+ import { commandAvailable, outputCommand, runCommand } from "./process.mjs";
3
+
4
+ if (!(await commandAvailable("docker"))) {
5
+ outputLine("Docker smoke skipped: docker executable not found");
6
+ process.exit(0);
7
+ }
8
+
9
+ const image = `web2gem:smoke-${process.pid}`;
10
+ let container = "";
11
+
12
+ try {
13
+ await runCommand("docker", ["build", "-t", image, "."]);
14
+ container = (
15
+ await outputCommand("docker", [
16
+ "run",
17
+ "-d",
18
+ "--rm",
19
+ "-p",
20
+ "127.0.0.1::52389",
21
+ "-e",
22
+ "API_KEYS=smoke-key",
23
+ "-e",
24
+ "CURRENT_INPUT_FILE_ENABLED=false",
25
+ image,
26
+ ])
27
+ ).trim();
28
+
29
+ const port = await mappedPort(container);
30
+ const base = `http://127.0.0.1:${port}`;
31
+ await waitForHealth(base);
32
+
33
+ const health = await fetch(`${base}/`);
34
+ assert(health.status === 200, `health status ${health.status}`);
35
+ const healthBody = await health.json();
36
+ assert(healthBody.status === "ok", "health payload did not report ok");
37
+
38
+ const authFailure = await fetch(`${base}/v1/models`);
39
+ assert(
40
+ authFailure.status === 401,
41
+ `auth failure status ${authFailure.status}`,
42
+ );
43
+
44
+ const models = await fetch(`${base}/v1/models`, {
45
+ headers: { Authorization: "Bearer smoke-key" },
46
+ });
47
+ assert(models.status === 200, `authenticated models status ${models.status}`);
48
+
49
+ const invalidModel = await fetch(`${base}/v1/chat/completions`, {
50
+ method: "POST",
51
+ headers: {
52
+ Authorization: "Bearer smoke-key",
53
+ "Content-Type": "application/json",
54
+ },
55
+ body: JSON.stringify({
56
+ model: "not-a-model",
57
+ messages: [{ role: "user", content: "hello" }],
58
+ }),
59
+ });
60
+ assert(
61
+ invalidModel.status === 400,
62
+ `invalid model status ${invalidModel.status}`,
63
+ );
64
+ const invalidBody = await invalidModel.json();
65
+ assert(
66
+ invalidBody.error && invalidBody.error.code === "model_not_found",
67
+ "invalid model did not return model_not_found",
68
+ );
69
+
70
+ outputLine("Docker smoke check passed");
71
+ } finally {
72
+ if (container) {
73
+ await outputCommand("docker", ["stop", container], { allowFailure: true });
74
+ }
75
+ await outputCommand("docker", ["rmi", image], { allowFailure: true });
76
+ }
77
+
78
+ async function mappedPort(containerId) {
79
+ for (let i = 0; i < 30; i++) {
80
+ const raw = (
81
+ await outputCommand("docker", ["port", containerId, "52389/tcp"], {
82
+ allowFailure: true,
83
+ })
84
+ ).trim();
85
+ const match = /:(\d+)\s*$/.exec(raw);
86
+ if (match) return Number(match[1]);
87
+ await delay(250);
88
+ }
89
+ throw new Error("Docker smoke failed: container port was not mapped");
90
+ }
91
+
92
+ async function waitForHealth(base) {
93
+ let lastError = null;
94
+ for (let i = 0; i < 60; i++) {
95
+ try {
96
+ const resp = await fetch(`${base}/`);
97
+ if (resp.status === 200) return;
98
+ lastError = new Error(`health status ${resp.status}`);
99
+ } catch (err) {
100
+ lastError = err;
101
+ }
102
+ await delay(250);
103
+ }
104
+ throw new Error(
105
+ `Docker smoke failed: health route did not become ready: ${lastError}`,
106
+ );
107
+ }
108
+
109
+ function delay(ms) {
110
+ return new Promise((resolve) => setTimeout(resolve, ms));
111
+ }
112
+
113
+ function assert(ok, message) {
114
+ if (!ok) throw new Error(`Docker smoke failed: ${message}`);
115
+ }
scripts/ensure-test-bundle-fresh.mjs ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { existsSync, globSync, statSync } from "node:fs";
2
+ import { runCommand } from "./process.mjs";
3
+
4
+ const bundlePaths = ["dist/worker.test.js", "dist/worker.js"];
5
+ const sourceGlobs = [
6
+ "src/**/*.ts",
7
+ "scripts/build.mjs",
8
+ "package.json",
9
+ "tsconfig.json",
10
+ ];
11
+
12
+ if (needsBuild()) {
13
+ await runCommand(process.execPath, ["scripts/build.mjs", "--test-bundle"]);
14
+ }
15
+
16
+ function needsBuild() {
17
+ if (bundlePaths.some((path) => !existsSync(path))) return true;
18
+
19
+ const oldestBundleMtime = Math.min(
20
+ ...bundlePaths.map((path) => statSync(path).mtimeMs),
21
+ );
22
+
23
+ for (const pattern of sourceGlobs) {
24
+ for (const path of globSync(pattern)) {
25
+ if (statSync(path).mtimeMs > oldestBundleMtime) return true;
26
+ }
27
+ }
28
+ return false;
29
+ }
scripts/io.mjs ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export function outputLine(...values) {
2
+ writeLine(process.stdout, values);
3
+ }
4
+
5
+ export function errorLine(...values) {
6
+ writeLine(process.stderr, values);
7
+ }
8
+
9
+ function writeLine(stream, values) {
10
+ stream.write(`${values.map(formatValue).join(" ")}\n`);
11
+ }
12
+
13
+ function formatValue(value) {
14
+ if (value instanceof Error) return value.stack || value.message;
15
+ if (typeof value === "string") return value;
16
+ if (value === null || value === undefined) return String(value);
17
+ if (typeof value === "object") {
18
+ try {
19
+ return JSON.stringify(value);
20
+ } catch (_) {
21
+ return String(value);
22
+ }
23
+ }
24
+ return String(value);
25
+ }
scripts/process.mjs ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { spawn } from "node:child_process";
2
+
3
+ export function runPnpm(args, options = {}) {
4
+ const env = options.env || process.env;
5
+ const npmExecPath = env.npm_execpath || process.env.npm_execpath;
6
+ if (npmExecPath) {
7
+ if (/\.(?:c?js|mjs)$/i.test(npmExecPath)) {
8
+ return runCommand(process.execPath, [npmExecPath, ...args], options);
9
+ }
10
+ return runCommand(npmExecPath, args, options);
11
+ }
12
+ return runCommand(
13
+ process.platform === "win32" ? "pnpm.cmd" : "pnpm",
14
+ args,
15
+ options,
16
+ );
17
+ }
18
+
19
+ export function runCommand(command, args, options = {}) {
20
+ return spawnCommand(command, args, {
21
+ ...options,
22
+ stdio: options.stdio || "inherit",
23
+ });
24
+ }
25
+
26
+ export function outputCommand(command, args, options = {}) {
27
+ return new Promise((resolve, reject) => {
28
+ const child = spawn(command, args, {
29
+ cwd: options.cwd || process.cwd(),
30
+ env: options.env || process.env,
31
+ stdio: ["ignore", "pipe", options.allowFailure ? "ignore" : "inherit"],
32
+ });
33
+ let stdout = "";
34
+ child.stdout.setEncoding("utf8");
35
+ child.stdout.on("data", (chunk) => {
36
+ stdout += chunk;
37
+ });
38
+ child.on("error", reject);
39
+ child.on("exit", (code, signal) => {
40
+ if (code === 0 || options.allowFailure) {
41
+ resolve(stdout);
42
+ return;
43
+ }
44
+ reject(commandFailure(command, args, code, signal));
45
+ });
46
+ });
47
+ }
48
+
49
+ export async function commandAvailable(command) {
50
+ try {
51
+ await outputCommand(command, ["--version"], { allowFailure: true });
52
+ return true;
53
+ } catch (error) {
54
+ return !isMissingExecutableError(error);
55
+ }
56
+ }
57
+
58
+ function spawnCommand(command, args, options) {
59
+ return new Promise((resolve, reject) => {
60
+ const child = spawn(command, args, {
61
+ cwd: options.cwd || process.cwd(),
62
+ env: options.env || process.env,
63
+ stdio: options.stdio,
64
+ });
65
+ child.on("error", reject);
66
+ child.on("exit", (code, signal) => {
67
+ if (code === 0 || options.allowFailure) {
68
+ resolve({ code, signal });
69
+ return;
70
+ }
71
+ reject(commandFailure(command, args, code, signal));
72
+ });
73
+ });
74
+ }
75
+
76
+ function commandFailure(command, args, code, signal) {
77
+ const suffix = signal ? `signal ${signal}` : `exit code ${code}`;
78
+ return new Error(`${command} ${args.join(" ")} failed with ${suffix}`);
79
+ }
80
+
81
+ function isMissingExecutableError(error) {
82
+ return (
83
+ error &&
84
+ typeof error === "object" &&
85
+ "code" in error &&
86
+ error.code === "ENOENT"
87
+ );
88
+ }
scripts/smoke.mjs ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const prod = await import("../dist/worker.js");
2
+ const testMod = await import("../dist/worker.test.js");
3
+
4
+ const expectedProductionExports = [
5
+ "MODELS",
6
+ "VERSION",
7
+ "default",
8
+ "generate",
9
+ "generateStream",
10
+ "getConfig",
11
+ "parseToolCalls",
12
+ "resolveModel",
13
+ ];
14
+
15
+ const productionExports = Object.keys(prod).sort();
16
+ const missingProductionExports = expectedProductionExports.filter(
17
+ (name) => !productionExports.includes(name),
18
+ );
19
+ const unexpectedProductionExports = productionExports.filter(
20
+ (name) => !expectedProductionExports.includes(name),
21
+ );
22
+ if (missingProductionExports.length || unexpectedProductionExports.length) {
23
+ const details = [
24
+ missingProductionExports.length
25
+ ? `missing: ${missingProductionExports.join(", ")}`
26
+ : "",
27
+ unexpectedProductionExports.length
28
+ ? `unexpected: ${unexpectedProductionExports.join(", ")}`
29
+ : "",
30
+ ]
31
+ .filter(Boolean)
32
+ .join("; ");
33
+ console.error(
34
+ `Smoke check failed: production bundle exports changed (${details})`,
35
+ );
36
+ process.exit(1);
37
+ }
38
+
39
+ const checks = [
40
+ ["default.fetch", prod.default && typeof prod.default.fetch === "function"],
41
+ ["MODELS", prod.MODELS && typeof prod.MODELS === "object"],
42
+ ["resolveModel", typeof prod.resolveModel === "function"],
43
+ ["getConfig", typeof prod.getConfig === "function"],
44
+ ["parseToolCalls", typeof prod.parseToolCalls === "function"],
45
+ ["test.buildPayload", typeof testMod.buildPayload === "function"],
46
+ [
47
+ "test.buildToolCallInstructions",
48
+ typeof testMod.buildToolCallInstructions === "function",
49
+ ],
50
+ [
51
+ "test.normalizeResponsesInputAsMessages",
52
+ typeof testMod.normalizeResponsesInputAsMessages === "function",
53
+ ],
54
+ ];
55
+
56
+ const failed = checks.filter(([, ok]) => !ok).map(([name]) => name);
57
+ if (failed.length) {
58
+ console.error(`Smoke check failed: ${failed.join(", ")}`);
59
+ process.exit(1);
60
+ }
61
+
62
+ const health = await prod.default.fetch(
63
+ new Request("https://worker.example/"),
64
+ {},
65
+ {},
66
+ );
67
+ if (health.status !== 200) {
68
+ console.error(`Smoke check failed: health status ${health.status}`);
69
+ process.exit(1);
70
+ }
71
+
72
+ const preflight = await prod.default.fetch(
73
+ new Request("https://worker.example/v1/chat/completions", {
74
+ method: "OPTIONS",
75
+ headers: {
76
+ Origin: "https://client.example",
77
+ "Access-Control-Request-Headers":
78
+ "content-type, x-custom, x-ds2-internal-token",
79
+ "Access-Control-Request-Private-Network": "true",
80
+ },
81
+ }),
82
+ {},
83
+ {},
84
+ );
85
+ if (preflight.status !== 204) {
86
+ console.error(
87
+ `Smoke check failed: CORS preflight status ${preflight.status}`,
88
+ );
89
+ process.exit(1);
90
+ }
91
+ if (
92
+ preflight.headers.get("Access-Control-Allow-Origin") !==
93
+ "https://client.example"
94
+ ) {
95
+ console.error("Smoke check failed: CORS origin was not reflected");
96
+ process.exit(1);
97
+ }
98
+ const allowHeaders =
99
+ preflight.headers.get("Access-Control-Allow-Headers") || "";
100
+ if (
101
+ !allowHeaders.includes("x-custom") ||
102
+ /x-ds2-internal-token/i.test(allowHeaders)
103
+ ) {
104
+ console.error(
105
+ "Smoke check failed: CORS allow headers filtering is incorrect",
106
+ );
107
+ process.exit(1);
108
+ }
109
+
110
+ const authFailure = await prod.default.fetch(
111
+ new Request("https://worker.example/v1/models"),
112
+ {
113
+ API_KEYS: "secret",
114
+ },
115
+ {},
116
+ );
117
+ if (authFailure.status !== 401) {
118
+ console.error(
119
+ `Smoke check failed: auth failure status ${authFailure.status}`,
120
+ );
121
+ process.exit(1);
122
+ }
123
+
124
+ const googleModel = await prod.default.fetch(
125
+ new Request("https://worker.example/v1beta/models/gemini-3.5-flash"),
126
+ {},
127
+ {},
128
+ );
129
+ if (googleModel.status !== 200) {
130
+ console.error(
131
+ `Smoke check failed: Google model detail status ${googleModel.status}`,
132
+ );
133
+ process.exit(1);
134
+ }
135
+ const googleModelBody = await googleModel.json();
136
+ if (
137
+ googleModelBody.name !== "models/gemini-3.5-flash" ||
138
+ googleModelBody.models
139
+ ) {
140
+ console.error(
141
+ "Smoke check failed: Google model detail did not return a single model",
142
+ );
143
+ process.exit(1);
144
+ }
145
+
146
+ const openAIReject = await prod.default.fetch(
147
+ new Request("https://worker.example/v1/chat/completions", {
148
+ method: "POST",
149
+ headers: { "Content-Type": "application/json" },
150
+ body: JSON.stringify({
151
+ model: "not-a-model",
152
+ messages: [{ role: "user", content: "hello" }],
153
+ }),
154
+ }),
155
+ {
156
+ API_KEYS: "",
157
+ CURRENT_INPUT_FILE_ENABLED: "false",
158
+ },
159
+ {},
160
+ );
161
+ if (openAIReject.status !== 400) {
162
+ console.error(
163
+ `Smoke check failed: OpenAI route status ${openAIReject.status}`,
164
+ );
165
+ process.exit(1);
166
+ }
167
+ const openAIRejectBody = await openAIReject.json();
168
+ if (openAIRejectBody.error?.code !== "model_not_found") {
169
+ console.error(
170
+ "Smoke check failed: OpenAI route did not return model_not_found",
171
+ );
172
+ process.exit(1);
173
+ }
174
+
175
+ const googleReject = await prod.default.fetch(
176
+ new Request(
177
+ "https://worker.example/v1beta/models/gemini-3.5-flash:generateContent",
178
+ {
179
+ method: "POST",
180
+ headers: { "Content-Type": "application/json" },
181
+ body: JSON.stringify({
182
+ contents: [{ role: "user", parts: [{ text: "call a tool" }] }],
183
+ toolConfig: { functionCallingConfig: { mode: "ANY" } },
184
+ }),
185
+ },
186
+ ),
187
+ {
188
+ API_KEYS: "",
189
+ CURRENT_INPUT_FILE_ENABLED: "false",
190
+ },
191
+ {},
192
+ );
193
+ if (googleReject.status !== 400) {
194
+ console.error(
195
+ `Smoke check failed: Google route status ${googleReject.status}`,
196
+ );
197
+ process.exit(1);
198
+ }
199
+ const googleRejectBody = await googleReject.json();
200
+ if (googleRejectBody.error?.code !== "invalid_tool_choice") {
201
+ console.error(
202
+ "Smoke check failed: Google route did not return invalid_tool_choice",
203
+ );
204
+ process.exit(1);
205
+ }
206
+
207
+ const toolInstructions = testMod.buildToolCallInstructions(["Read"]);
208
+ if (!toolInstructions.includes("Read-tool cache guard")) {
209
+ console.error(
210
+ "Smoke check failed: buildToolCallInstructions did not render read-tool guard",
211
+ );
212
+ process.exit(1);
213
+ }
214
+
215
+ const [, toolCalls] = prod.parseToolCalls(
216
+ '<|DSML|tool_calls><|DSML|invoke name="Read"><|DSML|parameter name="file_path"><![CDATA[README.md]]></|DSML|parameter></|DSML|invoke></|DSML|tool_calls>',
217
+ );
218
+ if (!toolCalls.length || toolCalls[0].function.name !== "Read") {
219
+ console.error(
220
+ "Smoke check failed: parseToolCalls did not parse DSML tool call",
221
+ );
222
+ process.exit(1);
223
+ }
224
+
225
+ console.log("Smoke check passed");
scripts/unit.mjs ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import { runCommand, runPnpm } from "./process.mjs";
2
+
3
+ const vitestArgs = normalizeVitestArgs(process.argv.slice(2));
4
+
5
+ await runCommand(process.execPath, ["scripts/build.mjs", "--test-bundle"]);
6
+ await runPnpm(["exec", "vitest", "run", ...vitestArgs]);
7
+
8
+ function normalizeVitestArgs(args) {
9
+ return args[0] === "--" ? args.slice(1) : args;
10
+ }
src/app.ts ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { createRuntimeConfig, getConfig, RuntimeConfigError } from "./config";
2
+ import {
3
+ authorized,
4
+ corsHeaders,
5
+ jsonResponse,
6
+ jsonTextResponse,
7
+ openAIErrorResponse,
8
+ withCORS,
9
+ } from "./http";
10
+ import {
11
+ handleChat,
12
+ handleImageEdits,
13
+ handleImageEditsMultipart,
14
+ handleImageGenerations,
15
+ handleResponses,
16
+ } from "./http/openai";
17
+ import { handleGoogleGenerate } from "./http/google/handlers";
18
+ import {
19
+ GOOGLE_MODEL_JSON_BY_ID,
20
+ GOOGLE_MODEL_LIST_JSON,
21
+ HEALTH_JSON,
22
+ NOT_FOUND_JSON,
23
+ OPENAI_MODEL_JSON_BY_ID,
24
+ OPENAI_MODEL_LIST_JSON,
25
+ } from "./http/core/model-routes";
26
+ import { googleJsonError, readRouteJsonPost } from "./http/core/route-json";
27
+ import { createGeminiCompletionProvider } from "./gemini/completion-provider";
28
+ import { elapsedMs, log, logStage, nowMs } from "./shared/logging";
29
+ import { errorLogSummary } from "./shared/errors";
30
+ import { uuid } from "./shared/crypto";
31
+ import type { RuntimeConfig, WorkerEnv } from "./config";
32
+ import type { RouteJsonPostResult } from "./http/core/route-json";
33
+
34
+ const GOOGLE_GENERATE_PATH_RE =
35
+ /^\/v(?:1beta|1)\/models\/[^/?#]+:generateContent$/;
36
+ const GOOGLE_STREAM_GENERATE_PATH_RE =
37
+ /^\/v(?:1beta|1)\/models\/[^/?#]+:streamGenerateContent$/;
38
+
39
+ export type ApplicationExecutionContext = Pick<
40
+ ExecutionContext,
41
+ "waitUntil"
42
+ > & {
43
+ runtimeProfile?: "docker";
44
+ };
45
+
46
+ type ApplicationRequestContext = {
47
+ request: Request;
48
+ env: WorkerEnv;
49
+ cfg: RuntimeConfig;
50
+ url: URL;
51
+ path: string;
52
+ };
53
+
54
+ export async function handleApplicationRequest(
55
+ request: Request,
56
+ env: WorkerEnv,
57
+ executionContext: ApplicationExecutionContext,
58
+ ): Promise<Response> {
59
+ const method = request.method.toUpperCase();
60
+ const url = new URL(request.url);
61
+ const path = url.pathname;
62
+ const requestId = uuid();
63
+ let activeConfig: RuntimeConfig | undefined;
64
+ let requestStartMs = 0;
65
+ const respond = (response: Response) => {
66
+ const corsResponse = withCORS(response, request);
67
+ const completed = withResponseHeader(
68
+ corsResponse,
69
+ "x-request-id",
70
+ requestId,
71
+ );
72
+ if (activeConfig?.log_requests) {
73
+ logStage(activeConfig, "request_complete", {
74
+ requestId,
75
+ method,
76
+ path,
77
+ status: completed.status,
78
+ ms: elapsedMs(requestStartMs),
79
+ });
80
+ }
81
+ return completed;
82
+ };
83
+
84
+ if (method === "OPTIONS") {
85
+ return new Response(null, {
86
+ status: 204,
87
+ headers: corsHeaders(request),
88
+ });
89
+ }
90
+
91
+ let cfg: RuntimeConfig;
92
+ try {
93
+ cfg = createRuntimeConfig(getConfig(env), {
94
+ execution_ctx: executionContext,
95
+ runtime_profile:
96
+ executionContext.runtimeProfile === "docker" ? "docker" : "worker",
97
+ });
98
+ activeConfig = cfg;
99
+ if (cfg.log_requests) requestStartMs = nowMs();
100
+ } catch (error) {
101
+ return respond(invalidRuntimeConfigResponse(error));
102
+ }
103
+
104
+ if (path !== "/" && !authorized(request, url, cfg)) {
105
+ return respond(openAIErrorResponse("invalid api key", 401));
106
+ }
107
+
108
+ const context: ApplicationRequestContext = {
109
+ request,
110
+ env,
111
+ cfg,
112
+ url,
113
+ path,
114
+ };
115
+ try {
116
+ const response = await dispatchApplicationRoute(method, context);
117
+ return respond(response);
118
+ } catch (error) {
119
+ log(cfg, `error: ${errorLogSummary(error)}`);
120
+ return respond(
121
+ jsonResponse(
122
+ {
123
+ error: {
124
+ message: "internal server error",
125
+ code: "internal_server_error",
126
+ },
127
+ },
128
+ 500,
129
+ ),
130
+ );
131
+ }
132
+ }
133
+
134
+ function withResponseHeader(
135
+ response: Response,
136
+ name: string,
137
+ value: string,
138
+ ): Response {
139
+ try {
140
+ response.headers.set(name, value);
141
+ return response;
142
+ } catch (_) {
143
+ const headers = new Headers(response.headers);
144
+ headers.set(name, value);
145
+ return new Response(response.body, {
146
+ status: response.status,
147
+ statusText: response.statusText,
148
+ headers,
149
+ });
150
+ }
151
+ }
152
+
153
+ async function dispatchApplicationRoute(
154
+ method: string,
155
+ context: ApplicationRequestContext,
156
+ ): Promise<Response> {
157
+ if (method === "GET") return handleGetRoute(context.path);
158
+ if (method === "POST") return handlePostRoute(context);
159
+ return jsonTextResponse(NOT_FOUND_JSON, 404);
160
+ }
161
+
162
+ function handleGetRoute(path: string): Response {
163
+ if (path === "/v1/models") return jsonTextResponse(OPENAI_MODEL_LIST_JSON);
164
+ if (path.startsWith("/v1/models/")) {
165
+ const id = decodeURIComponent(path.slice("/v1/models/".length));
166
+ const modelJson = OPENAI_MODEL_JSON_BY_ID.get(id);
167
+ if (!modelJson)
168
+ return openAIErrorResponse(
169
+ `model ${id} is not available`,
170
+ 404,
171
+ "model_not_found",
172
+ );
173
+ return jsonTextResponse(modelJson);
174
+ }
175
+ if (path === "/v1beta/models")
176
+ return jsonTextResponse(GOOGLE_MODEL_LIST_JSON);
177
+ if (path.startsWith("/v1beta/models/")) {
178
+ const id = decodeURIComponent(path.slice("/v1beta/models/".length));
179
+ const modelJson = GOOGLE_MODEL_JSON_BY_ID.get(id);
180
+ if (!modelJson)
181
+ return jsonResponse(
182
+ {
183
+ error: {
184
+ message: `model ${id} is not available`,
185
+ code: "model_not_found",
186
+ },
187
+ },
188
+ 404,
189
+ );
190
+ return jsonTextResponse(modelJson);
191
+ }
192
+ if (path === "/") return jsonTextResponse(HEALTH_JSON);
193
+ return jsonTextResponse(NOT_FOUND_JSON, 404);
194
+ }
195
+
196
+ async function handlePostRoute(
197
+ context: ApplicationRequestContext,
198
+ ): Promise<Response> {
199
+ const { request, cfg, path } = context;
200
+ if (path === "/v1/chat/completions") {
201
+ return handleOpenAIJsonPost(request, cfg, path, (body) =>
202
+ handleChat(body, cfg, createProvider(cfg)),
203
+ );
204
+ }
205
+ if (path === "/v1/responses") {
206
+ return handleOpenAIJsonPost(request, cfg, path, (body) =>
207
+ handleResponses(body, cfg, createProvider(cfg)),
208
+ );
209
+ }
210
+ if (path === "/v1/images/generations") {
211
+ return handleOpenAIJsonPost(request, cfg, path, (body) =>
212
+ handleImageGenerations(body, cfg, createProvider(cfg)),
213
+ );
214
+ }
215
+ if (path === "/v1/images/edits") {
216
+ if (isMultipartFormRequest(request)) {
217
+ return handleImageEditsMultipart(request, cfg, createProvider(cfg));
218
+ }
219
+ return handleOpenAIJsonPost(request, cfg, path, (body) =>
220
+ handleImageEdits(body, cfg, createProvider(cfg)),
221
+ );
222
+ }
223
+ if (GOOGLE_GENERATE_PATH_RE.test(path)) {
224
+ return handleGoogleJsonPost(request, cfg, path, (body) =>
225
+ handleGoogleGenerate(body, cfg, createProvider(cfg), path, false),
226
+ );
227
+ }
228
+ if (GOOGLE_STREAM_GENERATE_PATH_RE.test(path)) {
229
+ return handleGoogleJsonPost(request, cfg, path, (body) =>
230
+ handleGoogleGenerate(body, cfg, createProvider(cfg), path, true),
231
+ );
232
+ }
233
+ return jsonTextResponse(NOT_FOUND_JSON, 404);
234
+ }
235
+
236
+ function createProvider(cfg: RuntimeConfig) {
237
+ return createGeminiCompletionProvider(cfg);
238
+ }
239
+
240
+ async function handleOpenAIJsonPost(
241
+ request: Request,
242
+ cfg: RuntimeConfig,
243
+ path: string,
244
+ handler: (
245
+ body: NonNullable<RouteJsonPostResult["value"]>,
246
+ ) => Promise<Response>,
247
+ ): Promise<Response> {
248
+ const parsed = await readRouteJsonPost(request, cfg, path);
249
+ if (parsed.error !== undefined)
250
+ return openAIErrorResponse(parsed.error, parsed.status || 400, parsed.code);
251
+ return handler(parsed.value);
252
+ }
253
+
254
+ async function handleGoogleJsonPost(
255
+ request: Request,
256
+ cfg: RuntimeConfig,
257
+ path: string,
258
+ handler: (
259
+ body: NonNullable<RouteJsonPostResult["value"]>,
260
+ ) => Promise<Response>,
261
+ ): Promise<Response> {
262
+ const parsed = await readRouteJsonPost(request, cfg, path);
263
+ if (parsed.error !== undefined)
264
+ return jsonResponse(
265
+ googleJsonError(parsed.error, parsed.code),
266
+ parsed.status || 400,
267
+ );
268
+ return handler(parsed.value);
269
+ }
270
+
271
+ function isMultipartFormRequest(request: Request): boolean {
272
+ const contentType = request.headers.get("content-type") || "";
273
+ return (
274
+ contentType.split(";", 1)[0]?.trim().toLowerCase() === "multipart/form-data"
275
+ );
276
+ }
277
+
278
+ function invalidRuntimeConfigResponse(error: unknown): Response {
279
+ if (error instanceof RuntimeConfigError) {
280
+ return jsonResponse(
281
+ {
282
+ error: {
283
+ message: "invalid runtime configuration",
284
+ code: error.code,
285
+ setting: error.setting,
286
+ reason: error.reason,
287
+ },
288
+ },
289
+ 500,
290
+ );
291
+ }
292
+ return jsonResponse(
293
+ {
294
+ error: {
295
+ message: "invalid runtime configuration",
296
+ code: "invalid_runtime_config",
297
+ },
298
+ },
299
+ 500,
300
+ );
301
+ }
src/attachments/base64.ts ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export function base64DecodedByteLength(raw: string): number {
2
+ const compact = String(raw || "").replace(/\s+/g, "");
3
+ if (!compact) return 0;
4
+ return Math.floor((compact.replace(/=+$/, "").length * 3) / 4);
5
+ }
6
+
7
+ export function validateBase64Shape(raw: unknown): string {
8
+ const compact = String(raw || "").replace(/\s+/g, "");
9
+ if (
10
+ compact &&
11
+ (!/^[A-Za-z0-9+/_-]+={0,2}$/.test(compact) ||
12
+ compact.length % 4 === 1 ||
13
+ /=(?=.*[^=])/.test(compact))
14
+ )
15
+ throw new Error("invalid base64 payload");
16
+ return compact;
17
+ }
18
+
19
+ export function base64ToBytes(value: unknown): Uint8Array {
20
+ const source = String(value || "");
21
+ const nativeFromBase64 = (Uint8Array as Uint8ArrayBase64Constructor)
22
+ .fromBase64;
23
+ if (typeof nativeFromBase64 === "function") {
24
+ try {
25
+ return nativeFromBase64(
26
+ source,
27
+ /[-_]/.test(source) ? { alphabet: "base64url" } : undefined,
28
+ );
29
+ } catch (_) {
30
+ throw new Error("invalid base64 payload");
31
+ }
32
+ }
33
+ const compact = validateBase64Shape(source);
34
+ const standard = /[-_]/.test(compact)
35
+ ? compact.replace(/-/g, "+").replace(/_/g, "/")
36
+ : compact;
37
+ const binary = atob(standard.padEnd(Math.ceil(standard.length / 4) * 4, "="));
38
+ const bytes = new Uint8Array(binary.length);
39
+ for (let index = 0; index < binary.length; index++)
40
+ bytes[index] = binary.charCodeAt(index);
41
+ return bytes;
42
+ }
43
+
44
+ export function bytesToBase64(bytes: Uint8Array): string {
45
+ const nativeToBase64 = (bytes as Uint8ArrayBase64).toBase64;
46
+ if (typeof nativeToBase64 === "function") return nativeToBase64.call(bytes);
47
+ let binary = "";
48
+ for (let offset = 0; offset < bytes.byteLength; offset += 0x8000)
49
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
50
+ return btoa(binary);
51
+ }
52
+
53
+ type Uint8ArrayBase64Alphabet = "base64" | "base64url";
54
+ type Uint8ArrayBase64Constructor = typeof Uint8Array & {
55
+ fromBase64?: (
56
+ value: string,
57
+ options?: { alphabet?: Uint8ArrayBase64Alphabet },
58
+ ) => Uint8Array;
59
+ };
60
+ type Uint8ArrayBase64 = Uint8Array & {
61
+ toBase64?: (options?: {
62
+ alphabet?: Uint8ArrayBase64Alphabet;
63
+ omitPadding?: boolean;
64
+ }) => string;
65
+ };
src/attachments/collect-openai.ts ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { isRecord } from "../shared/types";
2
+ import {
3
+ imageFilenameFromObject,
4
+ normalizeUploadFileInput,
5
+ parseImageUrl,
6
+ uploadMimeFromObject,
7
+ type UploadFileInput,
8
+ } from "./input";
9
+ import { createAttachmentPlan } from "./plan";
10
+ import { collectOpenAIRefFileIDs } from "./refs";
11
+ import type { AttachmentPlan } from "./types";
12
+
13
+ const FULL_INLINE_UPLOAD_KEYS = [
14
+ "messages",
15
+ "input",
16
+ "attachments",
17
+ "content",
18
+ "files",
19
+ "items",
20
+ "data",
21
+ "source",
22
+ "file",
23
+ "image_url",
24
+ ];
25
+ const CONTAINER_INLINE_UPLOAD_KEYS = [
26
+ "attachments",
27
+ "files",
28
+ "items",
29
+ "data",
30
+ "source",
31
+ "file",
32
+ "image_url",
33
+ ];
34
+ const FILE_BLOCK_CONTAINER_KEYS = ["attachments", "files", "items"];
35
+
36
+ export function collectOpenAIRequestAttachmentPlan(
37
+ req: unknown,
38
+ ): AttachmentPlan {
39
+ const inline = collectOpenAIInlineUploads(req);
40
+ return createAttachmentPlan({
41
+ existingFileRefs: collectOpenAIRefFileIDs(req),
42
+ images: inline.images,
43
+ files: inline.files,
44
+ });
45
+ }
46
+
47
+ export function collectOpenAIInlineUploadFiles(
48
+ req: unknown,
49
+ ): UploadFileInput[] | null {
50
+ return collectOpenAIInlineUploads(req).files;
51
+ }
52
+
53
+ export function collectOpenAIInlineUploadImages(
54
+ req: unknown,
55
+ ): Array<{ b64: string; mime: string; filename?: string }> | null {
56
+ return collectOpenAIInlineUploads(req).images;
57
+ }
58
+
59
+ function collectOpenAIInlineUploads(req: unknown): {
60
+ files: UploadFileInput[] | null;
61
+ images: Array<{ b64: string; mime: string; filename?: string }> | null;
62
+ } {
63
+ if (!isRecord(req)) return { files: null, images: null };
64
+ const state: InlineUploadState = { files: [], images: [] };
65
+ for (const key of ["attachments", "files"])
66
+ appendOpenAIInlineUploadInputs(state, req[key], "full");
67
+ for (const key of ["messages", "input"])
68
+ appendOpenAIInlineUploadInputs(state, req[key], "container");
69
+ return {
70
+ files: state.files.length ? state.files : null,
71
+ images: state.images.length ? state.images : null,
72
+ };
73
+ }
74
+
75
+ type InlineUploadWalkMode = "full" | "container";
76
+ type InlineUploadState = {
77
+ files: UploadFileInput[];
78
+ images: Array<{ b64: string; mime: string; filename?: string }>;
79
+ };
80
+
81
+ function appendOpenAIInlineUploadInputs(
82
+ state: InlineUploadState,
83
+ raw: unknown,
84
+ mode: InlineUploadWalkMode,
85
+ ): void {
86
+ if (raw == null) return;
87
+ if (Array.isArray(raw)) {
88
+ for (const item of raw) appendOpenAIInlineUploadInputs(state, item, mode);
89
+ return;
90
+ }
91
+ if (!isRecord(raw)) return;
92
+ if (mode === "full") {
93
+ const image = normalizeImageUploadInput(raw);
94
+ if (image) {
95
+ state.images.push(image);
96
+ return;
97
+ }
98
+ const input = normalizeUploadFileInput(raw);
99
+ if (input) {
100
+ state.files.push(input);
101
+ return;
102
+ }
103
+ }
104
+ const keys = inlineUploadNestedKeys(raw, mode);
105
+ for (const key of keys) {
106
+ if (!(key in raw)) continue;
107
+ const nextMode: InlineUploadWalkMode =
108
+ key === "attachments" || key === "files" || key === "file"
109
+ ? "full"
110
+ : mode;
111
+ appendOpenAIInlineUploadInputs(state, raw[key], nextMode);
112
+ }
113
+ }
114
+
115
+ function inlineUploadNestedKeys(
116
+ raw: Record<string, unknown>,
117
+ mode: InlineUploadWalkMode,
118
+ ): readonly string[] {
119
+ if (mode === "full") return FULL_INLINE_UPLOAD_KEYS;
120
+ if (isOpenAIFileBlock(raw)) return FILE_BLOCK_CONTAINER_KEYS;
121
+ return CONTAINER_INLINE_UPLOAD_KEYS;
122
+ }
123
+
124
+ function isOpenAIFileBlock(raw: Record<string, unknown>): boolean {
125
+ const typ = String(raw.type || "")
126
+ .trim()
127
+ .toLowerCase();
128
+ return typ === "input_file" || typ === "file";
129
+ }
130
+
131
+ function normalizeImageUploadInput(
132
+ raw: Record<string, unknown>,
133
+ ): { b64: string; mime: string; filename?: string } | null {
134
+ const typ = String(raw.type || "")
135
+ .trim()
136
+ .toLowerCase();
137
+ if (
138
+ typ !== "image_url" &&
139
+ typ !== "image" &&
140
+ typ !== "input_image" &&
141
+ !("image_url" in raw)
142
+ )
143
+ return null;
144
+ const source = isRecord(raw.source) ? raw.source : null;
145
+ if (source && source.data != null) {
146
+ const out = {
147
+ b64: String(source.data || ""),
148
+ mime: uploadMimeFromObject(raw) || "image/png",
149
+ };
150
+ const filename = imageFilenameFromObject(raw);
151
+ return filename ? { ...out, filename } : out;
152
+ }
153
+ const imageUrl = raw.image_url != null ? raw.image_url : raw.url;
154
+ const parsed = parseImageUrl(
155
+ isRecord(imageUrl) ? imageUrl.url : imageUrl,
156
+ uploadMimeFromObject(raw),
157
+ );
158
+ if (!parsed) return null;
159
+ const filename = imageFilenameFromObject(raw);
160
+ return filename ? { ...parsed, filename } : parsed;
161
+ }
src/attachments/input.ts ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { firstRecord, isRecord, type UnknownRecord } from "../shared/types";
2
+ import { TEXT_ENCODER } from "../shared/encoding";
3
+ import { bytesToBase64 } from "./base64";
4
+ import {
5
+ cleanUploadMime,
6
+ firstNonEmptyString,
7
+ mimeFromFilename,
8
+ sanitizeUploadFilename,
9
+ } from "./mime";
10
+
11
+ export type ParsedUploadUrl = { b64: string; mime: string };
12
+ export type ParsedImageUrl = ParsedUploadUrl;
13
+ export type ParsedDataUrl = { b64: string; mime: string };
14
+ export type UploadFileInput = {
15
+ b64?: unknown;
16
+ mime?: unknown;
17
+ filename?: unknown;
18
+ name?: unknown;
19
+ invalidReason?: string;
20
+ };
21
+
22
+ export function parseDataUrl(url: unknown): ParsedDataUrl | null {
23
+ if (!url || typeof url !== "string") return null;
24
+ const trimmed = url.trim();
25
+ if (!isDataUrl(trimmed)) return null;
26
+ const comma = trimmed.indexOf(",");
27
+ if (comma < 0) return null;
28
+ const header = trimmed.slice(0, comma);
29
+ const payload = trimmed.slice(comma + 1);
30
+ const meta = header.slice(5);
31
+ const mime = cleanUploadMime((meta.split(";")[0] || "").toLowerCase());
32
+ if (/;base64(?:;|$)/i.test(meta)) return { b64: payload, mime };
33
+ try {
34
+ return {
35
+ b64: bytesToBase64(TEXT_ENCODER.encode(decodeURIComponent(payload))),
36
+ mime,
37
+ };
38
+ } catch (_) {
39
+ return null;
40
+ }
41
+ }
42
+
43
+ export function parseUploadUrl(url: unknown): ParsedUploadUrl | null {
44
+ if (!url || typeof url !== "string") return null;
45
+ const data = parseDataUrl(url);
46
+ if (data) return data;
47
+ return null;
48
+ }
49
+
50
+ export function parseImageUrl(
51
+ url: unknown,
52
+ explicitMime?: unknown,
53
+ ): ParsedImageUrl | null {
54
+ const parsed = parseUploadUrl(url);
55
+ if (!parsed) return null;
56
+ return {
57
+ ...parsed,
58
+ mime: firstNonEmptyString(
59
+ cleanUploadMime(explicitMime),
60
+ parsed.mime,
61
+ "image/png",
62
+ ),
63
+ };
64
+ }
65
+
66
+ export function uploadFilenameFromObject(obj: unknown): string {
67
+ if (!isRecord(obj)) return "";
68
+ const record = obj;
69
+ const source = isRecord(record.source) ? record.source : null;
70
+ const imageUrl = isRecord(record.image_url) ? record.image_url : null;
71
+ const inlineData =
72
+ asOptionalRecord(record.inlineData) || asOptionalRecord(record.inline_data);
73
+ const fileData =
74
+ asOptionalRecord(record.fileData) || asOptionalRecord(record.file_data);
75
+ const file = isRecord(record.file) ? record.file : null;
76
+ return firstNonEmptyString(
77
+ ...[
78
+ record.filename,
79
+ record.fileName,
80
+ record.file_name,
81
+ record.name,
82
+ record.displayName,
83
+ record.display_name,
84
+ source &&
85
+ (source.filename ||
86
+ source.fileName ||
87
+ source.file_name ||
88
+ source.name ||
89
+ source.displayName ||
90
+ source.display_name),
91
+ imageUrl &&
92
+ (imageUrl.filename ||
93
+ imageUrl.fileName ||
94
+ imageUrl.file_name ||
95
+ imageUrl.name ||
96
+ imageUrl.displayName ||
97
+ imageUrl.display_name),
98
+ inlineData &&
99
+ (inlineData.filename ||
100
+ inlineData.fileName ||
101
+ inlineData.file_name ||
102
+ inlineData.name ||
103
+ inlineData.displayName ||
104
+ inlineData.display_name),
105
+ fileData &&
106
+ (fileData.filename ||
107
+ fileData.fileName ||
108
+ fileData.file_name ||
109
+ fileData.name ||
110
+ fileData.displayName ||
111
+ fileData.display_name),
112
+ file &&
113
+ (file.filename ||
114
+ file.fileName ||
115
+ file.file_name ||
116
+ file.name ||
117
+ file.displayName ||
118
+ file.display_name),
119
+ ].map(sanitizeUploadFilename),
120
+ );
121
+ }
122
+
123
+ export function imageFilenameFromObject(obj: unknown): string {
124
+ return uploadFilenameFromObject(obj);
125
+ }
126
+
127
+ export function uploadMimeFromObject(obj: unknown): string {
128
+ if (!isRecord(obj)) return "";
129
+ const record = obj;
130
+ const source = isRecord(record.source) ? record.source : null;
131
+ const imageUrl = isRecord(record.image_url) ? record.image_url : null;
132
+ const inlineData =
133
+ asOptionalRecord(record.inlineData) || asOptionalRecord(record.inline_data);
134
+ const fileData =
135
+ asOptionalRecord(record.fileData) || asOptionalRecord(record.file_data);
136
+ const file = isRecord(record.file) ? record.file : null;
137
+ return firstNonEmptyString(
138
+ record.mime,
139
+ record.mime_type,
140
+ record.mimeType,
141
+ record.media_type,
142
+ record.mediaType,
143
+ record.content_type,
144
+ record.contentType,
145
+ source &&
146
+ (source.mime ||
147
+ source.mime_type ||
148
+ source.mimeType ||
149
+ source.media_type ||
150
+ source.mediaType ||
151
+ source.content_type ||
152
+ source.contentType),
153
+ imageUrl &&
154
+ (imageUrl.mime ||
155
+ imageUrl.mime_type ||
156
+ imageUrl.mimeType ||
157
+ imageUrl.content_type ||
158
+ imageUrl.contentType),
159
+ inlineData &&
160
+ (inlineData.mime ||
161
+ inlineData.mime_type ||
162
+ inlineData.mimeType ||
163
+ inlineData.media_type ||
164
+ inlineData.mediaType ||
165
+ inlineData.content_type ||
166
+ inlineData.contentType),
167
+ fileData &&
168
+ (fileData.mime ||
169
+ fileData.mime_type ||
170
+ fileData.mimeType ||
171
+ fileData.media_type ||
172
+ fileData.mediaType ||
173
+ fileData.content_type ||
174
+ fileData.contentType),
175
+ file &&
176
+ (file.mime ||
177
+ file.mime_type ||
178
+ file.mimeType ||
179
+ file.media_type ||
180
+ file.mediaType ||
181
+ file.content_type ||
182
+ file.contentType),
183
+ );
184
+ }
185
+
186
+ export function normalizeUploadFileInput(
187
+ file: unknown,
188
+ ): UploadFileInput | null {
189
+ if (typeof file === "string") {
190
+ const parsed = parseUploadUrl(file);
191
+ if (!parsed) return null;
192
+ return { b64: parsed.b64, mime: parsed.mime || "application/octet-stream" };
193
+ }
194
+ if (!isRecord(file)) return null;
195
+ const source = isRecord(file.source) ? file.source : null;
196
+ const nestedFile = isRecord(file.file) ? file.file : null;
197
+ const fileData = firstRecord(file.fileData, file.file_data);
198
+ const filename = uploadFilenameFromObject(file);
199
+ const explicitMime = uploadMimeFromObject(file);
200
+ const urlValue = firstNonEmptyString(
201
+ file.url,
202
+ file.file_url,
203
+ file.fileUrl,
204
+ source?.url,
205
+ nestedFile && (nestedFile.url || nestedFile.file_url || nestedFile.fileUrl),
206
+ fileData?.url,
207
+ );
208
+ const dataValue = firstNonNil(
209
+ fileData &&
210
+ (fileData.data ??
211
+ fileData.b64 ??
212
+ fileData.base64 ??
213
+ fileData.fileData ??
214
+ fileData.file_data),
215
+ file.file_data,
216
+ file.fileData,
217
+ file.data,
218
+ file.b64,
219
+ file.base64,
220
+ source && (source.data ?? source.b64 ?? source.base64),
221
+ nestedFile && (nestedFile.data ?? nestedFile.b64 ?? nestedFile.base64),
222
+ );
223
+ const parsedUrl = parseUploadUrl(urlValue);
224
+ if (parsedUrl)
225
+ return uploadInputFromParsed(parsedUrl, explicitMime, filename);
226
+ const parsedData = parseUploadUrl(dataValue);
227
+ if (parsedData)
228
+ return uploadInputFromParsed(parsedData, explicitMime, filename);
229
+ if (dataValue != null && typeof dataValue !== "object") {
230
+ const out: UploadFileInput = { b64: dataValue };
231
+ const mime = firstNonEmptyString(explicitMime, mimeFromFilename(filename));
232
+ if (mime) out.mime = mime;
233
+ if (filename) out.filename = filename;
234
+ return out;
235
+ }
236
+ if (
237
+ isExplicitUploadFileInput(file) &&
238
+ !hasExistingUploadFileReference(file) &&
239
+ !(fileData && (fileData.fileUri || fileData.file_uri))
240
+ ) {
241
+ const out: UploadFileInput = {
242
+ invalidReason: "missing generic file upload data",
243
+ };
244
+ const mime = firstNonEmptyString(explicitMime, mimeFromFilename(filename));
245
+ if (mime) out.mime = mime;
246
+ if (filename) out.filename = filename;
247
+ return out;
248
+ }
249
+ return null;
250
+ }
251
+
252
+ export function hasInlineUploadFilePayload(raw: unknown): boolean {
253
+ return !!normalizeUploadFileInput(raw);
254
+ }
255
+
256
+ export function isDataUrl(raw: string): boolean {
257
+ return /^data:/i.test(raw.trim());
258
+ }
259
+
260
+ function uploadInputFromParsed(
261
+ parsed: ParsedUploadUrl,
262
+ explicitMime: string,
263
+ filename: string,
264
+ ): UploadFileInput {
265
+ const out: UploadFileInput = {
266
+ b64: parsed.b64,
267
+ mime:
268
+ firstNonEmptyString(
269
+ explicitMime,
270
+ parsed.mime,
271
+ mimeFromFilename(filename),
272
+ ) || "application/octet-stream",
273
+ };
274
+ if (filename) out.filename = filename;
275
+ return out;
276
+ }
277
+
278
+ function firstNonNil(...values: unknown[]): unknown {
279
+ for (const value of values) {
280
+ if (value !== undefined && value !== null) return value;
281
+ }
282
+ return undefined;
283
+ }
284
+
285
+ function isExplicitUploadFileInput(file: UnknownRecord): boolean {
286
+ const typ = String(file.type || "")
287
+ .trim()
288
+ .toLowerCase();
289
+ return typ === "input_file" || typ === "file";
290
+ }
291
+
292
+ function hasExistingUploadFileReference(file: UnknownRecord): boolean {
293
+ if (file.file_id != null || file.id != null) return true;
294
+ const nestedFile = isRecord(file.file) ? file.file : null;
295
+ return !!(
296
+ nestedFile &&
297
+ (nestedFile.file_id != null || nestedFile.id != null)
298
+ );
299
+ }
300
+
301
+ function asOptionalRecord(value: unknown): UnknownRecord | null {
302
+ return isRecord(value) ? value : null;
303
+ }
src/attachments/materialize.ts ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { ErrorWithMetadata } from "../shared/types";
2
+ import { base64DecodedByteLength, base64ToBytes } from "./base64";
3
+ import {
4
+ chooseUploadMime,
5
+ detectUploadMimeFromBytes,
6
+ firstNonEmptyString,
7
+ genericFilenameFromMime,
8
+ imageFilenameFromMime,
9
+ mimeFromFilename,
10
+ } from "./mime";
11
+ import type { AttachmentCandidate, AttachmentDropReason } from "./types";
12
+
13
+ export type AttachmentLimits = {
14
+ maxFileBytes: number;
15
+ maxImageBytes: number;
16
+ };
17
+
18
+ export type MaterializedAttachment = {
19
+ candidate: AttachmentCandidate;
20
+ bytes: Uint8Array;
21
+ mime: string;
22
+ filename: string;
23
+ };
24
+
25
+ export const DEFAULT_ATTACHMENT_MAX_BYTES = 20 * 1024 * 1024;
26
+
27
+ export async function materializeAttachment(
28
+ candidate: AttachmentCandidate,
29
+ limits: AttachmentLimits,
30
+ ): Promise<MaterializedAttachment> {
31
+ const maxBytes = maxBytesForCandidate(candidate, limits);
32
+ if (candidate.source.type === "bytes") {
33
+ ensureWithinLimit(candidate, candidate.source.bytes.byteLength, maxBytes);
34
+ const mime = mimeForCandidate(candidate, candidate.source.bytes);
35
+ return {
36
+ candidate,
37
+ bytes: candidate.source.bytes,
38
+ mime,
39
+ filename: filenameForCandidate(candidate, mime),
40
+ };
41
+ }
42
+ const compact = String(candidate.source.data || "").replace(/\s+/g, "");
43
+ ensureWithinLimit(candidate, base64DecodedByteLength(compact), maxBytes);
44
+ try {
45
+ const bytes = base64ToBytes(compact);
46
+ ensureWithinLimit(candidate, bytes.byteLength, maxBytes);
47
+ const mime = mimeForCandidate(candidate, bytes);
48
+ return {
49
+ candidate,
50
+ bytes,
51
+ mime,
52
+ filename: filenameForCandidate(candidate, mime),
53
+ };
54
+ } catch (e) {
55
+ throw attachmentMaterializeFailure(
56
+ candidate,
57
+ "invalid_base64",
58
+ "invalid base64 payload",
59
+ 400,
60
+ e,
61
+ );
62
+ }
63
+ }
64
+
65
+ export function joinByteChunks(
66
+ chunks: readonly Uint8Array[],
67
+ total: number,
68
+ ): Uint8Array {
69
+ const out = new Uint8Array(total);
70
+ let offset = 0;
71
+ for (const chunk of chunks) {
72
+ out.set(chunk, offset);
73
+ offset += chunk.byteLength;
74
+ }
75
+ return out;
76
+ }
77
+
78
+ export function attachmentMaterializeFailure(
79
+ candidate: AttachmentCandidate,
80
+ code: AttachmentDropReason,
81
+ message: string,
82
+ status: number,
83
+ cause?: unknown,
84
+ ): ErrorWithMetadata {
85
+ const err: ErrorWithMetadata = new Error(message);
86
+ err.code = code;
87
+ err.status = status;
88
+ (err as ErrorWithMetadata & { attachmentKind?: string }).attachmentKind =
89
+ candidate.kind;
90
+ if (cause !== undefined) err.cause = cause;
91
+ return err;
92
+ }
93
+
94
+ function maxBytesForCandidate(
95
+ candidate: AttachmentCandidate,
96
+ limits: AttachmentLimits,
97
+ ): number {
98
+ if (candidate.kind === "image") return Math.max(0, limits.maxImageBytes);
99
+ return Math.max(0, limits.maxFileBytes);
100
+ }
101
+
102
+ function ensureWithinLimit(
103
+ candidate: AttachmentCandidate,
104
+ bytes: number,
105
+ maxBytes: number,
106
+ ): void {
107
+ if (bytes > maxBytes) {
108
+ throw attachmentMaterializeFailure(
109
+ candidate,
110
+ candidate.kind === "image" ? "image_too_large" : "file_too_large",
111
+ `${candidate.kind} attachment is too large (${bytes} bytes > ${maxBytes} bytes)`,
112
+ 413,
113
+ );
114
+ }
115
+ }
116
+
117
+ function mimeForCandidate(
118
+ candidate: AttachmentCandidate,
119
+ bytes: Uint8Array,
120
+ ): string {
121
+ return chooseUploadMime(
122
+ candidate.mime,
123
+ mimeFromFilename(candidate.filename),
124
+ detectUploadMimeFromBytes(bytes),
125
+ );
126
+ }
127
+
128
+ function filenameForCandidate(
129
+ candidate: AttachmentCandidate,
130
+ mimeHint: unknown,
131
+ ): string {
132
+ const explicit = firstNonEmptyString(candidate.filename);
133
+ if (explicit) return explicit;
134
+ if (candidate.kind === "image")
135
+ return imageFilenameFromMime(candidate.mime || mimeHint || "image/png", 1);
136
+ return genericFilenameFromMime(
137
+ candidate.mime || mimeHint || "application/octet-stream",
138
+ 1,
139
+ );
140
+ }
src/attachments/media.ts ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ export * from "./base64";
2
+ export * from "./input";
3
+ export * from "./mime";
src/attachments/mime.ts ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { TEXT_DECODER, UTF8_FATAL_DECODER } from "../shared/encoding";
2
+
3
+ const MIME_MAX_LENGTH = 180;
4
+
5
+ export function firstNonEmptyString(...values: unknown[]): string {
6
+ for (const value of values) {
7
+ if (typeof value === "string" && value.trim()) return value.trim();
8
+ }
9
+ return "";
10
+ }
11
+
12
+ export function sanitizeUploadFilename(name: unknown): string {
13
+ if (typeof name !== "string" && typeof name !== "number") return "";
14
+ let safeName = String(name || "").trim();
15
+ if (!safeName) return "";
16
+ safeName = safeName
17
+ .replace(/\0/g, "")
18
+ .replace(/[\r\n\t]/g, " ")
19
+ .trim();
20
+ safeName = safeName.split(/[\\/]/).filter(Boolean).pop() || "";
21
+ safeName = safeName.replace(/[\u0000-\u001f\u007f]/g, "").trim();
22
+ if (!safeName || safeName === "." || safeName === "..") return "";
23
+ return safeName.slice(0, 180);
24
+ }
25
+
26
+ export function filenameFromUrl(url: unknown): string {
27
+ if (!url || typeof url !== "string") return "";
28
+ try {
29
+ const parsed = new URL(url);
30
+ return sanitizeUploadFilename(
31
+ decodeURIComponent(
32
+ parsed.pathname.split("/").filter(Boolean).pop() || "",
33
+ ),
34
+ );
35
+ } catch (_) {
36
+ return sanitizeUploadFilename(String(url).split(/[?#]/)[0]);
37
+ }
38
+ }
39
+
40
+ export function mimeFromFilename(name: unknown): string {
41
+ const safeName = sanitizeUploadFilename(name).toLowerCase();
42
+ const extension = safeName.includes(".")
43
+ ? safeName.split(".").pop() || ""
44
+ : "";
45
+ const types: Record<string, string> = {
46
+ txt: "text/plain",
47
+ log: "text/plain",
48
+ md: "text/markdown",
49
+ markdown: "text/markdown",
50
+ csv: "text/csv",
51
+ json: "application/json",
52
+ jsonl: "application/x-ndjson",
53
+ js: "text/javascript",
54
+ mjs: "text/javascript",
55
+ cjs: "text/javascript",
56
+ ts: "text/typescript",
57
+ tsx: "text/typescript",
58
+ py: "text/x-python",
59
+ html: "text/html",
60
+ htm: "text/html",
61
+ css: "text/css",
62
+ xml: "application/xml",
63
+ pdf: "application/pdf",
64
+ };
65
+ return types[extension] || "";
66
+ }
67
+
68
+ export function genericFilenameFromMime(mime: unknown, index: number): string {
69
+ const base = `file-${Math.max(1, Math.floor(index) || 1)}`;
70
+ const type = normalizeMimeType(mime);
71
+ const extensions: Record<string, string> = {
72
+ "text/markdown": "md",
73
+ "text/csv": "csv",
74
+ "application/json": "json",
75
+ "application/x-ndjson": "jsonl",
76
+ "text/javascript": "js",
77
+ "application/javascript": "js",
78
+ "text/typescript": "ts",
79
+ "text/x-python": "py",
80
+ "text/html": "html",
81
+ "text/css": "css",
82
+ "application/xml": "xml",
83
+ "text/xml": "xml",
84
+ "application/pdf": "pdf",
85
+ "text/plain": "txt",
86
+ };
87
+ return `${base}.${extensions[type] || (type.startsWith("text/") ? "txt" : "bin")}`;
88
+ }
89
+
90
+ export function imageFilenameFromMime(mime: unknown, index: number): string {
91
+ const base = `image${index > 1 ? `-${index}` : ""}`;
92
+ const extensions: Record<string, string> = {
93
+ "image/jpeg": "jpg",
94
+ "image/jpg": "jpg",
95
+ "image/webp": "webp",
96
+ "image/gif": "gif",
97
+ "image/bmp": "bmp",
98
+ "image/heic": "heic",
99
+ "image/heif": "heif",
100
+ };
101
+ return `${base}.${extensions[normalizeMimeType(mime)] || "png"}`;
102
+ }
103
+
104
+ export function cleanUploadMime(value: unknown): string {
105
+ if (typeof value !== "string" && typeof value !== "number") return "";
106
+ return String(value || "")
107
+ .replace(/[\r\n]/g, "")
108
+ .trim()
109
+ .slice(0, MIME_MAX_LENGTH);
110
+ }
111
+
112
+ export function chooseUploadMime(...values: unknown[]): string {
113
+ for (const value of values) {
114
+ const mime = cleanUploadMime(value);
115
+ if (mime) return mime;
116
+ }
117
+ return "application/octet-stream";
118
+ }
119
+
120
+ export function normalizeMimeType(value: unknown): string {
121
+ return (String(value || "").split(";")[0] || "").trim().toLowerCase();
122
+ }
123
+
124
+ export function detectUploadMimeFromBytes(bytes: Uint8Array): string {
125
+ if (!bytes?.byteLength) return "";
126
+ if (startsWithBytes(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
127
+ return "image/png";
128
+ if (startsWithBytes(bytes, [0xff, 0xd8, 0xff])) return "image/jpeg";
129
+ if (startsWithAscii(bytes, "GIF87a") || startsWithAscii(bytes, "GIF89a"))
130
+ return "image/gif";
131
+ if (startsWithAscii(bytes, "RIFF") && asciiAt(bytes, 8, "WEBP"))
132
+ return "image/webp";
133
+ if (startsWithAscii(bytes, "%PDF-")) return "application/pdf";
134
+ if (startsWithBytes(bytes, [0x50, 0x4b, 0x03, 0x04]))
135
+ return "application/zip";
136
+ if (!looksLikeUtf8Text(bytes)) return "";
137
+ const text = TEXT_DECODER.decode(
138
+ bytes.slice(0, Math.min(bytes.byteLength, 4096)),
139
+ ).trimStart();
140
+ return text.startsWith("{") || text.startsWith("[")
141
+ ? "application/json"
142
+ : "text/plain";
143
+ }
144
+
145
+ function startsWithBytes(
146
+ bytes: Uint8Array,
147
+ prefix: readonly number[],
148
+ ): boolean {
149
+ return (
150
+ bytes.byteLength >= prefix.length &&
151
+ prefix.every((value, index) => bytes[index] === value)
152
+ );
153
+ }
154
+ function startsWithAscii(bytes: Uint8Array, prefix: string): boolean {
155
+ return asciiAt(bytes, 0, prefix);
156
+ }
157
+ function asciiAt(bytes: Uint8Array, offset: number, text: string): boolean {
158
+ if (bytes.byteLength < offset + text.length) return false;
159
+ for (let index = 0; index < text.length; index++)
160
+ if (bytes[offset + index] !== text.charCodeAt(index)) return false;
161
+ return true;
162
+ }
163
+ function looksLikeUtf8Text(bytes: Uint8Array): boolean {
164
+ const sample = bytes.slice(0, Math.min(bytes.byteLength, 4096));
165
+ for (const byte of sample)
166
+ if (byte === 0 || byte < 0x09 || (byte > 0x0d && byte < 0x20)) return false;
167
+ try {
168
+ UTF8_FATAL_DECODER.decode(sample);
169
+ return true;
170
+ } catch (_) {
171
+ return false;
172
+ }
173
+ }
src/attachments/notes.ts ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { sanitizeUploadFilename } from "./mime";
2
+ import type { AttachmentDrop, AttachmentKind } from "./types";
3
+
4
+ export function droppedAttachmentNote(
5
+ drops: readonly AttachmentDrop[] | null | undefined,
6
+ ): string {
7
+ if (!drops?.length) return "";
8
+ const groups = new Map<
9
+ string,
10
+ { kind: AttachmentKind; message: string; count: number }
11
+ >();
12
+ for (const drop of drops) {
13
+ const key = `${drop.kind}\x00${drop.message}`;
14
+ const existing = groups.get(key);
15
+ if (existing) existing.count += 1;
16
+ else groups.set(key, { kind: drop.kind, message: drop.message, count: 1 });
17
+ }
18
+ return [...groups.values()]
19
+ .map(
20
+ (group) =>
21
+ `\n\n[Note: ${group.count} ${group.kind}(s) were provided but ignored - ${group.message}.]`,
22
+ )
23
+ .join("");
24
+ }
25
+
26
+ export function attachmentDrop(
27
+ kind: AttachmentKind,
28
+ code: AttachmentDrop["code"],
29
+ message?: string,
30
+ filename?: unknown,
31
+ ): AttachmentDrop {
32
+ const drop: AttachmentDrop = {
33
+ kind,
34
+ code,
35
+ message: message || defaultDropMessage(code),
36
+ };
37
+ const safeName = sanitizeUploadFilename(filename);
38
+ if (safeName) drop.filename = safeName;
39
+ return drop;
40
+ }
41
+
42
+ function defaultDropMessage(code: AttachmentDrop["code"]): string {
43
+ switch (code) {
44
+ case "invalid_image_input":
45
+ return "invalid image input";
46
+ case "invalid_file_input":
47
+ return "invalid file input";
48
+ case "invalid_base64":
49
+ return "invalid base64 payload";
50
+ case "invalid_remote_url":
51
+ return "invalid remote URL";
52
+ case "file_too_large":
53
+ return "file attachment is too large";
54
+ case "image_too_large":
55
+ return "image attachment is too large";
56
+ case "too_many_files":
57
+ return "too many attachments";
58
+ case "upload_failed":
59
+ return "attachment upload failed";
60
+ }
61
+ }
src/attachments/plan.ts ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { isRecord } from "../shared/types";
2
+ import {
3
+ firstNonEmptyString,
4
+ genericFilenameFromMime,
5
+ imageFilenameFromMime,
6
+ mimeFromFilename,
7
+ sanitizeUploadFilename,
8
+ } from "./mime";
9
+ import {
10
+ imageFilenameFromObject,
11
+ normalizeUploadFileInput,
12
+ type UploadFileInput,
13
+ } from "./input";
14
+ import { attachmentDrop } from "./notes";
15
+ import { appendExistingFileRefs } from "./refs";
16
+ import type {
17
+ AttachmentCandidate,
18
+ AttachmentDrop,
19
+ AttachmentFileRef,
20
+ AttachmentKind,
21
+ AttachmentPlan,
22
+ } from "./types";
23
+
24
+ export const MAX_ATTACHMENTS_PER_REQUEST = 50;
25
+
26
+ type PlanState = {
27
+ candidates: AttachmentCandidate[];
28
+ existingFileRefs: AttachmentFileRef[];
29
+ dropped: AttachmentDrop[];
30
+ maxFiles: number;
31
+ nextID: number;
32
+ };
33
+
34
+ type CreatePlanInput = {
35
+ images?: unknown;
36
+ files?: unknown;
37
+ existingFileRefs?: unknown;
38
+ maxFiles?: number;
39
+ };
40
+
41
+ export function createAttachmentPlan(
42
+ input: CreatePlanInput = {},
43
+ ): AttachmentPlan {
44
+ const state: PlanState = {
45
+ candidates: [],
46
+ existingFileRefs: [],
47
+ dropped: [],
48
+ maxFiles: normalizeMaxFiles(input.maxFiles),
49
+ nextID: 1,
50
+ };
51
+ appendExistingFileRefs(state.existingFileRefs, input.existingFileRefs);
52
+ appendImageInputs(state, input.images);
53
+ appendFileInputs(state, input.files);
54
+ return finishPlan(state);
55
+ }
56
+
57
+ export function mergeAttachmentPlans(
58
+ ...plans: Array<AttachmentPlan | null | undefined>
59
+ ): AttachmentPlan {
60
+ const state: PlanState = {
61
+ candidates: [],
62
+ existingFileRefs: [],
63
+ dropped: [],
64
+ maxFiles: MAX_ATTACHMENTS_PER_REQUEST,
65
+ nextID: 1,
66
+ };
67
+ for (const plan of plans) {
68
+ if (!plan) continue;
69
+ state.maxFiles = Math.min(state.maxFiles, normalizeMaxFiles(plan.maxFiles));
70
+ appendExistingFileRefs(state.existingFileRefs, plan.existingFileRefs);
71
+ for (const candidate of plan.candidates) {
72
+ const meta: { filename?: string; mime?: string } = {};
73
+ if (candidate.filename) meta.filename = candidate.filename;
74
+ if (candidate.mime) meta.mime = candidate.mime;
75
+ addCandidate(state, candidate.kind, candidate.source, meta);
76
+ }
77
+ state.dropped.push(...plan.dropped);
78
+ }
79
+ return finishPlan(state);
80
+ }
81
+
82
+ function appendImageInputs(state: PlanState, raw: unknown): void {
83
+ if (!Array.isArray(raw)) return;
84
+ for (let i = 0; i < raw.length; i++) {
85
+ const image = raw[i];
86
+ if (!isRecord(image)) continue;
87
+ const b64 = image.b64;
88
+ if (b64 == null) {
89
+ state.dropped.push(
90
+ attachmentDrop(
91
+ "image",
92
+ "invalid_image_input",
93
+ "invalid image input",
94
+ imageFilenameFromObject(image),
95
+ ),
96
+ );
97
+ continue;
98
+ }
99
+ const name =
100
+ firstNonEmptyString(
101
+ sanitizeUploadFilename(image.filename),
102
+ sanitizeUploadFilename(image.name),
103
+ ) ||
104
+ imageFilenameFromMime(
105
+ image.mime || "image/png",
106
+ state.candidates.length + 1,
107
+ );
108
+ const source = { type: "base64" as const, data: b64 };
109
+ const mime = firstNonEmptyString(image.mime, "image/png");
110
+ addCandidate(state, "image", source, {
111
+ filename: name,
112
+ mime,
113
+ });
114
+ }
115
+ }
116
+
117
+ function appendFileInputs(state: PlanState, raw: unknown): void {
118
+ if (!Array.isArray(raw)) return;
119
+ for (const item of raw) {
120
+ const input = isNormalizedUploadFileInput(item)
121
+ ? item
122
+ : normalizeUploadFileInput(item);
123
+ if (!input) continue;
124
+ appendUploadFileInput(state, input);
125
+ }
126
+ }
127
+
128
+ function appendUploadFileInput(state: PlanState, input: UploadFileInput): void {
129
+ const nameHint = firstNonEmptyString(
130
+ sanitizeUploadFilename(input.filename),
131
+ sanitizeUploadFilename(input.name),
132
+ );
133
+ const mime = firstNonEmptyString(input.mime, mimeFromFilename(nameHint));
134
+ if (input.invalidReason) {
135
+ state.dropped.push(
136
+ attachmentDrop(
137
+ "file",
138
+ "invalid_file_input",
139
+ String(input.invalidReason || "invalid file input"),
140
+ nameHint,
141
+ ),
142
+ );
143
+ return;
144
+ }
145
+ if (input.b64 != null) {
146
+ const meta: { filename?: string; mime?: string } = {};
147
+ if (nameHint) meta.filename = nameHint;
148
+ else if (mime)
149
+ meta.filename = genericFilenameFromMime(
150
+ mime,
151
+ state.candidates.length + 1,
152
+ );
153
+ if (mime) meta.mime = mime;
154
+ addCandidate(
155
+ state,
156
+ "file",
157
+ { type: "base64", data: input.b64 },
158
+ {
159
+ ...meta,
160
+ },
161
+ );
162
+ }
163
+ }
164
+
165
+ function addCandidate(
166
+ state: PlanState,
167
+ kind: AttachmentKind,
168
+ source: AttachmentCandidate["source"],
169
+ meta: { filename?: string; mime?: string } = {},
170
+ ): void {
171
+ if (state.candidates.length >= state.maxFiles) {
172
+ state.dropped.push(
173
+ attachmentDrop(
174
+ kind,
175
+ "too_many_files",
176
+ `exceeded maximum of ${state.maxFiles} attachments per request`,
177
+ meta.filename,
178
+ ),
179
+ );
180
+ return;
181
+ }
182
+ const candidate: AttachmentCandidate = {
183
+ id: `att_${state.nextID++}`,
184
+ kind,
185
+ role: "request",
186
+ source,
187
+ };
188
+ const filename = sanitizeUploadFilename(meta.filename);
189
+ if (filename) candidate.filename = filename;
190
+ const mime = firstNonEmptyString(meta.mime);
191
+ if (mime) candidate.mime = mime;
192
+ state.candidates.push(candidate);
193
+ }
194
+
195
+ function finishPlan(state: PlanState): AttachmentPlan {
196
+ return {
197
+ candidates: state.candidates,
198
+ existingFileRefs: state.existingFileRefs.length
199
+ ? state.existingFileRefs
200
+ : null,
201
+ dropped: state.dropped,
202
+ maxFiles: state.maxFiles,
203
+ };
204
+ }
205
+
206
+ function normalizeMaxFiles(value: unknown): number {
207
+ const n = Number(value);
208
+ if (!Number.isFinite(n) || n <= 0) return MAX_ATTACHMENTS_PER_REQUEST;
209
+ return Math.max(1, Math.floor(n));
210
+ }
211
+
212
+ function isNormalizedUploadFileInput(value: unknown): value is UploadFileInput {
213
+ if (!isRecord(value)) return false;
214
+ return "invalidReason" in value || "b64" in value;
215
+ }
src/attachments/refs.ts ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { isRecord } from "../shared/types";
2
+ import { imageFilenameFromObject, normalizeUploadFileInput } from "./input";
3
+ import { sanitizeUploadFilename } from "./mime";
4
+ import type { AttachmentFileRef } from "./types";
5
+
6
+ type ExistingRefState = {
7
+ out: AttachmentFileRef[];
8
+ seen: Set<string>;
9
+ };
10
+
11
+ export function collectOpenAIRefFileIDs(
12
+ req: unknown,
13
+ ): AttachmentFileRef[] | null {
14
+ if (!isRecord(req)) return null;
15
+ const state: ExistingRefState = { out: [], seen: new Set() };
16
+ for (const key of [
17
+ "ref_file_ids",
18
+ "file_ids",
19
+ "attachments",
20
+ "messages",
21
+ "input",
22
+ ]) {
23
+ const raw = req[key];
24
+ if (raw == null) continue;
25
+ if ((key === "messages" || key === "input") && typeof raw === "string")
26
+ continue;
27
+ appendOpenAIRefFileIDs(state, raw);
28
+ }
29
+ return state.out.length ? state.out : null;
30
+ }
31
+
32
+ export function appendExistingFileRefs(
33
+ out: AttachmentFileRef[],
34
+ refs: unknown,
35
+ ): void {
36
+ const state: ExistingRefState = {
37
+ out,
38
+ seen: new Set(out.map(refKey).filter(Boolean) as string[]),
39
+ };
40
+ appendDirectOrOpenAIRefFileIDs(state, refs);
41
+ }
42
+
43
+ function appendOpenAIRefFileIDs(state: ExistingRefState, raw: unknown): void {
44
+ if (raw == null) return;
45
+ if (typeof raw === "string") {
46
+ addOpenAIRefFileID(state, raw);
47
+ return;
48
+ }
49
+ if (Array.isArray(raw)) {
50
+ for (const item of raw) appendOpenAIRefFileIDs(state, item);
51
+ return;
52
+ }
53
+ if (!isRecord(raw)) return;
54
+
55
+ const rawFilename = imageFilenameFromObject(raw);
56
+ if (raw.file_id != null) addOpenAIRefFileID(state, raw.file_id, rawFilename);
57
+ const typ = String(raw.type || "")
58
+ .trim()
59
+ .toLowerCase();
60
+ const hasInlinePayload =
61
+ typ.includes("file") && !!normalizeUploadFileInput(raw);
62
+ if (typ.includes("file") && !hasInlinePayload && raw.id != null)
63
+ addOpenAIRefFileID(state, raw.id, rawFilename);
64
+ const file = isRecord(raw.file) ? raw.file : null;
65
+ if (file) {
66
+ const fileFilename = imageFilenameFromObject(file) || rawFilename;
67
+ const nestedInlinePayload = !!normalizeUploadFileInput(file);
68
+ if (file.file_id != null)
69
+ addOpenAIRefFileID(state, file.file_id, fileFilename);
70
+ if (!nestedInlinePayload && file.id != null)
71
+ addOpenAIRefFileID(state, file.id, fileFilename);
72
+ }
73
+ for (const key of [
74
+ "ref_file_ids",
75
+ "file_ids",
76
+ "attachments",
77
+ "messages",
78
+ "input",
79
+ "content",
80
+ "files",
81
+ "items",
82
+ "data",
83
+ "source",
84
+ ]) {
85
+ if (!(key in raw)) continue;
86
+ if (hasInlinePayload && (key === "data" || key === "source")) continue;
87
+ const nested = raw[key];
88
+ if ((key === "content" || key === "input") && typeof nested === "string")
89
+ continue;
90
+ appendOpenAIRefFileIDs(state, nested);
91
+ }
92
+ }
93
+
94
+ function appendDirectOrOpenAIRefFileIDs(
95
+ state: ExistingRefState,
96
+ refs: unknown,
97
+ ): void {
98
+ if (refs == null) return;
99
+ if (typeof refs === "string") {
100
+ addOpenAIRefFileID(state, refs);
101
+ return;
102
+ }
103
+ if (Array.isArray(refs)) {
104
+ for (const ref of refs) appendDirectOrOpenAIRefFileIDs(state, ref);
105
+ return;
106
+ }
107
+ if (isRecord(refs)) {
108
+ const id = refs.ref || refs.fileRef || refs.id || refs.file_id;
109
+ const name = refs.name || refs.filename || refs.file_name;
110
+ if (id != null) {
111
+ addOpenAIRefFileID(state, id, name);
112
+ return;
113
+ }
114
+ }
115
+ appendOpenAIRefFileIDs(state, refs);
116
+ }
117
+
118
+ function addOpenAIRefFileID(
119
+ state: ExistingRefState,
120
+ fileID: unknown,
121
+ filename: unknown = undefined,
122
+ ): void {
123
+ const id = String(fileID || "").trim();
124
+ if (!id || state.seen.has(id)) return;
125
+ state.seen.add(id);
126
+ const name = sanitizeUploadFilename(filename);
127
+ state.out.push(name ? { id, name } : id);
128
+ }
129
+
130
+ function refKey(ref: AttachmentFileRef): string {
131
+ if (typeof ref === "string") return ref;
132
+ return ref.ref || ref.fileRef || ref.id || "";
133
+ }
src/attachments/types.ts ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export type AttachmentFileRef =
2
+ | string
3
+ | {
4
+ ref?: string;
5
+ fileRef?: string;
6
+ id?: string;
7
+ name?: string;
8
+ filename?: string;
9
+ };
10
+
11
+ export type AttachmentKind = "image" | "file";
12
+
13
+ export type AttachmentRole = "request" | "context";
14
+
15
+ export type AttachmentSource =
16
+ | { type: "base64"; data: unknown }
17
+ | { type: "bytes"; bytes: Uint8Array };
18
+
19
+ export type AttachmentCandidate = {
20
+ id: string;
21
+ kind: AttachmentKind;
22
+ role: AttachmentRole;
23
+ source: AttachmentSource;
24
+ filename?: string;
25
+ mime?: string;
26
+ };
27
+
28
+ export type AttachmentDropReason =
29
+ | "invalid_image_input"
30
+ | "invalid_file_input"
31
+ | "invalid_base64"
32
+ | "invalid_remote_url"
33
+ | "file_too_large"
34
+ | "image_too_large"
35
+ | "too_many_files"
36
+ | "upload_failed";
37
+
38
+ export type AttachmentDrop = {
39
+ kind: AttachmentKind;
40
+ code: AttachmentDropReason;
41
+ message: string;
42
+ filename?: string;
43
+ };
44
+
45
+ export type AttachmentPlan = {
46
+ candidates: AttachmentCandidate[];
47
+ existingFileRefs: AttachmentFileRef[] | null;
48
+ dropped: AttachmentDrop[];
49
+ maxFiles: number;
50
+ };
51
+
52
+ export type AttachmentUsage = {
53
+ uploadedFiles: number;
54
+ dedupedFiles: number;
55
+ uploadedBytes: number;
56
+ fileRefBytes: number;
57
+ inlinedFiles: number;
58
+ inlinedBytes: number;
59
+ droppedFiles: number;
60
+ multipartUploads: number;
61
+ };
62
+
63
+ export type AttachmentUploadResult = {
64
+ fileRefs: AttachmentFileRef[] | null;
65
+ imageFileRefs: AttachmentFileRef[] | null;
66
+ genericFileRefs: AttachmentFileRef[] | null;
67
+ promptText: string;
68
+ droppedNote: string;
69
+ supportsFileRefs: boolean;
70
+ usage: AttachmentUsage;
71
+ };
src/completion/context-files.ts ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { currentInputFilePrompt } from "../toolcall/content";
2
+ import { toolsContextTranscriptFor } from "../toolcall/tool-bundle";
3
+ import { elapsedMs, log, logStage, nowMs } from "../shared/logging";
4
+ import { errorLogSummary } from "../shared/errors";
5
+ import {
6
+ buildTextWithTokens,
7
+ promptByteLength,
8
+ promptByteLengthBounded,
9
+ promptByteLengthGreaterThan,
10
+ } from "../shared/tokens";
11
+ import type { PromptByteLengthBounded } from "../shared/tokens";
12
+ import type { ErrorWithMetadata } from "../shared/types";
13
+ import type {
14
+ ContextFileFailure,
15
+ ContextFileResult,
16
+ FileRef,
17
+ ToolDef,
18
+ } from "./types";
19
+
20
+ type ContextFileConfig = {
21
+ current_input_file_enabled?: unknown;
22
+ current_input_file_min_bytes?: unknown;
23
+ current_input_file_name?: unknown;
24
+ current_tools_file_name?: unknown;
25
+ supports_authenticated_session?: unknown;
26
+ cookie?: unknown;
27
+ log_requests?: unknown;
28
+ };
29
+ export type TextFileUploader = (
30
+ text: string,
31
+ filename: string,
32
+ ) => Promise<FileRef>;
33
+ export type ContextFilePromptByteCheck = PromptByteLengthBounded & {
34
+ thresholdBytes: number;
35
+ };
36
+
37
+ export function buildToolsContextTranscript(
38
+ toolDefs: readonly ToolDef[] | null | undefined,
39
+ choiceInstruction: unknown,
40
+ filename: unknown = "tools.txt",
41
+ ): string {
42
+ return toolsContextTranscriptFor(toolDefs, choiceInstruction, filename);
43
+ }
44
+
45
+ export function contextFileThreshold(cfg: ContextFileConfig): number {
46
+ return Math.max(0, Number(cfg.current_input_file_min_bytes) || 95000);
47
+ }
48
+
49
+ export function contextFilePromptByteCheck(
50
+ cfg: ContextFileConfig,
51
+ promptText: unknown,
52
+ ): ContextFilePromptByteCheck {
53
+ const thresholdBytes = contextFileThreshold(cfg);
54
+ return {
55
+ ...promptByteLengthBounded(promptText || "", thresholdBytes),
56
+ thresholdBytes,
57
+ };
58
+ }
59
+
60
+ export function contextFileConfigUnavailableReason(
61
+ cfg: ContextFileConfig,
62
+ ): string {
63
+ if (!cfg.current_input_file_enabled)
64
+ return "CURRENT_INPUT_FILE_ENABLED is disabled";
65
+ if (!(cfg.supports_authenticated_session ?? !!cfg.cookie))
66
+ return "GEMINI_COOKIE is not configured";
67
+ return "";
68
+ }
69
+
70
+ export function contextFileUploadUnavailableReason(
71
+ cfg: ContextFileConfig,
72
+ uploader?: TextFileUploader | null,
73
+ ): string {
74
+ return (
75
+ contextFileConfigUnavailableReason(cfg) ||
76
+ (uploader ? "" : "text file uploader is not configured")
77
+ );
78
+ }
79
+
80
+ export function shouldConsiderContextFiles(
81
+ cfg: ContextFileConfig,
82
+ promptText: unknown,
83
+ promptByteCheck?: ContextFilePromptByteCheck,
84
+ ): boolean {
85
+ if (contextFileConfigUnavailableReason(cfg)) return false;
86
+ return (promptByteCheck || contextFilePromptByteCheck(cfg, promptText))
87
+ .exceeded;
88
+ }
89
+
90
+ export function shouldUseContextFiles(
91
+ cfg: ContextFileConfig,
92
+ historyText: unknown,
93
+ latestInputText: unknown,
94
+ promptText: unknown,
95
+ promptByteCheck?: ContextFilePromptByteCheck,
96
+ ): boolean {
97
+ if (
98
+ !shouldConsiderContextFiles(cfg, promptText || historyText, promptByteCheck)
99
+ )
100
+ return false;
101
+ const latest = String(latestInputText || "").trim();
102
+ if (!latest) return false;
103
+ if (!String(historyText || "").trim()) return false;
104
+ return true;
105
+ }
106
+
107
+ export function oversizedInlineContextFailure(
108
+ cfg: ContextFileConfig,
109
+ promptText: unknown,
110
+ promptByteCheck?: ContextFilePromptByteCheck,
111
+ reason?: unknown,
112
+ ): ErrorWithMetadata {
113
+ const check = promptByteCheck || contextFilePromptByteCheck(cfg, promptText);
114
+ const unavailable = String(
115
+ reason ||
116
+ contextFileConfigUnavailableReason(cfg) ||
117
+ "context-file attachments are unavailable",
118
+ );
119
+ const err: ErrorWithMetadata = new Error(
120
+ `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`,
121
+ );
122
+ err.code = "large_context_inline_unsupported";
123
+ err.status = 413;
124
+ err.promptBytes = check.bytes;
125
+ err.promptBytesExact = check.exact;
126
+ err.thresholdBytes = check.thresholdBytes;
127
+ return err;
128
+ }
129
+
130
+ export function contextFileUploadFailure(
131
+ kind: unknown,
132
+ promptText: unknown,
133
+ cause: unknown,
134
+ promptByteCheck?: ContextFilePromptByteCheck,
135
+ ): ErrorWithMetadata {
136
+ const check = promptByteCheck || null;
137
+ const err: ErrorWithMetadata = new Error(
138
+ `failed to upload ${kind || "context"} text file for large prompt; refusing to fall back to oversized inline context`,
139
+ );
140
+ err.code = "large_context_file_upload_failed";
141
+ err.promptBytes = check ? check.bytes : promptByteLength(promptText || "");
142
+ err.promptBytesExact = check ? check.exact : true;
143
+ if (check) err.thresholdBytes = check.thresholdBytes;
144
+ err.cause = cause;
145
+ return err;
146
+ }
147
+
148
+ export function latestInputInlineLimit(cfg: ContextFileConfig): number {
149
+ return Math.max(
150
+ 4000,
151
+ Math.min(16000, Math.floor(contextFileThreshold(cfg) / 6)),
152
+ );
153
+ }
154
+
155
+ export function latestInputPromptForContextFile(
156
+ cfg: ContextFileConfig,
157
+ latestInputText: unknown,
158
+ ): string {
159
+ const latest = String(latestInputText || "").trim();
160
+ if (!latest) return "";
161
+ if (!promptByteLengthGreaterThan(latest, latestInputInlineLimit(cfg)))
162
+ return `Latest user request:\n${latest}`;
163
+ const historyName =
164
+ String(cfg?.current_input_file_name || "message.txt").trim() ||
165
+ "message.txt";
166
+ return [
167
+ `The latest user request is at the end of \`${historyName}\`; do not duplicate it inline.`,
168
+ "Read it from the txt file and answer directly.",
169
+ ].join("\n");
170
+ }
171
+
172
+ export async function prepareContextFiles(
173
+ cfg: ContextFileConfig,
174
+ historyText: string,
175
+ toolDefs: readonly ToolDef[] | null | undefined,
176
+ choiceInstruction: unknown,
177
+ latestInputText: unknown,
178
+ promptText: unknown,
179
+ uploader?: TextFileUploader,
180
+ promptByteCheck?: ContextFilePromptByteCheck,
181
+ toolPromptSource?: unknown,
182
+ ): Promise<ContextFileResult | ContextFileFailure | null> {
183
+ if (!uploader) {
184
+ if (
185
+ !shouldUseContextFiles(
186
+ cfg,
187
+ historyText,
188
+ latestInputText,
189
+ promptText,
190
+ promptByteCheck,
191
+ )
192
+ )
193
+ return null;
194
+ return {
195
+ error: contextFileUploadFailure(
196
+ "context",
197
+ promptText,
198
+ new Error("text file uploader is not configured"),
199
+ promptByteCheck,
200
+ ),
201
+ };
202
+ }
203
+ return prepareContextFilesWithUploader(
204
+ cfg,
205
+ historyText,
206
+ toolDefs,
207
+ choiceInstruction,
208
+ latestInputText,
209
+ promptText,
210
+ uploader,
211
+ promptByteCheck,
212
+ toolPromptSource,
213
+ );
214
+ }
215
+
216
+ export async function prepareContextFilesWithUploader(
217
+ cfg: ContextFileConfig,
218
+ historyText: string,
219
+ toolDefs: readonly ToolDef[] | null | undefined,
220
+ choiceInstruction: unknown,
221
+ latestInputText: unknown,
222
+ promptText: unknown,
223
+ uploader: TextFileUploader,
224
+ promptByteCheck?: ContextFilePromptByteCheck,
225
+ toolPromptSource?: unknown,
226
+ ): Promise<ContextFileResult | ContextFileFailure | null> {
227
+ if (
228
+ !shouldUseContextFiles(
229
+ cfg,
230
+ historyText,
231
+ latestInputText,
232
+ promptText,
233
+ promptByteCheck,
234
+ )
235
+ )
236
+ return null;
237
+ const refs: FileRef[] = [];
238
+ const toolSource = toolPromptSource || toolDefs;
239
+ const toolsText = toolsContextTranscriptFor(
240
+ toolSource,
241
+ choiceInstruction,
242
+ cfg.current_tools_file_name || "tools.txt",
243
+ toolDefs || [],
244
+ );
245
+ let toolsAttached = false;
246
+ const uploadJobs = [
247
+ uploader(historyText, String(cfg.current_input_file_name || "message.txt")),
248
+ ];
249
+ const hasToolsText = !!toolsText.trim();
250
+ if (hasToolsText)
251
+ uploadJobs.push(
252
+ uploader(toolsText, String(cfg.current_tools_file_name || "tools.txt")),
253
+ );
254
+ const logRequests = !!cfg.log_requests;
255
+ const uploadStart = logRequests ? nowMs() : 0;
256
+ const uploadResults = await Promise.allSettled(uploadJobs);
257
+ const historyUpload = uploadResults[0];
258
+ if (historyUpload && historyUpload.status === "fulfilled") {
259
+ refs.push(historyUpload.value);
260
+ } else {
261
+ const e = historyUpload?.reason || "missing history upload result";
262
+ log(
263
+ cfg,
264
+ `history context file upload failed for large prompt ${errorLogSummary(e)}`,
265
+ );
266
+ return {
267
+ error: contextFileUploadFailure(
268
+ "history context",
269
+ promptText,
270
+ e,
271
+ promptByteCheck,
272
+ ),
273
+ };
274
+ }
275
+ if (hasToolsText) {
276
+ const toolsUpload = uploadResults[1];
277
+ if (toolsUpload && toolsUpload.status === "fulfilled") {
278
+ refs.push(toolsUpload.value);
279
+ toolsAttached = true;
280
+ } else if (toolsUpload) {
281
+ const e = toolsUpload.reason;
282
+ log(
283
+ cfg,
284
+ `tools context file upload failed for large prompt ${errorLogSummary(e)}`,
285
+ );
286
+ return {
287
+ error: contextFileUploadFailure(
288
+ "tools context",
289
+ promptText,
290
+ e,
291
+ promptByteCheck,
292
+ ),
293
+ };
294
+ }
295
+ }
296
+ const livePrompt = [
297
+ currentInputFilePrompt(cfg, toolsAttached),
298
+ latestInputPromptForContextFile(cfg, latestInputText),
299
+ toolsText.trim() && !toolsAttached ? toolsText : "",
300
+ ]
301
+ .filter((s: unknown) => String(s || "").trim())
302
+ .join("\n\n");
303
+ const promptTokenParts = promptTokenTextParts(
304
+ historyText,
305
+ toolsText,
306
+ livePrompt,
307
+ );
308
+ const promptTokenPrepared = buildTextWithTokens(promptTokenParts, false);
309
+ if (logRequests) {
310
+ const threshold = contextFileThreshold(cfg);
311
+ logStage(cfg, "context_file_upload", {
312
+ ms: elapsedMs(uploadStart),
313
+ refs: refs.length,
314
+ toolsAttached,
315
+ historyBytes: formatByteLengthCheck(
316
+ promptByteLengthBounded(historyText, threshold),
317
+ ),
318
+ toolsBytes: formatByteLengthCheck(
319
+ promptByteLengthBounded(toolsText, threshold),
320
+ ),
321
+ latestBytes: formatByteLengthCheck(
322
+ promptByteLengthBounded(latestInputText, latestInputInlineLimit(cfg)),
323
+ ),
324
+ livePromptBytes: formatByteLengthCheck(
325
+ promptByteLengthBounded(livePrompt, threshold),
326
+ ),
327
+ });
328
+ }
329
+ const result: ContextFileResult = {
330
+ fileRefs: refs,
331
+ prompt: livePrompt,
332
+ promptTokenCounts: promptTokenPrepared.counts,
333
+ promptTokenText: "",
334
+ };
335
+ Object.defineProperty(result, "promptTokenText", {
336
+ enumerable: false,
337
+ get() {
338
+ return promptTokenParts.join("");
339
+ },
340
+ });
341
+ return result;
342
+ }
343
+
344
+ function formatByteLengthCheck(check: PromptByteLengthBounded): string {
345
+ return check.exact ? String(check.bytes) : `>${check.maxBytes}`;
346
+ }
347
+
348
+ function formatPromptByteComparison(check: ContextFilePromptByteCheck): string {
349
+ const prefix = check.exact ? "" : "at least ";
350
+ return `${prefix}${check.bytes} UTF-8 bytes > ${check.thresholdBytes}`;
351
+ }
352
+
353
+ function promptTokenTextParts(...texts: string[]): string[] {
354
+ const parts: string[] = [];
355
+ for (const text of texts) {
356
+ if (!text) continue;
357
+ if (parts.length) parts.push("\n");
358
+ parts.push(text);
359
+ }
360
+ return parts;
361
+ }
src/completion/context.ts ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ googleToolDefs,
3
+ mergeFileRefs,
4
+ openAIToolDefs,
5
+ } from "../toolcall/content";
6
+ import { buildToolChoiceInstructionFromPolicy } from "../toolcall/policy-openai";
7
+ import type { ToolBundle } from "../toolcall/tool-bundle";
8
+ import {
9
+ googleContentsToPrompt,
10
+ googleToolChoiceInstruction,
11
+ } from "../promptcompat/google";
12
+ import {
13
+ appendStructuredOutputInstructionToPrepared,
14
+ appendTextToPreparedWithTokens,
15
+ structuredInstruction,
16
+ withGeminiNativeHiddenToolsPromptForPrepared,
17
+ withGeminiNativeHiddenToolsPromptWithTokens,
18
+ } from "../promptcompat/prompt-build";
19
+ import {
20
+ buildGoogleHistoryTranscript,
21
+ buildOpenAIHistoryTranscript,
22
+ latestGoogleUserInputText,
23
+ latestOpenAIUserInputText,
24
+ } from "../promptcompat/history";
25
+ import { collectOpenAIRequestAttachmentPlan } from "../attachments/collect-openai";
26
+ import { droppedAttachmentNote } from "../attachments/notes";
27
+ import {
28
+ createAttachmentPlan,
29
+ mergeAttachmentPlans,
30
+ } from "../attachments/plan";
31
+ import { messagesToPrompt } from "../promptcompat/messages";
32
+ import type { RuntimeConfig } from "../config";
33
+ import { logStage } from "../shared/logging";
34
+
35
+ import {
36
+ prepareContextFiles,
37
+ shouldConsiderContextFiles,
38
+ } from "./context-files";
39
+ import {
40
+ contextFilePromptByteCheck,
41
+ contextFileThreshold,
42
+ contextFileUploadUnavailableReason,
43
+ oversizedInlineContextFailure,
44
+ } from "./context-files";
45
+ import type {
46
+ ContextFileFailure,
47
+ ContextFileResult,
48
+ FileRef,
49
+ GeminiContextPrepareResult,
50
+ LooseRequest,
51
+ PromptWithTokens,
52
+ ToolDef,
53
+ } from "./types";
54
+ import type { PromptMetadata } from "./types";
55
+ import { hasCompletionError } from "./types";
56
+ import type { CompletionProvider } from "./ports";
57
+ import type { ToolChoicePolicy } from "../toolcall/policy-openai";
58
+ import type { ContextFilePromptByteCheck } from "./context-files";
59
+ import {
60
+ buildTextWithTokens,
61
+ createPromptByteLengthSniffer,
62
+ type PromptByteLengthBounded,
63
+ } from "../shared/tokens";
64
+ import type { AttachmentPlan } from "../attachments/types";
65
+
66
+ export { currentInputFilePrompt } from "../toolcall/content";
67
+ export {
68
+ buildToolsContextTranscript,
69
+ contextFilePromptByteCheck,
70
+ contextFileThreshold,
71
+ contextFileUploadFailure,
72
+ latestInputInlineLimit,
73
+ latestInputPromptForContextFile,
74
+ oversizedInlineContextFailure,
75
+ prepareContextFiles,
76
+ prepareContextFilesWithUploader,
77
+ shouldConsiderContextFiles,
78
+ shouldUseContextFiles,
79
+ } from "./context-files";
80
+
81
+ export async function prepareOpenAIGeminiContext(
82
+ cfg: RuntimeConfig,
83
+ provider: CompletionProvider,
84
+ req: LooseRequest,
85
+ messages: unknown,
86
+ tools: unknown,
87
+ promptToolChoice: unknown,
88
+ toolPolicy: ToolChoicePolicy | null | undefined,
89
+ structured: unknown,
90
+ ): Promise<GeminiContextPrepareResult> {
91
+ const toolDefs = openAIToolDefs(tools) as ToolDef[];
92
+ const toolChoiceInstruction =
93
+ buildToolChoiceInstructionFromPolicy(toolPolicy);
94
+ const promptResult = messagesToPrompt(
95
+ messages,
96
+ tools,
97
+ promptToolChoice,
98
+ toolDefs,
99
+ toolChoiceInstruction,
100
+ contextFileThreshold(cfg),
101
+ );
102
+ const [prompt0, images] = promptResult as [string, unknown];
103
+ const attachmentPlan = mergeAttachmentPlans(
104
+ createAttachmentPlan({ images, files: promptResult.files }),
105
+ collectOpenAIRequestAttachmentPlan(req),
106
+ );
107
+ return preparePromptWithAttachments({
108
+ cfg,
109
+ provider,
110
+ basePrompt: prompt0,
111
+ basePromptPrepared: promptResultToPrepared(promptResult, prompt0),
112
+ basePromptByteCheck: contextFilePromptByteCheckFromBounded(
113
+ cfg,
114
+ promptResult.byteCheck,
115
+ ),
116
+ hiddenPromptInsertOffset: promptResult.hiddenPromptInsertOffset,
117
+ attachmentPlan,
118
+ toolDefs,
119
+ toolPromptSource: tools,
120
+ toolChoiceInstruction,
121
+ basePromptMetadata: promptResultMetadata(promptResult),
122
+ buildHistoryText: () =>
123
+ buildOpenAIHistoryTranscript(
124
+ messages,
125
+ cfg.current_input_file_name || "message.txt",
126
+ ),
127
+ getLatestInputText: () =>
128
+ promptResult.latestInputText != null
129
+ ? promptResult.latestInputText
130
+ : latestOpenAIUserInputText(messages),
131
+ structured,
132
+ buildFileRefGroups: (
133
+ contextFileRefs,
134
+ existingFileRefs,
135
+ genericFileRefs,
136
+ imageFileRefs,
137
+ ) => [contextFileRefs, existingFileRefs, genericFileRefs, imageFileRefs],
138
+ });
139
+ }
140
+
141
+ export async function prepareGoogleGeminiContext(
142
+ cfg: RuntimeConfig,
143
+ provider: CompletionProvider,
144
+ effectiveReq: LooseRequest,
145
+ hasTools: boolean,
146
+ toolBundle?: ToolBundle | null,
147
+ toolChoiceInstructionOverride?: string,
148
+ ): Promise<GeminiContextPrepareResult> {
149
+ const toolDefs = (
150
+ hasTools ? googleToolDefs(toolBundle || effectiveReq) : []
151
+ ) as ToolDef[];
152
+ const toolChoiceInstruction =
153
+ toolChoiceInstructionOverride ?? googleToolChoiceInstruction(effectiveReq);
154
+ const promptResult = googleContentsToPrompt(
155
+ effectiveReq,
156
+ toolDefs,
157
+ contextFileThreshold(cfg),
158
+ toolBundle || effectiveReq,
159
+ );
160
+ const [prompt0, images] = promptResult as [string, unknown];
161
+ const attachmentPlan = createAttachmentPlan({
162
+ images,
163
+ files: promptResult.files,
164
+ });
165
+ return preparePromptWithAttachments({
166
+ cfg,
167
+ provider,
168
+ basePrompt: prompt0,
169
+ basePromptPrepared: promptResultToPrepared(promptResult, prompt0),
170
+ basePromptByteCheck: contextFilePromptByteCheckFromBounded(
171
+ cfg,
172
+ promptResult.byteCheck,
173
+ ),
174
+ hiddenPromptInsertOffset: promptResult.hiddenPromptInsertOffset,
175
+ attachmentPlan,
176
+ toolDefs,
177
+ toolPromptSource: toolBundle || effectiveReq,
178
+ toolChoiceInstruction,
179
+ basePromptMetadata: promptResultMetadata(promptResult),
180
+ buildHistoryText: () =>
181
+ buildGoogleHistoryTranscript(
182
+ effectiveReq,
183
+ cfg.current_input_file_name || "message.txt",
184
+ ),
185
+ getLatestInputText: () =>
186
+ promptResult.latestInputText != null
187
+ ? promptResult.latestInputText
188
+ : latestGoogleUserInputText(effectiveReq),
189
+ structured: null,
190
+ buildFileRefGroups: (
191
+ contextFileRefs,
192
+ _existingFileRefs,
193
+ genericFileRefs,
194
+ imageFileRefs,
195
+ ) => [imageFileRefs, contextFileRefs, genericFileRefs],
196
+ });
197
+ }
198
+
199
+ type PromptWithAttachmentParams = {
200
+ cfg: RuntimeConfig;
201
+ provider: CompletionProvider;
202
+ basePrompt: string;
203
+ basePromptPrepared?: PromptWithTokens | null;
204
+ basePromptByteCheck?: ContextFilePromptByteCheck | null;
205
+ hiddenPromptInsertOffset?: number | undefined;
206
+ attachmentPlan: AttachmentPlan;
207
+ toolDefs: ToolDef[];
208
+ toolPromptSource?: unknown;
209
+ toolChoiceInstruction: string;
210
+ basePromptMetadata?: PromptMetadata;
211
+ buildHistoryText: () => string;
212
+ getLatestInputText: () => unknown;
213
+ structured: unknown;
214
+ buildFileRefGroups: (
215
+ contextFileRefs: FileRef[] | null,
216
+ existingFileRefs: FileRef[] | null,
217
+ genericFileRefs: FileRef[] | null,
218
+ imageFileRefs: FileRef[] | null,
219
+ ) => Array<FileRef[] | null>;
220
+ };
221
+
222
+ async function preparePromptWithAttachments(
223
+ params: PromptWithAttachmentParams,
224
+ ): Promise<GeminiContextPrepareResult> {
225
+ const plannedDroppedNote = droppedAttachmentNote(
226
+ params.attachmentPlan.dropped,
227
+ );
228
+ const preUploadPromptDecision = promptDecisionForDroppedNote(
229
+ params,
230
+ plannedDroppedNote,
231
+ );
232
+ if (preUploadPromptDecision.promptByteCheck.exceeded) {
233
+ const contextUnavailableReason = contextFileUploadUnavailableReason(
234
+ params.cfg,
235
+ params.provider.uploadTextFile,
236
+ );
237
+ if (contextUnavailableReason) {
238
+ return {
239
+ error: oversizedInlineContextFailure(
240
+ params.cfg,
241
+ preUploadPromptDecision.contextPromptText,
242
+ preUploadPromptDecision.promptByteCheck,
243
+ contextUnavailableReason,
244
+ ),
245
+ };
246
+ }
247
+ }
248
+
249
+ let contextFiles: ContextFileResult | null = null;
250
+ if (preUploadPromptDecision.considerContextFiles) {
251
+ const prepared = await prepareContextFilesForDecision(
252
+ params,
253
+ preUploadPromptDecision,
254
+ );
255
+ if (prepared && hasCompletionError(prepared))
256
+ return { error: prepared.error };
257
+ contextFiles = prepared;
258
+ }
259
+
260
+ const attachmentResult = await params.provider.resolveAttachments(
261
+ params.attachmentPlan,
262
+ );
263
+ const attachmentPromptText =
264
+ (attachmentResult.promptText || "") + (attachmentResult.droppedNote || "");
265
+ let basePromptWithAttachmentTextPrepared: PromptWithTokens | null = null;
266
+ const getBasePromptWithAttachmentTextPrepared =
267
+ (): PromptWithTokens | null => {
268
+ if (!params.basePromptPrepared) return null;
269
+ if (!basePromptWithAttachmentTextPrepared) {
270
+ basePromptWithAttachmentTextPrepared = appendTextToPreparedWithTokens(
271
+ params.basePromptPrepared,
272
+ [attachmentPromptText],
273
+ ) as PromptWithTokens;
274
+ }
275
+ return basePromptWithAttachmentTextPrepared;
276
+ };
277
+ let inlinePreparedPrompt: PromptWithTokens | null = null;
278
+ const getInlinePreparedPrompt = (): PromptWithTokens => {
279
+ if (!inlinePreparedPrompt) {
280
+ const preparedBase = getBasePromptWithAttachmentTextPrepared();
281
+ const inlineHiddenToolsPrompt = preparedBase
282
+ ? (withGeminiNativeHiddenToolsPromptForPrepared(
283
+ preparedBase,
284
+ true,
285
+ params.hiddenPromptInsertOffset,
286
+ ) as PromptWithTokens)
287
+ : (withGeminiNativeHiddenToolsPromptWithTokens(
288
+ params.basePrompt + attachmentPromptText,
289
+ true,
290
+ params.hiddenPromptInsertOffset,
291
+ ) as PromptWithTokens);
292
+ inlinePreparedPrompt = prepareStructuredPrompt(
293
+ inlineHiddenToolsPrompt,
294
+ params.structured,
295
+ );
296
+ }
297
+ return inlinePreparedPrompt;
298
+ };
299
+ let contextPromptText = preUploadPromptDecision.contextPromptText;
300
+ let promptCheckSource = preUploadPromptDecision.promptCheckSource;
301
+ let promptByteCheck = preUploadPromptDecision.promptByteCheck;
302
+ if (!contextFiles) {
303
+ const promptDecision = promptDecisionForDroppedNote(
304
+ params,
305
+ attachmentPromptText,
306
+ getInlinePreparedPrompt,
307
+ );
308
+ contextPromptText = promptDecision.contextPromptText;
309
+ promptCheckSource = promptDecision.promptCheckSource;
310
+ promptByteCheck = promptDecision.promptByteCheck;
311
+
312
+ const contextUnavailableReason = promptByteCheck.exceeded
313
+ ? contextFileUploadUnavailableReason(
314
+ params.cfg,
315
+ params.provider.uploadTextFile,
316
+ )
317
+ : "";
318
+ if (promptByteCheck.exceeded && contextUnavailableReason) {
319
+ return {
320
+ error: oversizedInlineContextFailure(
321
+ params.cfg,
322
+ contextPromptText,
323
+ promptByteCheck,
324
+ contextUnavailableReason,
325
+ ),
326
+ };
327
+ }
328
+
329
+ if (promptDecision.considerContextFiles) {
330
+ const prepared = await prepareContextFilesForDecision(
331
+ params,
332
+ promptDecision,
333
+ );
334
+ if (prepared && hasCompletionError(prepared))
335
+ return { error: prepared.error };
336
+ contextFiles = prepared;
337
+ }
338
+ }
339
+ if (params.cfg.log_requests) {
340
+ const contextPrepareStageFields: Record<string, unknown> = {
341
+ promptCheck: promptCheckSource,
342
+ promptBytes: promptByteCheck.exact
343
+ ? promptByteCheck.bytes
344
+ : `>${promptByteCheck.thresholdBytes}`,
345
+ threshold: promptByteCheck.thresholdBytes,
346
+ exceeded: promptByteCheck.exceeded,
347
+ contextFiles: !!contextFiles,
348
+ contextRefs: contextFiles ? contextFiles.fileRefs.length : 0,
349
+ genericFileRefs: attachmentResult.genericFileRefs
350
+ ? attachmentResult.genericFileRefs.length
351
+ : 0,
352
+ imageRefs: attachmentResult.imageFileRefs
353
+ ? attachmentResult.imageFileRefs.length
354
+ : 0,
355
+ droppedAttachments: attachmentResult.usage.droppedFiles,
356
+ dedupedAttachments: attachmentResult.usage.dedupedFiles,
357
+ toolDefs: params.toolDefs.length,
358
+ };
359
+ contextPrepareStageFields.basePromptHasToolBlock = String(
360
+ params.basePrompt || "",
361
+ ).includes("Available tools");
362
+ contextPrepareStageFields.basePromptHasToolNames = promptContainsToolNames(
363
+ params.basePrompt,
364
+ params.toolDefs,
365
+ );
366
+ logStage(params.cfg, "context_prepare", contextPrepareStageFields);
367
+ }
368
+
369
+ const contextFileRefs = contextFiles ? contextFiles.fileRefs : null;
370
+ const fileRefs = attachmentResult.supportsFileRefs
371
+ ? mergeFileRefs(
372
+ ...params.buildFileRefGroups(
373
+ contextFileRefs,
374
+ params.attachmentPlan.existingFileRefs as FileRef[] | null,
375
+ attachmentResult.genericFileRefs as FileRef[] | null,
376
+ attachmentResult.imageFileRefs as FileRef[] | null,
377
+ ),
378
+ )
379
+ : null;
380
+ const livePreparedPrompt = contextFiles
381
+ ? prepareStructuredPrompt(
382
+ buildTextWithTokens([
383
+ contextFiles.prompt,
384
+ attachmentPromptText,
385
+ ]) as PromptWithTokens,
386
+ params.structured,
387
+ )
388
+ : getInlinePreparedPrompt();
389
+ const usagePreparedPrompt = contextFiles
390
+ ? prepareStructuredPrompt(
391
+ appendTextToPreparedWithTokens(
392
+ { text: "", tokens: 0, counts: contextFiles.promptTokenCounts },
393
+ [attachmentPromptText],
394
+ false,
395
+ ) as PromptWithTokens,
396
+ params.structured,
397
+ false,
398
+ )
399
+ : livePreparedPrompt;
400
+ const attachmentFileRefTokens = attachmentFileRefTokenEstimate(
401
+ attachmentResult.usage,
402
+ );
403
+
404
+ return {
405
+ toolDefs: params.toolDefs,
406
+ toolChoiceInstruction: params.toolChoiceInstruction,
407
+ prompt: livePreparedPrompt.text,
408
+ promptTokens: usagePreparedPrompt.tokens + attachmentFileRefTokens,
409
+ fileRefs,
410
+ contextFiles,
411
+ promptMetadata: contextFiles
412
+ ? { hasToolInstructions: true }
413
+ : params.basePromptMetadata || {},
414
+ };
415
+ }
416
+
417
+ function attachmentFileRefTokenEstimate(
418
+ usage: { fileRefBytes?: unknown; uploadedBytes?: unknown } | null | undefined,
419
+ ): number {
420
+ if (!usage) return 0;
421
+ const bytes = Number(usage.fileRefBytes ?? usage.uploadedBytes);
422
+ if (!Number.isFinite(bytes) || bytes <= 0) return 0;
423
+ return Math.floor(bytes / 3);
424
+ }
425
+
426
+ type PromptDecision = {
427
+ contextPromptText: string;
428
+ promptCheckSource: string;
429
+ promptByteCheck: ContextFilePromptByteCheck;
430
+ considerContextFiles: boolean;
431
+ };
432
+
433
+ function promptDecisionForDroppedNote(
434
+ params: PromptWithAttachmentParams,
435
+ droppedNote: string,
436
+ getInlinePreparedPrompt?: () => PromptWithTokens,
437
+ ): PromptDecision {
438
+ let contextPromptText = params.basePrompt + droppedNote;
439
+ let promptCheckSource = "base";
440
+ let promptByteCheck = droppedNote
441
+ ? contextFilePromptByteCheck(params.cfg, contextPromptText)
442
+ : params.basePromptByteCheck ||
443
+ contextFilePromptByteCheck(params.cfg, contextPromptText);
444
+ let considerContextFiles = shouldConsiderContextFiles(
445
+ params.cfg,
446
+ contextPromptText,
447
+ promptByteCheck,
448
+ );
449
+ if (!promptByteCheck.exceeded) {
450
+ const inlineByteCheck = inlinePreparedPromptByteCheck(
451
+ params.cfg,
452
+ contextPromptText,
453
+ params.structured,
454
+ params.hiddenPromptInsertOffset,
455
+ );
456
+ if (inlineByteCheck.exceeded) {
457
+ promptByteCheck = inlineByteCheck;
458
+ promptCheckSource = "inline_estimate";
459
+ } else {
460
+ contextPromptText = getInlinePreparedPrompt
461
+ ? getInlinePreparedPrompt().text
462
+ : contextPromptText;
463
+ promptByteCheck = getInlinePreparedPrompt
464
+ ? contextFilePromptByteCheck(params.cfg, contextPromptText)
465
+ : inlineByteCheck;
466
+ promptCheckSource = getInlinePreparedPrompt
467
+ ? "inline"
468
+ : "inline_estimate";
469
+ }
470
+ considerContextFiles = shouldConsiderContextFiles(
471
+ params.cfg,
472
+ contextPromptText,
473
+ promptByteCheck,
474
+ );
475
+ }
476
+ return {
477
+ contextPromptText,
478
+ promptCheckSource,
479
+ promptByteCheck,
480
+ considerContextFiles,
481
+ };
482
+ }
483
+
484
+ async function prepareContextFilesForDecision(
485
+ params: PromptWithAttachmentParams,
486
+ decision: PromptDecision,
487
+ ): Promise<ContextFileResult | ContextFileFailure | null> {
488
+ const historyText = params.buildHistoryText();
489
+ const latestInputText = params.getLatestInputText();
490
+ return prepareContextFiles(
491
+ params.cfg,
492
+ historyText,
493
+ params.toolDefs,
494
+ params.toolChoiceInstruction,
495
+ latestInputText,
496
+ decision.contextPromptText,
497
+ params.provider.uploadTextFile,
498
+ decision.promptByteCheck,
499
+ params.toolPromptSource || params.toolDefs,
500
+ );
501
+ }
502
+
503
+ function prepareStructuredPrompt(
504
+ prompt: PromptWithTokens,
505
+ structured: unknown,
506
+ keepText = true,
507
+ ): PromptWithTokens {
508
+ return structured
509
+ ? (appendStructuredOutputInstructionToPrepared(
510
+ prompt,
511
+ structured,
512
+ keepText,
513
+ ) as PromptWithTokens)
514
+ : prompt;
515
+ }
516
+
517
+ function promptResultToPrepared(
518
+ promptResult: { tokens?: number; counts?: unknown },
519
+ text: string,
520
+ ): PromptWithTokens | null {
521
+ if (!promptResult?.counts) return null;
522
+ return {
523
+ text,
524
+ tokens: promptResult.tokens || 0,
525
+ counts: promptResult.counts,
526
+ };
527
+ }
528
+
529
+ function promptResultMetadata(promptResult: {
530
+ hasToolPrompt?: boolean;
531
+ hasToolInstructions?: boolean;
532
+ }): PromptMetadata {
533
+ return {
534
+ hasToolPrompt: !!promptResult.hasToolPrompt,
535
+ hasToolInstructions: !!promptResult.hasToolInstructions,
536
+ };
537
+ }
538
+
539
+ function contextFilePromptByteCheckFromBounded(
540
+ cfg: RuntimeConfig,
541
+ check: PromptByteLengthBounded | null | undefined,
542
+ ): ContextFilePromptByteCheck | null {
543
+ if (!check) return null;
544
+ const thresholdBytes = contextFileThreshold(cfg);
545
+ if (check.maxBytes !== thresholdBytes) return null;
546
+ return { ...check, thresholdBytes };
547
+ }
548
+
549
+ function inlinePreparedPromptByteCheck(
550
+ cfg: RuntimeConfig,
551
+ prompt: string,
552
+ structured: unknown,
553
+ hiddenPromptInsertOffset?: number,
554
+ ): ContextFilePromptByteCheck {
555
+ const thresholdBytes = contextFileThreshold(cfg);
556
+ const sniffer = createPromptByteLengthSniffer(thresholdBytes);
557
+ const prepared = withGeminiNativeHiddenToolsPromptWithTokens(
558
+ prompt,
559
+ true,
560
+ hiddenPromptInsertOffset,
561
+ ).text;
562
+ const hasText = !!prepared;
563
+ if (prepared) sniffer.append(prepared);
564
+ const instruction = structuredInstruction(structured);
565
+ if (instruction) {
566
+ if (hasText) sniffer.append("\n\n");
567
+ sniffer.append(instruction);
568
+ }
569
+ return { ...sniffer.result(), thresholdBytes };
570
+ }
571
+
572
+ function promptContainsToolNames(
573
+ prompt: unknown,
574
+ toolDefs: readonly ToolDef[],
575
+ ): boolean {
576
+ const text = String(prompt || "");
577
+ const names = toolDefs
578
+ .map((tool) => String(tool.name || "").trim())
579
+ .filter(Boolean);
580
+ return !!names.length && names.every((name) => text.includes(name));
581
+ }
src/completion/google-request.ts ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { RuntimeConfig } from "../config";
2
+ import type { CompletionProvider } from "./ports";
3
+ import { resolveModel } from "../models";
4
+ import type { ResolvedModel } from "../models";
5
+ import {
6
+ googleFunctionCallingConfig,
7
+ parseGoogleToolChoicePolicy,
8
+ validateGoogleToolChoiceConfig,
9
+ } from "../toolcall/policy-google";
10
+ import {
11
+ createToolBundle,
12
+ filterToolBundleByPolicy,
13
+ } from "../toolcall/tool-bundle";
14
+ import { googleToolChoiceInstruction } from "../promptcompat/google";
15
+ import { log } from "../shared/logging";
16
+ import {
17
+ upstreamErrorCode,
18
+ upstreamErrorMessage,
19
+ upstreamErrorStatus,
20
+ } from "../shared/errors";
21
+ import { prepareGoogleGeminiContext } from "./context";
22
+ import { ensureInlineToolPrompt } from "./tool-prompt-guard";
23
+ import type { ContextFileResult, FileRef, LooseRequest } from "./types";
24
+ import { hasCompletionError } from "./types";
25
+
26
+ export type GoogleCompletionPrepareError = {
27
+ message: string;
28
+ status: number;
29
+ code?: string;
30
+ };
31
+
32
+ export type PreparedGoogleCompletion = {
33
+ rm: Extract<ResolvedModel, { name: string }>;
34
+ effectiveReq: LooseRequest;
35
+ effectiveGoogleTools: LooseRequest[] | null;
36
+ hasTools: boolean;
37
+ prompt: string;
38
+ fileRefs: FileRef[] | null;
39
+ promptTokens: number;
40
+ contextFiles: ContextFileResult | null;
41
+ };
42
+
43
+ export async function prepareGoogleCompletion(
44
+ cfg: RuntimeConfig,
45
+ provider: CompletionProvider,
46
+ req: LooseRequest,
47
+ path: string,
48
+ ): Promise<PreparedGoogleCompletion | { error: GoogleCompletionPrepareError }> {
49
+ const m = /\/v(?:1beta|1)\/models\/([^:?/]+)/.exec(path);
50
+ const modelFromPath = m?.[1]
51
+ ? decodeURIComponent(m[1]).replace(/^models\//, "")
52
+ : undefined;
53
+ const rm = resolveModel(modelFromPath, cfg.default_model);
54
+ if (rm.name === undefined) {
55
+ log(
56
+ cfg,
57
+ `google completion model rejected model=${String(modelFromPath ?? "(default)")}`,
58
+ );
59
+ return {
60
+ error: { message: rm.error, status: 400, code: "model_not_found" },
61
+ };
62
+ }
63
+
64
+ const toolBundle = createToolBundle(req.tools);
65
+ const toolConfigViolation = validateGoogleToolChoiceConfig(req, toolBundle);
66
+ if (toolConfigViolation) {
67
+ return {
68
+ error: {
69
+ message: toolConfigViolation.message,
70
+ status: 400,
71
+ code: "invalid_tool_choice",
72
+ },
73
+ };
74
+ }
75
+
76
+ const fcMode = String(googleFunctionCallingConfig(req).mode || "AUTO")
77
+ .trim()
78
+ .toUpperCase();
79
+ const toolPolicy = parseGoogleToolChoicePolicy(req, toolBundle);
80
+ const effectiveToolBundle = filterToolBundleByPolicy(toolBundle, toolPolicy);
81
+ const effectiveGoogleTools = effectiveToolBundle.openAIFunctionTools.length
82
+ ? effectiveToolBundle.openAIFunctionTools
83
+ : null;
84
+ const effectiveReq = { ...req, tools: effectiveGoogleTools || [] };
85
+ const hasTools = !!effectiveGoogleTools && fcMode !== "NONE";
86
+ const toolChoiceInstruction = googleToolChoiceInstruction(effectiveReq);
87
+ const ctx = await prepareGoogleGeminiContext(
88
+ cfg,
89
+ provider,
90
+ effectiveReq,
91
+ hasTools,
92
+ effectiveToolBundle,
93
+ toolChoiceInstruction,
94
+ );
95
+ if (hasCompletionError(ctx)) {
96
+ const code = upstreamErrorCode(ctx.error) || "context_file_upload_failed";
97
+ return {
98
+ error: {
99
+ message: upstreamErrorMessage(ctx.error),
100
+ status: upstreamErrorStatus(ctx.error) || 502,
101
+ code,
102
+ },
103
+ };
104
+ }
105
+ let { prompt } = ctx;
106
+ const { fileRefs, promptTokens, contextFiles } = ctx;
107
+ const promptToolSource = effectiveToolBundle.defs.length
108
+ ? effectiveToolBundle
109
+ : toolBundle;
110
+ prompt = ensureInlineToolPrompt(
111
+ prompt,
112
+ promptToolSource,
113
+ toolChoiceInstruction,
114
+ contextFiles,
115
+ ctx.promptMetadata,
116
+ );
117
+ if (!String(prompt || "").trim())
118
+ return { error: { message: "empty content", status: 400 } };
119
+
120
+ return {
121
+ rm,
122
+ effectiveReq,
123
+ effectiveGoogleTools,
124
+ hasTools,
125
+ prompt,
126
+ fileRefs,
127
+ promptTokens,
128
+ contextFiles,
129
+ };
130
+ }
src/completion/google-turn.ts ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { parseGoogleFunctionCalls } from "../toolcall/google";
2
+ import { validateGoogleFunctionCalls } from "../toolcall/policy-google";
3
+ import type { GoogleFunctionCall } from "../toolcall/google";
4
+ import type { LooseRequest } from "./types";
5
+
6
+ export type GoogleResponsePart =
7
+ | { text: string }
8
+ | { functionCall: GoogleFunctionCall };
9
+
10
+ export type GoogleCompletionTurn =
11
+ | {
12
+ responseParts: GoogleResponsePart[];
13
+ upstreamEmpty: boolean;
14
+ error?: undefined;
15
+ }
16
+ | {
17
+ error: {
18
+ message: string;
19
+ status: number;
20
+ code?: string;
21
+ };
22
+ responseParts?: undefined;
23
+ upstreamEmpty?: undefined;
24
+ };
25
+
26
+ export function finalizeGoogleCompletionResult(
27
+ text: unknown,
28
+ options: {
29
+ effectiveReq: LooseRequest;
30
+ effectiveGoogleTools: LooseRequest[] | null;
31
+ hasTools: boolean;
32
+ },
33
+ ): GoogleCompletionTurn {
34
+ const source = String(text || "");
35
+ const responseParts: GoogleResponsePart[] = [];
36
+ if (options.hasTools && source) {
37
+ const [clean, fcs] = parseGoogleFunctionCalls(
38
+ source,
39
+ options.effectiveGoogleTools,
40
+ );
41
+ const googleToolViolation = validateGoogleFunctionCalls(
42
+ options.effectiveReq,
43
+ fcs,
44
+ );
45
+ if (googleToolViolation) {
46
+ return {
47
+ error: {
48
+ message: googleToolViolation.message,
49
+ status: 422,
50
+ code: googleToolViolation.code,
51
+ },
52
+ };
53
+ }
54
+ if (fcs.length) {
55
+ if (clean) responseParts.push({ text: clean });
56
+ for (const fc of fcs)
57
+ responseParts.push({ functionCall: { name: fc.name, args: fc.args } });
58
+ } else {
59
+ responseParts.push({ text: source });
60
+ }
61
+ } else {
62
+ const googleToolViolation = validateGoogleFunctionCalls(
63
+ options.effectiveReq,
64
+ [],
65
+ );
66
+ if (googleToolViolation) {
67
+ return {
68
+ error: {
69
+ message: googleToolViolation.message,
70
+ status: 422,
71
+ code: googleToolViolation.code,
72
+ },
73
+ };
74
+ }
75
+ responseParts.push({
76
+ text:
77
+ source ||
78
+ "I apologize, but I was unable to generate a response. Please try again.",
79
+ });
80
+ }
81
+ return { responseParts, upstreamEmpty: !source };
82
+ }
src/completion/google.ts ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { streamBufferedToolTextCompletionEvents } from "./runtime";
2
+ import type { CompletionProvider } from "./ports";
3
+ import type { ResolvedModel } from "../models";
4
+ import {
5
+ combinedTokenCount,
6
+ createTokenCounter,
7
+ emptyTokenCounts,
8
+ } from "../shared/tokens";
9
+ import { parseGoogleFunctionCalls } from "../toolcall/google";
10
+ import { validateGoogleFunctionCalls } from "../toolcall/policy-google";
11
+ import type { ToolPolicyViolation } from "../toolcall/policy-openai";
12
+ import type { GoogleFunctionCall } from "../toolcall/google";
13
+ import type { GoogleResponsePart } from "./google-turn";
14
+ import type { FileRef, LooseRequest } from "./types";
15
+ import { EMPTY_UPSTREAM_MSG } from "./turn";
16
+
17
+ export type GoogleToolCompletionEvent =
18
+ | {
19
+ type: "candidate";
20
+ parts: GoogleResponsePart[] | null;
21
+ finishReason: string | null;
22
+ }
23
+ | { type: "warning"; error: unknown; message?: string }
24
+ | { type: "error"; error: unknown }
25
+ | { type: "tool_policy_violation"; violation: ToolPolicyViolation }
26
+ | {
27
+ type: "done";
28
+ usageMetadata: {
29
+ promptTokenCount: number;
30
+ candidatesTokenCount: number;
31
+ totalTokenCount: number;
32
+ };
33
+ };
34
+
35
+ type GoogleToolCompletionParams = {
36
+ prompt: string;
37
+ rm: Extract<ResolvedModel, { name: string }>;
38
+ fileRefs: FileRef[] | null;
39
+ tools: LooseRequest[] | null;
40
+ effectiveReq: LooseRequest;
41
+ promptTokens: number;
42
+ signal: AbortSignal;
43
+ };
44
+
45
+ export async function* streamGoogleToolCompletionEvents(
46
+ provider: CompletionProvider,
47
+ params: GoogleToolCompletionParams,
48
+ ): AsyncIterable<GoogleToolCompletionEvent> {
49
+ const { prompt, rm, fileRefs, tools, effectiveReq, promptTokens, signal } =
50
+ params;
51
+ const extraTokenCounter = createTokenCounter();
52
+ let completionCounts = emptyTokenCounts();
53
+ let buffered = "";
54
+ let emittedText = false;
55
+ let issue: { error: unknown } | null = null;
56
+
57
+ for await (const event of streamBufferedToolTextCompletionEvents(
58
+ provider,
59
+ { prompt, rm, fileRefs },
60
+ { signal },
61
+ )) {
62
+ if (event.type === "text_delta") {
63
+ emittedText = true;
64
+ yield {
65
+ type: "candidate",
66
+ parts: [{ text: event.text }],
67
+ finishReason: null,
68
+ };
69
+ } else if (event.type === "buffered_text") {
70
+ buffered += event.text;
71
+ } else if (event.type === "warning" || event.type === "stream_error") {
72
+ issue = event;
73
+ } else if (event.type === "done") {
74
+ completionCounts = event.completionCounts;
75
+ }
76
+ }
77
+
78
+ const [clean, functionCalls]: [string, GoogleFunctionCall[]] =
79
+ parseGoogleFunctionCalls(buffered, tools);
80
+ if (clean) {
81
+ extraTokenCounter.append(clean);
82
+ yield { type: "candidate", parts: [{ text: clean }], finishReason: null };
83
+ }
84
+
85
+ const violation = validateGoogleFunctionCalls(effectiveReq, functionCalls);
86
+ if (violation) {
87
+ yield { type: "tool_policy_violation", violation };
88
+ return;
89
+ }
90
+ if (functionCalls?.length) {
91
+ if (issue) yield { type: "warning", error: issue.error };
92
+ yield {
93
+ type: "candidate",
94
+ parts: functionCalls.map((fc) => ({
95
+ functionCall: { name: fc.name, args: fc.args || {} },
96
+ })),
97
+ finishReason: null,
98
+ };
99
+ } else if (!emittedText && !clean) {
100
+ yield {
101
+ type: "error",
102
+ error: issue?.error || {
103
+ message: EMPTY_UPSTREAM_MSG,
104
+ code: "upstream_empty",
105
+ },
106
+ };
107
+ return;
108
+ } else if (issue) {
109
+ yield { type: "warning", error: issue.error };
110
+ }
111
+ const candidateTokens = combinedTokenCount(
112
+ completionCounts,
113
+ extraTokenCounter,
114
+ );
115
+ const promptTokenCount = Math.max(0, Number(promptTokens) || 0);
116
+ yield {
117
+ type: "done",
118
+ usageMetadata: {
119
+ promptTokenCount,
120
+ candidatesTokenCount: candidateTokens,
121
+ totalTokenCount: promptTokenCount + candidateTokens,
122
+ },
123
+ };
124
+ }
src/completion/image-generation.ts ADDED
@@ -0,0 +1,681 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { base64ToBytes } from "../attachments/base64";
2
+ import {
3
+ detectUploadMimeFromBytes,
4
+ firstNonEmptyString,
5
+ imageFilenameFromMime,
6
+ normalizeMimeType,
7
+ sanitizeUploadFilename,
8
+ } from "../attachments/mime";
9
+ import {
10
+ imageFilenameFromObject,
11
+ normalizeUploadFileInput,
12
+ parseImageUrl,
13
+ uploadFilenameFromObject,
14
+ uploadMimeFromObject,
15
+ } from "../attachments/input";
16
+ import { MAX_ATTACHMENTS_PER_REQUEST } from "../attachments/plan";
17
+ import type {
18
+ AttachmentCandidate,
19
+ AttachmentFileRef,
20
+ AttachmentPlan,
21
+ } from "../attachments/types";
22
+ import type { RuntimeConfig } from "../config";
23
+ import { resolveModel, type ResolvedModel } from "../models";
24
+ import { log } from "../shared/logging";
25
+ import {
26
+ upstreamErrorCode,
27
+ upstreamErrorMessage,
28
+ upstreamErrorStatus,
29
+ } from "../shared/errors";
30
+ import { firstRecord, isRecord, type UnknownRecord } from "../shared/types";
31
+ import { promptByteLength, tokenEst } from "../shared/tokens";
32
+ import { contextFileThreshold } from "./context-files";
33
+ import type { CompletionProvider } from "./ports";
34
+ import type {
35
+ AttachmentResolutionResult,
36
+ FileRef,
37
+ LooseRequest,
38
+ } from "./types";
39
+
40
+ export type ImageGenerationPrepareError = {
41
+ message: string;
42
+ status: number;
43
+ code: string;
44
+ };
45
+
46
+ export type PreparedImageGenerationCompletion = {
47
+ rm: Extract<ResolvedModel, { name: string }>;
48
+ prompt: string;
49
+ userPrompt: string;
50
+ fileRefs: FileRef[] | null;
51
+ promptTokens: number;
52
+ };
53
+
54
+ export type ImageGenerationRouteKind = "responses" | "chat";
55
+
56
+ export type ImageGenerationByteInput = {
57
+ bytes: Uint8Array;
58
+ filename?: string;
59
+ mime?: string;
60
+ };
61
+
62
+ export type ImageGenerationUserImageInput =
63
+ | { type: "part"; part: UnknownRecord }
64
+ | { type: "bytes"; image: ImageGenerationByteInput };
65
+
66
+ export type OpenAIImageGenerationUserInput = {
67
+ model?: unknown;
68
+ prompt: unknown;
69
+ imageInputs?: readonly ImageGenerationUserImageInput[];
70
+ imageParts?: readonly UnknownRecord[];
71
+ imageBytes?: readonly ImageGenerationByteInput[];
72
+ };
73
+
74
+ type FileSlot =
75
+ | { type: "existing"; ref: AttachmentFileRef }
76
+ | { type: "candidate"; index: number };
77
+
78
+ type ExtractionState = {
79
+ textParts: string[];
80
+ candidates: AttachmentCandidate[];
81
+ slots: FileSlot[];
82
+ error: ImageGenerationPrepareError | null;
83
+ nextID: number;
84
+ };
85
+
86
+ const IMAGE_GENERATION_INSTRUCTION = [
87
+ "IMAGE GENERATION ENABLED: Return a real generated image matching the user's request.",
88
+ "For edits to attached images, apply the requested changes and return a new generated version.",
89
+ "Do not provide explanations, process notes, placeholders, or apologies without an actual generated image attachment.",
90
+ ].join("\n");
91
+
92
+ const FORCED_IMAGE_GENERATION_INSTRUCTION =
93
+ "Image generation was explicitly requested. Return at least one generated image; a response without a generated image is a failure.";
94
+
95
+ export async function prepareOpenAIImageGenerationCompletion(
96
+ cfg: RuntimeConfig,
97
+ provider: CompletionProvider,
98
+ req: LooseRequest,
99
+ route: ImageGenerationRouteKind,
100
+ forced: boolean,
101
+ ): Promise<
102
+ PreparedImageGenerationCompletion | { error: ImageGenerationPrepareError }
103
+ > {
104
+ const state = createExtractionState();
105
+ if (route === "responses") extractResponsesUserInput(state, req.input);
106
+ else extractLatestChatUserInput(state, req.messages);
107
+ return prepareImageGenerationFromState(
108
+ cfg,
109
+ provider,
110
+ req.model,
111
+ state,
112
+ forced,
113
+ );
114
+ }
115
+
116
+ export async function prepareOpenAIImageGenerationFromUserInput(
117
+ cfg: RuntimeConfig,
118
+ provider: CompletionProvider,
119
+ input: OpenAIImageGenerationUserInput,
120
+ forced: boolean,
121
+ ): Promise<
122
+ PreparedImageGenerationCompletion | { error: ImageGenerationPrepareError }
123
+ > {
124
+ const state = createExtractionState();
125
+ appendText(state, input.prompt);
126
+ if (input.imageInputs) {
127
+ for (const imageInput of input.imageInputs) {
128
+ if (state.error) break;
129
+ if (imageInput.type === "part") appendImagePart(state, imageInput.part);
130
+ else appendImageBytes(state, imageInput.image);
131
+ }
132
+ } else if (input.imageParts) {
133
+ for (const part of input.imageParts) {
134
+ if (state.error) break;
135
+ appendImagePart(state, part);
136
+ }
137
+ }
138
+ if (!input.imageInputs && input.imageBytes) {
139
+ for (const image of input.imageBytes) {
140
+ if (state.error) break;
141
+ appendImageBytes(state, image);
142
+ }
143
+ }
144
+ return prepareImageGenerationFromState(
145
+ cfg,
146
+ provider,
147
+ input.model,
148
+ state,
149
+ forced,
150
+ );
151
+ }
152
+
153
+ async function prepareImageGenerationFromState(
154
+ cfg: RuntimeConfig,
155
+ provider: CompletionProvider,
156
+ model: unknown,
157
+ state: ExtractionState,
158
+ forced: boolean,
159
+ ): Promise<
160
+ PreparedImageGenerationCompletion | { error: ImageGenerationPrepareError }
161
+ > {
162
+ if (!(provider.supportsAuthenticatedSession ?? !!cfg.cookie)) {
163
+ return {
164
+ error: {
165
+ message: "image generation requires GEMINI_COOKIE",
166
+ status: 401,
167
+ code: "image_generation_requires_cookie",
168
+ },
169
+ };
170
+ }
171
+
172
+ const rm = resolveModel(model, cfg.default_model);
173
+ if (rm.name === undefined) {
174
+ log(
175
+ cfg,
176
+ `openai image generation model rejected model=${String(model ?? "(default)")}`,
177
+ );
178
+ return {
179
+ error: { message: rm.error, status: 400, code: "model_not_found" },
180
+ };
181
+ }
182
+
183
+ if (state.error) return { error: state.error };
184
+
185
+ const userPrompt = state.textParts
186
+ .map((part) => part.trim())
187
+ .filter(Boolean)
188
+ .join("\n")
189
+ .trim();
190
+ if (!userPrompt) {
191
+ return {
192
+ error: {
193
+ message: "image generation requires non-empty user prompt text",
194
+ status: 400,
195
+ code: "image_generation_empty_prompt",
196
+ },
197
+ };
198
+ }
199
+
200
+ const prompt = [
201
+ userPrompt,
202
+ IMAGE_GENERATION_INSTRUCTION,
203
+ forced ? FORCED_IMAGE_GENERATION_INSTRUCTION : "",
204
+ ]
205
+ .filter(Boolean)
206
+ .join("\n\n");
207
+ const promptBytes = promptByteLength(prompt);
208
+ const threshold = contextFileThreshold(cfg);
209
+ if (promptBytes > threshold) {
210
+ return {
211
+ error: {
212
+ message: `image generation prompt is too large for pass-through mode (${promptBytes} UTF-8 bytes > ${threshold})`,
213
+ status: 413,
214
+ code: "image_generation_prompt_too_large",
215
+ },
216
+ };
217
+ }
218
+
219
+ const fileRefsResult = await resolveImageGenerationFileRefs(provider, state);
220
+ if ("error" in fileRefsResult) return fileRefsResult;
221
+
222
+ return {
223
+ rm,
224
+ prompt,
225
+ userPrompt,
226
+ fileRefs: fileRefsResult.fileRefs,
227
+ promptTokens: tokenEst(prompt),
228
+ };
229
+ }
230
+
231
+ function createExtractionState(): ExtractionState {
232
+ return { textParts: [], candidates: [], slots: [], error: null, nextID: 1 };
233
+ }
234
+
235
+ function extractResponsesUserInput(
236
+ state: ExtractionState,
237
+ input: unknown,
238
+ ): void {
239
+ if (state.error || input == null) return;
240
+ if (typeof input === "string") {
241
+ appendText(state, input);
242
+ return;
243
+ }
244
+ if (Array.isArray(input)) {
245
+ for (const item of input) {
246
+ if (state.error) return;
247
+ extractResponseItem(state, item);
248
+ }
249
+ return;
250
+ }
251
+ extractResponseItem(state, input);
252
+ }
253
+
254
+ function extractResponseItem(state: ExtractionState, item: unknown): void {
255
+ if (state.error || item == null) return;
256
+ if (typeof item === "string") {
257
+ appendText(state, item);
258
+ return;
259
+ }
260
+ if (!isRecord(item)) return;
261
+ const role = normalizedType(item.role);
262
+ const typ = normalizedType(item.type);
263
+ if (role && role !== "user") return;
264
+ if (
265
+ typ === "output_text" ||
266
+ typ === "summary_text" ||
267
+ typ === "reasoning" ||
268
+ typ === "thinking" ||
269
+ typ === "function_call" ||
270
+ typ === "function_call_output"
271
+ )
272
+ return;
273
+ if (typ === "input_text" || typ === "text") {
274
+ appendText(state, item.text);
275
+ return;
276
+ }
277
+ if (isImagePartType(typ)) {
278
+ appendImagePart(state, item);
279
+ return;
280
+ }
281
+ if (isFilePartType(typ)) {
282
+ appendFilePart(state, item);
283
+ return;
284
+ }
285
+ if (role === "user" || typ === "message" || typ === "input_message") {
286
+ if (item.content != null) extractContent(state, item.content);
287
+ else appendText(state, item.text);
288
+ }
289
+ }
290
+
291
+ function extractLatestChatUserInput(
292
+ state: ExtractionState,
293
+ messages: unknown,
294
+ ): void {
295
+ if (!Array.isArray(messages)) return;
296
+ for (let i = messages.length - 1; i >= 0; i--) {
297
+ const msg = messages[i];
298
+ if (!isRecord(msg) || normalizedType(msg.role) !== "user") continue;
299
+ extractContent(state, msg.content != null ? msg.content : msg.text);
300
+ return;
301
+ }
302
+ }
303
+
304
+ function extractContent(state: ExtractionState, content: unknown): void {
305
+ if (state.error || content == null) return;
306
+ if (typeof content === "string") {
307
+ appendText(state, content);
308
+ return;
309
+ }
310
+ if (Array.isArray(content)) {
311
+ for (const part of content) {
312
+ if (state.error) return;
313
+ extractContentPart(state, part);
314
+ }
315
+ return;
316
+ }
317
+ extractContentPart(state, content);
318
+ }
319
+
320
+ function extractContentPart(state: ExtractionState, part: unknown): void {
321
+ if (state.error || part == null) return;
322
+ if (typeof part === "string") {
323
+ appendText(state, part);
324
+ return;
325
+ }
326
+ if (!isRecord(part)) return;
327
+ const typ = normalizedType(part.type);
328
+ if (typ === "text" || typ === "input_text") {
329
+ appendText(state, part.text);
330
+ return;
331
+ }
332
+ if (
333
+ typ === "output_text" ||
334
+ typ === "summary_text" ||
335
+ typ === "reasoning" ||
336
+ typ === "thinking"
337
+ )
338
+ return;
339
+ if (isImagePartType(typ) || part.image_url != null) {
340
+ appendImagePart(state, part);
341
+ return;
342
+ }
343
+ if (isFilePartType(typ)) appendFilePart(state, part);
344
+ }
345
+
346
+ function appendText(state: ExtractionState, value: unknown): void {
347
+ const text =
348
+ typeof value === "string" || typeof value === "number"
349
+ ? String(value).trim()
350
+ : "";
351
+ if (text) state.textParts.push(text);
352
+ }
353
+
354
+ function appendImagePart(state: ExtractionState, part: UnknownRecord): void {
355
+ if (remoteUrlFromPart(part)) {
356
+ state.error = unsupportedImageInput(
357
+ "remote image/file URLs are not supported in image generation mode",
358
+ );
359
+ return;
360
+ }
361
+ const existing = existingRefFromPart(part);
362
+ const hasInline = hasImageInlinePayload(part);
363
+ if (existing && !hasInline) {
364
+ state.slots.push({ type: "existing", ref: existing });
365
+ return;
366
+ }
367
+
368
+ const image = imageCandidateFromPart(part, state.nextID);
369
+ if ("error" in image) {
370
+ state.error = image.error;
371
+ return;
372
+ }
373
+ addCandidateSlot(state, image.candidate);
374
+ }
375
+
376
+ function appendImageBytes(
377
+ state: ExtractionState,
378
+ image: ImageGenerationByteInput,
379
+ ): void {
380
+ const detected = detectUploadMimeFromBytes(image.bytes);
381
+ if (!normalizeMimeType(detected).startsWith("image/")) {
382
+ state.error = unsupportedImageInput(
383
+ "image input bytes are not a supported image",
384
+ );
385
+ return;
386
+ }
387
+ const mime = firstNonEmptyString(detected, image.mime, "image/png");
388
+ const candidate: AttachmentCandidate = {
389
+ id: `att_${state.nextID}`,
390
+ kind: "image",
391
+ role: "request",
392
+ source: { type: "bytes", bytes: image.bytes },
393
+ };
394
+ const filename = firstNonEmptyString(
395
+ sanitizeUploadFilename(image.filename),
396
+ imageFilenameFromMime(mime, state.nextID),
397
+ );
398
+ if (filename) candidate.filename = filename;
399
+ if (mime) candidate.mime = mime;
400
+ addCandidateSlot(state, candidate);
401
+ }
402
+
403
+ function appendFilePart(state: ExtractionState, part: UnknownRecord): void {
404
+ if (remoteUrlFromPart(part)) {
405
+ state.error = unsupportedImageInput(
406
+ "remote image/file URLs are not supported in image generation mode",
407
+ );
408
+ return;
409
+ }
410
+ const existing = existingRefFromPart(part);
411
+ const input = normalizeUploadFileInput(part);
412
+ if (existing && !(input && input.b64 != null)) {
413
+ state.slots.push({ type: "existing", ref: existing });
414
+ return;
415
+ }
416
+ if (!input || input.b64 == null) {
417
+ state.error = unsupportedImageInput(
418
+ "image generation file input must be an inline payload or existing file reference",
419
+ );
420
+ return;
421
+ }
422
+ let bytes: Uint8Array;
423
+ try {
424
+ bytes = base64ToBytes(input.b64);
425
+ } catch (_) {
426
+ state.error = unsupportedImageInput("invalid file base64 payload");
427
+ return;
428
+ }
429
+ const detected = detectUploadMimeFromBytes(bytes);
430
+ if (!normalizeMimeType(detected).startsWith("image/")) {
431
+ state.error = unsupportedImageInput(
432
+ "image generation file input bytes are not a supported image",
433
+ );
434
+ return;
435
+ }
436
+ const mime = firstNonEmptyString(
437
+ detected,
438
+ input.mime,
439
+ uploadMimeFromObject(part),
440
+ "image/png",
441
+ );
442
+ const candidate: AttachmentCandidate = {
443
+ id: `att_${state.nextID}`,
444
+ kind: "image",
445
+ role: "request",
446
+ source: { type: "bytes", bytes },
447
+ };
448
+ const filename = firstNonEmptyString(
449
+ sanitizeUploadFilename(input.filename),
450
+ uploadFilenameFromObject(part),
451
+ imageFilenameFromMime(mime, state.nextID),
452
+ );
453
+ if (filename) candidate.filename = filename;
454
+ if (mime) candidate.mime = mime;
455
+ addCandidateSlot(state, candidate);
456
+ }
457
+
458
+ function imageCandidateFromPart(
459
+ part: UnknownRecord,
460
+ nextID: number,
461
+ ): { candidate: AttachmentCandidate } | { error: ImageGenerationPrepareError } {
462
+ const parsed = imagePayloadFromPart(part);
463
+ if (!parsed)
464
+ return {
465
+ error: unsupportedImageInput(
466
+ "image input must be an inline image payload or existing file reference",
467
+ ),
468
+ };
469
+ let bytes: Uint8Array;
470
+ try {
471
+ bytes = base64ToBytes(parsed.b64);
472
+ } catch (_) {
473
+ return { error: unsupportedImageInput("invalid image base64 payload") };
474
+ }
475
+ const detected = detectUploadMimeFromBytes(bytes);
476
+ if (!normalizeMimeType(detected).startsWith("image/")) {
477
+ return {
478
+ error: unsupportedImageInput(
479
+ "image input bytes are not a supported image",
480
+ ),
481
+ };
482
+ }
483
+ const mime = firstNonEmptyString(
484
+ detected,
485
+ parsed.mime,
486
+ uploadMimeFromObject(part),
487
+ "image/png",
488
+ );
489
+ const candidate: AttachmentCandidate = {
490
+ id: `att_${nextID}`,
491
+ kind: "image",
492
+ role: "request",
493
+ source: { type: "bytes", bytes },
494
+ };
495
+ const filename = firstNonEmptyString(
496
+ imageFilenameFromObject(part),
497
+ imageFilenameFromMime(mime, nextID),
498
+ );
499
+ if (filename) candidate.filename = filename;
500
+ if (mime) candidate.mime = mime;
501
+ return { candidate };
502
+ }
503
+
504
+ function imagePayloadFromPart(
505
+ part: UnknownRecord,
506
+ ): { b64: unknown; mime: string } | null {
507
+ const source = isRecord(part.source) ? part.source : null;
508
+ if (source && source.data != null) {
509
+ return {
510
+ b64: source.data,
511
+ mime: firstNonEmptyString(
512
+ uploadMimeFromObject(part),
513
+ source.media_type,
514
+ source.mime_type,
515
+ source.mimeType,
516
+ "image/png",
517
+ ),
518
+ };
519
+ }
520
+ const imageUrl = part.image_url != null ? part.image_url : part.url;
521
+ const rawUrl = isRecord(imageUrl) ? imageUrl.url : imageUrl;
522
+ const parsed = parseImageUrl(rawUrl, uploadMimeFromObject(part));
523
+ if (parsed) return parsed;
524
+ return null;
525
+ }
526
+
527
+ function hasImageInlinePayload(part: UnknownRecord): boolean {
528
+ const source = isRecord(part.source) ? part.source : null;
529
+ if (source && source.data != null) return true;
530
+ const imageUrl = part.image_url != null ? part.image_url : part.url;
531
+ const rawUrl = isRecord(imageUrl) ? imageUrl.url : imageUrl;
532
+ return typeof rawUrl === "string" && /^data:/i.test(rawUrl.trim());
533
+ }
534
+
535
+ function addCandidateSlot(
536
+ state: ExtractionState,
537
+ candidate: AttachmentCandidate,
538
+ ): void {
539
+ if (state.candidates.length >= MAX_ATTACHMENTS_PER_REQUEST) {
540
+ state.error = {
541
+ message: `image generation supports at most ${MAX_ATTACHMENTS_PER_REQUEST} user attachments`,
542
+ status: 400,
543
+ code: "image_input_unsupported",
544
+ };
545
+ return;
546
+ }
547
+ const index = state.candidates.length;
548
+ state.candidates.push(candidate);
549
+ state.slots.push({ type: "candidate", index });
550
+ state.nextID += 1;
551
+ }
552
+
553
+ async function resolveImageGenerationFileRefs(
554
+ provider: CompletionProvider,
555
+ state: ExtractionState,
556
+ ): Promise<
557
+ { fileRefs: FileRef[] | null } | { error: ImageGenerationPrepareError }
558
+ > {
559
+ if (
560
+ !state.candidates.length &&
561
+ !state.slots.some((slot) => slot.type === "existing")
562
+ )
563
+ return { fileRefs: null };
564
+ const plan: AttachmentPlan = {
565
+ candidates: state.candidates,
566
+ existingFileRefs: state.slots
567
+ .filter(
568
+ (slot): slot is { type: "existing"; ref: AttachmentFileRef } =>
569
+ slot.type === "existing",
570
+ )
571
+ .map((slot) => slot.ref),
572
+ dropped: [],
573
+ maxFiles: MAX_ATTACHMENTS_PER_REQUEST,
574
+ };
575
+ let result: AttachmentResolutionResult;
576
+ try {
577
+ result = await provider.resolveAttachments(plan);
578
+ } catch (e) {
579
+ return {
580
+ error: {
581
+ message: `failed to upload image generation input: ${upstreamErrorMessage(e)}`,
582
+ status: upstreamErrorStatus(e) || 502,
583
+ code: upstreamErrorCode(e) || "image_input_upload_failed",
584
+ },
585
+ };
586
+ }
587
+ const uploaded = result.fileRefs || [];
588
+ const out: FileRef[] = [];
589
+ for (const slot of state.slots) {
590
+ if (slot.type === "existing") {
591
+ out.push(slot.ref);
592
+ continue;
593
+ }
594
+ const ref = uploaded[slot.index];
595
+ if (!ref) {
596
+ return {
597
+ error: {
598
+ message: "failed to upload image generation input",
599
+ status: 502,
600
+ code: "image_input_upload_failed",
601
+ },
602
+ };
603
+ }
604
+ out.push(ref);
605
+ }
606
+ return { fileRefs: out.length ? out : null };
607
+ }
608
+
609
+ function existingRefFromPart(part: UnknownRecord): AttachmentFileRef | null {
610
+ const id =
611
+ part.file_id ?? part.fileId ?? part.file_ref ?? part.fileRef ?? part.ref;
612
+ if (id == null) {
613
+ const file = isRecord(part.file) ? part.file : null;
614
+ const nested = file
615
+ ? (file.file_id ??
616
+ file.fileId ??
617
+ file.file_ref ??
618
+ file.fileRef ??
619
+ file.ref ??
620
+ file.id)
621
+ : null;
622
+ if (nested == null) return null;
623
+ const name = firstNonEmptyString(
624
+ uploadFilenameFromObject(file),
625
+ uploadFilenameFromObject(part),
626
+ );
627
+ return name ? { id: String(nested), name } : String(nested);
628
+ }
629
+ const name = uploadFilenameFromObject(part);
630
+ return name ? { id: String(id), name } : String(id);
631
+ }
632
+
633
+ function remoteUrlFromPart(part: UnknownRecord): string {
634
+ const direct = firstNonEmptyString(part.url, part.file_url, part.fileUrl);
635
+ if (isRemoteUrl(direct)) return direct;
636
+ const source = isRecord(part.source) ? part.source : null;
637
+ const sourceUrl = source
638
+ ? firstNonEmptyString(
639
+ source.url,
640
+ source.file_url,
641
+ source.fileUrl,
642
+ source.file_uri,
643
+ source.fileUri,
644
+ )
645
+ : "";
646
+ if (isRemoteUrl(sourceUrl)) return sourceUrl;
647
+ const imageUrl = isRecord(part.image_url) ? part.image_url : null;
648
+ if (imageUrl && isRemoteUrl(imageUrl.url)) return String(imageUrl.url);
649
+ const file = isRecord(part.file) ? part.file : null;
650
+ const fileUrl = file
651
+ ? firstNonEmptyString(file.url, file.file_url, file.fileUrl)
652
+ : "";
653
+ if (isRemoteUrl(fileUrl)) return fileUrl;
654
+ const fileData = firstRecord(part.fileData, part.file_data);
655
+ const nestedUrl = fileData
656
+ ? firstNonEmptyString(fileData.url, fileData.file_uri, fileData.fileUri)
657
+ : "";
658
+ return isRemoteUrl(nestedUrl) ? nestedUrl : "";
659
+ }
660
+
661
+ function isRemoteUrl(value: unknown): boolean {
662
+ return typeof value === "string" && /^https?:\/\//i.test(value.trim());
663
+ }
664
+
665
+ function unsupportedImageInput(message: string): ImageGenerationPrepareError {
666
+ return { message, status: 400, code: "image_input_unsupported" };
667
+ }
668
+
669
+ function normalizedType(value: unknown): string {
670
+ return String(value || "")
671
+ .trim()
672
+ .toLowerCase();
673
+ }
674
+
675
+ function isImagePartType(typ: string): boolean {
676
+ return typ === "image_url" || typ === "image" || typ === "input_image";
677
+ }
678
+
679
+ function isFilePartType(typ: string): boolean {
680
+ return typ === "input_file" || typ === "file";
681
+ }
src/completion/index.ts ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export {
2
+ EMPTY_UPSTREAM_MSG,
3
+ finalizeOpenAICompletionResult,
4
+ upstreamEmptyWarning,
5
+ } from "./turn";
6
+ export type {
7
+ CompletionProvider,
8
+ CompletionProviderOptions,
9
+ CompletionRichOutput,
10
+ CompletionTextInput,
11
+ GeneratedImage,
12
+ } from "./ports";
13
+ export type {
14
+ CompletionStreamEvent,
15
+ CompletionStreamLifecycle,
16
+ } from "./runtime";
17
+ export {
18
+ createCompletionStreamLifecycle,
19
+ recordCompletionStreamEvent,
20
+ streamBufferedToolTextCompletionEvents,
21
+ streamPlainCompletionEvents,
22
+ streamToolSieveCompletionEvents,
23
+ } from "./runtime";
src/completion/openai.ts ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { RuntimeConfig } from "../config";
2
+ import type { CompletionProvider } from "./ports";
3
+ import { resolveModel } from "../models";
4
+ import type { ResolvedModel } from "../models";
5
+ import {
6
+ getStructuredResponseFormat,
7
+ buildStructuredOutputRequirement,
8
+ } from "../toolcall/structured";
9
+ import {
10
+ buildToolChoiceInstructionFromPolicy,
11
+ parseOpenAIToolChoicePolicy,
12
+ } from "../toolcall/policy-openai";
13
+ import type { ToolChoicePolicy } from "../toolcall/policy-openai";
14
+ import {
15
+ createToolBundle,
16
+ filterToolBundleByPolicy,
17
+ } from "../toolcall/tool-bundle";
18
+ import { log } from "../shared/logging";
19
+ import {
20
+ upstreamErrorCode,
21
+ upstreamErrorMessage,
22
+ upstreamErrorStatus,
23
+ } from "../shared/errors";
24
+ import { prepareOpenAIGeminiContext } from "./context";
25
+ import { ensureInlineToolPrompt } from "./tool-prompt-guard";
26
+ import type { ContextFileResult, FileRef, LooseRequest } from "./types";
27
+ import { hasCompletionError } from "./types";
28
+
29
+ export type OpenAICompletionPrepareError = {
30
+ message: string;
31
+ status: number;
32
+ code?: string;
33
+ };
34
+
35
+ export type PreparedOpenAICompletion = {
36
+ rm: Extract<ResolvedModel, { name: string }>;
37
+ structured: unknown;
38
+ allTools: unknown[];
39
+ tools: unknown[] | null;
40
+ toolPolicy: ToolChoicePolicy;
41
+ promptToolChoice: "none" | "required" | "auto";
42
+ prompt: string;
43
+ fileRefs: FileRef[] | null;
44
+ promptTokens: number;
45
+ contextFiles: ContextFileResult | null;
46
+ };
47
+
48
+ export type PrepareOpenAICompletionOptions = {
49
+ emptyPromptMessage: string;
50
+ };
51
+
52
+ export async function prepareOpenAICompletion(
53
+ cfg: RuntimeConfig,
54
+ provider: CompletionProvider,
55
+ req: LooseRequest,
56
+ messages: unknown,
57
+ toolsRaw: unknown,
58
+ options: PrepareOpenAICompletionOptions,
59
+ ): Promise<PreparedOpenAICompletion | { error: OpenAICompletionPrepareError }> {
60
+ const rm = resolveModel(req.model, cfg.default_model);
61
+ if (rm.name === undefined) {
62
+ log(
63
+ cfg,
64
+ `openai completion model rejected model=${String(req.model ?? "(default)")}`,
65
+ );
66
+ return {
67
+ error: { message: rm.error, status: 400, code: "model_not_found" },
68
+ };
69
+ }
70
+
71
+ const structured = buildStructuredOutputRequirement(
72
+ getStructuredResponseFormat(req),
73
+ );
74
+ if (structured?.error) {
75
+ return {
76
+ error: {
77
+ message: structured.error,
78
+ status: 400,
79
+ code: "invalid_response_format",
80
+ },
81
+ };
82
+ }
83
+
84
+ const toolBundle = createToolBundle(toolsRaw);
85
+ const toolPolicy = parseOpenAIToolChoicePolicy(
86
+ req.tool_choice != null ? req.tool_choice : "auto",
87
+ toolBundle,
88
+ );
89
+ if (toolPolicy.error)
90
+ return {
91
+ error: {
92
+ message: toolPolicy.error,
93
+ status: 400,
94
+ code: "invalid_tool_choice",
95
+ },
96
+ };
97
+
98
+ const filteredToolBundle = filterToolBundleByPolicy(toolBundle, toolPolicy);
99
+ const allTools = toolBundle.openAIFunctionTools;
100
+ const tools = filteredToolBundle.openAIFunctionTools.length
101
+ ? filteredToolBundle.openAIFunctionTools
102
+ : null;
103
+ let promptToolChoice: "auto" | "none" | "required" = "auto";
104
+ if (toolPolicy.mode === "none") promptToolChoice = "none";
105
+ else if (toolPolicy.mode === "required" || toolPolicy.mode === "forced")
106
+ promptToolChoice = "required";
107
+ const ctx = await prepareOpenAIGeminiContext(
108
+ cfg,
109
+ provider,
110
+ req,
111
+ messages,
112
+ filteredToolBundle,
113
+ promptToolChoice,
114
+ toolPolicy,
115
+ structured,
116
+ );
117
+ if (hasCompletionError(ctx)) {
118
+ const code = upstreamErrorCode(ctx.error);
119
+ const error: OpenAICompletionPrepareError = {
120
+ message: upstreamErrorMessage(ctx.error),
121
+ status: upstreamErrorStatus(ctx.error) || 502,
122
+ };
123
+ if (code) error.code = code;
124
+ return {
125
+ error,
126
+ };
127
+ }
128
+ let { prompt } = ctx;
129
+ const { fileRefs, promptTokens, contextFiles } = ctx;
130
+ let promptToolSource: unknown = [];
131
+ if (toolPolicy.mode !== "none") {
132
+ promptToolSource = filteredToolBundle.defs.length
133
+ ? filteredToolBundle
134
+ : toolBundle;
135
+ }
136
+ prompt = ensureInlineToolPrompt(
137
+ prompt,
138
+ promptToolSource,
139
+ buildToolChoiceInstructionFromPolicy(toolPolicy),
140
+ contextFiles,
141
+ ctx.promptMetadata,
142
+ );
143
+ if (!String(prompt || "").trim())
144
+ return { error: { message: options.emptyPromptMessage, status: 400 } };
145
+
146
+ return {
147
+ rm,
148
+ structured,
149
+ allTools,
150
+ tools,
151
+ toolPolicy,
152
+ promptToolChoice,
153
+ prompt,
154
+ fileRefs,
155
+ promptTokens,
156
+ contextFiles,
157
+ };
158
+ }
src/completion/ports.ts ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { ResolvedModel } from "../models";
2
+ import type { AttachmentPlan } from "../attachments/types";
3
+ import type { AttachmentResolutionResult, FileRef } from "./types";
4
+
5
+ export type CompletionTextInput = {
6
+ prompt: string;
7
+ rm: ResolvedModel;
8
+ fileRefs?: FileRef[] | null;
9
+ };
10
+
11
+ export type GeneratedImage = {
12
+ url: string;
13
+ source: "generated" | "web";
14
+ title?: string;
15
+ alt?: string;
16
+ imageId?: string;
17
+ cid?: string;
18
+ rid?: string;
19
+ rcid?: string;
20
+ base64?: string;
21
+ outputFormat?: "png" | "jpeg" | "gif" | "webp";
22
+ };
23
+
24
+ export type CompletionRichOutput = {
25
+ text: string;
26
+ images: GeneratedImage[];
27
+ };
28
+
29
+ export type CompletionProviderOptions = {
30
+ signal?: AbortSignal;
31
+ };
32
+
33
+ export type CompletionRichOptions = {
34
+ hydrateGeneratedImageBytes?: boolean;
35
+ };
36
+
37
+ export type CompletionProvider = {
38
+ supportsAuthenticatedSession?: boolean;
39
+ generateText(input: CompletionTextInput): Promise<string>;
40
+ generateRich?(
41
+ input: CompletionTextInput,
42
+ options?: CompletionRichOptions,
43
+ ): Promise<CompletionRichOutput>;
44
+ streamText(
45
+ input: CompletionTextInput,
46
+ options?: CompletionProviderOptions,
47
+ ): AsyncIterable<string>;
48
+ resolveAttachments(plan: AttachmentPlan): Promise<AttachmentResolutionResult>;
49
+ uploadTextFile(text: string, filename: string): Promise<FileRef>;
50
+ dispose?(): void | Promise<void>;
51
+ };
src/completion/runtime.ts ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export type { StreamConsumeOptions } from "./stream-coalesce";
2
+ export type {
3
+ CompletionStreamEvent,
4
+ CompletionStreamLifecycle,
5
+ GeminiCompletionInput,
6
+ } from "./stream-events";
7
+ export {
8
+ createCompletionStreamLifecycle,
9
+ streamBufferedToolTextCompletionEvents,
10
+ streamPlainCompletionEvents,
11
+ streamToolSieveCompletionEvents,
12
+ recordCompletionStreamEvent,
13
+ } from "./stream-events";
src/completion/stream-coalesce.ts ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { codePointLengthAtLeast } from "../shared/tokens";
2
+ import { isAbortError } from "../shared/abort";
3
+ import type {
4
+ CompletionProvider,
5
+ CompletionProviderOptions,
6
+ CompletionTextInput,
7
+ } from "./ports";
8
+
9
+ export type StreamConsumeOptions = CompletionProviderOptions;
10
+
11
+ export type TextDeltaCoalesceOptions = {
12
+ coalesceTextDeltas?: boolean;
13
+ minCoalescedTextChars?: number;
14
+ maxCoalescedTextWaitMs?: number;
15
+ };
16
+
17
+ export type StreamConsumeInternalOptions = StreamConsumeOptions &
18
+ TextDeltaCoalesceOptions;
19
+
20
+ type CoalescedTextRaceResult =
21
+ | { type: "next"; value: IteratorResult<unknown> }
22
+ | { type: "timer" };
23
+
24
+ const MIN_COALESCED_TEXT_DELTA_CHARS = 64;
25
+ const MAX_COALESCED_TEXT_DELTA_WAIT_MS = 20;
26
+
27
+ function streamCompletionText(
28
+ provider: CompletionProvider,
29
+ input: CompletionTextInput,
30
+ options: StreamConsumeOptions = {},
31
+ ) {
32
+ const providerOptions: CompletionProviderOptions = {};
33
+ if (options.signal) providerOptions.signal = options.signal;
34
+ return provider.streamText(input, providerOptions);
35
+ }
36
+
37
+ async function* coalesceTextDeltas(
38
+ deltas: AsyncIterable<unknown>,
39
+ options: TextDeltaCoalesceOptions = {},
40
+ ): AsyncIterable<string> {
41
+ const minChars = positiveCoalesceNumber(
42
+ options.minCoalescedTextChars,
43
+ MIN_COALESCED_TEXT_DELTA_CHARS,
44
+ );
45
+ const maxWaitMs = nonNegativeCoalesceNumber(
46
+ options.maxCoalescedTextWaitMs,
47
+ MAX_COALESCED_TEXT_DELTA_WAIT_MS,
48
+ );
49
+ const iterator = deltas[Symbol.asyncIterator]();
50
+ let next = iterator.next();
51
+ let pending = "";
52
+ let timer: Promise<CoalescedTextRaceResult> | null = null;
53
+ let firstText = true;
54
+
55
+ const scheduleTimer = () => {
56
+ if (!timer && maxWaitMs > 0)
57
+ timer = new Promise((resolve) =>
58
+ setTimeout(() => resolve({ type: "timer" }), maxWaitMs),
59
+ );
60
+ };
61
+ const flush = () => {
62
+ const out = pending;
63
+ pending = "";
64
+ timer = null;
65
+ return out;
66
+ };
67
+
68
+ try {
69
+ while (true) {
70
+ const nextResult: Promise<CoalescedTextRaceResult> = next.then(
71
+ (value) => ({ type: "next", value }),
72
+ );
73
+ const result: CoalescedTextRaceResult = timer
74
+ ? await Promise.race([nextResult, timer])
75
+ : await nextResult;
76
+
77
+ if (result.type === "timer") {
78
+ if (pending) yield flush();
79
+ continue;
80
+ }
81
+
82
+ const item = result.value;
83
+ if (item.done) {
84
+ if (pending) yield flush();
85
+ return;
86
+ }
87
+ next = iterator.next();
88
+
89
+ const text = String(item.value || "");
90
+ if (!text) continue;
91
+ if (firstText) {
92
+ firstText = false;
93
+ yield text;
94
+ continue;
95
+ }
96
+
97
+ pending += text;
98
+ if (codePointLengthAtLeast(pending, minChars)) {
99
+ yield flush();
100
+ } else {
101
+ scheduleTimer();
102
+ }
103
+ }
104
+ } catch (e) {
105
+ if (!isAbortError(e) && pending) yield flush();
106
+ throw e;
107
+ } finally {
108
+ if (iterator.return) {
109
+ try {
110
+ await iterator.return();
111
+ } catch (_) {}
112
+ }
113
+ }
114
+ }
115
+
116
+ export function completionTextDeltas(
117
+ provider: CompletionProvider,
118
+ input: CompletionTextInput,
119
+ options: StreamConsumeInternalOptions = {},
120
+ ): AsyncIterable<unknown> {
121
+ const deltas = streamCompletionText(provider, input, options);
122
+ return options.coalesceTextDeltas
123
+ ? coalesceTextDeltas(deltas, options)
124
+ : deltas;
125
+ }
126
+
127
+ function positiveCoalesceNumber(value: unknown, fallback: number): number {
128
+ const n = Math.floor(Number(value));
129
+ return Number.isFinite(n) && n > 0 ? n : fallback;
130
+ }
131
+
132
+ function nonNegativeCoalesceNumber(value: unknown, fallback: number): number {
133
+ const n = Math.floor(Number(value));
134
+ return Number.isFinite(n) && n >= 0 ? n : fallback;
135
+ }
src/completion/stream-events.ts ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { createTokenCounter, emptyTokenCounts } from "../shared/tokens";
2
+ import type { TokenCharCounts } from "../shared/tokens";
3
+ import { isAbortError } from "../shared/abort";
4
+ import {
5
+ createToolSieveState,
6
+ flushToolSieve,
7
+ processToolSieveChunk,
8
+ toolSieveBufferedText,
9
+ } from "../toolstream";
10
+ import { validateRequiredToolCalls } from "../toolcall/policy-openai";
11
+ import type { CompletionProvider, CompletionTextInput } from "./ports";
12
+ import type { OpenAIToolCall } from "../toolcall/openai-format";
13
+ import type {
14
+ ToolChoicePolicy,
15
+ ToolPolicyViolation,
16
+ } from "../toolcall/policy-openai";
17
+ import { completionTextDeltas } from "./stream-coalesce";
18
+ import type { StreamConsumeInternalOptions } from "./stream-coalesce";
19
+
20
+ export type GeminiCompletionInput = CompletionTextInput;
21
+
22
+ export type CompletionStreamEvent =
23
+ | { type: "text_delta"; text: string }
24
+ | { type: "buffered_text"; text: string }
25
+ | { type: "tool_calls"; toolCalls: OpenAIToolCall[] }
26
+ | { type: "tool_policy_violation"; violation: ToolPolicyViolation }
27
+ | { type: "warning"; error: unknown; message: string }
28
+ | { type: "stream_error"; error: unknown; message: string }
29
+ | { type: "empty" }
30
+ | {
31
+ type: "done";
32
+ emittedText: boolean;
33
+ completionTokens: number;
34
+ completionCounts: TokenCharCounts & { hasText: boolean };
35
+ };
36
+
37
+ export type CompletionStreamLifecycle = {
38
+ emittedText: boolean;
39
+ empty: boolean;
40
+ issue: Extract<
41
+ CompletionStreamEvent,
42
+ { type: "warning" } | { type: "stream_error" }
43
+ > | null;
44
+ toolCalls: OpenAIToolCall[] | null;
45
+ violation: ToolPolicyViolation | null;
46
+ completionCounts: TokenCharCounts & { hasText: boolean };
47
+ };
48
+
49
+ export function createCompletionStreamLifecycle(): CompletionStreamLifecycle {
50
+ return {
51
+ emittedText: false,
52
+ empty: false,
53
+ issue: null,
54
+ toolCalls: null,
55
+ violation: null,
56
+ completionCounts: emptyTokenCounts(),
57
+ };
58
+ }
59
+
60
+ export function recordCompletionStreamEvent(
61
+ lifecycle: CompletionStreamLifecycle,
62
+ event: CompletionStreamEvent,
63
+ ): void {
64
+ switch (event.type) {
65
+ case "text_delta":
66
+ case "buffered_text":
67
+ lifecycle.emittedText ||= !!event.text;
68
+ break;
69
+ case "warning":
70
+ case "stream_error":
71
+ lifecycle.issue = event;
72
+ break;
73
+ case "tool_calls":
74
+ lifecycle.toolCalls = event.toolCalls;
75
+ break;
76
+ case "tool_policy_violation":
77
+ lifecycle.violation = event.violation;
78
+ break;
79
+ case "empty":
80
+ lifecycle.empty = true;
81
+ break;
82
+ case "done":
83
+ lifecycle.emittedText ||= event.emittedText;
84
+ lifecycle.completionCounts = event.completionCounts;
85
+ }
86
+ }
87
+
88
+ export async function* streamPlainCompletionEvents(
89
+ provider: CompletionProvider,
90
+ input: GeminiCompletionInput,
91
+ options: StreamConsumeInternalOptions = {},
92
+ ): AsyncIterable<CompletionStreamEvent> {
93
+ let emittedText = false;
94
+ let streamErr: unknown = null;
95
+ const completionTokenCounter = createTokenCounter();
96
+
97
+ try {
98
+ for await (const delta of completionTextDeltas(provider, input, options)) {
99
+ if (!delta) continue;
100
+ const text = String(delta);
101
+ if (!text) continue;
102
+ emittedText = true;
103
+ completionTokenCounter.append(text);
104
+ yield { type: "text_delta", text };
105
+ }
106
+ } catch (e) {
107
+ if (isAbortError(e)) throw e;
108
+ streamErr = e;
109
+ }
110
+
111
+ if (streamErr) {
112
+ yield streamErrorEvent(streamErr, emittedText);
113
+ } else if (!emittedText) {
114
+ yield { type: "empty" };
115
+ }
116
+ yield {
117
+ type: "done",
118
+ emittedText,
119
+ completionTokens: completionTokenCounter.tokens(),
120
+ completionCounts: completionTokenCounter.counts(),
121
+ };
122
+ }
123
+
124
+ export async function* streamToolSieveCompletionEvents(
125
+ provider: CompletionProvider,
126
+ input: GeminiCompletionInput & {
127
+ tools: unknown;
128
+ toolPolicy?: ToolChoicePolicy | null | undefined;
129
+ },
130
+ options: StreamConsumeInternalOptions = {},
131
+ ): AsyncIterable<CompletionStreamEvent> {
132
+ const state = createToolSieveState();
133
+ let emittedText = false;
134
+ let streamErr: unknown = null;
135
+ const completionTokenCounter = createTokenCounter();
136
+
137
+ try {
138
+ for await (const deltaText of completionTextDeltas(
139
+ provider,
140
+ input,
141
+ options,
142
+ )) {
143
+ for (const text of processToolSieveChunk(state, deltaText)) {
144
+ if (!text) continue;
145
+ emittedText = true;
146
+ completionTokenCounter.append(text);
147
+ yield { type: "text_delta", text };
148
+ }
149
+ }
150
+ } catch (e) {
151
+ if (isAbortError(e)) throw e;
152
+ streamErr = e;
153
+ }
154
+
155
+ const flushed = flushToolSieve(state, input.tools);
156
+ if (flushed.text) {
157
+ emittedText = true;
158
+ completionTokenCounter.append(flushed.text);
159
+ yield { type: "text_delta", text: flushed.text };
160
+ }
161
+ const toolCalls = flushed.toolCalls;
162
+ const violation = validateRequiredToolCalls(input.toolPolicy, toolCalls);
163
+
164
+ if (streamErr)
165
+ yield streamErrorEvent(streamErr, emittedText || !!toolCalls?.length);
166
+ if (violation) yield { type: "tool_policy_violation", violation };
167
+ if (toolCalls?.length) yield { type: "tool_calls", toolCalls };
168
+ if (!streamErr && !emittedText && !toolCalls?.length) yield { type: "empty" };
169
+ yield {
170
+ type: "done",
171
+ emittedText,
172
+ completionTokens: completionTokenCounter.tokens(),
173
+ completionCounts: completionTokenCounter.counts(),
174
+ };
175
+ }
176
+
177
+ export async function* streamBufferedToolTextCompletionEvents(
178
+ provider: CompletionProvider,
179
+ input: GeminiCompletionInput,
180
+ options: StreamConsumeInternalOptions = {},
181
+ ): AsyncIterable<CompletionStreamEvent> {
182
+ const state = createToolSieveState();
183
+ let emittedText = false;
184
+ let streamErr: unknown = null;
185
+ const completionTokenCounter = createTokenCounter();
186
+
187
+ try {
188
+ for await (const deltaText of completionTextDeltas(
189
+ provider,
190
+ input,
191
+ options,
192
+ )) {
193
+ for (const text of processToolSieveChunk(state, deltaText)) {
194
+ if (!text) continue;
195
+ emittedText = true;
196
+ completionTokenCounter.append(text);
197
+ yield { type: "text_delta", text };
198
+ }
199
+ }
200
+ } catch (e) {
201
+ if (isAbortError(e)) throw e;
202
+ streamErr = e;
203
+ }
204
+
205
+ const bufferedText = toolSieveBufferedText(state);
206
+ if (bufferedText) yield { type: "buffered_text", text: bufferedText };
207
+ if (streamErr) {
208
+ yield streamErrorEvent(streamErr, emittedText);
209
+ } else if (!emittedText && !bufferedText) {
210
+ yield { type: "empty" };
211
+ }
212
+ yield {
213
+ type: "done",
214
+ emittedText,
215
+ completionTokens: completionTokenCounter.tokens(),
216
+ completionCounts: completionTokenCounter.counts(),
217
+ };
218
+ }
219
+
220
+ function streamErrorEvent(
221
+ error: unknown,
222
+ afterPartialOutput: boolean,
223
+ ): CompletionStreamEvent {
224
+ return {
225
+ type: afterPartialOutput ? "warning" : "stream_error",
226
+ error,
227
+ message: errorMessage(error),
228
+ };
229
+ }
230
+
231
+ function errorMessage(error: unknown): string {
232
+ return String(
233
+ error && typeof error === "object" && "message" in error
234
+ ? (error as { message?: unknown }).message
235
+ : error,
236
+ );
237
+ }