MD Mahadi commited on
Commit
c7ba288
·
1 Parent(s): f553d1f

Deploy OmniRoute gateway on Hugging Face Docker Space with dataset persistence

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 +5 -16
  2. .gitignore +1 -0
  3. Dockerfile +37 -57
  4. README.md +16 -11
  5. cli/LICENSE +0 -21
  6. cli/README.md +0 -117
  7. cli/eslint.config.js +0 -28
  8. cli/package.json +0 -77
  9. cli/src/__snapshots__/tools.test.ts.snap +0 -1009
  10. cli/src/config-files.test.ts +0 -582
  11. cli/src/config-files.ts +0 -449
  12. cli/src/detect.test.ts +0 -78
  13. cli/src/detect.ts +0 -83
  14. cli/src/doctor.test.ts +0 -399
  15. cli/src/doctor.ts +0 -508
  16. cli/src/index.test.ts +0 -271
  17. cli/src/index.ts +0 -534
  18. cli/src/keys.test.ts +0 -210
  19. cli/src/keys.ts +0 -184
  20. cli/src/models.test.ts +0 -81
  21. cli/src/models.ts +0 -81
  22. cli/src/tools.test.ts +0 -709
  23. cli/src/tools.ts +0 -1173
  24. cli/src/types.ts +0 -59
  25. cli/tools.json +0 -23
  26. cli/tsconfig.json +0 -17
  27. client/.gitignore +0 -24
  28. client/README.md +0 -73
  29. client/components.json +0 -25
  30. client/dev/mockApi.ts +0 -152
  31. client/eslint.config.js +0 -23
  32. client/index.html +0 -36
  33. client/package.json +0 -59
  34. client/public/favicon.svg +0 -9
  35. client/public/icons.svg +0 -24
  36. client/scripts/check-i18n.mjs +0 -88
  37. client/src/App.test.ts +0 -38
  38. client/src/App.tsx +0 -522
  39. client/src/assets/vite.svg +0 -1
  40. client/src/components/agent-icons.tsx +0 -391
  41. client/src/components/api-usage.tsx +0 -26
  42. client/src/components/auth-gate.desktop-browser.test.tsx +0 -93
  43. client/src/components/auth-gate.desktop.test.tsx +0 -182
  44. client/src/components/auth-gate.login-identifier.test.tsx +0 -121
  45. client/src/components/auth-gate.reset-signs-in.test.tsx +0 -124
  46. client/src/components/auth-gate.tsx +0 -547
  47. client/src/components/chain-manager.test.ts +0 -116
  48. client/src/components/chain-manager.tsx +0 -328
  49. client/src/components/code-block.tsx +0 -24
  50. client/src/components/command-palette-state.ts +0 -5
.dockerignore CHANGED
@@ -1,21 +1,10 @@
1
  .git
2
  .github
3
  node_modules
4
- client/node_modules
5
- server/node_modules
6
- shared/node_modules
7
- client/dist
8
- server/dist
9
- server/data
10
- dist
11
  .env
12
  .env.*
13
- *.db
14
- *.db-wal
15
- *.db-shm
16
- *.bak
17
- .encryption-key
18
- .DS_Store
19
- npm-debug.log*
20
- repo-assets
21
- free-ai-apis.pdf
 
1
  .git
2
  .github
3
  node_modules
4
+ *.log
 
 
 
 
 
 
5
  .env
6
  .env.*
7
+ *.sqlite*
8
+ *.db*
9
+ lost+found
10
+ __pycache__/
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ __pycache__/
Dockerfile CHANGED
@@ -1,65 +1,45 @@
1
  # syntax=docker/dockerfile:1.7
2
-
3
- ARG NODE_IMAGE=node:24.22.1-bookworm-slim
4
-
5
- FROM ${NODE_IMAGE} AS deps
6
- WORKDIR /app
7
-
8
- # better-sqlite3 is a native module; compiles from source via node-gyp with python3 + C++ toolchain
9
- RUN apt-get update \
10
- && apt-get install -y --no-install-recommends python3 make g++ \
11
- && rm -rf /var/lib/apt/lists/*
12
-
13
- COPY package.json package-lock.json ./
14
- COPY shared/package.json ./shared/
15
- COPY server/package.json ./server/
16
- COPY client/package.json ./client/
17
- COPY cli/package.json ./cli/
18
-
19
- RUN npm ci
20
-
21
- FROM deps AS build
22
- WORKDIR /app
23
-
24
- COPY . .
25
-
26
- RUN npm run build
27
- RUN npm prune --omit=dev
28
-
29
- FROM ${NODE_IMAGE} AS runtime
30
- WORKDIR /app
31
-
32
- ENV NODE_ENV=production
33
- ENV PORT=7860
34
- ENV HOST=0.0.0.0
35
- ENV ALLOWED_HOSTS=*
36
- ENV FREELLMAPI_INSTALL_METHOD=docker
37
- ENV FREEAPI_DB_PATH=/data/freellmapi.db
38
- ENV FREEAPI_DB_BACKUP_PATH=/data/backups/freellmapi.db.backup
39
- ENV FREEAPI_DB_DIR_HARDENING=0
40
- ENV TRUST_PROXY=true
41
-
42
- COPY --from=build --chown=node:node /app/package.json /app/package-lock.json ./
43
- COPY --from=build --chown=node:node /app/node_modules ./node_modules
44
- COPY --from=build --chown=node:node /app/server/node_modules ./server/node_modules
45
- COPY --from=build --chown=node:node /app/shared ./shared
46
- COPY --from=build --chown=node:node /app/server/package.json ./server/package.json
47
- COPY --from=build --chown=node:node /app/desktop/package.json ./desktop/package.json
48
- COPY --from=build --chown=node:node /app/server/dist ./server/dist
49
- COPY --from=build --chown=node:node /app/client/dist ./client/dist
50
-
51
- RUN mkdir -p /app/server/data /data /data/logs /data/backups \
52
- && chown -R node:node /app /data
53
-
54
- COPY --chmod=755 docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
55
 
56
  USER root
57
 
58
- ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
  EXPOSE 7860
61
 
62
- HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
63
- CMD node -e "fetch('http://127.0.0.1:' + (process.env.PORT || 7860) + '/api/ping').then((res) => { if (!res.ok) process.exit(1); }).catch(() => process.exit(1));"
 
 
64
 
65
- CMD ["node", "server/dist/index.js"]
 
1
  # syntax=docker/dockerfile:1.7
2
+ FROM diegosouzapw/omniroute:latest
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  USER root
5
 
6
+ # Install Python runtime, pip, sqlite3, and ca-certificates for dataset persistence sync
7
+ RUN apt-get update && apt-get install -y --no-install-recommends \
8
+ python3 \
9
+ python3-pip \
10
+ sqlite3 \
11
+ ca-certificates \
12
+ curl \
13
+ && rm -rf /var/lib/apt/lists/* \
14
+ && pip3 install --no-cache-dir --break-system-packages "huggingface_hub[cli]>=0.23.0"
15
+
16
+ # Prepare persistent data mount path and assign ownership to node user (UID 1000)
17
+ RUN mkdir -p /data /app/data \
18
+ && chown -R node:node /data /app/data \
19
+ && chmod -R 775 /data
20
+
21
+ # Deploy scripts
22
+ COPY --chown=node:node --chmod=755 sync.py /usr/local/bin/sync.py
23
+ COPY --chown=node:node --chmod=755 docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
24
+
25
+ # Hugging Face Spaces port, routing and storage configuration
26
+ ENV PORT=7860 \
27
+ DASHBOARD_PORT=7860 \
28
+ API_PORT=7860 \
29
+ HOSTNAME=0.0.0.0 \
30
+ APP_BIND_HOST=0.0.0.0 \
31
+ DATA_DIR=/data \
32
+ NODE_ENV=production \
33
+ HF_DATASET_REPO=userbymahadi/OmniRoute-storage
34
+
35
+ # Switch to standard non-root user (UID 1000) required by Hugging Face Spaces
36
+ USER node
37
 
38
  EXPOSE 7860
39
 
40
+ ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
41
+
42
+ HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
43
+ CMD node -e "fetch('http://127.0.0.1:' + (process.env.PORT || 7860) + '/healthz').then((res) => { if (!res.ok) process.exit(1); }).catch(() => process.exit(1));"
44
 
45
+ CMD ["node", "dev/run-standalone.mjs"]
README.md CHANGED
@@ -1,19 +1,24 @@
1
  ---
2
- title: FreeLLMAPI
3
- emoji: ⚡
4
- colorFrom: indigo
5
- colorTo: red
6
  sdk: docker
7
  app_port: 7860
8
  pinned: false
9
  ---
10
 
11
- # FreeLLMAPI on Hugging Face Spaces
12
 
13
- A unified reverse-proxy and router for free & paid LLM provider APIs with automatic failover, health probing, load balancing, and persistent storage.
14
 
15
- ## Features
16
- - **Persistent Storage**: SQLite database, tokens, encryption key, and logs persist in Hugging Face Bucket Storage (`userbymahadi/FreeLLMAPI-storage`) mounted at `/data`.
17
- - **Automatic Fallback Chain**: Zero-downtime routing across multiple LLM providers.
18
- - **Unified API Endpoint**: OpenAI-compatible API endpoint `/v1/chat/completions`.
19
- - **Health Probing**: Real-time status checks and latency measurement.
 
 
 
 
 
 
1
  ---
2
+ title: OmniRoute
3
+ emoji: 🔀
4
+ colorFrom: blue
5
+ colorTo: indigo
6
  sdk: docker
7
  app_port: 7860
8
  pinned: false
9
  ---
10
 
11
+ # OmniRoute on Hugging Face Spaces
12
 
13
+ OmniRoute is an open-source, production-grade AI gateway and intelligent multi-provider router with unified OpenAI-compatible endpoints, latency optimization, and automated failover.
14
 
15
+ ## Deployment Specifications
16
+ - **App & API Port**: `7860` (standard Hugging Face Docker port)
17
+ - **Persistent Data Directory**: `/data` (SQLite database, configuration, and API keys)
18
+ - **Cloud State Synchronization**: Automatically linked to dataset repository `userbymahadi/OmniRoute-storage`
19
+ - **Upstream Repository**: [cheaper-inference/OmniRoute](https://github.com/cheaper-inference/OmniRoute)
20
+ - **Official Docker Guide**: [OmniRoute DOCKER_GUIDE.md](https://github.com/cheaper-inference/OmniRoute/blob/release/v3.8.53/docs/guides/DOCKER_GUIDE.md)
21
+
22
+ ## Persistence Architecture
23
+ 1. **Hugging Face Hardware Persistent Storage**: If persistent storage is enabled in Space settings, `/data` is backed by dedicated volume storage.
24
+ 2. **Dataset Synchronization Daemon**: When `HF_TOKEN` is configured as a Secret, the container synchronizes all state (`storage.sqlite`, `server.env`) to the private dataset `userbymahadi/OmniRoute-storage` at startup, every 5 minutes during runtime, and upon graceful shutdown.
cli/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Tashfeen Ahmed
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.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/README.md DELETED
@@ -1,117 +0,0 @@
1
- # freellmapi
2
-
3
- Point your coding agent at a [FreeLLMAPI](https://github.com/tashfeenahmed/freellmapi)
4
- gateway in one command. The generators read the models your server is actually
5
- serving and write the config file each tool expects.
6
-
7
- ```bash
8
- npx freellmapi setup-claude --url http://localhost:3001 --api-key <your-key>
9
- ```
10
-
11
- No install step, no account. The unified API key comes from your FreeLLMAPI
12
- dashboard (or the tray popover in the desktop app).
13
-
14
- ## Commands
15
-
16
- | Command | Tool |
17
- | --- | --- |
18
- | `setup-claude` | Claude Code |
19
- | `setup-codex` | Codex CLI |
20
- | `setup-cline` | Cline |
21
- | `setup-continue` | Continue |
22
- | `setup-aider` | Aider |
23
- | `setup-opencode` | OpenCode |
24
- | `setup-goose` | Goose |
25
- | `setup-qwen` | Qwen Code |
26
- | `setup-roo` | Roo Code |
27
- | `setup-kilo` | Kilo Code |
28
- | `setup-crush` | Crush |
29
- | `setup-dsh` | DeepSeek Harness (`dsh`) |
30
- | `setup-mimo` | MiMo Code (`mimo`) |
31
- | `setup-atomcode` | AtomCode (`atomcode`) |
32
- | `setup-openclaw` | OpenClaw |
33
- | `setup-hermes` | Hermes Agent (`hermes`) |
34
- | `setup-pi` | Pi (`pi`) |
35
- | `setup-reasonix` | Reasonix (`reasonix`) |
36
- | `setup-zcode` | ZCode (`zcode`) |
37
- | `setup-cursor` | Cursor |
38
- | `setup-generic` | Any OpenAI-compatible client |
39
- | `launch` | Run Claude Code with credentials injected into the child process |
40
- | `launch-codex` | Run Codex the same way |
41
- | `list` | Print the supported tools and their base URLs |
42
- | `keys` | Add, list, remove, or test provider keys (`keys --help`) |
43
-
44
- ## Options
45
-
46
- | Flag | Meaning |
47
- | --- | --- |
48
- | `--url URL` | Gateway base URL (default `http://localhost:3001`) |
49
- | `--api-key KEY` | Unified API key |
50
- | `--profile NAME` | Name the generated profile/provider entry |
51
- | `--model ID` | Pin a specific model instead of the catalog default |
52
- | `--dry-run` | Print the diff and write nothing |
53
-
54
- `FREELLMAPI_URL` and `FREELLMAPI_API_KEY` work in place of `--url` / `--api-key`.
55
-
56
- ## Provider keys
57
-
58
- The `keys` commands use a **dashboard session token**. Set
59
- `FREELLMAPI_DASHBOARD_TOKEN`, or pass `--token TOKEN` to override it. This is the
60
- session returned by dashboard sign-in (stored in the signed-in browser's local
61
- storage as `freellmapi_dashboard_token`). The unified `--api-key` /
62
- `FREELLMAPI_API_KEY` used by coding agents cannot authenticate these commands.
63
- The CLI does not log in or persist the dashboard token.
64
-
65
- ```bash
66
- export FREELLMAPI_URL=http://localhost:3001
67
- export FREELLMAPI_DASHBOARD_TOKEN='<dashboard-session-token>'
68
-
69
- npx freellmapi keys add groq # hidden provider-key prompt
70
- npx freellmapi keys add groq --key '<key>' # non-interactive alternative
71
- npx freellmapi keys list
72
- npx freellmapi keys test groq # check every stored Groq key
73
- npx freellmapi keys test groq --id 7 # check one key
74
- npx freellmapi keys remove groq --id 7
75
- ```
76
-
77
- `keys list` prints each key's ID, platform, enabled chat model count,
78
- enabled/disabled state, and stored health status. Counts respect the key's model
79
- scope; custom keys count models registered to their endpoint. Credentials and
80
- masked keys are never printed. Use the IDs from this list when a platform has
81
- multiple keys: `remove` requires `--id` in that case, and also checks that the ID
82
- belongs to the requested platform. With one matching key, `--id` is optional.
83
-
84
- `add` saves the key and immediately validates it through the gateway. A failed or
85
- inconclusive check exits with code 1 and **leaves the key saved** for later testing
86
- or removal. `test` also exits with code 1 if any selected key is not healthy or the
87
- gateway cannot confirm its validity (for example, after a provider network
88
- failure). Successful commands exit with code 0; argument, authentication, and
89
- request errors exit with code 1. Validation uses the gateway's usual health
90
- checks, including its policy of disabling a key after repeated confirmed failures.
91
-
92
- Keyless providers skip the prompt. Custom endpoints need a URL and model
93
- registration, so create them in the dashboard; existing custom keys can be
94
- listed, tested, and removed here. Requests accept `--url` / `FREELLMAPI_URL` and
95
- `--timeout MS` (30,000 ms per request by default). `--dry-run` is not supported for
96
- `keys`; it is rejected before any request.
97
-
98
- ## Safety
99
-
100
- Every generator is non-destructive: it merges into your existing configuration
101
- rather than replacing it, and takes a timestamped backup before touching a file
102
- that already exists. `--dry-run` shows the exact diff first.
103
-
104
- The two `launch` commands never write credentials to disk at all — they inject
105
- them into the child process environment for that run only.
106
-
107
- ## Requirements
108
-
109
- Node.js >= 20.18. A running FreeLLMAPI gateway
110
- ([install guide](https://github.com/tashfeenahmed/freellmapi/blob/main/docs/en/install/01-install.md)).
111
-
112
- ## Links
113
-
114
- - [Clients & coding agents guide](https://github.com/tashfeenahmed/freellmapi/blob/main/docs/en/clients/01-agent-clients.md)
115
- - [Issue tracker](https://github.com/tashfeenahmed/freellmapi/issues)
116
-
117
- MIT © Tashfeen Ahmed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/eslint.config.js DELETED
@@ -1,28 +0,0 @@
1
- import js from '@eslint/js'
2
- import globals from 'globals'
3
- import tseslint from 'typescript-eslint'
4
- import { defineConfig, globalIgnores } from 'eslint/config'
5
-
6
- export default defineConfig([
7
- globalIgnores(['dist']),
8
- {
9
- files: ['**/*.ts'],
10
- extends: [
11
- js.configs.recommended,
12
- tseslint.configs.recommended,
13
- ],
14
- languageOptions: {
15
- ecmaVersion: 2022,
16
- globals: globals.node,
17
- },
18
- rules: {
19
- '@typescript-eslint/no-explicit-any': 'off',
20
- '@typescript-eslint/no-unused-vars': ['error', {
21
- argsIgnorePattern: '^_',
22
- varsIgnorePattern: '^_',
23
- caughtErrorsIgnorePattern: '^_',
24
- }],
25
- 'no-empty': ['error', { allowEmptyCatch: true }],
26
- },
27
- },
28
- ])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/package.json DELETED
@@ -1,77 +0,0 @@
1
- {
2
- "name": "freellmapi",
3
- "version": "0.8.2",
4
- "description": "Set up coding agents to use a FreeLLMAPI gateway",
5
- "license": "MIT",
6
- "repository": {
7
- "type": "git",
8
- "url": "git+https://github.com/tashfeenahmed/freellmapi.git",
9
- "directory": "cli"
10
- },
11
- "homepage": "https://github.com/tashfeenahmed/freellmapi/tree/main/cli#readme",
12
- "bugs": {
13
- "url": "https://github.com/tashfeenahmed/freellmapi/issues"
14
- },
15
- "keywords": [
16
- "freellmapi",
17
- "llm",
18
- "openai-compatible",
19
- "claude-code",
20
- "codex",
21
- "aider",
22
- "cline",
23
- "coding-agent",
24
- "cli"
25
- ],
26
- "type": "module",
27
- "bin": {
28
- "freellmapi": "dist/index.js"
29
- },
30
- "exports": {
31
- ".": "./dist/index.js",
32
- "./tools": "./dist/tools.js"
33
- },
34
- "files": [
35
- "README.md",
36
- "LICENSE",
37
- "dist/index.js",
38
- "dist/index.d.ts",
39
- "dist/config-files.js",
40
- "dist/config-files.d.ts",
41
- "dist/doctor.js",
42
- "dist/doctor.d.ts",
43
- "dist/keys.js",
44
- "dist/keys.d.ts",
45
- "dist/models.js",
46
- "dist/models.d.ts",
47
- "dist/tools.js",
48
- "dist/tools.d.ts",
49
- "dist/types.js",
50
- "dist/types.d.ts",
51
- "tools.json"
52
- ],
53
- "scripts": {
54
- "build": "tsc",
55
- "test": "vitest run",
56
- "lint": "eslint .",
57
- "prepublishOnly": "npm run build && npm test"
58
- },
59
- "engines": {
60
- "node": ">=20.18.0 <25.0.0"
61
- },
62
- "dependencies": {
63
- "cross-spawn": "^7.0.6",
64
- "jsonc-parser": "^3.3.1",
65
- "yaml": "^2.9.0"
66
- },
67
- "devDependencies": {
68
- "@types/cross-spawn": "^6.0.6",
69
- "@types/node": "^24.12.2",
70
- "typescript": "~6.0.2",
71
- "vitest": "^3.1.3",
72
- "@eslint/js": "^9.39.4",
73
- "eslint": "^9.39.4",
74
- "globals": "^17.4.0",
75
- "typescript-eslint": "^8.58.0"
76
- }
77
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/src/__snapshots__/tools.test.ts.snap DELETED
@@ -1,1009 +0,0 @@
1
- // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
2
-
3
- exports[`tool generators > setup-aider has stable golden output 1`] = `
4
- {
5
- "files": [
6
- {
7
- "content": "# freellmapi:start
8
- openai-api-base: "http://localhost:3000/v1"
9
- openai-api-key: "freellmapi-test-key"
10
- model: "openai/fast-coder"
11
- # freellmapi:end
12
- ",
13
- "format": "yaml",
14
- "path": "/home/tester/.aider.conf.yml",
15
- "sensitive": true,
16
- },
17
- ],
18
- "notes": [
19
- "Environment-only alternative: OPENAI_API_BASE=http://localhost:3000/v1 OPENAI_API_KEY=… aider --model openai/fast-coder",
20
- ],
21
- }
22
- `;
23
-
24
- exports[`tool generators > setup-atomcode has stable golden output 1`] = `
25
- {
26
- "files": [
27
- {
28
- "content": "default_provider = "freellmapi"
29
-
30
- [providers.freellmapi]
31
- type = "openai"
32
- base_url = "http://localhost:3000/v1"
33
- api_key = "freellmapi-test-key"
34
- model = "fast-coder"
35
- context_window = 131072",
36
- "format": "toml",
37
- "path": "/home/tester/.atomcode/config.toml",
38
- "sensitive": true,
39
- },
40
- ],
41
- "notes": [
42
- "AtomCode reads ~/.atomcode/config.toml; other [providers.*] tables in it are kept.",
43
- "default_provider now points at [providers.freellmapi] with fast-coder as its model.",
44
- "Point base_url at the unified /v1 endpoint; api_key is the unified key shown on the Agents page.",
45
- "One-shot check: atomcode -p "Say hello" (telemetry is on by default: atomcode telemetry disable).",
46
- ],
47
- }
48
- `;
49
-
50
- exports[`tool generators > setup-claude has stable golden output 1`] = `
51
- {
52
- "files": [
53
- {
54
- "format": "json",
55
- "path": "/home/tester/.claude/settings.json",
56
- "sensitive": true,
57
- "value": {
58
- "env": {
59
- "ANTHROPIC_AUTH_TOKEN": "freellmapi-test-key",
60
- "ANTHROPIC_BASE_URL": "http://localhost:3000",
61
- "ANTHROPIC_DEFAULT_HAIKU_MODEL": "fast-coder",
62
- "ANTHROPIC_DEFAULT_OPUS_MODEL": "fast-coder",
63
- "ANTHROPIC_DEFAULT_SONNET_MODEL": "fast-coder",
64
- "ANTHROPIC_MODEL": "fast-coder",
65
- "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "131072",
66
- "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY": "1",
67
- },
68
- },
69
- },
70
- ],
71
- "notes": [
72
- "Claude Code will read this configuration automatically.",
73
- "For zero-persistence credentials, prefer: freellmapi launch",
74
- ],
75
- }
76
- `;
77
-
78
- exports[`tool generators > setup-cline has stable golden output 1`] = `
79
- {
80
- "files": [
81
- {
82
- "format": "json",
83
- "path": "/home/tester/.cline/data/settings/providers.json",
84
- "sensitive": true,
85
- "value": {
86
- "lastUsedProvider": "openai-compatible",
87
- "providers": {
88
- "openai-compatible": {
89
- "settings": {
90
- "apiKey": "freellmapi-test-key",
91
- "baseUrl": "http://localhost:3000/v1",
92
- "capabilities": [
93
- "streaming",
94
- "tools",
95
- ],
96
- "client": "openai-compatible",
97
- "contextWindow": 131072,
98
- "model": "fast-coder",
99
- "protocol": "openai-chat",
100
- "provider": "openai-compatible",
101
- },
102
- "tokenSource": "manual",
103
- "updatedAt": "2026-07-27T00:00:00.000Z",
104
- },
105
- },
106
- "version": 1,
107
- },
108
- },
109
- ],
110
- "notes": [
111
- "Cline will use the generated OpenAI Compatible provider immediately.",
112
- ],
113
- }
114
- `;
115
-
116
- exports[`tool generators > setup-codex has stable golden output 1`] = `
117
- {
118
- "files": [
119
- {
120
- "content": "# freellmapi:start
121
- model = "fast-coder"
122
- model_provider = "freellmapi"
123
- model_context_window = 131072
124
- model_auto_compact_token_limit = 117964
125
- tool_output_token_limit = 20000
126
-
127
- [model_providers.freellmapi]
128
- name = "FreeLLMAPI"
129
- base_url = "http://localhost:3000/v1"
130
- wire_api = "responses"
131
- env_key = "FREELLMAPI_API_KEY"
132
- requires_openai_auth = false
133
- # freellmapi:end
134
- ",
135
- "format": "toml",
136
- "path": "/home/tester/.codex/config.toml",
137
- },
138
- ],
139
- "notes": [
140
- "No Codex CLI detected on this machine.",
141
- "Install the CLI with: npm install -g @openai/codex",
142
- "Export FREELLMAPI_API_KEY before running codex; the key is not written to config.toml.",
143
- "Selected fast-coder with a 131072 token context window.",
144
- ],
145
- }
146
- `;
147
-
148
- exports[`tool generators > setup-codex with a named profile has stable golden output 1`] = `
149
- {
150
- "files": [
151
- {
152
- "content": "# freellmapi:start
153
- [model_providers.freellmapi]
154
- name = "FreeLLMAPI"
155
- base_url = "http://localhost:3000/v1"
156
- wire_api = "responses"
157
- env_key = "FREELLMAPI_API_KEY"
158
- requires_openai_auth = false
159
-
160
- [profiles.work]
161
- model = "fast-coder"
162
- model_provider = "freellmapi"
163
- # freellmapi:end
164
- ",
165
- "format": "toml",
166
- "path": "/home/tester/.codex/config.toml",
167
- },
168
- ],
169
- "notes": [
170
- "No Codex CLI detected on this machine.",
171
- "Install the CLI with: npm install -g @openai/codex",
172
- "Export FREELLMAPI_API_KEY before running codex; the key is not written to config.toml.",
173
- "Activate this profile with: codex --profile work",
174
- "Selected fast-coder with a 131072 token context window.",
175
- ],
176
- }
177
- `;
178
-
179
- exports[`tool generators > setup-continue has stable golden output 1`] = `
180
- {
181
- "files": [
182
- {
183
- "content": "# freellmapi:start
184
- name: FreeLLMAPI
185
- version: 1.0.0
186
- schema: v1
187
- models:
188
- - name: FreeLLMAPI
189
- provider: openai
190
- model: "fast-coder"
191
- apiBase: "http://localhost:3000/v1"
192
- apiKey: \${{ secrets.FREELLMAPI_API_KEY }}
193
- capabilities:
194
- - tool_use
195
- defaultCompletionOptions:
196
- contextLength: 131072
197
- # freellmapi:end
198
- ",
199
- "format": "yaml",
200
- "path": "/home/tester/.continue/config.yaml",
201
- },
202
- {
203
- "content": "FREELLMAPI_API_KEY=freellmapi-test-key
204
- ",
205
- "format": "env",
206
- "path": "/home/tester/.continue/.env",
207
- "sensitive": true,
208
- },
209
- ],
210
- "notes": [
211
- "The key is in ~/.continue/.env (read by the Continue CLI and the IDE extensions); config.yaml references it as a secret.",
212
- "One-shot check with the CLI (npm install -g @continuedev/cli): cn -p "Say hello"",
213
- ],
214
- }
215
- `;
216
-
217
- exports[`tool generators > setup-crush has stable golden output 1`] = `
218
- {
219
- "files": [
220
- {
221
- "format": "json",
222
- "path": "/home/tester/.config/crush/crush.json",
223
- "value": {
224
- "$schema": "https://charm.land/crush.json",
225
- "models": {
226
- "large": {
227
- "model": "fast-coder",
228
- "provider": "freellmapi",
229
- },
230
- "small": {
231
- "model": "fast-coder",
232
- "provider": "freellmapi",
233
- },
234
- },
235
- "providers": {
236
- "freellmapi": {
237
- "api_key": "$FREELLMAPI_API_KEY",
238
- "base_url": "http://localhost:3000/v1",
239
- "models": [
240
- {
241
- "can_reason": false,
242
- "context_window": 131072,
243
- "cost_per_1m_in": 0,
244
- "cost_per_1m_in_cached": 0,
245
- "cost_per_1m_out": 0,
246
- "cost_per_1m_out_cached": 0,
247
- "default_max_tokens": 8192,
248
- "id": "fast-coder",
249
- "name": "Fast Coder",
250
- "supports_attachments": false,
251
- },
252
- {
253
- "can_reason": false,
254
- "context_window": 262144,
255
- "cost_per_1m_in": 0,
256
- "cost_per_1m_in_cached": 0,
257
- "cost_per_1m_out": 0,
258
- "cost_per_1m_out_cached": 0,
259
- "default_max_tokens": 8192,
260
- "id": "reasoning-model",
261
- "name": "Reasoning Model",
262
- "supports_attachments": false,
263
- },
264
- ],
265
- "name": "FreeLLMAPI",
266
- "type": "openai-compat",
267
- },
268
- },
269
- },
270
- },
271
- ],
272
- "notes": [
273
- "Export FREELLMAPI_API_KEY before starting Crush.",
274
- "freellmapi/fast-coder is now the large and small model.",
275
- ],
276
- }
277
- `;
278
-
279
- exports[`tool generators > setup-cursor has stable golden output 1`] = `
280
- {
281
- "files": [],
282
- "notes": [
283
- "Cursor sends model traffic through its cloud service, so localhost is not reachable from Cursor.",
284
- "Expose the gateway through a trusted HTTPS tunnel, then open Cursor Settings → Models, enable Override OpenAI Base URL, and enter <public-url>/v1.",
285
- "Cursor only documents custom keys for standard chat models; custom base-URL overrides may not support Responses-based or built-in models.",
286
- "The override affects Cursor globally while enabled, so disable it before switching back to built-in providers.",
287
- "Use a separately revocable URL token if the client cannot set an Authorization header.",
288
- ],
289
- }
290
- `;
291
-
292
- exports[`tool generators > setup-dsh has stable golden output 1`] = `
293
- {
294
- "files": [
295
- {
296
- "format": "yaml",
297
- "path": "/home/tester/.dsh/settings.yaml",
298
- "value": {
299
- "agent-default-model": {
300
- "model": "fast-coder",
301
- "provider": "freellmapi",
302
- "reasoningEffort": undefined,
303
- },
304
- "llm-pi-ai": {
305
- "providers": {
306
- "freellmapi": {
307
- "api": "openai-completions",
308
- "apiKeyEnv": "FREELLMAPI_API_KEY",
309
- "baseURL": "http://localhost:3000/v1",
310
- "displayName": "FreeLLMAPI",
311
- "models": [
312
- {
313
- "contextWindow": 131072,
314
- "id": "fast-coder",
315
- "maxTokens": 8192,
316
- "name": "Fast Coder",
317
- },
318
- {
319
- "contextWindow": 262144,
320
- "id": "reasoning-model",
321
- "maxTokens": 8192,
322
- "name": "Reasoning Model",
323
- },
324
- ],
325
- },
326
- },
327
- },
328
- },
329
- },
330
- {
331
- "content": "FREELLMAPI_API_KEY=freellmapi-test-key
332
- ",
333
- "format": "env",
334
- "path": "/home/tester/.dsh/.env",
335
- "sensitive": true,
336
- },
337
- ],
338
- "notes": [
339
- "Start DeepSeek Harness with: npx @deepseek-ai/dsh web — freellmapi/fast-coder is the default model.",
340
- "One-shot check: npx @deepseek-ai/dsh --profile headless "Say hello"",
341
- "Settings are hot-reloaded, so a running dsh picks this up on its next request.",
342
- "Models are declared text-only; give a vision model \`input: [text, image]\` under freellmapi.models in settings.yaml to send it images.",
343
- ],
344
- }
345
- `;
346
-
347
- exports[`tool generators > setup-generic has stable golden output 1`] = `
348
- {
349
- "files": [],
350
- "notes": [
351
- "OPENAI_BASE_URL=http://localhost:3000/v1",
352
- "OPENAI_API_KEY=freellmapi-test-key",
353
- "OPENAI_MODEL=fast-coder",
354
- "curl http://localhost:3000/v1/chat/completions -H "Authorization: Bearer $OPENAI_API_KEY" -H "Content-Type: application/json" -d '{"model":"fast-coder","messages":[{"role":"user","content":"Hello"}]}'",
355
- ],
356
- }
357
- `;
358
-
359
- exports[`tool generators > setup-goose has stable golden output 1`] = `
360
- {
361
- "files": [
362
- {
363
- "format": "json",
364
- "path": "/home/tester/.config/goose/custom_providers/freellmapi.json",
365
- "value": {
366
- "api_key_env": "FREELLMAPI_API_KEY",
367
- "base_url": "http://localhost:3000/v1",
368
- "description": "FreeLLMAPI OpenAI-compatible gateway",
369
- "display_name": "FreeLLMAPI",
370
- "dynamic_models": false,
371
- "engine": "openai",
372
- "models": [
373
- {
374
- "context_limit": 131072,
375
- "name": "fast-coder",
376
- },
377
- {
378
- "context_limit": 262144,
379
- "name": "reasoning-model",
380
- },
381
- ],
382
- "name": "freellmapi",
383
- "preserves_thinking": true,
384
- "requires_auth": true,
385
- "supports_streaming": true,
386
- },
387
- },
388
- {
389
- "content": "# freellmapi:start
390
- GOOSE_PROVIDER: freellmapi
391
- GOOSE_MODEL: "fast-coder"
392
- # freellmapi:end
393
- ",
394
- "format": "yaml",
395
- "path": "/home/tester/.config/goose/config.yaml",
396
- },
397
- ],
398
- "notes": [
399
- "Export FREELLMAPI_API_KEY before starting Goose.",
400
- ],
401
- }
402
- `;
403
-
404
- exports[`tool generators > setup-hermes has stable golden output 1`] = `
405
- {
406
- "files": [
407
- {
408
- "format": "yaml",
409
- "path": "/home/tester/.hermes/config.yaml",
410
- "value": {
411
- "model": {
412
- "api_key": "\${FREELLMAPI_API_KEY}",
413
- "api_key_env": undefined,
414
- "api_mode": "chat_completions",
415
- "base_url": "http://localhost:3000/v1",
416
- "context_length": 131072,
417
- "default": "fast-coder",
418
- "default_headers": {
419
- "User-Agent": "hermes-agent",
420
- },
421
- "key_env": undefined,
422
- "provider": "custom",
423
- },
424
- },
425
- },
426
- {
427
- "content": "FREELLMAPI_API_KEY=freellmapi-test-key
428
- ",
429
- "format": "env",
430
- "path": "/home/tester/.hermes/.env",
431
- "sensitive": true,
432
- },
433
- ],
434
- "notes": [
435
- "Install Hermes Agent with: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash -s -- --skip-setup",
436
- "Try it with: hermes -z "Say hello" — custom/fast-coder is the default model.",
437
- "A running \`hermes gateway\` (Telegram, Discord, …) needs a restart to pick the change up.",
438
- ],
439
- }
440
- `;
441
-
442
- exports[`tool generators > setup-kilo has stable golden output 1`] = `
443
- {
444
- "files": [
445
- {
446
- "format": "json",
447
- "path": "/home/tester/.config/kilo/kilo.jsonc",
448
- "value": {
449
- "$schema": "https://app.kilo.ai/config.json",
450
- "model": "openai-compatible/fast-coder",
451
- "provider": {
452
- "openai-compatible": {
453
- "models": {
454
- "fast-coder": {
455
- "limit": {
456
- "context": 131072,
457
- "output": 8192,
458
- },
459
- "name": "Fast Coder",
460
- "tool_call": true,
461
- },
462
- "reasoning-model": {
463
- "limit": {
464
- "context": 262144,
465
- "output": 8192,
466
- },
467
- "name": "Reasoning Model",
468
- "tool_call": true,
469
- },
470
- },
471
- "options": {
472
- "apiKey": "{env:FREELLMAPI_API_KEY}",
473
- "baseURL": "http://localhost:3000/v1",
474
- },
475
- },
476
- },
477
- },
478
- },
479
- ],
480
- "notes": [
481
- "Export FREELLMAPI_API_KEY before starting Kilo; global config is trusted for {env:…} expansion.",
482
- "One-shot check: kilo run "Say hello" — openai-compatible/fast-coder is the default model.",
483
- ],
484
- }
485
- `;
486
-
487
- exports[`tool generators > setup-mimo has stable golden output 1`] = `
488
- {
489
- "files": [
490
- {
491
- "format": "json",
492
- "path": "/home/tester/.config/mimocode/config.json",
493
- "value": {
494
- "$schema": "https://mimo.xiaomi.com/mimocode/config.json",
495
- "model": "freellmapi/fast-coder",
496
- "provider": {
497
- "freellmapi": {
498
- "models": {
499
- "fast-coder": {
500
- "limit": {
501
- "context": 131072,
502
- "output": 8192,
503
- },
504
- "name": "Fast Coder",
505
- },
506
- "reasoning-model": {
507
- "limit": {
508
- "context": 262144,
509
- "output": 8192,
510
- },
511
- "name": "Reasoning Model",
512
- },
513
- },
514
- "name": "FreeLLMAPI",
515
- "npm": "@ai-sdk/openai-compatible",
516
- "options": {
517
- "apiKey": "{env:FREELLMAPI_API_KEY}",
518
- "baseURL": "http://localhost:3000/v1",
519
- },
520
- },
521
- },
522
- },
523
- },
524
- ],
525
- "notes": [
526
- "Install MiMo Code with: curl -fsSL https://mimo.xiaomi.com/install | bash",
527
- "Export FREELLMAPI_API_KEY before starting MiMo Code.",
528
- "Start it with \`mimo\` — freellmapi/fast-coder is the default model.",
529
- "One-shot check: mimo run "Say hello"",
530
- ],
531
- }
532
- `;
533
-
534
- exports[`tool generators > setup-openclaw has stable golden output 1`] = `
535
- {
536
- "files": [
537
- {
538
- "format": "json",
539
- "path": "/home/tester/.openclaw/openclaw.json",
540
- "value": {
541
- "agents": {
542
- "defaults": {
543
- "model": {
544
- "primary": "freellmapi/fast-coder",
545
- },
546
- },
547
- },
548
- "models": {
549
- "providers": {
550
- "freellmapi": {
551
- "api": "openai-completions",
552
- "apiKey": "\${FREELLMAPI_API_KEY}",
553
- "baseUrl": "http://localhost:3000/v1",
554
- "headers": {
555
- "User-Agent": "openclaw",
556
- },
557
- "models": [
558
- {
559
- "contextWindow": 131072,
560
- "cost": {
561
- "cacheRead": 0,
562
- "cacheWrite": 0,
563
- "input": 0,
564
- "output": 0,
565
- },
566
- "id": "fast-coder",
567
- "input": [
568
- "text",
569
- ],
570
- "maxTokens": 8192,
571
- "name": "Fast Coder",
572
- "reasoning": false,
573
- },
574
- {
575
- "contextWindow": 262144,
576
- "cost": {
577
- "cacheRead": 0,
578
- "cacheWrite": 0,
579
- "input": 0,
580
- "output": 0,
581
- },
582
- "id": "reasoning-model",
583
- "input": [
584
- "text",
585
- ],
586
- "maxTokens": 8192,
587
- "name": "Reasoning Model",
588
- "reasoning": false,
589
- },
590
- ],
591
- },
592
- },
593
- },
594
- },
595
- },
596
- {
597
- "content": "FREELLMAPI_API_KEY=freellmapi-test-key
598
- ",
599
- "format": "env",
600
- "path": "/home/tester/.openclaw/.env",
601
- "sensitive": true,
602
- },
603
- ],
604
- "notes": [
605
- "Install OpenClaw with: npm install -g openclaw@latest --allow-scripts=openclaw",
606
- "Try it without the gateway daemon: openclaw agent exec --model freellmapi/fast-coder "Say hello"",
607
- "freellmapi/fast-coder is the default model; a running \`openclaw gateway\` needs a restart to pick the change up.",
608
- "Models are declared text-only; give a vision model \`input: ["text", "image"]\` under models.providers.freellmapi to send it images.",
609
- ],
610
- }
611
- `;
612
-
613
- exports[`tool generators > setup-opencode has stable golden output 1`] = `
614
- {
615
- "files": [
616
- {
617
- "format": "json",
618
- "path": "/home/tester/.config/opencode/opencode.json",
619
- "value": {
620
- "$schema": "https://opencode.ai/config.json",
621
- "model": "freellmapi/fast-coder",
622
- "provider": {
623
- "freellmapi": {
624
- "models": {
625
- "fast-coder": {
626
- "limit": {
627
- "context": 131072,
628
- "output": 8192,
629
- },
630
- "name": "Fast Coder",
631
- },
632
- "reasoning-model": {
633
- "limit": {
634
- "context": 262144,
635
- "output": 8192,
636
- },
637
- "name": "Reasoning Model",
638
- },
639
- },
640
- "name": "FreeLLMAPI",
641
- "npm": "@ai-sdk/openai-compatible",
642
- "options": {
643
- "apiKey": "{env:FREELLMAPI_API_KEY}",
644
- "baseURL": "http://localhost:3000/v1",
645
- },
646
- },
647
- },
648
- },
649
- },
650
- ],
651
- "notes": [
652
- "Export FREELLMAPI_API_KEY before starting OpenCode.",
653
- "freellmapi/fast-coder is now the default model.",
654
- ],
655
- }
656
- `;
657
-
658
- exports[`tool generators > setup-pi has stable golden output 1`] = `
659
- {
660
- "files": [
661
- {
662
- "format": "json",
663
- "path": "/home/tester/.pi/agent/models.json",
664
- "sensitive": true,
665
- "value": {
666
- "providers": {
667
- "freellmapi": {
668
- "api": "openai-completions",
669
- "apiKey": "freellmapi-test-key",
670
- "baseUrl": "http://localhost:3000/v1",
671
- "headers": {
672
- "User-Agent": "pi-coding-agent",
673
- },
674
- "models": [
675
- {
676
- "contextWindow": 131072,
677
- "cost": {
678
- "cacheRead": 0,
679
- "cacheWrite": 0,
680
- "input": 0,
681
- "output": 0,
682
- },
683
- "id": "fast-coder",
684
- "input": [
685
- "text",
686
- ],
687
- "maxTokens": 8192,
688
- "name": "Fast Coder",
689
- "reasoning": false,
690
- },
691
- {
692
- "contextWindow": 262144,
693
- "cost": {
694
- "cacheRead": 0,
695
- "cacheWrite": 0,
696
- "input": 0,
697
- "output": 0,
698
- },
699
- "id": "reasoning-model",
700
- "input": [
701
- "text",
702
- ],
703
- "maxTokens": 8192,
704
- "name": "Reasoning Model",
705
- "reasoning": false,
706
- },
707
- ],
708
- "name": "FreeLLMAPI",
709
- },
710
- },
711
- },
712
- },
713
- {
714
- "format": "json",
715
- "path": "/home/tester/.pi/agent/settings.json",
716
- "value": {
717
- "defaultModel": "fast-coder",
718
- "defaultProvider": "freellmapi",
719
- },
720
- },
721
- ],
722
- "notes": [
723
- "Install Pi with: npm install -g @earendil-works/pi-coding-agent (or curl -fsSL https://pi.dev/install.sh | sh)",
724
- "Try it with: pi -p "Say hello" — freellmapi/fast-coder is the default model.",
725
- "Every catalog model is in /model; a running Pi session picks the change up when /model is opened.",
726
- "Models are declared text-only; give a vision model \`input: ["text", "image"]\` under providers.freellmapi in models.json to send it images.",
727
- ],
728
- }
729
- `;
730
-
731
- exports[`tool generators > setup-qwen has stable golden output 1`] = `
732
- {
733
- "files": [
734
- {
735
- "format": "json",
736
- "path": "/home/tester/.qwen/settings.json",
737
- "value": {
738
- "model": {
739
- "name": "fast-coder",
740
- },
741
- "modelProviders": {
742
- "openai": {
743
- "models": [
744
- {
745
- "baseUrl": "http://localhost:3000/v1",
746
- "envKey": "FREELLMAPI_API_KEY",
747
- "generationConfig": {
748
- "contextWindowSize": 131072,
749
- },
750
- "id": "fast-coder",
751
- "name": "Fast Coder",
752
- },
753
- {
754
- "baseUrl": "http://localhost:3000/v1",
755
- "envKey": "FREELLMAPI_API_KEY",
756
- "generationConfig": {
757
- "contextWindowSize": 262144,
758
- },
759
- "id": "reasoning-model",
760
- "name": "Reasoning Model",
761
- },
762
- ],
763
- "protocol": "openai",
764
- },
765
- },
766
- "security": {
767
- "auth": {
768
- "selectedType": "openai",
769
- },
770
- },
771
- },
772
- },
773
- {
774
- "content": "FREELLMAPI_API_KEY=freellmapi-test-key
775
- ",
776
- "format": "env",
777
- "path": "/home/tester/.qwen/.env",
778
- "sensitive": true,
779
- },
780
- ],
781
- "notes": [
782
- "Native Gemini mode is also available at http://localhost:3000/v1beta with GEMINI_API_KEY.",
783
- ],
784
- }
785
- `;
786
-
787
- exports[`tool generators > setup-reasonix has stable golden output 1`] = `
788
- {
789
- "files": [
790
- {
791
- "content": "default_model = "freellmapi/fast-coder"
792
-
793
- [[providers]]
794
- name = "freellmapi"
795
- display_name = "FreeLLMAPI"
796
- kind = "openai"
797
- base_url = "http://localhost:3000/v1"
798
- models = ["fast-coder", "reasoning-model"]
799
- default = "fast-coder"
800
- api_key_env = "FREELLMAPI_API_KEY"
801
- context_window = 131072
802
- price = { cache_hit = 0, input = 0, output = 0, currency = "$" }",
803
- "format": "toml",
804
- "path": "/home/tester/.reasonix/config.toml",
805
- },
806
- {
807
- "content": "FREELLMAPI_API_KEY=freellmapi-test-key
808
- ",
809
- "format": "env",
810
- "path": "/home/tester/.reasonix/.env",
811
- "sensitive": true,
812
- },
813
- ],
814
- "notes": [
815
- "Install Reasonix with: npm install -g reasonix (or brew install esengine/reasonix/reasonix)",
816
- "Try it with: reasonix -p "Say hello" — freellmapi/fast-coder is the default model.",
817
- "Every catalog model is in /model as freellmapi/<id>; other [[providers]] entries in config.toml are kept.",
818
- "Reasonix Studio lists only the providers in [desktop].provider_access when that list is set; add "freellmapi" there, or under Settings → Model → Access.",
819
- ],
820
- }
821
- `;
822
-
823
- exports[`tool generators > setup-roo has stable golden output 1`] = `
824
- {
825
- "files": [
826
- {
827
- "format": "json",
828
- "path": "/home/tester/.roo/freellmapi.json",
829
- "sensitive": true,
830
- "value": {
831
- "globalSettings": {},
832
- "providerProfiles": {
833
- "apiConfigs": {
834
- "freellmapi": {
835
- "apiProvider": "openai",
836
- "openAiApiKey": "freellmapi-test-key",
837
- "openAiBaseUrl": "http://localhost:3000/v1",
838
- "openAiCustomModelInfo": {
839
- "contextWindow": 131072,
840
- "maxTokens": 8192,
841
- "supportsPromptCache": false,
842
- },
843
- "openAiModelId": "fast-coder",
844
- "openAiStreamingEnabled": true,
845
- },
846
- "freellmapi-cli": {
847
- "apiProvider": "openrouter",
848
- "openRouterApiKey": "freellmapi-test-key",
849
- "openRouterBaseUrl": "http://localhost:3000/v1",
850
- "openRouterModelId": "fast-coder",
851
- },
852
- },
853
- "currentApiConfigName": "freellmapi",
854
- },
855
- },
856
- },
857
- {
858
- "format": "json",
859
- "path": "/home/tester/.roo/freellmapi-cli.json",
860
- "sensitive": true,
861
- "value": {
862
- "globalSettings": {},
863
- "providerProfiles": {
864
- "apiConfigs": {
865
- "freellmapi-cli": {
866
- "apiProvider": "openrouter",
867
- "openRouterApiKey": "freellmapi-test-key",
868
- "openRouterBaseUrl": "http://localhost:3000/v1",
869
- "openRouterModelId": "fast-coder",
870
- },
871
- },
872
- "currentApiConfigName": "freellmapi-cli",
873
- },
874
- },
875
- },
876
- {
877
- "format": "json",
878
- "path": "/home/tester/.roo/cli-settings.json",
879
- "value": {
880
- "model": "fast-coder",
881
- "provider": "openrouter",
882
- },
883
- },
884
- ],
885
- "notes": [
886
- "VS Code: add "roo-cline.autoImportSettingsPath": "/home/tester/.roo/freellmapi.json" to settings.json and reload (or Roo Settings → Import); the freellmapi profile becomes current.",
887
- "Roo CLI: merge {"roo-cline.autoImportSettingsPath": "/home/tester/.roo/freellmapi-cli.json"} into ~/.vscode-mock/global-storage/global-state.json (create it if missing), then:",
888
- " export OPENROUTER_API_KEY=<unified-key> # the CLI refuses to start without it, even with the key in the profile",
889
- " roo -m fast-coder "Say hello" # -m is required: the CLI's built-in default model shadows cli-settings.json",
890
- ],
891
- }
892
- `;
893
-
894
- exports[`tool generators > setup-zcode has stable golden output 1`] = `
895
- {
896
- "files": [
897
- {
898
- "arrays": {
899
- "config.modelConfigRules.manualProviderModelRules": {
900
- "ownedBy": {
901
- "providerId": "freellmapi",
902
- },
903
- },
904
- "config.modelConfigRules.providerModelRules": {
905
- "ownedBy": {
906
- "providerId": "freellmapi",
907
- },
908
- },
909
- "config.providerConfigRules.providerRules": {
910
- "ownedBy": {
911
- "providerId": "freellmapi",
912
- },
913
- },
914
- "config.providerOrder": {
915
- "union": true,
916
- },
917
- },
918
- "format": "json",
919
- "path": "/home/tester/.zcode/v2/provider_config.json",
920
- "sensitive": true,
921
- "value": {
922
- "config": {
923
- "defaultModelSelection": {
924
- "modelId": "fast-coder",
925
- "providerId": "freellmapi",
926
- },
927
- "modelConfigRules": {
928
- "manualProviderModelRules": [],
929
- "providerModelRules": [
930
- {
931
- "config": {
932
- "enabled": true,
933
- "optionSpecs": {
934
- "maxOutputTokens": {
935
- "map": "{"max_tokens": maxOutputTokens}",
936
- "max": 8192,
937
- },
938
- },
939
- "properties": {
940
- "contextWindow": 131072,
941
- },
942
- },
943
- "modelId": "fast-coder",
944
- "providerId": "freellmapi",
945
- },
946
- {
947
- "config": {
948
- "enabled": true,
949
- "optionSpecs": {
950
- "maxOutputTokens": {
951
- "map": "{"max_tokens": maxOutputTokens}",
952
- "max": 8192,
953
- },
954
- },
955
- "properties": {
956
- "contextWindow": 262144,
957
- },
958
- },
959
- "modelId": "reasoning-model",
960
- "providerId": "freellmapi",
961
- },
962
- ],
963
- },
964
- "providerConfigRules": {
965
- "providerRules": [
966
- {
967
- "config": {
968
- "access": {
969
- "apiKey": "freellmapi-test-key",
970
- "type": "api-key",
971
- },
972
- "api": {
973
- "baseUrl": "http://localhost:3000/v1",
974
- "type": "openai-chat-completions",
975
- },
976
- "group": "standard-personal",
977
- "modelOrder": [
978
- "fast-coder",
979
- "reasoning-model",
980
- ],
981
- "personalModelIds": [
982
- "fast-coder",
983
- "reasoning-model",
984
- ],
985
- "visibility": "visible",
986
- },
987
- "enabled": true,
988
- "providerId": "freellmapi",
989
- "providerName": "FreeLLMAPI",
990
- "templateId": null,
991
- },
992
- ],
993
- },
994
- "providerOrder": [
995
- "freellmapi",
996
- ],
997
- },
998
- "schemaVersion": 1,
999
- },
1000
- },
1001
- ],
1002
- "notes": [
1003
- "Install ZCode from https://zcode.z.ai (or the community terminal client: npm i -g zcode-app-cli).",
1004
- "Quit ZCode Desktop before running this so it does not save its in-memory registry over the file.",
1005
- "freellmapi/fast-coder is now the default model; pick another under freellmapi in the model picker (or /model in the CLI). Other providers are kept.",
1006
- "The API key lives in the provider file (written 0600): ZCode has no env lookup for custom providers.",
1007
- ],
1008
- }
1009
- `;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/src/config-files.test.ts DELETED
@@ -1,582 +0,0 @@
1
- import fs from 'node:fs';
2
- import os from 'node:os';
3
- import path from 'node:path';
4
- import { parse } from 'jsonc-parser';
5
- import { afterEach, describe, expect, it } from 'vitest';
6
- import { applyGeneratedFile, applyGeneratedFiles, renderFile } from './config-files.js';
7
-
8
- const temporary: string[] = [];
9
-
10
- afterEach(() => {
11
- for (const directory of temporary.splice(0)) {
12
- fs.rmSync(directory, { recursive: true, force: true });
13
- }
14
- });
15
-
16
- describe('safe config writes', () => {
17
- it('writes a fresh env file without a leading blank line', () => {
18
- const rendered = renderFile({ path: '/unused', format: 'env', content: 'FREELLMAPI_API_KEY=k\n' }, '');
19
- expect(rendered).toBe('FREELLMAPI_API_KEY=k\n');
20
- expect(renderFile({ path: '/unused', format: 'env', content: 'FREELLMAPI_API_KEY=k\n' }, rendered)).toBe(rendered);
21
- });
22
-
23
- it('appends a new env key without leaving a blank line before it', () => {
24
- const merged = renderFile(
25
- { path: '/unused/.env', format: 'env', content: 'FREELLMAPI_API_KEY=k\n' },
26
- 'DEEPSEEK_API_KEY=sk-keep\n',
27
- );
28
- expect(merged).toBe('DEEPSEEK_API_KEY=sk-keep\nFREELLMAPI_API_KEY=k\n');
29
- });
30
-
31
- it('merges keyed JSON arrays per owner instead of replacing them (ZCode)', () => {
32
- const existing = JSON.stringify({
33
- schemaVersion: 1,
34
- config: {
35
- providerConfigRules: { providerRules: [
36
- { providerId: 'local', providerName: 'Mine' },
37
- { providerId: 'freellmapi', providerName: 'Old' },
38
- ] },
39
- modelConfigRules: {
40
- providerModelRules: [{ providerId: 'local', modelId: 'm' }, { providerId: 'freellmapi', modelId: 'gone' }],
41
- manualProviderModelRules: [{ providerId: 'freellmapi', modelId: 'fast' }, { providerId: 'local', modelId: 'x' }],
42
- },
43
- providerOrder: ['local', 'freellmapi'],
44
- },
45
- }, null, 2);
46
- const file = {
47
- path: '/unused/provider_config.json',
48
- format: 'json' as const,
49
- arrays: {
50
- 'config.providerConfigRules.providerRules': { ownedBy: { providerId: 'freellmapi' } },
51
- 'config.modelConfigRules.providerModelRules': { ownedBy: { providerId: 'freellmapi' } },
52
- 'config.modelConfigRules.manualProviderModelRules': { ownedBy: { providerId: 'freellmapi' } },
53
- 'config.providerOrder': { union: true as const },
54
- },
55
- value: {
56
- config: {
57
- providerConfigRules: { providerRules: [{ providerId: 'freellmapi', providerName: 'FreeLLMAPI' }] },
58
- modelConfigRules: {
59
- providerModelRules: [{ providerId: 'freellmapi', modelId: 'fast' }],
60
- manualProviderModelRules: [],
61
- },
62
- providerOrder: ['freellmapi'],
63
- },
64
- },
65
- };
66
- const once = renderFile(file, existing);
67
- const merged = parse(once).config;
68
- expect(merged.providerConfigRules.providerRules).toEqual([
69
- { providerId: 'local', providerName: 'Mine' },
70
- { providerId: 'freellmapi', providerName: 'FreeLLMAPI' },
71
- ]);
72
- expect(merged.modelConfigRules.providerModelRules).toEqual([
73
- { providerId: 'local', modelId: 'm' },
74
- { providerId: 'freellmapi', modelId: 'fast' },
75
- ]);
76
- expect(merged.modelConfigRules.manualProviderModelRules).toEqual([{ providerId: 'local', modelId: 'x' }]);
77
- expect(merged.providerOrder).toEqual(['local', 'freellmapi']);
78
- expect(renderFile(file, once)).toBe(once);
79
- });
80
-
81
- it('renders a fresh Continue config idempotently', () => {
82
- const generated = [
83
- '# freellmapi:start',
84
- 'name: FreeLLMAPI',
85
- 'version: 1.0.0',
86
- 'schema: v1',
87
- 'models:',
88
- ' - name: FreeLLMAPI',
89
- ' provider: openai',
90
- ' model: coder',
91
- '# freellmapi:end',
92
- '',
93
- ].join('\n');
94
- const first = renderFile({
95
- path: '/unused',
96
- format: 'yaml',
97
- content: generated,
98
- });
99
- const second = renderFile({
100
- path: '/unused',
101
- format: 'yaml',
102
- content: generated,
103
- }, first);
104
- expect(second).toBe(first);
105
- expect(first).not.toContain('freellmapi:start');
106
- expect(first.match(/^models:$/gm)).toHaveLength(1);
107
- });
108
-
109
- it('deep-merges JSONC and retains inline and leading comments', () => {
110
- const existing = [
111
- '// user configuration',
112
- '{',
113
- ' // keep the chosen theme',
114
- ' "theme": "dark",',
115
- ' "provider": {',
116
- ' /* keep the unrelated provider */',
117
- ' "other": true,',
118
- ' },',
119
- '}',
120
- '',
121
- ].join('\n');
122
- const rendered = renderFile({
123
- path: '/unused',
124
- format: 'json',
125
- value: { provider: { freellmapi: true } },
126
- }, existing);
127
- expect(rendered).toContain('// user configuration');
128
- expect(rendered).toContain('// keep the chosen theme');
129
- expect(rendered).toContain('/* keep the unrelated provider */');
130
- expect(parse(rendered)).toEqual({
131
- theme: 'dark',
132
- provider: { other: true, freellmapi: true },
133
- });
134
- });
135
-
136
- it('merges Continue into an existing config without replacing other models', () => {
137
- const existing = [
138
- '# personal config',
139
- 'name: Personal',
140
- 'version: 2.0.0',
141
- 'schema: v1',
142
- 'models:',
143
- ' - name: Existing',
144
- ' provider: ollama',
145
- ' model: qwen',
146
- 'rules:',
147
- ' - Keep this rule',
148
- '',
149
- ].join('\n');
150
- const generated = [
151
- '# freellmapi:start',
152
- 'name: FreeLLMAPI',
153
- 'version: 1.0.0',
154
- 'schema: v1',
155
- 'models:',
156
- ' - name: FreeLLMAPI',
157
- ' provider: openai',
158
- ' model: coder',
159
- '# freellmapi:end',
160
- '',
161
- ].join('\n');
162
- const first = renderFile({
163
- path: '/unused',
164
- format: 'yaml',
165
- content: generated,
166
- }, existing);
167
- const second = renderFile({
168
- path: '/unused',
169
- format: 'yaml',
170
- content: generated,
171
- }, first);
172
- expect(second).toBe(first);
173
- expect(first).toContain('# personal config');
174
- expect(first).toContain('name: Personal');
175
- expect(first).toContain(' - name: Existing');
176
- expect(first).toContain(' - name: FreeLLMAPI');
177
- expect(first).toContain('rules:\n - Keep this rule');
178
- expect(first.match(/^models:$/gm)).toHaveLength(1);
179
- });
180
-
181
- it('upgrades a previously marked Continue block without leaving duplicate keys', () => {
182
- const existing = [
183
- 'name: Personal',
184
- 'version: 2.0.0',
185
- 'schema: v1',
186
- 'models:',
187
- ' - name: Existing',
188
- ' provider: ollama',
189
- ' model: qwen',
190
- '# freellmapi:start',
191
- 'models:',
192
- ' - name: FreeLLMAPI',
193
- ' provider: openai',
194
- ' model: old',
195
- '# freellmapi:end',
196
- '',
197
- ].join('\n');
198
- const generated = [
199
- '# freellmapi:start',
200
- 'name: FreeLLMAPI',
201
- 'version: 1.0.0',
202
- 'schema: v1',
203
- 'models:',
204
- ' - name: FreeLLMAPI',
205
- ' provider: openai',
206
- ' model: current',
207
- '# freellmapi:end',
208
- '',
209
- ].join('\n');
210
- const rendered = renderFile({
211
- path: '/unused',
212
- format: 'yaml',
213
- content: generated,
214
- }, existing);
215
- expect(rendered.match(/^name:/gm)).toHaveLength(1);
216
- expect(rendered.match(/^version:/gm)).toHaveLength(1);
217
- expect(rendered.match(/^schema:/gm)).toHaveLength(1);
218
- expect(rendered.match(/^models:/gm)).toHaveLength(1);
219
- expect(rendered).toContain(' - name: Existing');
220
- expect(rendered).toContain(' model: current');
221
- expect(rendered).not.toContain(' model: old');
222
- });
223
-
224
- it('replaces generated YAML scalar keys without creating duplicates', () => {
225
- const existing = '# user config\nGOOSE_PROVIDER: old\nGOOSE_MODEL: old\nkeep: true\n';
226
- const generated = [
227
- '# freellmapi:start',
228
- 'GOOSE_PROVIDER: freellmapi',
229
- 'GOOSE_MODEL: coder',
230
- '# freellmapi:end',
231
- '',
232
- ].join('\n');
233
- const first = renderFile({
234
- path: '/unused',
235
- format: 'yaml',
236
- content: generated,
237
- }, existing);
238
- const second = renderFile({
239
- path: '/unused',
240
- format: 'yaml',
241
- content: generated,
242
- }, first);
243
- expect(second).toBe(first);
244
- expect(first).toContain('# user config');
245
- expect(first).toContain('keep: true');
246
- expect(first.match(/^GOOSE_PROVIDER:/gm)).toHaveLength(1);
247
- expect(first.match(/^GOOSE_MODEL:/gm)).toHaveLength(1);
248
- });
249
-
250
- it('deep-merges structured YAML and retains sibling routes and comments', () => {
251
- // DeepSeek Harness keeps every provider under one `llm-pi-ai.providers`
252
- // dict. The marked-block YAML merge removes whole top-level keys it
253
- // re-emits, which here would delete the user's other providers; the
254
- // structured merge must touch only the path it sets.
255
- const existing = [
256
- '# my settings',
257
- 'llm-pi-ai:',
258
- ' providers:',
259
- ' anthropic:',
260
- ' # keep me',
261
- ' apiKeyEnv: ANTHROPIC_API_KEY',
262
- ' freellmapi:',
263
- ' baseURL: http://old:1/v1',
264
- ' models:',
265
- ' - id: stale',
266
- 'agent-default-model:',
267
- ' provider: anthropic',
268
- ' model: claude-sonnet-4-5',
269
- ' reasoningEffort: high',
270
- 'other: { a: 1 }',
271
- '',
272
- ].join('\n');
273
- const file = {
274
- path: '/tmp/settings.yaml',
275
- format: 'yaml' as const,
276
- value: {
277
- 'llm-pi-ai': {
278
- providers: {
279
- freellmapi: {
280
- baseURL: 'http://localhost:3001/v1',
281
- models: [{ id: 'auto' }],
282
- },
283
- },
284
- },
285
- 'agent-default-model': {
286
- provider: 'freellmapi',
287
- model: 'auto',
288
- reasoningEffort: undefined,
289
- },
290
- },
291
- };
292
- const once = renderFile(file, existing);
293
- expect(once).toContain('# my settings');
294
- expect(once).toContain('# keep me');
295
- expect(once).toContain('apiKeyEnv: ANTHROPIC_API_KEY');
296
- expect(once).toContain('baseURL: http://localhost:3001/v1');
297
- expect(once).not.toContain('http://old:1/v1');
298
- expect(once).not.toContain('stale');
299
- expect(once).toContain('provider: freellmapi');
300
- expect(once).not.toContain('reasoningEffort');
301
- expect(once).toContain('other: { a: 1 }');
302
- expect(renderFile(file, once)).toBe(once);
303
- });
304
-
305
- it('renders structured YAML from an empty or comment-only document', () => {
306
- const file = {
307
- path: '/tmp/settings.yaml',
308
- format: 'yaml' as const,
309
- value: { a: { b: [1, 2] }, c: undefined },
310
- };
311
- expect(renderFile(file, '')).toBe('a:\n b:\n - 1\n - 2\n');
312
- expect(renderFile(file, '# only a comment\n')).toContain('a:\n b:\n - 1\n - 2\n');
313
- });
314
-
315
- it('refuses to merge structured YAML into a document it cannot parse', () => {
316
- const file = {
317
- path: '/tmp/settings.yaml',
318
- format: 'yaml' as const,
319
- value: { a: 1 },
320
- };
321
- expect(() => renderFile(file, 'a: [1, 2\n')).toThrow(/cannot be parsed/);
322
- expect(() => renderFile(file, '- just\n- a list\n')).toThrow(/not a mapping/);
323
- });
324
-
325
- it('replaces conflicting Codex TOML settings and retains unrelated tables', () => {
326
- const existing = [
327
- '# personal config',
328
- 'model = "old"',
329
- 'model_provider = "old"',
330
- '',
331
- '[model_providers.freellmapi]',
332
- 'name = "Old"',
333
- 'base_url = "https://old.invalid/v1"',
334
- '',
335
- '[mcp_servers.personal]',
336
- 'command = "keep-me"',
337
- '',
338
- ].join('\n');
339
- const generated = [
340
- '# freellmapi:start',
341
- 'model = "coder"',
342
- 'model_provider = "freellmapi"',
343
- '',
344
- '[model_providers.freellmapi]',
345
- 'name = "FreeLLMAPI"',
346
- 'base_url = "http://localhost:3000/v1"',
347
- '# freellmapi:end',
348
- '',
349
- ].join('\n');
350
- const first = renderFile({
351
- path: '/unused',
352
- format: 'toml',
353
- content: generated,
354
- }, existing);
355
- const second = renderFile({
356
- path: '/unused',
357
- format: 'toml',
358
- content: generated,
359
- }, first);
360
- expect(second).toBe(first);
361
- expect(first).toContain('# personal config');
362
- expect(first).toContain('[mcp_servers.personal]\ncommand = "keep-me"');
363
- expect(first.match(/^model =/gm)).toHaveLength(1);
364
- expect(first.match(/^\[model_providers\.freellmapi\]$/gm)).toHaveLength(1);
365
- });
366
-
367
- it('keeps generated root TOML keys in the root region when the file ends in a table', () => {
368
- const existing = [
369
- '# personal config',
370
- 'sandbox_mode = "workspace-write"',
371
- '',
372
- '[mcp_servers.personal]',
373
- 'command = "keep-me"',
374
- 'args = ["--serve"]',
375
- '',
376
- ].join('\n');
377
- const generated = [
378
- '# freellmapi:start',
379
- 'model = "coder"',
380
- 'model_provider = "freellmapi"',
381
- '',
382
- '[model_providers.freellmapi]',
383
- 'name = "FreeLLMAPI"',
384
- 'base_url = "http://localhost:3000/v1"',
385
- '# freellmapi:end',
386
- '',
387
- ].join('\n');
388
- const first = renderFile({
389
- path: '/unused',
390
- format: 'toml',
391
- content: generated,
392
- }, existing);
393
- const second = renderFile({
394
- path: '/unused',
395
- format: 'toml',
396
- content: generated,
397
- }, first);
398
- expect(second).toBe(first);
399
-
400
- // Root-level keys must appear BEFORE the first table header, otherwise
401
- // TOML assigns them to that table.
402
- const lines = first.split('\n');
403
- const firstHeader = lines.findIndex(line => /^\[[^\]]+\]$/.test(line));
404
- const modelLine = lines.findIndex(line => line === 'model = "coder"');
405
- const providerLine = lines.findIndex(line => line === 'model_provider = "freellmapi"');
406
- expect(firstHeader).toBeGreaterThan(-1);
407
- expect(modelLine).toBeGreaterThan(-1);
408
- expect(modelLine).toBeLessThan(firstHeader);
409
- expect(providerLine).toBeGreaterThan(-1);
410
- expect(providerLine).toBeLessThan(firstHeader);
411
- expect(first).toContain('sandbox_mode = "workspace-write"');
412
- expect(first).toContain('[mcp_servers.personal]\ncommand = "keep-me"\nargs = ["--serve"]');
413
- expect(first).toContain('[model_providers.freellmapi]');
414
- });
415
-
416
- it('only strips root TOML keys that the generated root region sets', () => {
417
- const existing = [
418
- 'name = "my personal codex"',
419
- 'model = "old"',
420
- '',
421
- '[mcp_servers.personal]',
422
- 'command = "keep-me"',
423
- '',
424
- ].join('\n');
425
- const generated = [
426
- '# freellmapi:start',
427
- 'model = "coder"',
428
- '',
429
- '[model_providers.freellmapi]',
430
- 'name = "FreeLLMAPI"',
431
- '# freellmapi:end',
432
- '',
433
- ].join('\n');
434
- const first = renderFile({
435
- path: '/unused',
436
- format: 'toml',
437
- content: generated,
438
- }, existing);
439
- // The generated TABLE sets `name`, but the user's ROOT-level `name` is a
440
- // different key and must survive.
441
- expect(first).toContain('name = "my personal codex"');
442
- expect(first.match(/^model =/gm)).toHaveLength(1);
443
- expect(first).toContain('model = "coder"');
444
- });
445
-
446
- it('does not write any file when a later file in the batch fails to merge', () => {
447
- const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'freellmapi-cli-'));
448
- temporary.push(directory);
449
- const good = path.join(directory, 'good.json');
450
- const bad = path.join(directory, 'bad.json');
451
- fs.writeFileSync(bad, '{ this is not json');
452
- expect(() => applyGeneratedFiles([
453
- { path: good, format: 'json', value: { enabled: true } },
454
- { path: bad, format: 'json', value: { enabled: true } },
455
- ], false)).toThrow('cannot be parsed safely');
456
- expect(fs.existsSync(good)).toBe(false);
457
- expect(fs.readFileSync(bad, 'utf8')).toBe('{ this is not json');
458
- });
459
-
460
- it('merges an AtomCode config: root key above existing tables, other providers kept', () => {
461
- // A user with a DeepSeek provider already configured runs setup-atomcode:
462
- // `default_provider` must land in the root region (a key appended after
463
- // `[providers.deepseek]` would become that table's key), the deepseek
464
- // table must survive, and a stale `[providers.freellmapi]` is replaced.
465
- const existing = [
466
- 'default_provider = "deepseek"',
467
- 'auto_update = true',
468
- '',
469
- '[providers.deepseek]',
470
- 'type = "openai"',
471
- 'api_key = "sk-keep"',
472
- 'model = "deepseek-chat"',
473
- '',
474
- '[providers.freellmapi]',
475
- 'type = "openai"',
476
- 'model = "stale-model"',
477
- '',
478
- ].join('\n');
479
- const generated = [
480
- 'default_provider = "freellmapi"',
481
- '',
482
- '[providers.freellmapi]',
483
- 'type = "openai"',
484
- 'base_url = "http://localhost:3000/v1"',
485
- 'api_key = "freellmapi-test-key"',
486
- 'model = "fast-coder"',
487
- 'context_window = 131072',
488
- ].join('\n');
489
- const merged = renderFile({ path: '/unused', format: 'toml', content: generated }, existing);
490
- const lines = merged.split('\n');
491
- const firstTable = lines.findIndex(line => line.startsWith('['));
492
- expect(lines.slice(0, firstTable)).toContain('default_provider = "freellmapi"');
493
- expect(lines.slice(0, firstTable)).toContain('auto_update = true');
494
- expect(merged.match(/^default_provider =/gm)).toHaveLength(1);
495
- expect(merged).toContain('[providers.deepseek]\ntype = "openai"\napi_key = "sk-keep"');
496
- expect(merged.match(/^\[providers\.freellmapi\]$/gm)).toHaveLength(1);
497
- expect(merged).not.toContain('stale-model');
498
- expect(merged).toContain('context_window = 131072');
499
- expect(renderFile({ path: '/unused', format: 'toml', content: generated }, merged)).toBe(merged);
500
- });
501
-
502
- it('merges a Reasonix config: replaces only the [[providers]] entry with the same name', () => {
503
- // Reasonix keeps every endpoint as a `[[providers]]` array entry. A rerun
504
- // must swap the stale freellmapi entry (and its sub-table) for the new one
505
- // and leave the deepseek entry, the [desktop] table and root keys alone.
506
- const existing = [
507
- 'config_version = 1',
508
- 'default_model = "deepseek/deepseek-flash"',
509
- '',
510
- '[desktop]',
511
- 'provider_access = ["deepseek"]',
512
- '',
513
- '[[providers]]',
514
- 'name = "deepseek"',
515
- 'kind = "openai"',
516
- 'api_key_env = "DEEPSEEK_API_KEY"',
517
- '',
518
- '[[providers]]',
519
- "name = 'freellmapi'",
520
- 'base_url = "http://stale:9/v1"',
521
- '',
522
- '[providers.model_overrides]',
523
- 'stale = { context_window = 1 }',
524
- '',
525
- '[[plugins]]',
526
- 'name = "freellmapi"',
527
- 'command = "keep-me"',
528
- '',
529
- ].join('\n');
530
- const generated = [
531
- 'default_model = "freellmapi/auto"',
532
- '',
533
- '[[providers]]',
534
- 'name = "freellmapi"',
535
- 'kind = "openai"',
536
- 'base_url = "http://localhost:3001/v1"',
537
- 'models = ["auto"]',
538
- ].join('\n');
539
- const merged = renderFile({ path: '/unused', format: 'toml', content: generated }, existing);
540
- const lines = merged.split('\n');
541
- const firstTable = lines.findIndex(line => line.startsWith('['));
542
- expect(lines.slice(0, firstTable)).toContain('default_model = "freellmapi/auto"');
543
- expect(lines.slice(0, firstTable)).toContain('config_version = 1');
544
- expect(merged.match(/^default_model =/gm)).toHaveLength(1);
545
- expect(merged).toContain('[desktop]\nprovider_access = ["deepseek"]');
546
- expect(merged).toContain('name = "deepseek"\nkind = "openai"');
547
- expect(merged).toContain('[[plugins]]\nname = "freellmapi"\ncommand = "keep-me"');
548
- expect(merged.match(/^\[\[providers\]\]$/gm)).toHaveLength(2);
549
- expect(merged).not.toContain('stale');
550
- expect(merged).toContain('base_url = "http://localhost:3001/v1"');
551
- expect(renderFile({ path: '/unused', format: 'toml', content: generated }, merged)).toBe(merged);
552
- });
553
-
554
- it('creates a timestamped backup before replacing a real file', () => {
555
- const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'freellmapi-cli-'));
556
- temporary.push(directory);
557
- const target = path.join(directory, 'config.toml');
558
- fs.writeFileSync(target, 'user_setting = true\n');
559
- const result = applyGeneratedFile({
560
- path: target,
561
- format: 'toml',
562
- content: '# freellmapi:start\nmodel = "auto"\n# freellmapi:end\n',
563
- }, false);
564
- expect(result.backupPath).toBeTruthy();
565
- expect(fs.readFileSync(result.backupPath!, 'utf8')).toBe('user_setting = true\n');
566
- expect(fs.readFileSync(target, 'utf8')).toContain('user_setting = true');
567
- expect(fs.readFileSync(target, 'utf8')).toContain('model = "auto"');
568
- });
569
-
570
- it('does not write in dry-run mode', () => {
571
- const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'freellmapi-cli-'));
572
- temporary.push(directory);
573
- const target = path.join(directory, 'new.json');
574
- const result = applyGeneratedFile({
575
- path: target,
576
- format: 'json',
577
- value: { enabled: true },
578
- }, true);
579
- expect(result.changed).toBe(true);
580
- expect(fs.existsSync(target)).toBe(false);
581
- });
582
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/src/config-files.ts DELETED
@@ -1,449 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import {
4
- applyEdits,
5
- modify,
6
- parse,
7
- type ParseError,
8
- } from 'jsonc-parser';
9
- import { Document, isMap, parseDocument } from 'yaml';
10
- import type { GeneratedFile, JsonArrayMerge } from './types.js';
11
-
12
- function isRecord(value: unknown): value is Record<string, unknown> {
13
- return Boolean(value)
14
- && typeof value === 'object'
15
- && !Array.isArray(value);
16
- }
17
-
18
- function mergeJsonArray(current: unknown[], next: unknown[], rule: JsonArrayMerge): unknown[] {
19
- if ('union' in rule) {
20
- return [...current, ...next.filter(item => !current.some(existing => JSON.stringify(existing) === JSON.stringify(item)))];
21
- }
22
- const owned = (item: unknown) => isRecord(item)
23
- && Object.entries(rule.ownedBy).every(([field, expected]) => item[field] === expected);
24
- return [...current.filter(item => !owned(item)), ...next];
25
- }
26
-
27
- function mergeJson(existing: string, value: Record<string, unknown>, arrays: Record<string, JsonArrayMerge> = {}): string {
28
- let rendered = existing.trim() ? existing : '{}\n';
29
- const errors: ParseError[] = [];
30
- const parsed = parse(rendered, errors, {
31
- allowTrailingComma: true,
32
- disallowComments: false,
33
- });
34
- if (errors.length || !isRecord(parsed)) {
35
- throw new Error('Existing JSON/JSONC cannot be parsed safely');
36
- }
37
-
38
- const formattingOptions = {
39
- insertSpaces: true,
40
- tabSize: 2,
41
- eol: '\n',
42
- };
43
- const applyPatch = (
44
- base: Record<string, unknown>,
45
- patch: Record<string, unknown>,
46
- parentPath: (string | number)[] = [],
47
- ) => {
48
- for (const [key, next] of Object.entries(patch)) {
49
- const current = base[key];
50
- const propertyPath = [...parentPath, key];
51
- if (isRecord(current) && isRecord(next)) {
52
- applyPatch(current, next, propertyPath);
53
- continue;
54
- }
55
- const arrayRule = arrays[propertyPath.join('.')];
56
- const merged = arrayRule && Array.isArray(current) && Array.isArray(next)
57
- ? mergeJsonArray(current, next, arrayRule)
58
- : next;
59
- rendered = applyEdits(rendered, modify(
60
- rendered,
61
- propertyPath,
62
- merged,
63
- { formattingOptions },
64
- ));
65
- }
66
- };
67
- applyPatch(parsed, value);
68
- return rendered.endsWith('\n') ? rendered : `${rendered}\n`;
69
- }
70
-
71
- // Structural YAML merge, the `mergeJson` rule applied to a YAML document:
72
- // nested objects recurse, everything else (scalars, arrays) is replaced at
73
- // that path, and an explicit `undefined` deletes the key (a generator's way
74
- // to retire a sibling the new value makes stale). Editing the parsed
75
- // Document rather than re-rendering from a plain object keeps the user's
76
- // comments, key order, and quoting for every node the patch does not touch —
77
- // a settings.yaml shared with other providers (DeepSeek Harness keeps every
78
- // route under one `llm-pi-ai` key) must not lose its siblings just because
79
- // ours changed.
80
- function mergeYamlDocument(existing: string, value: Record<string, unknown>): string {
81
- if (!existing.trim()) {
82
- const fresh = new Document(JSON.parse(JSON.stringify(value)));
83
- return fresh.toString({ lineWidth: 0 });
84
- }
85
- const doc = parseDocument(existing);
86
- if (doc.errors.length) {
87
- throw new Error(`Existing YAML cannot be parsed safely: ${doc.errors[0].message}`);
88
- }
89
- if (doc.contents !== null && !isMap(doc.contents)) {
90
- throw new Error('Existing YAML is not a mapping at the top level');
91
- }
92
- const applyPatch = (patch: Record<string, unknown>, parentPath: string[] = []) => {
93
- for (const [key, next] of Object.entries(patch)) {
94
- const propertyPath = [...parentPath, key];
95
- if (next === undefined) {
96
- doc.deleteIn(propertyPath);
97
- continue;
98
- }
99
- const current = doc.getIn(propertyPath, true);
100
- if (isRecord(next) && isMap(current)) {
101
- applyPatch(next, propertyPath);
102
- continue;
103
- }
104
- doc.setIn(propertyPath, next);
105
- }
106
- };
107
- applyPatch(value);
108
- const rendered = doc.toString({ lineWidth: 0 });
109
- return rendered.endsWith('\n') ? rendered : `${rendered}\n`;
110
- }
111
-
112
- function markerPattern(): RegExp {
113
- return new RegExp(
114
- `^[ \\t]*(?:#|//) freellmapi:start[\\s\\S]*?^[ \\t]*(?:#|//) freellmapi:end\\s*`,
115
- 'm',
116
- );
117
- }
118
-
119
- function mergeMarked(existing: string, generated: string): string {
120
- const start = generated.match(/^[ \t]*(?:#|\/\/) freellmapi:start$/m)?.[0];
121
- const end = generated.match(/^[ \t]*(?:#|\/\/) freellmapi:end$/m)?.[0];
122
- if (!start || !end) return generated;
123
- const marked = markerPattern();
124
- if (marked.test(existing)) {
125
- return existing.replace(marked, `${generated.trimEnd()}\n`);
126
- }
127
- const separator = existing.length && !existing.endsWith('\n') ? '\n' : '';
128
- return `${existing}${separator}${existing.trim() ? '\n' : ''}${generated}`;
129
- }
130
-
131
- function topLevelYamlKey(line: string): string | undefined {
132
- return line.match(/^([A-Za-z0-9_-]+):(?:\s|$)/)?.[1];
133
- }
134
-
135
- function generatedYamlKeys(generated: string): Set<string> {
136
- return new Set(generated.split(/\r?\n/)
137
- .map(topLevelYamlKey)
138
- .filter((key): key is string => Boolean(key)));
139
- }
140
-
141
- function removeYamlKeys(existing: string, keys: Set<string>): string {
142
- const lines = existing.split(/\r?\n/);
143
- const output: string[] = [];
144
- for (let index = 0; index < lines.length;) {
145
- const key = topLevelYamlKey(lines[index]);
146
- if (!key || !keys.has(key)) {
147
- output.push(lines[index]);
148
- index += 1;
149
- continue;
150
- }
151
- index += 1;
152
- while (index < lines.length && !topLevelYamlKey(lines[index])) index += 1;
153
- }
154
- return output.join('\n').replace(/\n{3,}/g, '\n\n').trimEnd();
155
- }
156
-
157
- function continueModelLines(generated: string): string[] {
158
- const lines = generated.split(/\r?\n/);
159
- const modelsIndex = lines.findIndex(line => line === 'models:');
160
- const endIndex = lines.findIndex(
161
- (line, index) => index > modelsIndex && line === '# freellmapi:end',
162
- );
163
- return lines.slice(modelsIndex + 1, endIndex < 0 ? undefined : endIndex);
164
- }
165
-
166
- function mergeContinueYaml(existing: string, generated: string): string {
167
- const generatedLines = generated.split(/\r?\n/);
168
- const missingHeader = ['name', 'version', 'schema']
169
- .filter(key => !existing.split(/\r?\n/).some(line => topLevelYamlKey(line) === key))
170
- .map(key => generatedLines.find(line => topLevelYamlKey(line) === key)!)
171
- .filter(Boolean);
172
- let lines = existing.split(/\r?\n/);
173
- const modelsIndex = lines.findIndex(line => topLevelYamlKey(line) === 'models');
174
- const modelLines = continueModelLines(generated);
175
-
176
- if (modelsIndex < 0) {
177
- const prefix = missingHeader.length ? `${missingHeader.join('\n')}\n` : '';
178
- const separator = existing.trim() ? '\n\n' : '';
179
- return `${prefix}${existing.trimEnd()}${separator}models:\n${modelLines.join('\n')}\n`;
180
- }
181
-
182
- let modelsEnd = modelsIndex + 1;
183
- while (modelsEnd < lines.length && !topLevelYamlKey(lines[modelsEnd])) modelsEnd += 1;
184
- const entryStart = lines.findIndex(
185
- (line, index) => index > modelsIndex
186
- && index < modelsEnd
187
- && /^\s{2}-\s+name:\s+["']?FreeLLMAPI["']?\s*$/.test(line),
188
- );
189
- if (entryStart >= 0) {
190
- let entryEnd = entryStart + 1;
191
- while (
192
- entryEnd < modelsEnd
193
- && !/^\s{2}-\s+/.test(lines[entryEnd])
194
- && !topLevelYamlKey(lines[entryEnd])
195
- ) {
196
- entryEnd += 1;
197
- }
198
- lines.splice(entryStart, entryEnd - entryStart, ...modelLines);
199
- } else {
200
- lines.splice(modelsEnd, 0, ...modelLines);
201
- }
202
- if (missingHeader.length) lines = [...missingHeader, ...lines];
203
- return `${lines.join('\n').replace(/\n+$/, '')}\n`;
204
- }
205
-
206
- function mergeYaml(existing: string, generated: string): string {
207
- if (/^name: FreeLLMAPI$/m.test(generated) && /^models:$/m.test(generated)) {
208
- const withoutOldBlock = existing.replace(markerPattern(), '').trimEnd();
209
- return mergeContinueYaml(withoutOldBlock, generated);
210
- }
211
- if (!existing.trim()) return generated;
212
- if (/^# freellmapi:start$/m.test(existing)) return mergeMarked(existing, generated);
213
- const withoutConflicts = removeYamlKeys(existing, generatedYamlKeys(generated));
214
- return mergeMarked(withoutConflicts, generated);
215
- }
216
-
217
- function tomlTableHeader(line: string): string | undefined {
218
- return line.match(/^\[([^\]]+)\]$/)?.[1];
219
- }
220
-
221
- function tomlArrayHeader(line: string): string | undefined {
222
- return line.match(/^\[\[([^\]]+)\]\]$/)?.[1];
223
- }
224
-
225
- function isTomlHeader(line: string): boolean {
226
- return tomlTableHeader(line) !== undefined || tomlArrayHeader(line) !== undefined;
227
- }
228
-
229
- // An array-of-tables entry (`[[providers]]`) has no name of its own; the
230
- // `name = "..."` key inside it is what tools use to tell entries apart.
231
- function tomlEntryName(lines: string[]): string | undefined {
232
- for (const line of lines.slice(1)) {
233
- if (isTomlHeader(line)) break;
234
- const value = line.match(/^\s*name\s*=\s*(?:"([^"]*)"|'([^']*)')/);
235
- if (value) return value[1] ?? value[2];
236
- }
237
- return undefined;
238
- }
239
-
240
- // Splits a document into its root region and one block per header, each block
241
- // running up to the next header.
242
- function tomlBlocks(lines: string[]): string[][] {
243
- const blocks: string[][] = [[]];
244
- for (const line of lines) {
245
- if (isTomlHeader(line)) blocks.push([]);
246
- blocks[blocks.length - 1].push(line);
247
- }
248
- return blocks;
249
- }
250
-
251
- function tomlRootKey(line: string): string | undefined {
252
- return line.match(/^([A-Za-z0-9_.-]+)\s*=/)?.[1];
253
- }
254
-
255
- function isTomlMarkerLine(line: string): boolean {
256
- return /^[ \t]*# freellmapi:(?:start|end)$/.test(line);
257
- }
258
-
259
- function trimBlankEdges(lines: string[]): string[] {
260
- let start = 0;
261
- let end = lines.length;
262
- while (start < end && !lines[start].trim()) start += 1;
263
- while (end > start && !lines[end - 1].trim()) end -= 1;
264
- return lines.slice(start, end);
265
- }
266
-
267
- interface TomlSections {
268
- root: string[];
269
- tables: string[];
270
- }
271
-
272
- function splitTomlSections(generated: string): TomlSections {
273
- const lines = generated.split(/\r?\n/).filter(line => !isTomlMarkerLine(line));
274
- const firstTable = lines.findIndex(isTomlHeader);
275
- if (firstTable < 0) return { root: trimBlankEdges(lines), tables: [] };
276
- return {
277
- root: trimBlankEdges(lines.slice(0, firstTable)),
278
- tables: trimBlankEdges(lines.slice(firstTable)),
279
- };
280
- }
281
-
282
- // TOML keys written after a `[table]` header belong to that table, so
283
- // generated root-level keys must be inserted BEFORE the first table header of
284
- // the existing file, never appended after it. Generated tables are appended at
285
- // the end, and only root keys that the generated ROOT REGION sets are removed
286
- // from the existing root region. An existing `[[array]]` entry is replaced only
287
- // when a generated entry of the same array carries the same `name` — together
288
- // with the `[array.sub]` tables that belong to it — so the user's other entries
289
- // in that array stay put.
290
- function mergeToml(existing: string, generated: string): string {
291
- if (!existing.trim()) return generated;
292
- const { root: generatedRoot, tables: generatedTables } = splitTomlSections(generated);
293
- const rootKeys = new Set(generatedRoot
294
- .map(tomlRootKey)
295
- .filter((key): key is string => Boolean(key)));
296
- const tableNames = new Set(generatedTables
297
- .map(tomlTableHeader)
298
- .filter((name): name is string => Boolean(name)));
299
- const arrayEntries = new Set(tomlBlocks(generatedTables)
300
- .filter(block => block.length && tomlArrayHeader(block[0]))
301
- .map(block => `${tomlArrayHeader(block[0])}\0${tomlEntryName(block)}`));
302
-
303
- const kept: string[] = [];
304
- let droppedArray: string | undefined;
305
- const [existingRoot, ...existingBlocks] = tomlBlocks(
306
- existing.split(/\r?\n/).filter(line => !isTomlMarkerLine(line)),
307
- );
308
- kept.push(...existingRoot.filter(line => !rootKeys.has(tomlRootKey(line) ?? '')));
309
- for (const block of existingBlocks) {
310
- const table = tomlTableHeader(block[0]);
311
- const array = tomlArrayHeader(block[0]);
312
- const name = table ?? array ?? '';
313
- if (droppedArray && name.startsWith(`${droppedArray}.`)) continue;
314
- droppedArray = undefined;
315
- if (table && tableNames.has(table)) continue;
316
- if (array && arrayEntries.has(`${array}\0${tomlEntryName(block)}`)) {
317
- droppedArray = array;
318
- continue;
319
- }
320
- kept.push(...block);
321
- }
322
-
323
- const wrap = (lines: string[]): string[] => (lines.length
324
- ? ['# freellmapi:start', ...lines, '# freellmapi:end']
325
- : []);
326
- const firstTable = kept.findIndex(isTomlHeader);
327
- const head = firstTable < 0 ? kept : kept.slice(0, firstTable);
328
- const tail = firstTable < 0 ? [] : kept.slice(firstTable);
329
- const sections = [head, wrap(generatedRoot), tail, wrap(generatedTables)]
330
- .map(lines => trimBlankEdges(lines).join('\n').replace(/\n{3,}/g, '\n\n'))
331
- .filter(Boolean);
332
- return `${sections.join('\n\n')}\n`;
333
- }
334
-
335
- function mergeEnv(existing: string, generated: string): string {
336
- const replacements = new Map(
337
- generated.split(/\r?\n/)
338
- .filter(line => line && !line.startsWith('#') && line.includes('='))
339
- .map(line => [line.slice(0, line.indexOf('=')), line]),
340
- );
341
- // An absent or empty file has no lines: splitting '' yields [''] and that
342
- // empty line survived as a blank first line in every freshly written .env.
343
- // Trailing blank lines go too, or an appended key lands after a gap.
344
- const lines = existing.trim() ? existing.replace(/(?:\r?\n)+$/, '').split(/\r?\n/) : [];
345
- const seen = new Set<string>();
346
- const output = lines.map(line => {
347
- const separator = line.indexOf('=');
348
- if (separator < 1 || line.trimStart().startsWith('#')) return line;
349
- const key = line.slice(0, separator);
350
- const replacement = replacements.get(key);
351
- if (!replacement) return line;
352
- seen.add(key);
353
- return replacement;
354
- });
355
- for (const [key, line] of replacements) {
356
- if (!seen.has(key)) output.push(line);
357
- }
358
- return `${output.filter((line, index) => line || index < output.length - 1).join('\n')}\n`;
359
- }
360
-
361
- export function renderFile(file: GeneratedFile, existing = ''): string {
362
- if (file.format === 'json') return mergeJson(existing, file.value ?? {}, file.arrays);
363
- if (file.format === 'env') return mergeEnv(existing, file.content ?? '');
364
- if (file.format === 'yaml') {
365
- return file.value
366
- ? mergeYamlDocument(existing, file.value)
367
- : mergeYaml(existing, file.content ?? '');
368
- }
369
- return mergeToml(existing, file.content ?? '');
370
- }
371
-
372
- function timestamp(): string {
373
- return new Date().toISOString().replace(/[:.]/g, '-');
374
- }
375
-
376
- export interface ApplyResult {
377
- path: string;
378
- changed: boolean;
379
- backupPath?: string;
380
- rendered: string;
381
- previous: string;
382
- }
383
-
384
- interface PlannedWrite extends ApplyResult {
385
- file: GeneratedFile;
386
- exists: boolean;
387
- }
388
-
389
- function planGeneratedFile(file: GeneratedFile): PlannedWrite {
390
- const exists = fs.existsSync(file.path);
391
- const previous = exists ? fs.readFileSync(file.path, 'utf8') : '';
392
- const rendered = renderFile(file, previous);
393
- return {
394
- file,
395
- exists,
396
- path: file.path,
397
- changed: rendered !== previous,
398
- rendered,
399
- previous,
400
- };
401
- }
402
-
403
- function commitPlannedWrite(plan: PlannedWrite): ApplyResult {
404
- const { file, exists, ...result } = plan;
405
- if (!plan.changed) return result;
406
- fs.mkdirSync(path.dirname(file.path), { recursive: true, mode: 0o700 });
407
- let backupPath: string | undefined;
408
- if (exists) {
409
- backupPath = `${file.path}.backup-${timestamp()}`;
410
- fs.copyFileSync(file.path, backupPath);
411
- }
412
- const temporary = `${file.path}.freellmapi-${process.pid}.tmp`;
413
- fs.writeFileSync(temporary, plan.rendered, { mode: file.sensitive ? 0o600 : 0o644 });
414
- fs.renameSync(temporary, file.path);
415
- if (file.sensitive) fs.chmodSync(file.path, 0o600);
416
- return { ...result, backupPath };
417
- }
418
-
419
- // Two-phase apply: every target file is read and merged BEFORE the first
420
- // write, so a merge failure on any file aborts the whole batch without
421
- // leaving earlier files modified.
422
- export function applyGeneratedFiles(
423
- files: GeneratedFile[],
424
- dryRun: boolean,
425
- ): ApplyResult[] {
426
- const plans = files.map(planGeneratedFile);
427
- if (dryRun) return plans.map(({ file: _file, exists: _exists, ...result }) => result);
428
- return plans.map(commitPlannedWrite);
429
- }
430
-
431
- export function applyGeneratedFile(file: GeneratedFile, dryRun: boolean): ApplyResult {
432
- return applyGeneratedFiles([file], dryRun)[0];
433
- }
434
-
435
- export function printDryRunDiff(result: ApplyResult): string {
436
- const oldLines = result.previous.split(/\r?\n/);
437
- const newLines = result.rendered.split(/\r?\n/);
438
- const lines = [`--- ${result.path}`, `+++ ${result.path}`];
439
- if (!result.previous) {
440
- lines.push(...newLines.map(line => `+${line}`));
441
- return lines.join('\n');
442
- }
443
- const prefix = oldLines.findIndex((line, index) => line !== newLines[index]);
444
- const changedAt = prefix < 0 ? 0 : prefix;
445
- lines.push(`@@ line ${changedAt + 1} @@`);
446
- lines.push(...oldLines.slice(changedAt).map(line => `-${line}`));
447
- lines.push(...newLines.slice(changedAt).map(line => `+${line}`));
448
- return lines.join('\n');
449
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/src/detect.test.ts DELETED
@@ -1,78 +0,0 @@
1
- import fs from 'node:fs';
2
- import { describe, expect, it, vi, afterEach } from 'vitest';
3
- import {
4
- clientNotes,
5
- desktopAppPath,
6
- detectChatGptClient,
7
- } from './detect.js';
8
-
9
- afterEach(() => {
10
- vi.restoreAllMocks();
11
- vi.unstubAllEnvs();
12
- });
13
-
14
- describe('desktopAppPath', () => {
15
- it('points at /Applications/ChatGPT.app on macOS only', () => {
16
- expect(desktopAppPath('darwin')).toBe('/Applications/ChatGPT.app');
17
- expect(desktopAppPath('linux')).toBeUndefined();
18
- expect(desktopAppPath('win32')).toBeUndefined();
19
- });
20
- });
21
-
22
- describe('detectChatGptClient', () => {
23
- it('detects the CLI when a codex binary is on PATH', () => {
24
- vi.stubEnv('PATH', '/opt/tools/bin');
25
- vi.spyOn(fs, 'accessSync').mockImplementation(() => {});
26
- vi.spyOn(fs, 'statSync').mockReturnValue({ isFile: () => true } as fs.Stats);
27
- vi.spyOn(fs, 'existsSync').mockReturnValue(false);
28
- const found = detectChatGptClient('linux');
29
- expect(found).toEqual({ kind: 'cli', cliPath: '/opt/tools/bin/codex' });
30
- });
31
-
32
- it('ignores PATH directories that merely shadow the binary name', () => {
33
- vi.stubEnv('PATH', '/opt/shadow');
34
- vi.spyOn(fs, 'accessSync').mockImplementation(() => {});
35
- vi.spyOn(fs, 'statSync').mockReturnValue({ isFile: () => false } as fs.Stats);
36
- vi.spyOn(fs, 'existsSync').mockReturnValue(false);
37
- expect(detectChatGptClient('linux')).toBeUndefined();
38
- });
39
-
40
- it('detects the desktop app alone on macOS', () => {
41
- vi.stubEnv('PATH', '');
42
- vi.spyOn(fs, 'existsSync').mockReturnValue(true);
43
- const found = detectChatGptClient('darwin');
44
- expect(found).toEqual({ kind: 'desktop', desktopPath: '/Applications/ChatGPT.app' });
45
- });
46
-
47
- it('reports both when the CLI and the desktop app coexist', () => {
48
- vi.stubEnv('PATH', '/usr/bin');
49
- vi.spyOn(fs, 'accessSync').mockImplementation(() => {});
50
- vi.spyOn(fs, 'statSync').mockReturnValue({ isFile: () => true } as fs.Stats);
51
- vi.spyOn(fs, 'existsSync').mockReturnValue(true);
52
- const found = detectChatGptClient('darwin');
53
- expect(found?.kind).toBe('both');
54
- });
55
-
56
- it('returns undefined when nothing is installed', () => {
57
- vi.stubEnv('PATH', '');
58
- vi.spyOn(fs, 'existsSync').mockReturnValue(false);
59
- expect(detectChatGptClient('darwin')).toBeUndefined();
60
- });
61
- });
62
-
63
- describe('clientNotes', () => {
64
- it('offers the install command when no client exists', () => {
65
- const notes = clientNotes(undefined);
66
- expect(notes.join('\n')).toContain('npm install -g @openai/codex');
67
- });
68
-
69
- it('points a desktop-only install at the Codex CLI', () => {
70
- const notes = clientNotes({ kind: 'desktop', desktopPath: '/Applications/ChatGPT.app' });
71
- expect(notes.join('\n')).toContain('this setup configures the Codex CLI');
72
- });
73
-
74
- it('names the CLI path when it is detected', () => {
75
- const notes = clientNotes({ kind: 'cli', cliPath: '/usr/local/bin/codex' });
76
- expect(notes.join('\n')).toContain('/usr/local/bin/codex');
77
- });
78
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/src/detect.ts DELETED
@@ -1,83 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
-
4
- // Client detection for the Codex CLI integration. `setup-codex` only WRITES a
5
- // config; this module tells the user WHICH client they actually have so the
6
- // setup note can say something true about their machine instead of a generic
7
- // "install X" line. Purely filesystem/PATH based — no network, no spawning
8
- // processes — so it stays fast and testable.
9
-
10
- export interface DetectedClient {
11
- /** `cli` — the `codex` binary is on PATH; `desktop` — the ChatGPT desktop
12
- * app is installed (macOS); `both` — self-explanatory. */
13
- kind: 'cli' | 'desktop' | 'both';
14
- /** Absolute path of the first `codex` binary found on PATH, when present. */
15
- cliPath?: string;
16
- /** Absolute path of the ChatGPT.app bundle, when present. */
17
- desktopPath?: string;
18
- }
19
-
20
- /** Where the ChatGPT desktop app lives per platform. Only macOS ships a
21
- * well-known .app bundle; Windows/Linux register no stable path we can
22
- * probe cheaply, so those return nothing (a UI integration there would need
23
- * registry/freedesktop lookups — out of scope). */
24
- export function desktopAppPath(platform: string = process.platform): string | undefined {
25
- if (platform !== 'darwin') return undefined;
26
- return '/Applications/ChatGPT.app';
27
- }
28
-
29
- function executableOnPath(name: string): string | undefined {
30
- const dirs = (process.env.PATH ?? '').split(path.delimiter).filter(Boolean);
31
- for (const dir of dirs) {
32
- const candidate = path.join(dir, name);
33
- try {
34
- fs.accessSync(candidate, fs.constants.X_OK);
35
- // Directories on PATH shadow real binaries (a common nvm artifact);
36
- // only a regular file counts.
37
- if (fs.statSync(candidate).isFile()) return candidate;
38
- } catch {
39
- // Not here; keep scanning.
40
- }
41
- }
42
- return undefined;
43
- }
44
-
45
- /** Detects the `codex` CLI on PATH and the ChatGPT desktop app on macOS.
46
- * Only the `codex` binary is probed: the CLI still ships and runs as
47
- * `codex`, and that is the only surface `setup-codex` configures. */
48
- export function detectChatGptClient(
49
- platform: string = process.platform,
50
- ): DetectedClient | undefined {
51
- const cliPath = executableOnPath('codex');
52
- const appPath = desktopAppPath(platform);
53
- const hasDesktop = appPath !== undefined && fs.existsSync(appPath);
54
- if (cliPath && hasDesktop) return { kind: 'both', cliPath, desktopPath: appPath };
55
- if (cliPath) return { kind: 'cli', cliPath };
56
- if (hasDesktop) return { kind: 'desktop', desktopPath: appPath };
57
- return undefined;
58
- }
59
-
60
- /** Human-readable guidance appended to `setup-codex` output. This setup only
61
- * writes the Codex CLI config, so the desktop app is reported but never
62
- * configured. */
63
- export function clientNotes(client: DetectedClient | undefined): string[] {
64
- if (!client) {
65
- return [
66
- 'No Codex CLI detected on this machine.',
67
- 'Install the CLI with: npm install -g @openai/codex',
68
- ];
69
- }
70
- if (client.kind === 'desktop') {
71
- return [
72
- `ChatGPT desktop app detected at ${client.desktopPath}; this setup configures the Codex CLI.`,
73
- 'The generated configuration targets the Codex CLI — install it with: npm install -g @openai/codex',
74
- ];
75
- }
76
- if (client.kind === 'both') {
77
- return [
78
- `Codex CLI detected at ${client.cliPath}; the configuration above applies to it.`,
79
- 'ChatGPT desktop app also detected; it is not configured by this setup.',
80
- ];
81
- }
82
- return [`Codex CLI detected at ${client.cliPath}; the configuration above applies to it.`];
83
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/src/doctor.test.ts DELETED
@@ -1,399 +0,0 @@
1
- import fs from 'node:fs';
2
- import os from 'node:os';
3
- import path from 'node:path';
4
- import { afterEach, describe, expect, it } from 'vitest';
5
- import {
6
- DEFAULT_PROBE_TIMEOUT_MS,
7
- claudeLayers,
8
- codexLayers,
9
- diagnose,
10
- exitCodeFor,
11
- managedSettingsDir,
12
- managedSettingsPaths,
13
- normalizeUrl,
14
- probeGateway,
15
- sameGateway,
16
- } from './doctor.js';
17
-
18
- const temporary: string[] = [];
19
- function tempHome(): string {
20
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'freellmapi-doctor-'));
21
- temporary.push(dir);
22
- return dir;
23
- }
24
- afterEach(() => {
25
- for (const dir of temporary.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
26
- });
27
-
28
- /** A fetch double that answers /livez exactly as the real gateway does. */
29
- function gatewayFetch(
30
- body: unknown = { status: 'ok', version: '0.7.0', uptime_s: 12 },
31
- status = 200,
32
- ): typeof fetch {
33
- return (async () => ({ status, json: async () => body })) as unknown as typeof fetch;
34
- }
35
-
36
- /** The real 503 body from routes/status.ts when the db or encryption key is down. */
37
- const UNAVAILABLE = { status: 'unavailable', version: '0.7.0', uptime_s: 12, checks: { db: false } };
38
- const deadFetch = (async () => { throw new Error('ECONNREFUSED'); }) as unknown as typeof fetch;
39
-
40
- function writeClaudeSettings(home: string, value: Record<string, unknown>): void {
41
- const dir = path.join(home, '.claude');
42
- fs.mkdirSync(dir, { recursive: true });
43
- fs.writeFileSync(path.join(dir, 'settings.json'), JSON.stringify(value));
44
- }
45
-
46
- function writeCodexConfig(home: string, toml: string): void {
47
- const dir = path.join(home, '.codex');
48
- fs.mkdirSync(dir, { recursive: true });
49
- fs.writeFileSync(path.join(dir, 'config.toml'), toml);
50
- }
51
-
52
- describe('managed settings locations', () => {
53
- // The reported paths are built with the TARGET platform's separator, but the
54
- // test's own `path.join` uses the HOST's — on Windows the two disagree, so
55
- // compare separator-normalized forms (#1392).
56
- function asPosix(p: string): string {
57
- return p.replaceAll('\\', '/');
58
- }
59
- it('uses the documented system directory for each platform', () => {
60
- expect(managedSettingsDir('darwin')).toBe('/Library/Application Support/ClaudeCode');
61
- expect(managedSettingsDir('linux')).toBe('/etc/claude-code');
62
- expect(managedSettingsDir('win32')).toBe('C:\\Program Files\\ClaudeCode');
63
- });
64
-
65
- it('falls back to the base file alone when there is no drop-in directory', () => {
66
- // The usual case: an unreadable or absent managed-settings.d contributes
67
- // nothing rather than failing the whole report.
68
- const dir = tempHome();
69
- expect(managedSettingsPaths('linux', dir).map(asPosix)).toEqual([path.join(dir, 'managed-settings.json')].map(asPosix));
70
- });
71
-
72
- it('ranks managed-settings.d drop-ins above the base file, last one first', () => {
73
- // The drop-in files are merged alphabetically ON TOP of the base, so the
74
- // alphabetically LAST one wins and the base loses to all of them. Getting
75
- // this order backwards would name the wrong layer as effective for a
76
- // fleet-managed install — the exact confident-wrong answer doctor exists
77
- // to prevent.
78
- const dir = tempHome();
79
- fs.mkdirSync(path.join(dir, 'managed-settings.d'));
80
- for (const name of ['20-b.json', '10-a.json', 'notes.txt']) {
81
- fs.writeFileSync(path.join(dir, 'managed-settings.d', name), '{}');
82
- }
83
-
84
- expect(managedSettingsPaths('linux', dir).map(asPosix)).toEqual([
85
- path.join(dir, 'managed-settings.d', '20-b.json'),
86
- path.join(dir, 'managed-settings.d', '10-a.json'),
87
- path.join(dir, 'managed-settings.json'),
88
- ].map(asPosix));
89
- });
90
- });
91
-
92
- describe('url comparison', () => {
93
- it('ignores trailing slashes, a /v1 suffix, and host case', () => {
94
- expect(normalizeUrl('http://Localhost:3000/v1/')).toBe('http://localhost:3000');
95
- expect(sameGateway('http://localhost:3000', 'http://localhost:3000/v1')).toBe(true);
96
- expect(sameGateway('http://localhost:3000', 'http://localhost:3001')).toBe(false);
97
- expect(sameGateway(undefined, 'http://localhost:3000')).toBe(false);
98
- });
99
-
100
- it('keeps a path prefix, so two mounts on one host are not confused', () => {
101
- // A gateway mounted under a prefix is a different endpoint. Folding the
102
- // path away reported these as the same gateway.
103
- expect(normalizeUrl('http://host/gateway/v1/')).toBe('http://host/gateway');
104
- expect(sameGateway('http://host/gateway', 'http://host/other')).toBe(false);
105
- expect(sameGateway('http://host/gateway/v1', 'http://host/gateway/')).toBe(true);
106
- expect(sameGateway('http://host/gateway', 'http://host')).toBe(false);
107
- });
108
-
109
- it('keeps path case, which is case-sensitive, while folding the host', () => {
110
- expect(normalizeUrl('HTTP://Host:3000/Gateway')).toBe('http://host:3000/Gateway');
111
- expect(sameGateway('http://host/Gateway', 'http://host/gateway')).toBe(false);
112
- });
113
-
114
- it('drops query and fragment, which never identify the endpoint', () => {
115
- expect(normalizeUrl('http://host:3000/v1?k=1#x')).toBe('http://host:3000');
116
- });
117
-
118
- it('falls back to lexical trimming for an unparseable value', () => {
119
- // A malformed config value must still produce a report, not an exception.
120
- expect(normalizeUrl('localhost:3000/v1/')).toBe('localhost:3000');
121
- });
122
- });
123
-
124
- describe('claude precedence', () => {
125
- it('ranks a settings env block ABOVE the inherited shell environment', () => {
126
- // The easy thing to get backwards, and I did: Claude Code writes each
127
- // `env` entry into the process environment at startup, REPLACING what the
128
- // shell exported. The shell is the lowest layer, not the highest.
129
- const home = tempHome();
130
- writeClaudeSettings(home, { env: { ANTHROPIC_BASE_URL: 'http://localhost:3000' } });
131
- const layers = claudeLayers({ ANTHROPIC_BASE_URL: 'https://api.anthropic.com' }, home, tempHome());
132
-
133
- expect(layers[0]).toMatchObject({ value: 'http://localhost:3000', effective: true });
134
- expect(layers[1]).toMatchObject({ value: 'https://api.anthropic.com', effective: false });
135
- });
136
-
137
- it('uses the shell value when no settings file names one', () => {
138
- expect(claudeLayers({ ANTHROPIC_BASE_URL: 'http://localhost:3000' }, tempHome(), tempHome())[0])
139
- .toMatchObject({ value: 'http://localhost:3000', effective: true });
140
- });
141
-
142
- it('ranks project-local settings above the user scope', () => {
143
- const home = tempHome();
144
- const project = tempHome();
145
- writeClaudeSettings(home, { env: { ANTHROPIC_BASE_URL: 'http://user:1' } });
146
- fs.mkdirSync(path.join(project, '.claude'), { recursive: true });
147
- fs.writeFileSync(
148
- path.join(project, '.claude', 'settings.local.json'),
149
- JSON.stringify({ env: { ANTHROPIC_BASE_URL: 'http://project-local:2' } }),
150
- );
151
-
152
- expect(claudeLayers({}, home, project)[0])
153
- .toMatchObject({ value: 'http://project-local:2', effective: true });
154
- });
155
-
156
- it('honours CLAUDE_CONFIG_DIR for the user scope', () => {
157
- // Relocates the user scope wholesale; missing it reads a settings file the
158
- // running tool never opens.
159
- const home = tempHome();
160
- const configDir = tempHome();
161
- writeClaudeSettings(home, { env: { ANTHROPIC_BASE_URL: 'http://ignored:1' } });
162
- fs.writeFileSync(
163
- path.join(configDir, 'settings.json'),
164
- JSON.stringify({ env: { ANTHROPIC_BASE_URL: 'http://relocated:2' } }),
165
- );
166
-
167
- expect(claudeLayers({ CLAUDE_CONFIG_DIR: configDir }, home, tempHome())[0]?.value)
168
- .toBe('http://relocated:2');
169
- });
170
-
171
- it('reports no layers rather than throwing on absent or malformed settings', () => {
172
- const home = tempHome();
173
- expect(claudeLayers({}, home, tempHome())).toEqual([]);
174
- fs.mkdirSync(path.join(home, '.claude'), { recursive: true });
175
- fs.writeFileSync(path.join(home, '.claude', 'settings.json'), '{ not json');
176
- expect(claudeLayers({}, home, tempHome())).toEqual([]);
177
- });
178
- });
179
-
180
- describe('codex precedence', () => {
181
- it('resolves the SELECTED provider, not the first base_url in the file', () => {
182
- // Codex names a provider and the provider carries the url. Reading any
183
- // base_url would report a provider the user is not selecting.
184
- const home = tempHome();
185
- writeCodexConfig(home, [
186
- 'model_provider = "freellmapi"',
187
- '',
188
- '[model_providers.other]',
189
- 'base_url = "http://not-this-one:9999/v1"',
190
- '',
191
- '[model_providers.freellmapi]',
192
- 'base_url = "http://localhost:3000/v1"',
193
- ].join('\n'));
194
-
195
- expect(codexLayers({}, home)[0]).toMatchObject({
196
- value: 'http://localhost:3000/v1',
197
- effective: true,
198
- });
199
- });
200
-
201
- it('reads the dotted-key spelling too', () => {
202
- const home = tempHome();
203
- writeCodexConfig(home, [
204
- 'model_provider = "freellmapi"',
205
- 'model_providers.freellmapi.base_url = "http://localhost:3000/v1"',
206
- ].join('\n'));
207
- expect(codexLayers({}, home)[0]?.value).toBe('http://localhost:3000/v1');
208
- });
209
-
210
- it('honours CODEX_HOME over the default location', () => {
211
- const home = tempHome();
212
- const alternate = tempHome();
213
- writeCodexConfig(home, 'model_provider = "a"\n[model_providers.a]\nbase_url = "http://default:1/v1"');
214
- writeCodexConfig(alternate, 'model_provider = "b"\n[model_providers.b]\nbase_url = "http://override:2/v1"');
215
-
216
- const layers = codexLayers({ CODEX_HOME: path.join(alternate, '.codex') }, home);
217
- expect(layers[0]?.value).toBe('http://override:2/v1');
218
- });
219
-
220
- it('records a selected provider that names no base_url instead of skipping it', () => {
221
- const home = tempHome();
222
- writeCodexConfig(home, 'model_provider = "freellmapi"\n');
223
- const layer = codexLayers({}, home)[0];
224
- expect(layer.effective).toBe(true);
225
- expect(layer.value).toBeUndefined();
226
- expect(layer.source).toContain('no base_url found');
227
- });
228
- });
229
-
230
- describe('verdicts', () => {
231
- const url = 'http://localhost:3000';
232
-
233
- it('routed only when the tool reaches THIS gateway', async () => {
234
- const report = await diagnose('claude', {
235
- expectedUrl: url,
236
- env: { ANTHROPIC_BASE_URL: url },
237
- homeDir: tempHome(), cwd: tempHome(),
238
- fetchImpl: gatewayFetch(),
239
- });
240
- expect(report.verdict).toBe('routed');
241
- expect(report.gateway?.version).toBe('0.7.0');
242
- });
243
-
244
- it('elsewhere — not routed — when the tool reaches a different host that is alive', async () => {
245
- // The regression this guards: reporting `routed` for a Claude Code pinned
246
- // to api.anthropic.com, because it does reach what it is configured to
247
- // reach. That is a confident wrong answer to the question being asked.
248
- const report = await diagnose('claude', {
249
- expectedUrl: url,
250
- env: { ANTHROPIC_BASE_URL: 'https://api.anthropic.com' },
251
- homeDir: tempHome(), cwd: tempHome(),
252
- fetchImpl: gatewayFetch(),
253
- });
254
- expect(report.verdict).toBe('elsewhere');
255
- expect(report.detail).toContain('does not touch this gateway');
256
- });
257
-
258
- it('elsewhere when the right port answers, but not the way this gateway does', async () => {
259
- const report = await diagnose('claude', {
260
- expectedUrl: url,
261
- env: { ANTHROPIC_BASE_URL: url },
262
- homeDir: tempHome(), cwd: tempHome(),
263
- fetchImpl: gatewayFetch({ hello: 'some other service' }),
264
- });
265
- expect(report.verdict).toBe('elsewhere');
266
- });
267
-
268
- it('shadowed names the layer that wins, and the value it beat', async () => {
269
- const home = tempHome();
270
- writeClaudeSettings(home, { env: { ANTHROPIC_BASE_URL: url } });
271
- const report = await diagnose('claude', {
272
- expectedUrl: url,
273
- env: { ANTHROPIC_BASE_URL: 'https://api.anthropic.com' },
274
- homeDir: home, cwd: tempHome(),
275
- fetchImpl: gatewayFetch(),
276
- });
277
-
278
- expect(report.verdict).toBe('shadowed');
279
- // The settings block is what wins, so it is what shadows — and the shell
280
- // export the user probably set by hand is what got overridden.
281
- expect(report.shadowedBy).toContain('settings.json');
282
- expect(report.detail).toContain('process environment');
283
- expect(report.detail).toContain('https://api.anthropic.com');
284
- });
285
-
286
- it('degraded — not routed, not elsewhere — when this gateway says it cannot serve', async () => {
287
- // Routing is correct and the gateway is unmistakably this one; it is sick.
288
- // `routed` would send the user hunting through config that is already
289
- // right, and `elsewhere` would blame a service that is not there.
290
- const report = await diagnose('claude', {
291
- expectedUrl: url,
292
- env: { ANTHROPIC_BASE_URL: url },
293
- homeDir: tempHome(), cwd: tempHome(),
294
- fetchImpl: gatewayFetch(UNAVAILABLE, 503),
295
- });
296
- expect(report.verdict).toBe('degraded');
297
- expect(report.detail).toContain('that IS this gateway');
298
- expect(report.detail).toContain('unavailable');
299
- expect(report.gateway).toMatchObject({ identified: true, healthy: false });
300
- });
301
-
302
- it('unreachable when the configured endpoint answers nothing', async () => {
303
- const report = await diagnose('claude', {
304
- expectedUrl: url,
305
- env: { ANTHROPIC_BASE_URL: url },
306
- homeDir: tempHome(), cwd: tempHome(),
307
- fetchImpl: deadFetch,
308
- });
309
- expect(report.verdict).toBe('unreachable');
310
- expect(report.detail).toContain('ECONNREFUSED');
311
- });
312
-
313
- it('unknown when nothing configures the tool at all', async () => {
314
- const report = await diagnose('claude', {
315
- expectedUrl: url,
316
- env: {},
317
- homeDir: tempHome(), cwd: tempHome(),
318
- fetchImpl: gatewayFetch(),
319
- });
320
- expect(report.verdict).toBe('unknown');
321
- expect(report.detail).toContain('vendor default');
322
- });
323
-
324
- it('unknown, not a crash, for a tool doctor does not model', async () => {
325
- const report = await diagnose('aider', { expectedUrl: url, env: {}, homeDir: tempHome() });
326
- expect(report.verdict).toBe('unknown');
327
- expect(report.detail).toContain('claude');
328
- });
329
- });
330
-
331
- describe('probeGateway', () => {
332
- it('requires all three /livez fields before claiming identity', async () => {
333
- // /livez carries no product marker, so the shape is the only evidence
334
- // available. Two of three fields is not it.
335
- expect((await probeGateway('http://x', gatewayFetch({ status: 'ok', version: '1' }))).identified)
336
- .toBe(false);
337
- expect((await probeGateway('http://x', gatewayFetch())).identified).toBe(true);
338
- });
339
-
340
- it('treats a non-JSON body as reachable but unidentified', async () => {
341
- const htmlFetch = (async () => ({
342
- status: 200,
343
- json: async () => { throw new Error('not json'); },
344
- })) as unknown as typeof fetch;
345
- expect(await probeGateway('http://x', htmlFetch))
346
- .toMatchObject({ reachable: true, identified: false, healthy: false });
347
- });
348
-
349
- it('still IDENTIFIES the gateway when it answers 503 unavailable', async () => {
350
- // The server really emits this when the db or encryption key is down, and
351
- // it is unmistakably this gateway. Folding health into identity would
352
- // report a correctly-routed sick gateway as a foreign service.
353
- expect(await probeGateway('http://x', gatewayFetch(UNAVAILABLE, 503))).toMatchObject({
354
- reachable: true,
355
- identified: true,
356
- healthy: false,
357
- serviceStatus: 'unavailable',
358
- status: 503,
359
- });
360
- });
361
-
362
- it('treats an unrecognized status value as unhealthy, not unidentified', async () => {
363
- // A status added later must degrade into a truthful "this gateway says
364
- // <status>", never into a claim that it is some other service.
365
- const probe = await probeGateway(
366
- 'http://x',
367
- gatewayFetch({ status: 'draining', version: '9', uptime_s: 1 }),
368
- );
369
- expect(probe).toMatchObject({ identified: true, healthy: false, serviceStatus: 'draining' });
370
- });
371
-
372
- it('is unhealthy when a non-2xx carries an ok body', async () => {
373
- expect((await probeGateway('http://x', gatewayFetch(undefined, 500))).healthy).toBe(false);
374
- });
375
-
376
- it('honours the caller-supplied timeout instead of the hard-coded default', async () => {
377
- // Threaded so a slow link is not misreported as unreachable. That the
378
- // caller's 20ms fires at all is the proof: the 5s default would not have.
379
- const neverAnswers = (async (_url: string, init: RequestInit) => new Promise((_resolve, reject) => {
380
- init.signal?.addEventListener('abort', () => reject(new Error('The operation was aborted')));
381
- })) as unknown as typeof fetch;
382
-
383
- const started = Date.now();
384
- const probe = await probeGateway('http://x', neverAnswers, 20);
385
- expect(Date.now() - started).toBeLessThan(DEFAULT_PROBE_TIMEOUT_MS);
386
- expect(probe).toMatchObject({ reachable: false, identified: false, healthy: false });
387
- expect(probe.error).toContain('abort');
388
- });
389
- });
390
-
391
- describe('exit code', () => {
392
- it('is zero only when every tool is routed', () => {
393
- expect(exitCodeFor([{ verdict: 'routed' } as never])).toBe(0);
394
- expect(exitCodeFor([{ verdict: 'routed' } as never, { verdict: 'elsewhere' } as never])).toBe(1);
395
- expect(exitCodeFor([{ verdict: 'unknown' } as never])).toBe(1);
396
- // A gateway that cannot serve is a failed precondition, not a pass.
397
- expect(exitCodeFor([{ verdict: 'degraded' } as never])).toBe(1);
398
- });
399
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/src/doctor.ts DELETED
@@ -1,508 +0,0 @@
1
- // `freellmapi doctor` — does this tool's traffic actually reach this gateway?
2
- //
3
- // The load-bearing constraint: the verdict must be computed in a process that
4
- // INHERITS THE USER'S SESSION ENVIRONMENT. The server cannot answer this
5
- // question, because the failure being diagnosed is a request that never
6
- // arrives — there is nothing in any server-side log to look at. So the check
7
- // resolves each tool's effective connection the way that tool resolves it, in
8
- // this process, and only then asks the gateway whether it is alive.
9
- //
10
- // The motivating failure is real and silent: a launcher that sets
11
- // ANTHROPIC_BASE_URL into the process environment overrides the `env` block of
12
- // ~/.claude/settings.json, so a user who edited settings.json is routed
13
- // somewhere else entirely and nothing says so.
14
-
15
- import fs from 'node:fs';
16
- import os from 'node:os';
17
- import path from 'node:path';
18
-
19
- // 'elsewhere' is not decoration. Without it the first real run of this command
20
- // reported `OK claude: routed` for a Claude Code pinned to api.anthropic.com —
21
- // technically "it reaches what it is configured to reach", and precisely the
22
- // confident-wrong answer the command exists to prevent. `routed` now means
23
- // "reaches THIS gateway", which is the only question the user is asking.
24
- export type Verdict = 'routed' | 'degraded' | 'elsewhere' | 'shadowed' | 'unreachable' | 'unknown';
25
-
26
- export interface Layer {
27
- /** Where the value came from, in the tool's own vocabulary. */
28
- source: string;
29
- value?: string;
30
- /** True for the layer whose value the tool will actually use. */
31
- effective: boolean;
32
- }
33
-
34
- export interface ToolReport {
35
- tool: string;
36
- verdict: Verdict;
37
- /** Every layer that set a value, highest precedence first. */
38
- layers: Layer[];
39
- /** The base URL the tool will really use, if one could be determined. */
40
- effectiveUrl?: string;
41
- /** For 'shadowed': the layer that beat the one the user probably edited. */
42
- shadowedBy?: string;
43
- /** Gateway identity, when the effective URL was probed. */
44
- gateway?: GatewayProbe;
45
- detail: string;
46
- }
47
-
48
- export interface GatewayProbe {
49
- reachable: boolean;
50
- /** Whether the response looks like this product. See probeGateway. */
51
- identified: boolean;
52
- /** Whether the gateway says it can actually serve requests right now. */
53
- healthy: boolean;
54
- /** The `status` field verbatim: 'ok', 'unavailable', or anything added later. */
55
- serviceStatus?: string;
56
- version?: string;
57
- /** HTTP status of the /livez response. */
58
- status?: number;
59
- error?: string;
60
- }
61
-
62
- /**
63
- * Normalize for comparison: scheme + host + port + path prefix, with any
64
- * trailing slash and `/v1` suffix removed.
65
- *
66
- * The path is KEPT, and kept case-sensitively. A gateway mounted under a prefix
67
- * (`http://host/gateway`) is a different endpoint from `http://host/other`, and
68
- * folding the path away would report the two as the same gateway. Only the
69
- * scheme and host are case-folded, because only those are case-insensitive.
70
- * Query and fragment are dropped: they never identify the endpoint.
71
- *
72
- * The result is also what the probe is built on, so it must stay a usable URL.
73
- */
74
- export function normalizeUrl(url: string): string {
75
- const trimmed = url.trim();
76
- const lexical = (): string => trimmed.replace(/\/+$/, '').replace(/\/v1$/i, '').toLowerCase();
77
- let parsed: URL;
78
- try {
79
- parsed = new URL(trimmed);
80
- } catch {
81
- // Not parseable at all — fall back to lexical trimming rather than
82
- // throwing, so a malformed config value still yields a report.
83
- return lexical();
84
- }
85
- // A scheme-less value like `localhost:3000/v1` PARSES, as the opaque path
86
- // `3000/v1` under a `localhost:` scheme, and rebuilding it from parts would
87
- // produce nonsense. An empty host is the tell.
88
- if (!parsed.host) return lexical();
89
- const prefix = parsed.pathname.replace(/\/+$/, '').replace(/\/v1$/i, '');
90
- return `${parsed.protocol.toLowerCase()}//${parsed.host.toLowerCase()}${prefix}`;
91
- }
92
-
93
- export function sameGateway(a: string | undefined, b: string | undefined): boolean {
94
- if (!a || !b) return false;
95
- return normalizeUrl(a) === normalizeUrl(b);
96
- }
97
-
98
- function readJsonIfPresent(file: string): Record<string, unknown> | undefined {
99
- try {
100
- if (!fs.existsSync(file)) return undefined;
101
- // Claude Code's settings.json is strict JSON, not JSONC.
102
- return JSON.parse(fs.readFileSync(file, 'utf8')) as Record<string, unknown>;
103
- } catch {
104
- return undefined;
105
- }
106
- }
107
-
108
- /** The system directory holding Claude Code's MANAGED settings — the scope
109
- * nothing else can override. */
110
- export function managedSettingsDir(platform: string = process.platform): string {
111
- if (platform === 'win32') return 'C:\\Program Files\\ClaudeCode';
112
- if (platform === 'darwin') return '/Library/Application Support/ClaudeCode';
113
- return '/etc/claude-code';
114
- }
115
-
116
- /**
117
- * Managed settings files, HIGHEST PRECEDENCE FIRST.
118
- *
119
- * Not one file. The same directory also supports a `managed-settings.d/`
120
- * drop-in, whose `*.json` files are merged alphabetically ON TOP of the base
121
- * `managed-settings.json` — so a drop-in outranks the base, and the
122
- * alphabetically LAST drop-in outranks the ones before it. Reading only the
123
- * base file is how this command would confidently name the wrong effective
124
- * URL for exactly the fleet-managed install most likely to have one imposed:
125
- * it would report the layer the operator can see and miss the one actually
126
- * winning.
127
- *
128
- * An unreadable directory (the usual case — it does not exist) contributes
129
- * nothing rather than failing the report.
130
- */
131
- export function managedSettingsPaths(
132
- platform: string = process.platform,
133
- dir: string = managedSettingsDir(platform),
134
- ): string[] {
135
- const separator = platform === 'win32' ? '\\' : '/';
136
- const dropInDir = `${dir}${separator}managed-settings.d`;
137
- let dropIns: string[] = [];
138
- try {
139
- dropIns = fs.readdirSync(dropInDir)
140
- .filter(name => name.endsWith('.json'))
141
- .sort()
142
- .reverse() // alphabetically last is merged last, so it wins
143
- .map(name => `${dropInDir}${separator}${name}`);
144
- } catch {
145
- dropIns = [];
146
- }
147
- return [...dropIns, `${dir}${separator}managed-settings.json`];
148
- }
149
-
150
- /** ANTHROPIC_BASE_URL out of a settings file's `env` block. */
151
- function envBlockUrl(file: string): string | undefined {
152
- const block = readJsonIfPresent(file)?.env;
153
- if (!block || typeof block !== 'object' || Array.isArray(block)) return undefined;
154
- const value = (block as Record<string, unknown>).ANTHROPIC_BASE_URL;
155
- return typeof value === 'string' && value ? value : undefined;
156
- }
157
-
158
- /**
159
- * Claude Code's base-URL layers, HIGHEST PRECEDENCE FIRST.
160
- *
161
- * The ordering that matters, and the one it is easy to get backwards: a
162
- * settings file's `env` block BEATS the inherited shell environment. Claude
163
- * Code writes each `env` entry into the process environment at startup and
164
- * again when the file changes, replacing what the shell exported. So the
165
- * process environment is the LOWEST layer here, not the highest.
166
- *
167
- * The familiar "my launcher overrode my settings.json" case is not a
168
- * counter-example: a launcher that wins is writing MANAGED settings, which
169
- * outrank every other scope — note that the rest of that same `env` block
170
- * still applies, which is what makes the override so hard to see by reading
171
- * config alone.
172
- */
173
- export function claudeLayers(
174
- env: NodeJS.ProcessEnv,
175
- homeDir: string,
176
- cwd: string = process.cwd(),
177
- platform: string = process.platform,
178
- ): Layer[] {
179
- const layers: Layer[] = [];
180
-
181
- for (const managed of managedSettingsPaths(platform)) {
182
- const value = envBlockUrl(managed);
183
- if (value) layers.push({ source: `${managed} (MANAGED env block)`, value, effective: false });
184
- }
185
-
186
- for (const file of [
187
- path.join(cwd, '.claude', 'settings.local.json'),
188
- path.join(cwd, '.claude', 'settings.json'),
189
- // CLAUDE_CONFIG_DIR relocates the user scope wholesale; missing it reads
190
- // a settings file the running tool never opens.
191
- path.join(env.CLAUDE_CONFIG_DIR ?? path.join(homeDir, '.claude'), 'settings.json'),
192
- ]) {
193
- const value = envBlockUrl(file);
194
- if (value) layers.push({ source: `${file} (env block)`, value, effective: false });
195
- }
196
-
197
- if (env.ANTHROPIC_BASE_URL) {
198
- layers.push({
199
- source: 'ANTHROPIC_BASE_URL (process environment)',
200
- value: env.ANTHROPIC_BASE_URL,
201
- effective: false,
202
- });
203
- }
204
-
205
- if (layers.length) layers[0].effective = true;
206
- return layers;
207
- }
208
-
209
- /**
210
- * Codex's base-URL layers, highest precedence first.
211
- *
212
- * Codex resolves a PROVIDER, not a URL: `model_provider` names a key in the
213
- * `[model_providers]` table and that entry carries base_url. Reading only
214
- * `base_url` occurrences would report a provider the user is not selecting,
215
- * so the selected name is resolved first.
216
- */
217
- export function codexLayers(
218
- env: NodeJS.ProcessEnv,
219
- homeDir: string,
220
- ): Layer[] {
221
- const layers: Layer[] = [];
222
- const configPath = path.join(env.CODEX_HOME ?? path.join(homeDir, '.codex'), 'config.toml');
223
- let toml = '';
224
- try {
225
- toml = fs.existsSync(configPath) ? fs.readFileSync(configPath, 'utf8') : '';
226
- } catch {
227
- toml = '';
228
- }
229
-
230
- const selected = /^\s*model_provider\s*=\s*["']([^"']+)["']/m.exec(toml)?.[1];
231
- if (selected) {
232
- // Both spellings the file format allows: a dotted key and a section.
233
- const dotted = new RegExp(
234
- `^\\s*model_providers\\.${escapeRegExp(selected)}\\.base_url\\s*=\\s*["']([^"']+)["']`,
235
- 'm',
236
- ).exec(toml)?.[1];
237
- const section = sectionValue(toml, `model_providers.${selected}`, 'base_url');
238
- const url = dotted ?? section;
239
- if (url) {
240
- layers.push({
241
- source: `${configPath} ([model_providers.${selected}] base_url)`,
242
- value: url,
243
- effective: false,
244
- });
245
- } else {
246
- layers.push({
247
- source: `${configPath} (model_provider = "${selected}", no base_url found)`,
248
- effective: false,
249
- });
250
- }
251
- }
252
-
253
- if (layers.length) layers[0].effective = true;
254
- return layers;
255
- }
256
-
257
- function escapeRegExp(value: string): string {
258
- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
259
- }
260
-
261
- /** Value of `key` inside a `[section]` block of a TOML document. */
262
- function sectionValue(toml: string, section: string, key: string): string | undefined {
263
- const lines = toml.split('\n');
264
- let inSection = false;
265
- for (const raw of lines) {
266
- const line = raw.trim();
267
- const header = /^\[([^\]]+)\]$/.exec(line);
268
- if (header) {
269
- inSection = header[1].trim() === section;
270
- continue;
271
- }
272
- if (!inSection) continue;
273
- const match = new RegExp(`^${escapeRegExp(key)}\\s*=\\s*["']([^"']+)["']`).exec(line);
274
- if (match) return match[1];
275
- }
276
- return undefined;
277
- }
278
-
279
- /** How long the /livez probe waits before calling an endpoint unreachable. */
280
- export const DEFAULT_PROBE_TIMEOUT_MS = 5_000;
281
-
282
- /**
283
- * Probe a base URL's identity AND its health — two separate questions that must
284
- * not be collapsed.
285
- *
286
- * IDENTITY is structural: `/livez` answers `{status, version, uptime_s}` and
287
- * carries NO product identifier, so a body with that exact shape is evidence,
288
- * not proof — another service could serve the same three keys. `identified`
289
- * therefore means "responds the way this gateway responds", and the report says
290
- * so. Asserting identity harder would need either an authenticated call (the
291
- * CLI does not have a key here) or a product marker the server does not emit.
292
- *
293
- * HEALTH is the `status` VALUE, and it is deliberately not folded into
294
- * identity. The server really does emit `{status: 'unavailable', ...}` with a
295
- * 503 when the database or the encryption key is down (routes/status.ts), and
296
- * that response is still unmistakably this gateway. Requiring `status === 'ok'`
297
- * to identify it would report a correctly-routed but sick gateway as "probably
298
- * a different service on that port" — the confident wrong answer this command
299
- * exists to prevent. Anything that is not a 2xx `'ok'` is reported as
300
- * unhealthy and the raw status is echoed, so a status added later degrades into
301
- * a truthful "reaches this gateway, which says: <status>" instead of a lie.
302
- */
303
- export async function probeGateway(
304
- baseUrl: string,
305
- fetchImpl: typeof fetch = fetch,
306
- timeoutMs: number = DEFAULT_PROBE_TIMEOUT_MS,
307
- ): Promise<GatewayProbe> {
308
- let response: Response;
309
- try {
310
- response = await fetchImpl(`${normalizeUrl(baseUrl)}/livez`, {
311
- signal: AbortSignal.timeout(timeoutMs),
312
- });
313
- } catch (error) {
314
- return {
315
- reachable: false,
316
- identified: false,
317
- healthy: false,
318
- error: error instanceof Error ? error.message : String(error),
319
- };
320
- }
321
- let body: Record<string, unknown> = {};
322
- try {
323
- body = await response.json() as Record<string, unknown>;
324
- } catch {
325
- return {
326
- reachable: true,
327
- identified: false,
328
- healthy: false,
329
- status: response.status,
330
- error: 'response was not JSON',
331
- };
332
- }
333
- const serviceStatus = typeof body.status === 'string' ? body.status : undefined;
334
- const identified = serviceStatus !== undefined
335
- && typeof body.version === 'string'
336
- && typeof body.uptime_s === 'number';
337
- return {
338
- reachable: true,
339
- identified,
340
- healthy: identified && serviceStatus === 'ok' && response.status >= 200 && response.status < 300,
341
- serviceStatus,
342
- status: response.status,
343
- version: typeof body.version === 'string' ? body.version : undefined,
344
- };
345
- }
346
-
347
- export interface DoctorOptions {
348
- /** The gateway the user believes they are using (--url / FREELLMAPI_URL). */
349
- expectedUrl: string;
350
- env?: NodeJS.ProcessEnv;
351
- homeDir?: string;
352
- /** Project-scoped settings are resolved relative to this. */
353
- cwd?: string;
354
- fetchImpl?: typeof fetch;
355
- /** Probe timeout. Raise it on a slow link, where the default would report a
356
- * reachable gateway as unreachable. */
357
- timeoutMs?: number;
358
- }
359
-
360
- const LAYER_RESOLVERS: Record<string, (env: NodeJS.ProcessEnv, homeDir: string, cwd: string) => Layer[]> = {
361
- claude: (env, homeDir, cwd) => claudeLayers(env, homeDir, cwd),
362
- codex: (env, homeDir) => codexLayers(env, homeDir),
363
- };
364
-
365
- export const DOCTOR_TOOLS = Object.keys(LAYER_RESOLVERS);
366
-
367
- export async function diagnose(tool: string, options: DoctorOptions): Promise<ToolReport> {
368
- const env = options.env ?? process.env;
369
- const homeDir = options.homeDir ?? os.homedir();
370
- const resolve = LAYER_RESOLVERS[tool];
371
- if (!resolve) {
372
- return {
373
- tool,
374
- verdict: 'unknown',
375
- layers: [],
376
- detail: `doctor does not know how ${tool} resolves its endpoint. Known tools: ${DOCTOR_TOOLS.join(', ')}.`,
377
- };
378
- }
379
-
380
- const layers = resolve(env, homeDir, options.cwd ?? process.cwd());
381
- const effective = layers.find(layer => layer.effective);
382
-
383
- if (!effective?.value) {
384
- return {
385
- tool,
386
- verdict: 'unknown',
387
- layers,
388
- detail: layers.length
389
- ? 'A configuration layer was found but names no base URL, so the tool falls back to its vendor default.'
390
- : `No configuration found. ${tool} will use its vendor default endpoint, not this gateway.`,
391
- };
392
- }
393
-
394
- const gateway = await probeGateway(effective.value, options.fetchImpl, options.timeoutMs);
395
-
396
- // A lower-precedence layer naming a DIFFERENT url is the silent-override
397
- // case: the user edited that file and something outranks it.
398
- const overridden = layers.find(
399
- layer => !layer.effective && layer.value && !sameGateway(layer.value, effective.value),
400
- );
401
-
402
- if (!gateway.reachable) {
403
- return {
404
- tool,
405
- verdict: 'unreachable',
406
- layers,
407
- effectiveUrl: effective.value,
408
- gateway,
409
- detail: `${tool} is configured to use ${effective.value}, but nothing answered there (${gateway.error}).`,
410
- };
411
- }
412
-
413
- if (overridden) {
414
- return {
415
- tool,
416
- verdict: 'shadowed',
417
- layers,
418
- effectiveUrl: effective.value,
419
- shadowedBy: effective.source,
420
- gateway,
421
- detail:
422
- `${overridden.source} sets ${overridden.value}, but ${effective.source} outranks it, `
423
- + `so ${tool} actually uses ${effective.value}.`,
424
- };
425
- }
426
-
427
- // Two distinct ways to be pointed somewhere else, and both must fail the
428
- // check: a different host entirely, or the right host answering nothing that
429
- // looks like this gateway.
430
- if (!sameGateway(effective.value, options.expectedUrl)) {
431
- return {
432
- tool,
433
- verdict: 'elsewhere',
434
- layers,
435
- effectiveUrl: effective.value,
436
- gateway,
437
- detail:
438
- `${tool} reaches ${effective.value}, NOT the ${options.expectedUrl} this command was pointed at. `
439
- + 'Its traffic does not touch this gateway.',
440
- };
441
- }
442
-
443
- if (!gateway.identified) {
444
- return {
445
- tool,
446
- verdict: 'elsewhere',
447
- layers,
448
- effectiveUrl: effective.value,
449
- gateway,
450
- detail:
451
- `Something is listening at ${effective.value} and ${tool} would reach it, but it did not answer `
452
- + '/livez the way this gateway does — so it is probably a different service on that port.',
453
- };
454
- }
455
-
456
- // Routing is correct here and the gateway is unmistakably this one — it just
457
- // says it cannot serve. Reporting that as `routed` would send the user
458
- // hunting through config that is already right, so it gets its own verdict
459
- // and a nonzero exit.
460
- if (!gateway.healthy) {
461
- return {
462
- tool,
463
- verdict: 'degraded',
464
- layers,
465
- effectiveUrl: effective.value,
466
- gateway,
467
- detail:
468
- `${tool} reaches ${effective.value} and that IS this gateway, but it reports `
469
- + `status "${gateway.serviceStatus}" (HTTP ${gateway.status}) — it cannot serve requests. `
470
- + 'The routing is fine; the gateway is not.',
471
- };
472
- }
473
-
474
- return {
475
- tool,
476
- verdict: 'routed',
477
- layers,
478
- effectiveUrl: effective.value,
479
- gateway,
480
- detail: `${tool} reaches ${effective.value}${gateway.version ? ` (gateway v${gateway.version})` : ''}.`,
481
- };
482
- }
483
-
484
- const SYMBOL: Record<Verdict, string> = {
485
- routed: 'OK ',
486
- degraded: 'WARN',
487
- elsewhere: 'FAIL',
488
- shadowed: 'WARN',
489
- unreachable: 'FAIL',
490
- unknown: '? ',
491
- };
492
-
493
- export function formatReport(report: ToolReport): string {
494
- const lines = [`${SYMBOL[report.verdict]} ${report.tool}: ${report.verdict}`, ` ${report.detail}`];
495
- for (const layer of report.layers) {
496
- lines.push(` ${layer.effective ? '->' : ' '} ${layer.source}${layer.value ? ` = ${layer.value}` : ''}`);
497
- }
498
- if (report.gateway?.reachable && !report.gateway.identified) {
499
- lines.push(' note: something answered, but not with this gateway\'s /livez shape.');
500
- }
501
- return lines.join('\n');
502
- }
503
-
504
- /** Exit code: 0 when every tool is routed, 1 otherwise — so it is usable in a
505
- * script, not only by eye. */
506
- export function exitCodeFor(reports: ToolReport[]): number {
507
- return reports.every(report => report.verdict === 'routed') ? 0 : 1;
508
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/src/index.test.ts DELETED
@@ -1,271 +0,0 @@
1
- import fs from 'node:fs';
2
- import os from 'node:os';
3
- import path from 'node:path';
4
- import { afterEach, describe, expect, it } from 'vitest';
5
- import { claudeLaunchEnv, codexArgs, main, parseArgs, resolvePinnedModel, unsupportedNodeVersion } from './index.js';
6
- import { UnknownModelError } from './models.js';
7
- import type { CatalogModel } from './types.js';
8
-
9
- describe('CLI arguments and launchers', () => {
10
- it('defaults to the gateway port when no URL is configured', () => {
11
- const previous = process.env.FREELLMAPI_URL;
12
- delete process.env.FREELLMAPI_URL;
13
- try {
14
- expect(parseArgs(['setup-generic']).options.url).toBe('http://localhost:3001');
15
- } finally {
16
- if (previous === undefined) delete process.env.FREELLMAPI_URL;
17
- else process.env.FREELLMAPI_URL = previous;
18
- }
19
- });
20
-
21
- it('parses setup options before or after the command', () => {
22
- expect(parseArgs([
23
- '--url',
24
- 'http://localhost:3001/v1',
25
- 'setup-codex',
26
- '--profile=work',
27
- '--dry-run',
28
- ])).toMatchObject({
29
- command: 'setup-codex',
30
- options: {
31
- url: 'http://localhost:3001/v1',
32
- profile: 'work',
33
- dryRun: true,
34
- },
35
- });
36
- });
37
-
38
- it('rejects profile names that can escape the intended config directory', () => {
39
- expect(() => parseArgs(['setup-codex', '--profile', '../../outside']))
40
- .toThrow('--profile must use only');
41
- expect(() => parseArgs(['setup-codex', '--profile', '..']))
42
- .toThrow('--profile must use only');
43
- });
44
-
45
- it('rejects a missing option value instead of consuming the next flag', () => {
46
- expect(() => parseArgs(['setup-codex', '--profile', '--dry-run']))
47
- .toThrow('--profile requires a value');
48
- });
49
-
50
- it('parses doctor --timeout, and rejects a value that is not milliseconds', () => {
51
- expect(parseArgs(['doctor', '--timeout', '30000']).options.timeoutMs).toBe(30_000);
52
- expect(parseArgs(['doctor', '--timeout=250']).options.timeoutMs).toBe(250);
53
- // Left undefined rather than defaulted here, so doctor.ts owns the default.
54
- expect(parseArgs(['doctor']).options.timeoutMs).toBeUndefined();
55
- // Rejected, not silently ignored: a typo quietly becoming the default is
56
- // exactly the quiet no-op this command exists to catch.
57
- expect(() => parseArgs(['doctor', '--timeout', '5s'])).toThrow('positive number of milliseconds');
58
- expect(() => parseArgs(['doctor', '--timeout', '0'])).toThrow('positive number of milliseconds');
59
- });
60
-
61
- it('still rejects a stray positional for commands that take none', async () => {
62
- // `doctor` is the only command with positional arguments, so parseArgs
63
- // collects them generically. The dispatcher has to reject them for every
64
- // other command BEFORE dispatch — checked after the setup-* branch, the
65
- // stray word would be silently ignored instead of erroring.
66
- await expect(main(['setup-claude', 'typo'])).rejects.toThrow('Unknown option: typo');
67
- await expect(main(['launch', 'typo'])).rejects.toThrow('Unknown option: typo');
68
- // ...and doctor still takes them.
69
- expect(parseArgs(['doctor', 'claude']).options.args).toEqual(['claude']);
70
- });
71
-
72
- const models: CatalogModel[] = [
73
- { id: 'auto' },
74
- { id: 'fast-coder', available: true, context_window: 131072 },
75
- { id: 'reasoning-model', available: true, context_window: 262144 },
76
- ];
77
- const baseOptions = {
78
- url: 'http://localhost:3000',
79
- profile: 'default',
80
- dryRun: false,
81
- };
82
- const temporary: string[] = [];
83
-
84
- afterEach(() => {
85
- for (const directory of temporary.splice(0)) {
86
- fs.rmSync(directory, { recursive: true, force: true });
87
- }
88
- });
89
-
90
- it.skipIf(process.platform !== 'win32')('launches Windows command shims for both agents', async () => {
91
- const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'freellmapi-launch-'));
92
- temporary.push(directory);
93
- for (const command of ['codex', 'claude']) {
94
- fs.writeFileSync(path.join(directory, `${command}.cmd`),
95
- `@echo off\r\necho ${command} > "%FREELLMAPI_TEST_MARKER%"\r\nexit /b 17\r\n`);
96
- }
97
- const previousPath = process.env.PATH;
98
- const previousMarker = process.env.FREELLMAPI_TEST_MARKER;
99
- const previousFetch = globalThis.fetch;
100
- const marker = path.join(directory, 'launched.txt');
101
- process.env.PATH = `${directory};${process.env.SystemRoot}\\System32`;
102
- process.env.FREELLMAPI_TEST_MARKER = marker;
103
- globalThis.fetch = async () => new Response(JSON.stringify({
104
- data: [{ id: 'test-model', available: true }],
105
- }), { headers: { 'Content-Type': 'application/json' } });
106
- try {
107
- for (const [command, agent] of [['launch-codex', 'codex'], ['launch', 'claude']]) {
108
- fs.rmSync(marker, { force: true });
109
- expect(await main([command, '--url', 'http://127.0.0.1:3001', '--api-key', 'test-key']))
110
- .toBe(17);
111
- expect(fs.readFileSync(marker, 'utf8').trim()).toBe(agent);
112
- }
113
- } finally {
114
- globalThis.fetch = previousFetch;
115
- if (previousPath === undefined) delete process.env.PATH;
116
- else process.env.PATH = previousPath;
117
- if (previousMarker === undefined) delete process.env.FREELLMAPI_TEST_MARKER;
118
- else process.env.FREELLMAPI_TEST_MARKER = previousMarker;
119
- }
120
- });
121
-
122
- it('uses --model for ANTHROPIC_MODEL and defaults to the first available model', () => {
123
- const explicit = claudeLaunchEnv(
124
- { ...baseOptions, model: 'reasoning-model' },
125
- 'unified-key',
126
- models,
127
- {},
128
- '/home/tester',
129
- );
130
- expect(explicit.ANTHROPIC_MODEL).toBe('reasoning-model');
131
- expect(explicit.CLAUDE_CODE_AUTO_COMPACT_WINDOW).toBe('262144');
132
-
133
- const fallback = claudeLaunchEnv(baseOptions, 'unified-key', models, {}, '/home/tester');
134
- expect(fallback.ANTHROPIC_MODEL).toBe('fast-coder');
135
- expect(fallback.ANTHROPIC_AUTH_TOKEN).toBe('unified-key');
136
- expect(fallback.ANTHROPIC_BASE_URL).toBe('http://localhost:3000');
137
- });
138
-
139
- it('never uses the profile name as a model id', () => {
140
- const home = fs.mkdtempSync(path.join(os.tmpdir(), 'freellmapi-cli-'));
141
- temporary.push(home);
142
- const profileDir = path.join(home, '.claude', 'profiles', 'work');
143
- fs.mkdirSync(profileDir, { recursive: true });
144
- const env = claudeLaunchEnv(
145
- { ...baseOptions, profile: 'work' },
146
- 'unified-key',
147
- models,
148
- {},
149
- home,
150
- );
151
- expect(env.ANTHROPIC_MODEL).toBe('fast-coder');
152
- expect(env.CLAUDE_CONFIG_DIR).toBe(profileDir);
153
- });
154
-
155
- it('rejects a profile whose configuration directory does not exist', () => {
156
- const home = fs.mkdtempSync(path.join(os.tmpdir(), 'freellmapi-cli-'));
157
- temporary.push(home);
158
- expect(() => claudeLaunchEnv(
159
- { ...baseOptions, profile: 'missing' },
160
- 'unified-key',
161
- models,
162
- {},
163
- home,
164
- )).toThrow("freellmapi setup-claude --profile missing");
165
- });
166
-
167
- it('strips the user\'s real Anthropic credentials from the child environment', () => {
168
- const env = claudeLaunchEnv(baseOptions, 'unified-key', models, {
169
- ANTHROPIC_API_KEY: 'real-anthropic-key',
170
- ANTHROPIC_AUTH_TOKEN: 'real-anthropic-token',
171
- PATH: '/usr/bin',
172
- }, '/home/tester');
173
- expect(env.ANTHROPIC_API_KEY).toBeUndefined();
174
- expect(env.ANTHROPIC_AUTH_TOKEN).toBe('unified-key');
175
- expect(env.PATH).toBe('/usr/bin');
176
- expect(JSON.stringify(env)).not.toContain('real-anthropic');
177
- });
178
-
179
- describe('resolvePinnedModel', () => {
180
- const available: CatalogModel[] = [{ id: 'auto' }, { id: 'fast-coder', available: true }];
181
- const full: CatalogModel[] = [...available, { id: 'benched', available: false }];
182
-
183
- function collect(): { warnings: string[]; warn: (message: string) => void } {
184
- const warnings: string[] = [];
185
- return { warnings, warn: message => { warnings.push(message); } };
186
- }
187
-
188
- it('is silent for an available pinned model', () => {
189
- const { warnings, warn } = collect();
190
- expect(resolvePinnedModel('fast-coder', { available, full }, warn)?.id).toBe('fast-coder');
191
- expect(warnings).toEqual([]);
192
- });
193
-
194
- it('warns but still resolves a registered-but-unavailable model', () => {
195
- const { warnings, warn } = collect();
196
- expect(resolvePinnedModel('benched', { available, full }, warn))
197
- .toMatchObject({ id: 'benched', unavailable: true });
198
- expect(warnings.join()).toContain('not currently available');
199
- });
200
-
201
- it('WARNS when the unfiltered roster could not be fetched', () => {
202
- // Silently degrading to the filtered roster would reinstate exactly the
203
- // ambiguity this pair of fetches removes: the user would see a quota
204
- // problem reported as a typo, with nothing saying the check was weaker.
205
- const { warnings, warn } = collect();
206
- resolvePinnedModel(
207
- 'fast-coder',
208
- { available, full: available, degradedReason: 'HTTP 400' },
209
- warn,
210
- );
211
- expect(warnings.join()).toContain('could not fetch the unfiltered model catalog');
212
- expect(warnings.join()).toContain('HTTP 400');
213
- });
214
-
215
- it('still reports an id in neither roster as unknown, degraded or not', () => {
216
- const { warn } = collect();
217
- expect(() => resolvePinnedModel('nope', { available, full }, warn))
218
- .toThrow(UnknownModelError);
219
- });
220
-
221
- it('does nothing at all when no model was pinned', () => {
222
- // Nothing to warn about: the launcher picks from the filtered roster,
223
- // where there is no unknown-vs-unavailable ambiguity to lose.
224
- const { warnings, warn } = collect();
225
- expect(resolvePinnedModel(undefined, { available, full, degradedReason: 'x' }, warn))
226
- .toBeUndefined();
227
- expect(warnings).toEqual([]);
228
- });
229
- });
230
-
231
- it('passes a complete Responses provider to Codex', () => {
232
- const args = codexArgs('http://localhost:3001/v1/', 'coder');
233
- expect(args).toContain('model_provider="freellmapi"');
234
- expect(args).toContain('model="coder"');
235
- expect(args).toContain('model_providers.freellmapi.name="FreeLLMAPI"');
236
- expect(args).toContain(
237
- 'model_providers.freellmapi.base_url="http://localhost:3001/v1"',
238
- );
239
- expect(args).toContain('model_providers.freellmapi.wire_api="responses"');
240
- });
241
-
242
- // #1283: on Node <17.4 the CLI died at module-load time with
243
- // ERR_UNKNOWN_BUILTIN_MODULE because `node:readline/promises` was imported
244
- // statically, so no command — not even --help — could run, let alone print
245
- // a readable reason. Two layers fix it: the readline import is now lazy
246
- // (only the interactive key prompt needs it), and this pure check turns an
247
- // old runtime into one clear sentence before main() runs.
248
- describe('unsupportedNodeVersion (#1283)', () => {
249
- it('accepts Node 20 and newer', () => {
250
- expect(unsupportedNodeVersion('20.18.0')).toBeNull();
251
- expect(unsupportedNodeVersion('22.5.1')).toBeNull();
252
- expect(unsupportedNodeVersion('26.9.0')).toBeNull();
253
- });
254
-
255
- it('rejects the older runtimes from the issue reports', () => {
256
- for (const version of ['12.22.12', '14.21.3', '16.20.2', '18.19.0', '19.9.0']) {
257
- const message = unsupportedNodeVersion(version);
258
- expect(message).toContain('Node.js 20 or newer');
259
- expect(message).toContain(version);
260
- }
261
- });
262
-
263
- it('says nothing when the runtime is unrecognised', () => {
264
- // A non-Node runtime (or a mocked process) must not be told it is
265
- // "old"; the failure, if any, should come from the code itself.
266
- expect(unsupportedNodeVersion(undefined)).toBeNull();
267
- expect(unsupportedNodeVersion('')).toBeNull();
268
- expect(unsupportedNodeVersion('nightly')).toBeNull();
269
- });
270
- });
271
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/src/index.ts DELETED
@@ -1,534 +0,0 @@
1
- #!/usr/bin/env node
2
- import os from 'node:os';
3
- import fs from 'node:fs';
4
- import path from 'node:path';
5
- import process from 'node:process';
6
- import spawn from 'cross-spawn';
7
- import { Writable } from 'node:stream';
8
- import { fileURLToPath } from 'node:url';
9
- import { applyGeneratedFiles, printDryRunDiff } from './config-files.js';
10
- import { detectChatGptClient } from './detect.js';
11
- import { getTool, tools } from './tools.js';
12
- import { resolveLaunchModel, type ResolvedModel } from './models.js';
13
- import { DOCTOR_TOOLS, diagnose, exitCodeFor, formatReport, type ToolReport } from './doctor.js';
14
- import { keysHelp, runKeys, type KeyCommandOptions } from './keys.js';
15
- import type { CatalogModel, GenerateContext } from './types.js';
16
-
17
- interface CliOptions extends KeyCommandOptions {
18
- apiKey?: string;
19
- profile: string;
20
- model?: string;
21
- }
22
-
23
- function rootUrl(url: string): string {
24
- return url.trim().replace(/\/+$/, '').replace(/\/v1$/i, '');
25
- }
26
-
27
- function validateProfile(profile: string): string {
28
- if (
29
- !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(profile)
30
- || profile === '.'
31
- || profile === '..'
32
- ) {
33
- throw new Error(
34
- '--profile must use only letters, numbers, dots, underscores, or hyphens',
35
- );
36
- }
37
- return profile;
38
- }
39
-
40
- function parseTimeout(value: string): number {
41
- const ms = Number(value);
42
- // Rejected rather than clamped: a typo'd `--timeout 5s` parsing to NaN and
43
- // silently becoming the default is the kind of quiet no-op this command is
44
- // supposed to be immune to.
45
- if (!Number.isFinite(ms) || ms <= 0) {
46
- throw new Error(`--timeout must be a positive number of milliseconds, got '${value}'`);
47
- }
48
- return ms;
49
- }
50
-
51
- export function parseArgs(argv: string[]): { command?: string; options: CliOptions } {
52
- const options: CliOptions = {
53
- url: process.env.FREELLMAPI_URL || 'http://localhost:3001',
54
- apiKey: process.env.FREELLMAPI_API_KEY,
55
- token: process.env.FREELLMAPI_DASHBOARD_TOKEN,
56
- profile: 'default',
57
- dryRun: false,
58
- args: [],
59
- };
60
- let command: string | undefined;
61
- for (let index = 0; index < argv.length; index += 1) {
62
- const arg = argv[index];
63
- if (!arg.startsWith('-') && !command) {
64
- command = arg;
65
- continue;
66
- }
67
- if (!arg.startsWith('-')) {
68
- // Collected rather than rejected here so the parser stays generic; the
69
- // dispatcher rejects extras for commands that take none, which keeps
70
- // `setup-claude typo` an error instead of a silently ignored word.
71
- options.args.push(arg);
72
- continue;
73
- }
74
- if (arg === '--dry-run') {
75
- options.dryRun = true;
76
- continue;
77
- }
78
- const equals = arg.indexOf('=');
79
- const flag = equals < 0 ? arg : arg.slice(0, equals);
80
- const inline = equals < 0 ? undefined : arg.slice(equals + 1);
81
- const value = inline ?? argv[index + 1];
82
- if (
83
- flag === '--url' || flag === '--api-key' || flag === '--profile'
84
- || flag === '--model' || flag === '--timeout'
85
- || flag === '--token' || flag === '--key' || flag === '--id'
86
- ) {
87
- if (inline === undefined) index += 1;
88
- if (!value || (inline === undefined && value.startsWith('-'))) {
89
- throw new Error(`${flag} requires a value`);
90
- }
91
- if (flag === '--url') options.url = value;
92
- else if (flag === '--api-key') options.apiKey = value;
93
- else if (flag === '--profile') options.profile = validateProfile(value);
94
- else if (flag === '--timeout') options.timeoutMs = parseTimeout(value);
95
- else if (flag === '--token') options.token = value;
96
- else if (flag === '--key') options.key = value;
97
- else if (flag === '--id') {
98
- if (!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value))) {
99
- throw new Error('--id must be a positive integer');
100
- }
101
- options.keyId = Number(value);
102
- }
103
- else options.model = value;
104
- continue;
105
- }
106
- if (arg !== '--help' && arg !== '-h') throw new Error(`Unknown option: ${arg}`);
107
- }
108
- return { command, options };
109
- }
110
-
111
- async function promptForKey(provider = false): Promise<string> {
112
- if (!process.stdin.isTTY) {
113
- throw new Error(
114
- provider
115
- ? 'No provider key supplied. Pass --key or use an interactive terminal for hidden input.'
116
- : 'No API key supplied. Pass --api-key or set FREELLMAPI_API_KEY.',
117
- );
118
- }
119
- // Imported lazily, not statically: `node:readline/promises` only exists on
120
- // Node >=17.4, and a static import of it crashes the whole CLI at load time
121
- // on older runtimes (#1283) — `npx freellmapi --help` died with
122
- // ERR_UNKNOWN_BUILTIN_MODULE before main() or the engines check could say
123
- // anything useful. Deferring it means only the interactive key prompt needs
124
- // a modern Node; every other command degrades to the readable error below.
125
- const readline = (await import('node:readline/promises')).default;
126
- let muted = false;
127
- const output = new Writable({
128
- write(chunk, _encoding, callback) {
129
- if (!muted) process.stderr.write(chunk);
130
- callback();
131
- },
132
- });
133
- const rl = readline.createInterface({
134
- input: process.stdin,
135
- output,
136
- terminal: true,
137
- });
138
- const controller = new AbortController();
139
- const cancel = (): void => { controller.abort(); };
140
- rl.on('SIGINT', cancel);
141
- rl.on('close', cancel);
142
- try {
143
- const answer = rl.question(provider ? 'Provider API key: ' : 'FreeLLMAPI unified API key: ', {
144
- signal: controller.signal,
145
- });
146
- muted = true;
147
- const value = (await answer).trim();
148
- muted = false;
149
- process.stderr.write('\n');
150
- if (!value) throw new Error('An API key is required');
151
- return value;
152
- } catch (error) {
153
- if (controller.signal.aborted) throw new Error('Key entry cancelled');
154
- throw error;
155
- } finally {
156
- muted = false;
157
- rl.off('SIGINT', cancel);
158
- rl.off('close', cancel);
159
- rl.close();
160
- }
161
- }
162
-
163
- async function catalog(url: string, apiKey: string, availableOnly = true): Promise<CatalogModel[]> {
164
- let response: Response;
165
- try {
166
- response = await fetch(`${rootUrl(url)}/v1/models${availableOnly ? '?available=true' : ''}`, {
167
- headers: { Authorization: `Bearer ${apiKey}` },
168
- signal: AbortSignal.timeout(10_000),
169
- });
170
- } catch (error) {
171
- const cause = error instanceof Error && error.cause instanceof Error
172
- ? error.cause.message
173
- : undefined;
174
- const reason = cause ?? (error instanceof Error ? error.message : String(error));
175
- throw new Error(
176
- `Could not reach the FreeLLMAPI gateway at ${rootUrl(url)} (${reason}). `
177
- + 'Check that the server is running, or point the CLI at it with --url or FREELLMAPI_URL.',
178
- );
179
- }
180
- if (!response.ok) {
181
- const detail = (await response.text()).slice(0, 200);
182
- throw new Error(`Catalog request failed (HTTP ${response.status}): ${detail}`);
183
- }
184
- const body = await response.json() as { data?: CatalogModel[] };
185
- const models = body.data ?? [];
186
- if (!models.length) throw new Error('The live catalog returned no models');
187
- return models;
188
- }
189
-
190
- export interface Catalogs {
191
- available: CatalogModel[];
192
- full: CatalogModel[];
193
- /** Why the unfiltered fetch failed. Set means `full` is really the FILTERED
194
- * roster, so "unknown model" and "out of quota" can no longer be told
195
- * apart — the exact ambiguity this pair of fetches exists to remove. */
196
- degradedReason?: string;
197
- }
198
-
199
- /**
200
- * The available-only roster plus the unfiltered one.
201
- *
202
- * Only the unfiltered roster can distinguish "no such model" from "that model
203
- * exists but is out of quota right now", and reporting the second as the first
204
- * turns a rate limit into a spurious typo error. The unfiltered fetch is
205
- * best-effort: an older gateway that ignores the parameter, or any failure,
206
- * degrades to the filtered roster rather than blocking a launch — but it
207
- * RECORDS that it degraded, so the degradation can be reported instead of
208
- * silently reinstating the ambiguity.
209
- */
210
- export async function catalogs(url: string, apiKey: string): Promise<Catalogs> {
211
- const available = await catalog(url, apiKey);
212
- try {
213
- return { available, full: await catalog(url, apiKey, false) };
214
- } catch (error) {
215
- return {
216
- available,
217
- full: available,
218
- degradedReason: error instanceof Error ? error.message : String(error),
219
- };
220
- }
221
- }
222
-
223
- /**
224
- * Resolve a pinned `--model` ONCE, and say out loud anything that makes the
225
- * verdict less than certain.
226
- *
227
- * One resolution feeding both the id that gets pinned and the warning the user
228
- * reads, so the two can never disagree. Returns undefined when nothing was
229
- * pinned — the launcher then picks from the filtered roster, where there is no
230
- * ambiguity to lose and so nothing to warn about.
231
- */
232
- export function resolvePinnedModel(
233
- requested: string | undefined,
234
- rosters: Catalogs,
235
- warn: (message: string) => void = message => process.stderr.write(message),
236
- ): ResolvedModel | undefined {
237
- if (!requested) return undefined;
238
-
239
- // Reported, never silent: degrading to the filtered roster is exactly the
240
- // state in which an out-of-quota model gets called a typo, so the user has
241
- // to be told which roster the verdict below came from.
242
- if (rosters.degradedReason) {
243
- warn(
244
- `freellmapi: could not fetch the unfiltered model catalog (${rosters.degradedReason}). `
245
- + `Checking '${requested}' against the available-only roster instead — a model that `
246
- + 'exists but is out of quota may be reported as unknown.\n',
247
- );
248
- }
249
-
250
- const resolved = resolveLaunchModel(requested, rosters.available, rosters.full);
251
- // A pinned model that is registered but not servable right now is a launch we
252
- // should still make — the router may recover it mid-session — but never one
253
- // we should make silently.
254
- if (resolved.unavailable) {
255
- warn(
256
- `freellmapi: '${resolved.id}' is registered but not currently available `
257
- + '(out of quota, cooling down, or its key is disabled). Launching anyway.\n',
258
- );
259
- }
260
- return resolved;
261
- }
262
-
263
- function help(): string {
264
- return [
265
- 'FreeLLMAPI coding-agent setup and provider key management',
266
- '',
267
- 'Usage:',
268
- ' freellmapi <command> [--url URL] [--api-key KEY] [--profile NAME] [--model ID] [--dry-run]',
269
- '',
270
- 'Commands:',
271
- ...tools.map(tool => ` ${tool.command.padEnd(17)} ${tool.name}`),
272
- ' doctor [tool…] Check whether a tool\'s requests actually reach this gateway',
273
- ' (--timeout MS raises the probe wait on a slow link)',
274
- ' launch Run Claude Code with credentials injected into the child environment',
275
- ' launch-codex Run Codex CLI with provider overrides and injected credentials',
276
- ' list List supported coding agents',
277
- ' keys Add, list, remove, or test provider keys (keys --help)',
278
- '',
279
- 'Environment:',
280
- ' FREELLMAPI_URL, FREELLMAPI_API_KEY, FREELLMAPI_DASHBOARD_TOKEN (keys only)',
281
- ].join('\n');
282
- }
283
-
284
- async function setup(command: string, options: CliOptions): Promise<void> {
285
- const tool = getTool(command.replace(/^setup-/, ''));
286
- if (!tool) throw new Error(`Unknown setup command '${command}'`);
287
- const apiKey = options.apiKey ?? await promptForKey();
288
- const rosters = await catalogs(options.url, apiKey);
289
- // --model was parsed but never reached the generators, so `setup-x --model y`
290
- // silently wrote whatever primaryModel() preferred. Validate it against the
291
- // unfiltered catalog (so an out-of-quota model is not reported as a typo)
292
- // and thread it through.
293
- const requestedModelId = resolvePinnedModel(options.model, rosters)?.id;
294
- const context: GenerateContext = {
295
- url: rootUrl(options.url),
296
- apiKey,
297
- profile: options.profile,
298
- models: rosters.available,
299
- homeDir: os.homedir(),
300
- requestedModelId,
301
- detectedClient: detectChatGptClient(),
302
- };
303
- const generation = tool.generate(context);
304
-
305
- if (generation.files.length === 0) {
306
- for (const note of generation.notes) process.stdout.write(`${note}\n`);
307
- return;
308
- }
309
-
310
- const results = applyGeneratedFiles(generation.files, options.dryRun);
311
- for (const result of results) {
312
- if (options.dryRun && result.changed) {
313
- process.stdout.write(`${printDryRunDiff(result)}\n`);
314
- } else if (result.changed) {
315
- process.stdout.write(`Updated ${result.path}\n`);
316
- if (result.backupPath) process.stdout.write(`Backup: ${result.backupPath}\n`);
317
- } else {
318
- process.stdout.write(`Unchanged ${result.path}\n`);
319
- }
320
- }
321
- for (const note of generation.notes) process.stdout.write(`\n${note}\n`);
322
- }
323
-
324
- // Runs an interactive child with inherited stdio. SIGINT is ignored in the
325
- // wrapper (the foreground child receives it from the terminal and decides
326
- // what to do), SIGTERM is forwarded, and the child's exit code is returned.
327
- function runChild(
328
- command: string,
329
- args: string[],
330
- env: NodeJS.ProcessEnv,
331
- ): Promise<number> {
332
- const child = spawn(command, args, { stdio: 'inherit', env });
333
- const ignoreSigint = (): void => {};
334
- const forwardSigterm = (): void => { child.kill('SIGTERM'); };
335
- process.on('SIGINT', ignoreSigint);
336
- process.on('SIGTERM', forwardSigterm);
337
- const cleanup = (): void => {
338
- process.off('SIGINT', ignoreSigint);
339
- process.off('SIGTERM', forwardSigterm);
340
- };
341
- return new Promise<number>((resolve, reject) => {
342
- child.once('error', error => {
343
- cleanup();
344
- reject(error);
345
- });
346
- child.once('exit', (code, signal) => {
347
- cleanup();
348
- if (code !== null) resolve(code);
349
- else if (signal) resolve(128 + (os.constants.signals[signal] ?? 0));
350
- else resolve(1);
351
- });
352
- });
353
- }
354
-
355
- // `--profile` selects a CLAUDE_CONFIG_DIR generated by setup-claude and is
356
- // never a model id; `--model` picks the model explicitly.
357
- export function claudeLaunchEnv(
358
- options: CliOptions,
359
- apiKey: string,
360
- models: CatalogModel[],
361
- baseEnv: NodeJS.ProcessEnv = process.env,
362
- homeDir = os.homedir(),
363
- fullCatalog: CatalogModel[] = models,
364
- ): NodeJS.ProcessEnv {
365
- const resolved = resolveLaunchModel(options.model, models, fullCatalog);
366
- const selected = resolved.id;
367
- const env: NodeJS.ProcessEnv = { ...baseEnv };
368
- // Never leak the user's real Anthropic credentials to the gateway.
369
- delete env.ANTHROPIC_API_KEY;
370
- delete env.ANTHROPIC_AUTH_TOKEN;
371
- if (options.profile !== 'default') {
372
- const directory = path.join(homeDir, '.claude', 'profiles', options.profile);
373
- if (!fs.existsSync(directory)) {
374
- throw new Error(
375
- `Claude profile '${options.profile}' has no configuration directory at ${directory}. `
376
- + `Create it with: freellmapi setup-claude --profile ${options.profile}`,
377
- );
378
- }
379
- env.CLAUDE_CONFIG_DIR = directory;
380
- }
381
- Object.assign(env, {
382
- ANTHROPIC_BASE_URL: rootUrl(options.url),
383
- ANTHROPIC_AUTH_TOKEN: apiKey,
384
- ANTHROPIC_MODEL: selected,
385
- ANTHROPIC_DEFAULT_OPUS_MODEL: selected,
386
- ANTHROPIC_DEFAULT_SONNET_MODEL: selected,
387
- ANTHROPIC_DEFAULT_HAIKU_MODEL: selected,
388
- CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: '1',
389
- });
390
- // Only pin the compaction window when the catalog actually published one.
391
- // The old `?? 128_000` invented a number for every model with no stated
392
- // window, and a wrong window is worse than none: too high and Claude Code
393
- // compacts after the gateway has already rejected the request, too low and
394
- // it compacts a conversation that still fits. Absent, Claude Code applies
395
- // its own default.
396
- if (resolved.contextWindow !== undefined) {
397
- env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = String(resolved.contextWindow);
398
- } else {
399
- delete env.CLAUDE_CODE_AUTO_COMPACT_WINDOW;
400
- }
401
- return env;
402
- }
403
-
404
- async function launchClaude(options: CliOptions): Promise<number> {
405
- const apiKey = options.apiKey ?? await promptForKey();
406
- const rosters = await catalogs(options.url, apiKey);
407
- // Resolved here for the warning; claudeLaunchEnv resolves again to build the
408
- // environment. Both are pure calls over the same two rosters, so they cannot
409
- // reach different verdicts — keeping claudeLaunchEnv a side-effect-free env
410
- // builder is worth more than eliding the second call.
411
- resolvePinnedModel(options.model, rosters);
412
- const env = claudeLaunchEnv(
413
- options, apiKey, rosters.available, process.env, os.homedir(), rosters.full,
414
- );
415
- return runChild('claude', [], env);
416
- }
417
-
418
- export function codexArgs(url: string, selected: string): string[] {
419
- return [
420
- '-c', 'model_provider="freellmapi"',
421
- '-c', `model=${JSON.stringify(selected)}`,
422
- '-c', 'model_providers.freellmapi.name="FreeLLMAPI"',
423
- '-c', `model_providers.freellmapi.base_url=${JSON.stringify(`${rootUrl(url)}/v1`)}`,
424
- '-c', 'model_providers.freellmapi.wire_api="responses"',
425
- '-c', 'model_providers.freellmapi.env_key="FREELLMAPI_API_KEY"',
426
- '-c', 'model_providers.freellmapi.requires_openai_auth=false',
427
- ];
428
- }
429
-
430
- async function launchCodex(options: CliOptions): Promise<number> {
431
- const apiKey = options.apiKey ?? await promptForKey();
432
- const rosters = await catalogs(options.url, apiKey);
433
- const selected = (
434
- resolvePinnedModel(options.model, rosters)
435
- ?? resolveLaunchModel(undefined, rosters.available, rosters.full)
436
- ).id;
437
- const env = { ...process.env, FREELLMAPI_API_KEY: apiKey };
438
- const args = codexArgs(options.url, selected);
439
- return runChild('codex', args, env);
440
- }
441
-
442
- async function runDoctor(options: CliOptions): Promise<number> {
443
- const requested = options.args.length ? options.args : DOCTOR_TOOLS;
444
- const reports: ToolReport[] = [];
445
- for (const tool of requested) {
446
- reports.push(await diagnose(tool, {
447
- expectedUrl: rootUrl(options.url),
448
- timeoutMs: options.timeoutMs,
449
- }));
450
- }
451
- for (const report of reports) process.stdout.write(`${formatReport(report)}\n`);
452
- // Nonzero when anything is not routed, so this is usable as a precondition
453
- // in a script rather than only readable by eye.
454
- return exitCodeFor(reports);
455
- }
456
-
457
- export async function main(argv = process.argv.slice(2)): Promise<number> {
458
- const { command, options } = parseArgs(argv);
459
- if (!command || command === 'help' || argv.includes('--help') || argv.includes('-h')) {
460
- process.stdout.write(`${command === 'keys' ? keysHelp() : help()}\n`);
461
- return 0;
462
- }
463
- for (const arg of argv) {
464
- const flag = arg.split('=', 1)[0];
465
- if (command !== 'keys' && ['--token', '--key', '--id'].includes(flag)) {
466
- throw new Error(`${flag} is only supported by keys`);
467
- }
468
- if (command === 'keys' && ['--api-key', '--profile', '--model'].includes(flag)) {
469
- throw new Error(`${flag} is not supported by keys; use keys --help for available options`);
470
- }
471
- }
472
- if (command === 'keys') return runKeys(options, () => promptForKey(true));
473
- // `doctor` and `keys` take positional arguments. Every other
474
- // one rejects them here, BEFORE dispatch — checking after the setup-* branch
475
- // would let `setup-claude typo` run with the stray word silently ignored,
476
- // where it used to be an error.
477
- if (command !== 'doctor' && options.args.length) {
478
- throw new Error(`Unknown option: ${options.args[0]}`);
479
- }
480
- if (command === 'list') {
481
- for (const tool of tools) {
482
- process.stdout.write(`${tool.id}\t${tool.protocol}\t${tool.baseUrlSupport}\n`);
483
- }
484
- return 0;
485
- }
486
- if (command.startsWith('setup-')) {
487
- await setup(command, options);
488
- return 0;
489
- }
490
- if (command === 'doctor') return runDoctor(options);
491
- if (command === 'launch') return launchClaude(options);
492
- if (command === 'launch-codex') return launchCodex(options);
493
- throw new Error(`Unknown command '${command}'\n\n${help()}`);
494
- }
495
-
496
- function isDirectExecution(): boolean {
497
- if (!process.argv[1]) return false;
498
- try {
499
- return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
500
- } catch {
501
- return false;
502
- }
503
- }
504
-
505
- /** Minimum Node major this CLI actually runs on: `AbortSignal.timeout`
506
- * (17.3), global `fetch` (18), `node:readline/promises` (17.4) — rounded to
507
- * the package's engines floor of 20. npm treats `engines` as a warning by
508
- * default (and npm 6, still common on Windows boxes hitting #1283, ignores it
509
- * for `npx`), so without this check an unsupported runtime gets a stack
510
- * trace instead of a sentence. Returns null when the runtime is fine. */
511
- export function unsupportedNodeVersion(
512
- version: string | undefined = process.versions.node,
513
- major: number | undefined = Number(version?.split('.')[0]),
514
- ): string | null {
515
- if (!version || !Number.isFinite(major)) return null; // Non-Node runtimes: don't guess.
516
- if (major >= 20) return null;
517
- return `freellmapi requires Node.js 20 or newer (found ${version}). Install one from https://nodejs.org and re-run.`;
518
- }
519
-
520
- if (isDirectExecution()) {
521
- const unsupported = unsupportedNodeVersion();
522
- if (unsupported) {
523
- process.stderr.write(`freellmapi: ${unsupported}\n`);
524
- process.exitCode = 1;
525
- } else {
526
- main().then(
527
- code => { process.exitCode = code; },
528
- error => {
529
- process.stderr.write(`freellmapi: ${error instanceof Error ? error.message : String(error)}\n`);
530
- process.exitCode = 1;
531
- },
532
- );
533
- }
534
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/src/keys.test.ts DELETED
@@ -1,210 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
- import { main, parseArgs } from './index.js';
3
-
4
- const token = 'dashboard-session==';
5
- const secret = 'provider-secret==';
6
- const key = { id: 7, platform: 'groq', enabled: true, status: 'healthy', maskedKey: secret, lastHealthError: null as string | null };
7
- const calls: Array<{ path: string; init: RequestInit }> = [];
8
- let keys: Array<typeof key & { modelScope?: string[]; models?: Array<{ id: number; kind: string }> }>;
9
- let output: string;
10
-
11
- beforeEach(() => {
12
- keys = [{ ...key }];
13
- output = '';
14
- calls.length = 0;
15
- vi.stubEnv('FREELLMAPI_DASHBOARD_TOKEN', token);
16
- vi.spyOn(process.stdout, 'write').mockImplementation(chunk => { output += String(chunk); return true; });
17
- vi.stubGlobal('fetch', vi.fn(async (input: string, init: RequestInit = {}) => {
18
- const path = new URL(input).pathname;
19
- calls.push({ path, init });
20
- if (path === '/api/keys/providers') return Response.json({ providers: [{ platform: 'groq' }, { platform: 'kilo', keyless: true }] });
21
- if (path === '/api/keys' && init.method === 'POST') return Response.json({ id: 7, platform: 'groq', maskedKey: secret }, { status: 201 });
22
- if (path === '/api/keys') return Response.json(keys);
23
- if (path === '/api/models') return Response.json([
24
- { id: 1, platform: 'groq', modelId: 'model-a', enabled: true },
25
- { id: 2, platform: 'groq', modelId: 'model-b', enabled: true },
26
- { id: 3, platform: 'groq', modelId: 'disabled', enabled: false },
27
- { id: 4, platform: 'other', modelId: 'other', enabled: true },
28
- ]);
29
- if (path.startsWith('/api/health/check/')) return Response.json({ keyId: Number(path.split('/').at(-1)), status: 'healthy' });
30
- if (path.startsWith('/api/keys/') && init.method === 'DELETE') return Response.json({ success: true });
31
- throw new Error(`Unexpected request: ${path}`);
32
- }));
33
- });
34
-
35
- afterEach(() => {
36
- vi.restoreAllMocks();
37
- vi.unstubAllGlobals();
38
- vi.unstubAllEnvs();
39
- });
40
-
41
- describe('provider key commands', () => {
42
- it('preserves equals signs in credentials and lets --token override the environment', async () => {
43
- expect(parseArgs(['keys', 'add', 'groq', `--token=${token}`, `--key=${secret}`]).options)
44
- .toMatchObject({ token, key: secret });
45
- await main(['--url', 'http://localhost:3100/v1/', 'keys', 'add', 'groq', '--token', 'override', `--key=${secret}`]);
46
- expect(calls.map(c => c.path)).toEqual(['/api/keys/providers', '/api/keys', '/api/health/check/7', '/api/keys']);
47
- expect(calls[1].init.body).toBe(JSON.stringify({ platform: 'groq', key: secret }));
48
- for (const call of calls) expect(new Headers(call.init.headers).get('Authorization')).toBe('Bearer override');
49
- expect(output).toContain('Saved groq key 7');
50
- expect(output).not.toContain(secret);
51
- expect(output).not.toContain(token);
52
- });
53
-
54
- it('lists metadata and enabled chat model counts, without printing even masked keys', async () => {
55
- keys.push({ ...key, id: 8, enabled: false, modelScope: ['model-b'] });
56
- expect(await main(['keys', 'list'])).toBe(0);
57
- expect(output).toContain('7\tgroq\t2\tenabled\thealthy');
58
- expect(output).toContain('8\tgroq\t1\tdisabled\thealthy');
59
- expect(output).not.toContain(secret);
60
- expect(output).not.toContain(token);
61
- });
62
-
63
- it('requires an id to remove one of several keys and verifies its platform', async () => {
64
- keys.push({ ...key, id: 8 });
65
- await expect(main(['keys', 'remove', 'groq'])).rejects.toThrow('--id');
66
- await expect(main(['keys', 'remove', 'other', '--id', '7'])).rejects.toThrow('No matching key');
67
- expect(calls.every(c => c.init.method !== 'DELETE')).toBe(true);
68
- expect(await main(['keys', 'remove', 'groq', '--id', '8'])).toBe(0);
69
- expect(calls.at(-1)).toMatchObject({ path: '/api/keys/8', init: { method: 'DELETE' } });
70
- });
71
-
72
- it('removes a single matching key without touching other providers', async () => {
73
- keys.push({ ...key, id: 8, platform: 'other' });
74
- await main(['keys', 'remove', 'groq']);
75
- expect(calls.filter(c => c.init.method === 'DELETE').map(c => c.path)).toEqual(['/api/keys/7']);
76
- });
77
-
78
- it('does not equate HTTP 200 with successful validation', async () => {
79
- keys[0].status = 'invalid';
80
- expect(await main(['keys', 'test', 'groq'])).toBe(1);
81
- expect(output).toContain('invalid');
82
- });
83
-
84
- it('reports inconclusive validation when the server preserves a previously healthy status', async () => {
85
- keys[0] = { ...key, lastHealthError: secret };
86
- expect(await main(['keys', 'test', 'groq'])).toBe(1);
87
- expect(output).toContain('inconclusive');
88
- expect(output).not.toContain(secret);
89
- });
90
-
91
- it('checks every matching key and combines unsuccessful results', async () => {
92
- keys.push({ ...key, id: 8, status: 'invalid' }, { ...key, id: 9, platform: 'other' });
93
- expect(await main(['keys', 'test', 'groq'])).toBe(1);
94
- expect(calls.filter(c => c.path.startsWith('/api/health')).map(c => c.path))
95
- .toEqual(['/api/health/check/7', '/api/health/check/8']);
96
- });
97
-
98
- it('keeps a newly saved key when validation fails and returns a failure exit code', async () => {
99
- keys[0].status = 'invalid';
100
- expect(await main(['keys', 'add', 'groq', '--key', secret])).toBe(1);
101
- expect(output).toContain('Saved groq key 7');
102
- expect(calls.every(c => c.init.method !== 'DELETE')).toBe(true);
103
- });
104
-
105
- it('does not prompt for a keyless provider', async () => {
106
- keys[0].platform = 'kilo';
107
- expect(await main(['keys', 'add', 'kilo'])).toBe(0);
108
- expect(JSON.parse(calls[1].init.body as string)).toEqual({ platform: 'kilo', key: '' });
109
- });
110
-
111
- it('rejects a missing provider key in a non-interactive terminal without adding one', async () => {
112
- const descriptor = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY');
113
- Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: false });
114
- try {
115
- await expect(main(['keys', 'add', 'groq'])).rejects.toThrow('Pass --key');
116
- expect(calls.some(c => c.init.method === 'POST')).toBe(false);
117
- } finally {
118
- if (descriptor) Object.defineProperty(process.stdin, 'isTTY', descriptor);
119
- else Reflect.deleteProperty(process.stdin, 'isTTY');
120
- }
121
- });
122
-
123
- it('does not treat a failed health probe as success when the stored status is healthy', async () => {
124
- const request = vi.mocked(fetch).getMockImplementation()!;
125
- vi.mocked(fetch).mockImplementation((input, init) => String(input).includes('/api/health/check/')
126
- ? Promise.resolve(Response.json({ keyId: 7, status: 'error' }))
127
- : request(input, init));
128
- expect(await main(['keys', 'test', 'groq'])).toBe(1);
129
- expect(output).toContain('7\tgroq\terror');
130
- });
131
-
132
- it('rejects malformed key IDs from the gateway before attempting deletion', async () => {
133
- vi.mocked(fetch).mockResolvedValue(Response.json([{ ...key, id: '../providers' }]));
134
- await expect(main(['keys', 'remove', 'groq'])).rejects.toThrow('invalid key list');
135
- expect(fetch).toHaveBeenCalledTimes(1);
136
- });
137
-
138
- it('counts only enabled chat models on the same custom endpoint', async () => {
139
- keys = [{ ...key, platform: 'custom', models: [{ id: 1, kind: 'chat' }, { id: 4, kind: 'embedding' }] }];
140
- vi.mocked(fetch).mockImplementation(async (input) => new URL(String(input)).pathname === '/api/keys'
141
- ? Response.json(keys)
142
- : Response.json([
143
- { id: 1, platform: 'custom', modelId: 'first', enabled: true, keyId: 8 },
144
- { id: 2, platform: 'custom', modelId: 'other-endpoint', enabled: true, keyId: 9 },
145
- { id: 4, platform: 'custom', modelId: 'id-shared-with-embedding', enabled: true, keyId: 9 },
146
- ]));
147
- await main(['keys', 'list']);
148
- expect(output).toContain('7\tcustom\t1\tenabled\thealthy');
149
- });
150
-
151
- it('does not write when the provider identifier is unknown', async () => {
152
- await expect(main(['keys', 'add', 'missing', '--key', secret])).rejects.toThrow('Unknown provider');
153
- expect(calls.some(c => c.init.method === 'POST')).toBe(false);
154
- });
155
-
156
- it('requires a dashboard token rather than using the unified API key', async () => {
157
- vi.stubEnv('FREELLMAPI_DASHBOARD_TOKEN', '');
158
- vi.stubEnv('FREELLMAPI_API_KEY', 'unified-secret');
159
- await expect(main(['keys', 'list'])).rejects.toThrow('FREELLMAPI_DASHBOARD_TOKEN');
160
- expect(calls).toEqual([]);
161
- });
162
-
163
- it.each([
164
- ['keys', 'remove', 'groq', '--id', '7abc'],
165
- ['keys', 'remove', 'groq', '--id', '0'],
166
- ['keys', 'list', 'extra'],
167
- ['keys', 'remove'],
168
- ['keys', 'remove', 'groq', '--dry-run'],
169
- ['keys', 'list', '--key', secret],
170
- ['keys', 'add', 'groq', '--api-key', secret],
171
- ['keys', 'remove', 'groq', '--model', 'model-a'],
172
- ['keys', 'remove', 'groq', '--profile', 'work'],
173
- ['setup-claude', '--token', token],
174
- ['setup-claude', '--key', secret],
175
- ['list', '--id', '7'],
176
- ])('rejects invalid or inapplicable arguments before making requests: %j', async (...args) => {
177
- await expect(main(args)).rejects.toThrow();
178
- expect(calls).toEqual([]);
179
- });
180
-
181
- it('does not print server error bodies containing credentials', async () => {
182
- vi.mocked(fetch).mockResolvedValue(Response.json({ error: { message: `${secret} ${token}` } }, { status: 401 }));
183
- await expect(main(['keys', 'list'])).rejects.toThrow('Dashboard authentication failed');
184
- expect(output).toBe('');
185
- });
186
-
187
- it('omits secrets from non-authentication failures and transport errors', async () => {
188
- vi.mocked(fetch).mockResolvedValueOnce(Response.json({ error: secret }, { status: 500 }));
189
- await expect(main(['keys', 'list'])).rejects.toThrow(/^Dashboard request failed \(HTTP 500\)$/);
190
- vi.mocked(fetch).mockRejectedValueOnce(new Error(token));
191
- await expect(main(['keys', 'list'])).rejects.toThrow(/^Could not complete the dashboard request\./);
192
- expect(output).toBe('');
193
- });
194
-
195
- it('does not send dashboard credentials to redirects and applies the timeout', async () => {
196
- const timeout = vi.spyOn(AbortSignal, 'timeout');
197
- await main(['keys', 'test', 'groq', '--id', '7', '--timeout', '5000']);
198
- expect(calls[0].init).toMatchObject({ redirect: 'error', signal: expect.any(AbortSignal) });
199
- expect(timeout).toHaveBeenCalledWith(5000);
200
- await expect(main(['keys', 'list', '--url', 'http://user:password@localhost:3000'])).rejects.toThrow('without credentials');
201
- });
202
-
203
- it('shows key-specific help without requiring credentials or making requests', async () => {
204
- vi.stubEnv('FREELLMAPI_DASHBOARD_TOKEN', '');
205
- expect(await main(['keys', '--help'])).toBe(0);
206
- expect(output).toContain('keys add <platform>');
207
- expect(output).toContain('FREELLMAPI_DASHBOARD_TOKEN');
208
- expect(calls).toEqual([]);
209
- });
210
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/src/keys.ts DELETED
@@ -1,184 +0,0 @@
1
- export interface KeyCommandOptions {
2
- url: string;
3
- args: string[];
4
- token?: string;
5
- key?: string;
6
- keyId?: number;
7
- timeoutMs?: number;
8
- dryRun: boolean;
9
- }
10
-
11
- interface KeyRow {
12
- id: number;
13
- platform: string;
14
- enabled: boolean;
15
- status: string;
16
- lastHealthError?: string | null;
17
- modelScope?: string[] | null;
18
- models?: Array<{ id: number; kind: string }>;
19
- }
20
-
21
- interface ModelRow {
22
- id: number;
23
- platform: string;
24
- modelId: string;
25
- enabled: boolean;
26
- keyId?: number | null;
27
- }
28
-
29
- export function keysHelp(): string {
30
- return [
31
- 'Provider key management (dashboard authentication):',
32
- ' freellmapi keys add <platform> [--key KEY]',
33
- ' freellmapi keys list',
34
- ' freellmapi keys remove <platform> [--id ID]',
35
- ' freellmapi keys test <platform> [--id ID]',
36
- '',
37
- 'Options: --url URL, --token TOKEN, --timeout MS (default 30000)',
38
- 'Use FREELLMAPI_DASHBOARD_TOKEN or --token for the dashboard session token.',
39
- 'The unified --api-key / FREELLMAPI_API_KEY is not dashboard authentication.',
40
- 'Omit --key for hidden terminal input. Keyless providers do not prompt.',
41
- 'remove requires --id when a platform has multiple keys; test checks all matches.',
42
- 'list shows enabled chat model counts, respecting each key\'s model scope.',
43
- 'add saves the key, then checks it; failed validation leaves it saved and exits 1.',
44
- ].join('\n');
45
- }
46
-
47
- function gatewayRoot(value: string): string {
48
- let url: URL;
49
- try { url = new URL(value.trim()); } catch { throw new Error('--url must be an HTTP(S) gateway URL'); }
50
- if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
51
- throw new Error('--url must be an HTTP(S) URL without credentials, a query, or a fragment');
52
- }
53
- return url.href.replace(/\/+$/, '').replace(/\/v1$/i, '');
54
- }
55
-
56
- function modelCount(key: KeyRow, models: ModelRow[]): number {
57
- const customIds = new Set(key.models?.filter(m => m.kind === 'chat').map(m => m.id));
58
- return models.filter(model => model.enabled && model.platform === key.platform
59
- && (!key.modelScope?.length || key.modelScope.includes(model.modelId))
60
- && (key.platform === 'custom' ? customIds.has(model.id) : !model.keyId || model.keyId === key.id)).length;
61
- }
62
-
63
- const statuses = new Set(['healthy', 'invalid', 'unknown', 'rate_limited', 'error']);
64
- function statusOf(status: string): string {
65
- return statuses.has(status) ? status : 'unknown';
66
- }
67
-
68
- export async function runKeys(
69
- options: KeyCommandOptions,
70
- prompt: () => Promise<string>,
71
- ): Promise<number> {
72
- const [action, rawPlatform, ...extra] = options.args;
73
- if (!action || !['add', 'list', 'remove', 'test'].includes(action)) {
74
- throw new Error(`Expected keys add, list, remove, or test.\n\n${keysHelp()}`);
75
- }
76
- if (extra.length || (action === 'list' ? rawPlatform !== undefined : !rawPlatform)) {
77
- throw new Error(`Invalid arguments for keys ${action}.\n\n${keysHelp()}`);
78
- }
79
- if (options.dryRun) throw new Error('--dry-run is not supported by keys; no request was made');
80
- if (options.key !== undefined && action !== 'add') throw new Error('--key is only supported by keys add');
81
- if (options.keyId !== undefined && action !== 'remove' && action !== 'test') {
82
- throw new Error('--id is only supported by keys remove and keys test');
83
- }
84
- const platform = rawPlatform?.toLowerCase();
85
- if (platform && !/^[a-z][a-z0-9_-]*$/.test(platform)) throw new Error('Invalid provider platform identifier');
86
- const token = options.token?.trim();
87
- if (!token) throw new Error('Set FREELLMAPI_DASHBOARD_TOKEN or pass --token with a dashboard session token');
88
- const root = gatewayRoot(options.url);
89
- const timeout = options.timeoutMs ?? 30_000;
90
- if (!Number.isSafeInteger(timeout) || timeout <= 0 || timeout > 2_147_483_647) {
91
- throw new Error('--timeout must be a positive integer of at most 2147483647 milliseconds');
92
- }
93
-
94
- async function request<T>(path: string, method = 'GET', body?: unknown): Promise<T> {
95
- let response: Response;
96
- try {
97
- response = await fetch(`${root}${path}`, {
98
- method,
99
- headers: { Authorization: `Bearer ${token}`, ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
100
- body: body === undefined ? undefined : JSON.stringify(body),
101
- signal: AbortSignal.timeout(timeout),
102
- redirect: 'error',
103
- cache: 'no-store',
104
- });
105
- } catch {
106
- throw new Error('Could not complete the dashboard request. Check --url, connectivity, and --timeout.');
107
- }
108
- // Provider error bodies may contain credentials. Only report the HTTP
109
- // status, never echo arbitrary response bodies or transport errors.
110
- if (response.status === 401 || response.status === 403) {
111
- throw new Error('Dashboard authentication failed. Supply a current dashboard session token with --token or FREELLMAPI_DASHBOARD_TOKEN.');
112
- }
113
- if (!response.ok) throw new Error(`Dashboard request failed (HTTP ${response.status})`);
114
- if (response.status === 204) return undefined as T;
115
- try { return await response.json() as T; } catch { throw new Error('The gateway returned an invalid JSON response'); }
116
- }
117
-
118
- async function listKeys(): Promise<KeyRow[]> {
119
- const rows = await request<KeyRow[]>('/api/keys');
120
- if (!Array.isArray(rows) || rows.some(row => !row || !Number.isSafeInteger(row.id)
121
- || row.id <= 0 || typeof row.platform !== 'string')) {
122
- throw new Error('The gateway returned an invalid key list');
123
- }
124
- return rows;
125
- }
126
-
127
- async function check(id: number, provider: string): Promise<number> {
128
- const result = await request<{ keyId: number; status: string }>(`/api/health/check/${id}`, 'POST');
129
- if (!result || result.keyId !== id) throw new Error('The gateway returned an invalid health check result');
130
- // A transport failure preserves the previous status on the server, so
131
- // HTTP 200 / status=healthy alone cannot prove this check succeeded.
132
- const current = (await listKeys()).find(row => row.id === id);
133
- if (!current) throw new Error('The key no longer exists');
134
- const status = statusOf(result.status === 'healthy' ? current.status : result.status);
135
- const inconclusive = !!current.lastHealthError && status !== 'invalid';
136
- process.stdout.write(`${id}\t${provider}\t${inconclusive ? `inconclusive (stored status: ${statusOf(current.status)})` : status}\n`);
137
- return status === 'healthy' && !inconclusive ? 0 : 1;
138
- }
139
-
140
- if (action === 'add') {
141
- const { providers } = await request<{ providers: Array<{ platform: string; keyless?: boolean }> }>('/api/keys/providers');
142
- const provider = providers.find(p => p.platform === platform);
143
- if (!provider) {
144
- throw new Error(platform === 'custom'
145
- ? 'Custom endpoints require URL and model registration; add them in the dashboard.'
146
- : 'Unknown provider platform. Use the provider identifier shown in the dashboard.');
147
- }
148
- const value = (options.key ?? (provider.keyless ? '' : await prompt())).trim();
149
- if (!value && !provider.keyless) throw new Error('A provider API key is required');
150
- const saved = await request<{ id: number }>('/api/keys', 'POST', { platform, key: value });
151
- if (!Number.isSafeInteger(saved.id) || saved.id <= 0) throw new Error('The gateway did not return a valid saved key ID');
152
- process.stdout.write(`Saved ${platform} key ${saved.id}. Checking it now; the key remains saved if validation fails.\n`);
153
- return check(saved.id, platform!);
154
- }
155
-
156
- const rows = await listKeys();
157
- if (action === 'list') {
158
- if (!rows.length) {
159
- process.stdout.write('No provider keys configured.\n');
160
- return 0;
161
- }
162
- const models = await request<ModelRow[]>('/api/models');
163
- if (!Array.isArray(models)) throw new Error('The gateway returned an invalid model list');
164
- process.stdout.write('ID\tPLATFORM\tMODELS\tENABLED\tSTATUS\n');
165
- for (const row of rows) {
166
- const provider = /^[a-z][a-z0-9_-]*$/.test(row.platform) ? row.platform : 'unknown';
167
- process.stdout.write(`${row.id}\t${provider}\t${modelCount(row, models)}\t${row.enabled ? 'enabled' : 'disabled'}\t${statusOf(row.status)}\n`);
168
- }
169
- return 0;
170
- }
171
-
172
- const selected = rows.filter(row => row.platform === platform && (options.keyId === undefined || row.id === options.keyId));
173
- if (!selected.length) throw new Error('No matching key found for that platform and ID');
174
- if (action === 'remove') {
175
- if (selected.length > 1) throw new Error('Multiple keys match. Run keys list and specify one with --id.');
176
- await request(`/api/keys/${selected[0].id}`, 'DELETE');
177
- process.stdout.write(`Removed ${platform} key ${selected[0].id}.\n`);
178
- return 0;
179
- }
180
-
181
- let exitCode = 0;
182
- for (const row of selected) exitCode = Math.max(exitCode, await check(row.id, platform!));
183
- return exitCode;
184
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/src/models.test.ts DELETED
@@ -1,81 +0,0 @@
1
- import { describe, expect, it } from 'vitest';
2
- import { UnknownModelError, contextWindowOf, defaultModelId, resolveLaunchModel } from './models.js';
3
- import type { CatalogModel } from './types.js';
4
-
5
- // The distinction this module exists for: the CLI's catalog() fetches
6
- // `?available=true`, so absence from that roster means EITHER "no such model"
7
- // OR "exists, out of quota right now". Only the unfiltered roster separates
8
- // them, and conflating them reports a healthy pinned model as a typo the
9
- // moment its provider rate-limits.
10
-
11
- const AVAILABLE: CatalogModel[] = [
12
- { id: 'auto' },
13
- { id: 'fast-coder', available: true, context_window: 131072 },
14
- ];
15
-
16
- const FULL: CatalogModel[] = [
17
- ...AVAILABLE,
18
- { id: 'benched-model', available: false, context_window: 32768 },
19
- { id: 'no-window-model', available: true },
20
- ];
21
-
22
- describe('resolveLaunchModel', () => {
23
- it('accepts a model that is registered but not currently servable', () => {
24
- const resolved = resolveLaunchModel('benched-model', AVAILABLE, FULL);
25
- expect(resolved.id).toBe('benched-model');
26
- expect(resolved.unavailable).toBe(true);
27
- expect(resolved.contextWindow).toBe(32768);
28
- });
29
-
30
- it('rejects a model that is in neither roster', () => {
31
- expect(() => resolveLaunchModel('no-such-model', AVAILABLE, FULL))
32
- .toThrow(UnknownModelError);
33
- });
34
-
35
- it('suggests near-matches on an unknown id rather than only refusing', () => {
36
- expect(() => resolveLaunchModel('coder', AVAILABLE, FULL))
37
- .toThrow(/fast-coder/);
38
- });
39
-
40
- it('reports an available model as available', () => {
41
- expect(resolveLaunchModel('fast-coder', AVAILABLE, FULL))
42
- .toMatchObject({ id: 'fast-coder', unavailable: false, contextWindow: 131072 });
43
- });
44
-
45
- it('leaves the context window undefined when the catalog publishes none', () => {
46
- // Not 128000. An unpublished window is a different fact from a known one,
47
- // and inventing a number is how the launcher pinned a wrong compaction
48
- // threshold for every model whose provider states no window.
49
- expect(resolveLaunchModel('no-window-model', AVAILABLE, FULL).contextWindow)
50
- .toBeUndefined();
51
- });
52
-
53
- it('serves `auto` even though the router never lists it as a catalog row', () => {
54
- expect(resolveLaunchModel('auto', [], [])).toMatchObject({ id: 'auto', unavailable: false });
55
- });
56
-
57
- it('falls back to the filtered roster when the unfiltered one is unavailable', () => {
58
- // Degraded mode: an older gateway ignoring ?available=true, or a failed
59
- // second fetch. A known-good id must still resolve.
60
- expect(resolveLaunchModel('fast-coder', AVAILABLE).id).toBe('fast-coder');
61
- });
62
- });
63
-
64
- describe('defaultModelId', () => {
65
- it('prefers a concrete servable model over auto, so the session names its model', () => {
66
- expect(defaultModelId(AVAILABLE)).toBe('fast-coder');
67
- });
68
-
69
- it('falls back to auto when nothing concrete is servable', () => {
70
- expect(defaultModelId([{ id: 'auto' }, { id: 'x', available: false }])).toBe('auto');
71
- });
72
- });
73
-
74
- describe('contextWindowOf', () => {
75
- it('accepts either catalog spelling and undefined for neither', () => {
76
- expect(contextWindowOf({ id: 'a', context_window: 1000 })).toBe(1000);
77
- expect(contextWindowOf({ id: 'b', context_length: 2000 })).toBe(2000);
78
- expect(contextWindowOf({ id: 'c' })).toBeUndefined();
79
- expect(contextWindowOf({ id: 'd', context_window: null })).toBeUndefined();
80
- });
81
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/src/models.ts DELETED
@@ -1,81 +0,0 @@
1
- // Resolving a model id against the catalog, for the launchers.
2
- //
3
- // The subtlety this module exists for: `catalog()` fetches `/v1/models` with
4
- // `?available=true`, so a model missing from that response has TWO possible
5
- // meanings — it does not exist, or it exists and is merely out of quota right
6
- // now. Treating absence as "unknown model" reports a healthy pinned model as a
7
- // typo the moment its provider hits a rate limit. Only the UNFILTERED roster
8
- // can tell those apart, so `--model` is validated against that.
9
-
10
- import type { CatalogModel } from './types.js';
11
-
12
- export interface ResolvedModel {
13
- id: string;
14
- /** Context window in tokens, or undefined when the catalog does not publish
15
- * one. Undefined is a fact — an unpublished window is not the same as a
16
- * known 128k, and callers must not invent one. */
17
- contextWindow?: number;
18
- /** The catalog lists this model but it is not currently servable. */
19
- unavailable: boolean;
20
- }
21
-
22
- export class UnknownModelError extends Error {}
23
-
24
- export function contextWindowOf(model: CatalogModel): number | undefined {
25
- return model.context_window ?? model.context_length ?? undefined;
26
- }
27
-
28
- /**
29
- * The launcher's default when the caller did not pin one: the first servable
30
- * concrete model, falling back to `auto`.
31
- *
32
- * Deliberately NOT the same default as the setup generators, which prefer
33
- * `auto`. A generated config file is long-lived and should let the router
34
- * choose per request; a launch pins one id into ANTHROPIC_MODEL for the whole
35
- * session, and naming a concrete model there is what makes the session's model
36
- * visible and reproducible. Unifying the two silently changes what
37
- * `freellmapi launch` runs.
38
- */
39
- export function defaultModelId(models: CatalogModel[]): string {
40
- return models.find(model => model.id !== 'auto' && model.available !== false)?.id ?? 'auto';
41
- }
42
-
43
- /**
44
- * Resolve the model a launcher should pin.
45
- *
46
- * `available` is the filtered roster the CLI already fetches; `full` is the
47
- * unfiltered one. Pass the same array twice only when the unfiltered roster
48
- * could not be fetched — the caller then loses the ability to distinguish an
49
- * unknown id from an unavailable one, which is exactly the ambiguity this
50
- * function exists to remove.
51
- */
52
- export function resolveLaunchModel(
53
- requested: string | undefined,
54
- available: CatalogModel[],
55
- full: CatalogModel[] = available,
56
- ): ResolvedModel {
57
- const id = requested ?? defaultModelId(available);
58
- const known = full.find(model => model.id === id) ?? available.find(model => model.id === id);
59
-
60
- if (!known) {
61
- // `auto` is served by the router itself and need not appear in any roster.
62
- if (id === 'auto') return { id, unavailable: false };
63
- const suggestions = full
64
- .map(model => model.id)
65
- .filter(candidate => candidate.includes(id) || id.includes(candidate))
66
- .slice(0, 5);
67
- throw new UnknownModelError(
68
- `No model '${id}' in this gateway's catalog.`
69
- + (suggestions.length ? ` Did you mean: ${suggestions.join(', ')}?` : '')
70
- + ' Run `freellmapi list-models` to see what is registered.',
71
- );
72
- }
73
-
74
- return {
75
- id,
76
- contextWindow: contextWindowOf(known),
77
- // Absent from the filtered roster but present in the full one = registered
78
- // but not servable right now (quota, cooldown, a disabled key).
79
- unavailable: known.available === false || !available.some(model => model.id === id),
80
- };
81
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/src/tools.test.ts DELETED
@@ -1,709 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
4
- import { tools } from './tools.js';
5
- import type { GenerateContext } from './types.js';
6
-
7
- // Pinning ctx.detectedClient is not enough: tools.ts falls back to a live
8
- // detectChatGptClient() when it is undefined, so a runner with `codex` on
9
- // PATH (or ChatGPT.app installed) would still shift the golden notes. Mock
10
- // the module outright — undefined keeps the snapshots host-independent.
11
- vi.mock('./detect.js', () => ({
12
- detectChatGptClient: () => undefined,
13
- clientNotes: () => [
14
- 'No Codex CLI detected on this machine.',
15
- 'Install the CLI with: npm install -g @openai/codex',
16
- ],
17
- }));
18
-
19
- // CI runners export XDG_CONFIG_HOME (and could export MIMOCODE_HOME / DSH_HOME),
20
- // which the XDG-aware generators honour over ctx.homeDir. Pin them so golden
21
- // output is stable everywhere.
22
- beforeEach(() => {
23
- vi.stubEnv('XDG_CONFIG_HOME', '');
24
- vi.stubEnv('MIMOCODE_HOME', '');
25
- vi.stubEnv('DSH_HOME', '');
26
- vi.stubEnv('OPENCLAW_HOME', '');
27
- vi.stubEnv('OPENCLAW_STATE_DIR', '');
28
- vi.stubEnv('OPENCLAW_CONFIG_PATH', '');
29
- vi.stubEnv('HERMES_HOME', '');
30
- vi.stubEnv('PI_CODING_AGENT_DIR', '');
31
- vi.stubEnv('REASONIX_HOME', '');
32
- // Reasonix keeps its home under %APPDATA% on Windows instead of ~/.reasonix;
33
- // pin it so asPosix can map that home back to the POSIX golden (#1392).
34
- if (process.platform === 'win32') vi.stubEnv('APPDATA', WIN_APPDATA);
35
- });
36
- afterEach(() => {
37
- vi.unstubAllEnvs();
38
- });
39
-
40
- // Golden snapshots must not depend on the host: pin the client detection the
41
- // same way the XDG env vars above are pinned (a machine with `codex` on PATH
42
- // or ChatGPT.app installed would otherwise produce different notes than CI).
43
- const context: GenerateContext = {
44
- url: 'http://localhost:3000',
45
- apiKey: 'freellmapi-test-key',
46
- profile: 'default',
47
- homeDir: '/home/tester',
48
- detectedClient: undefined,
49
- models: [
50
- {
51
- id: 'fast-coder',
52
- name: 'Fast Coder',
53
- available: true,
54
- context_window: 131072,
55
- },
56
- {
57
- id: 'reasoning-model',
58
- name: 'Reasoning Model',
59
- available: true,
60
- context_window: 262144,
61
- },
62
- ],
63
- };
64
-
65
- // Generated file paths come from the host's path.join, so on Windows the
66
- // separator is '\\' while the golden strings here are POSIX (#1392). Normalize
67
- // before comparing, and map the pinned Windows Reasonix home to ~/.reasonix.
68
- const WIN_APPDATA = 'C:\\Users\\tester\\AppData\\Roaming';
69
- function asPosix(p: string): string {
70
- if (process.platform !== 'win32') return p;
71
- return p.replaceAll('\\', '/').replace('C:/Users/tester/AppData/Roaming/reasonix', '/home/tester/.reasonix');
72
- }
73
-
74
- // Snapshots embed the generated file paths verbatim; normalize them so the
75
- // golden files stay POSIX on every host (#1392).
76
- interface GeneratedFile {
77
- path: string;
78
- [key: string]: unknown;
79
- }
80
- function normalizeGenerationPaths<T extends { files: GeneratedFile[]; notes?: string[] }>(generation: T): T {
81
- return {
82
- ...generation,
83
- files: generation.files.map(f => ({ ...f, path: asPosix(f.path) })),
84
- // Generators also interpolate host-joined paths into their note text — Roo's
85
- // `autoImportSettingsPath` instructions quote the import file by full path —
86
- // so the notes are golden input as well (#1392).
87
- ...(generation.notes ? { notes: generation.notes.map(asPosix) } : {}),
88
- };
89
- }
90
-
91
- describe('tool generators', () => {
92
- it('defaults to auto, never fusion, when the live catalog lists virtual models first', () => {
93
- const liveContext: GenerateContext = {
94
- ...context,
95
- models: [
96
- { id: 'auto', name: 'Auto', available: true, context_window: 200_000 },
97
- { id: 'fusion', name: 'Fusion', available: true, context_window: 2_000_000 },
98
- ...context.models,
99
- ],
100
- };
101
- const claude = tools.find(tool => tool.id === 'claude')!.generate(liveContext);
102
- const settings = claude.files[0].value as { env: Record<string, string> };
103
- expect(settings.env.ANTHROPIC_MODEL).toBe('auto');
104
- const codex = tools.find(tool => tool.id === 'codex')!.generate(liveContext);
105
- expect(codex.files[0].content).toContain('model = "auto"');
106
- expect(codex.files[0].content).not.toContain('"fusion"');
107
- });
108
-
109
- for (const tool of tools) {
110
- it(`${tool.command} has stable golden output`, () => {
111
- expect(normalizeGenerationPaths(tool.generate(context))).toMatchSnapshot();
112
- });
113
- }
114
-
115
- it('honours an explicit --model instead of the default-model heuristic', () => {
116
- // `--model` was parsed into CliOptions and then dropped: it never reached
117
- // GenerateContext, so `setup-claude --model X` wrote whatever
118
- // primaryModel() preferred and said nothing about ignoring the flag.
119
- const pinned = { ...context, requestedModelId: 'reasoning-model' };
120
- const claude = tools.find(tool => tool.id === 'claude')!.generate(pinned);
121
- expect(JSON.stringify(claude.files)).toContain('reasoning-model');
122
- });
123
-
124
- it('pins a requested model that the available-roster does not carry', () => {
125
- // Validated against the UNFILTERED catalog upstream, so an id missing from
126
- // ctx.models here is registered-but-out-of-quota, not a typo. Writing a
127
- // different model into the user's config would be the wrong repair.
128
- const pinned = { ...context, requestedModelId: 'benched-model' };
129
- const claude = tools.find(tool => tool.id === 'claude')!.generate(pinned);
130
- expect(JSON.stringify(claude.files)).toContain('benched-model');
131
- });
132
-
133
- it('setup-codex with a named profile has stable golden output', () => {
134
- const generation = tools.find(tool => tool.id === 'codex')!
135
- .generate({ ...context, profile: 'work' });
136
- expect(normalizeGenerationPaths(generation)).toMatchSnapshot();
137
- });
138
-
139
- it('writes named Codex profiles as [profiles.NAME] inside config.toml', () => {
140
- const generation = tools.find(tool => tool.id === 'codex')!
141
- .generate({ ...context, profile: 'work' });
142
- expect(generation.files).toHaveLength(1);
143
- const file = generation.files[0];
144
- // Codex only reads ~/.codex/config.toml; per-profile files are ignored.
145
- expect(asPosix(file.path)).toBe('/home/tester/.codex/config.toml');
146
- expect(file.content).toContain('[profiles.work]');
147
- expect(file.content).toContain('model = "fast-coder"');
148
- expect(file.content).toContain('model_provider = "freellmapi"');
149
- expect(file.content).toContain('[model_providers.freellmapi]');
150
- // A named profile must not hijack the root/default model selection.
151
- expect(file.content!.split('\n').findIndex(line => line.startsWith('model =')))
152
- .toBeGreaterThan(file.content!.split('\n').indexOf('[profiles.work]'));
153
- expect(generation.notes.join('\n')).toContain('codex --profile work');
154
- });
155
-
156
- it('generates Cline current provider settings with repeatable selection', () => {
157
- const file = tools.find(tool => tool.id === 'cline')!.generate(context).files[0];
158
- const state = file.value as any;
159
- expect(asPosix(file.path)).toBe('/home/tester/.cline/data/settings/providers.json');
160
- expect(state).toMatchObject({
161
- version: 1,
162
- lastUsedProvider: 'openai-compatible',
163
- });
164
- expect(state.providers['openai-compatible']).toMatchObject({
165
- settings: {
166
- provider: 'openai-compatible',
167
- protocol: 'openai-chat',
168
- client: 'openai-compatible',
169
- model: 'fast-coder',
170
- baseUrl: 'http://localhost:3000/v1',
171
- apiKey: 'freellmapi-test-key',
172
- contextWindow: 131072,
173
- capabilities: ['streaming', 'tools'],
174
- },
175
- tokenSource: 'manual',
176
- });
177
- });
178
-
179
- it('generates a complete Continue v1 config with Agent tool support', () => {
180
- const config = tools.find(tool => tool.id === 'continue')!
181
- .generate(context).files[0].content!;
182
- expect(config).toContain('name: FreeLLMAPI');
183
- expect(config).toContain('version: 1.0.0');
184
- expect(config).toContain('schema: v1');
185
- expect(config).toContain(' - tool_use');
186
- expect(config).toContain(' apiKey: ${{ secrets.FREELLMAPI_API_KEY }}');
187
- });
188
-
189
- it('generates Goose custom-provider registration without persisting the key', () => {
190
- const generation = tools.find(tool => tool.id === 'goose')!.generate(context);
191
- const provider = generation.files.find(file => file.path.endsWith('freellmapi.json'))!.value as any;
192
- const selection = generation.files.find(file => file.path.endsWith('config.yaml'))!.content!;
193
- expect(provider).toMatchObject({
194
- name: 'freellmapi',
195
- engine: 'openai',
196
- api_key_env: 'FREELLMAPI_API_KEY',
197
- base_url: 'http://localhost:3000/v1',
198
- requires_auth: true,
199
- dynamic_models: false,
200
- });
201
- expect(provider.models.map((model: any) => model.name)).toEqual([
202
- 'fast-coder',
203
- 'reasoning-model',
204
- ]);
205
- expect(selection).toContain('GOOSE_PROVIDER: freellmapi');
206
- expect(JSON.stringify(generation)).not.toContain('freellmapi-test-key');
207
- });
208
-
209
- it('generates Qwen Code provider catalogs using a supported auth type', () => {
210
- const generation = tools.find(tool => tool.id === 'qwen')!.generate(context);
211
- const settings = generation.files.find(file => file.path.endsWith('settings.json'))!.value as any;
212
- expect(settings.security.auth.selectedType).toBe('openai');
213
- expect(settings.model).toEqual({ name: 'fast-coder' });
214
- expect(settings.modelProviders.openai.protocol).toBe('openai');
215
- expect(settings.modelProviders.openai.models).toHaveLength(2);
216
- expect(settings.modelProviders.openai.models[0]).toMatchObject({
217
- id: 'fast-coder',
218
- envKey: 'FREELLMAPI_API_KEY',
219
- baseUrl: 'http://localhost:3000/v1',
220
- generationConfig: { contextWindowSize: 131072 },
221
- });
222
- expect(settings.modelProviders).not.toHaveProperty('freellmapi');
223
- });
224
-
225
- it('wraps Roo Code imports in the documented provider profile envelope', () => {
226
- const config = tools.find(tool => tool.id === 'roo')!
227
- .generate(context).files[0].value as any;
228
- expect(config.providerProfiles.currentApiConfigName).toBe('freellmapi');
229
- expect(config.providerProfiles.apiConfigs.freellmapi).toMatchObject({
230
- apiProvider: 'openai',
231
- openAiBaseUrl: 'http://localhost:3000/v1',
232
- openAiModelId: 'fast-coder',
233
- });
234
- expect(config.globalSettings).toEqual({});
235
- });
236
-
237
- it('writes Kilo trusted global config with every catalog model', () => {
238
- const file = tools.find(tool => tool.id === 'kilo')!.generate(context).files[0];
239
- const config = file.value as any;
240
- expect(asPosix(file.path)).toBe('/home/tester/.config/kilo/kilo.jsonc');
241
- expect(config.$schema).toBe('https://app.kilo.ai/config.json');
242
- expect(config.model).toBe('openai-compatible/fast-coder');
243
- expect(config.provider['openai-compatible'].options).toEqual({
244
- apiKey: '{env:FREELLMAPI_API_KEY}',
245
- baseURL: 'http://localhost:3000/v1',
246
- });
247
- expect(Object.keys(config.provider['openai-compatible'].models)).toEqual([
248
- 'fast-coder',
249
- 'reasoning-model',
250
- ]);
251
- expect(config.provider['openai-compatible'].models['fast-coder']).toMatchObject({
252
- tool_call: true,
253
- limit: { context: 131072, output: 8192 },
254
- });
255
- expect(JSON.stringify(config)).not.toContain('freellmapi-test-key');
256
- });
257
-
258
- it('uses Crush openai-compat schema, lists every catalog model, and selects the default', () => {
259
- const config = tools.find(tool => tool.id === 'crush')!
260
- .generate(context).files[0].value as any;
261
- expect(config.$schema).toBe('https://charm.land/crush.json');
262
- expect(config.providers.freellmapi.type).toBe('openai-compat');
263
- expect(config.providers.freellmapi.models.map((model: any) => model.id)).toEqual([
264
- 'fast-coder',
265
- 'reasoning-model',
266
- ]);
267
- // A provider entry alone is never used: Crush auto-detects from whatever
268
- // credentials it finds on the machine unless `models.large`/`small` name it.
269
- expect(config.models).toEqual({
270
- large: { provider: 'freellmapi', model: 'fast-coder' },
271
- small: { provider: 'freellmapi', model: 'fast-coder' },
272
- });
273
- for (const model of config.providers.freellmapi.models) {
274
- expect(model).toMatchObject({
275
- cost_per_1m_in: 0,
276
- cost_per_1m_out: 0,
277
- cost_per_1m_in_cached: 0,
278
- cost_per_1m_out_cached: 0,
279
- can_reason: false,
280
- supports_attachments: false,
281
- });
282
- }
283
- });
284
-
285
- it('keeps `auto` in the OpenCode, Crush and Goose rosters when it is the default', () => {
286
- // OpenCode resolves `freellmapi/auto` only if `auto` is a declared model,
287
- // and Crush's `models.large` must name a listed model; with `auto` in the
288
- // live catalog all three generators put it first rather than filter it out.
289
- const liveContext: GenerateContext = {
290
- ...context,
291
- models: [{ id: 'auto', name: 'Auto', available: true, context_window: 200_000 }, ...context.models],
292
- };
293
- const opencode = tools.find(tool => tool.id === 'opencode')!.generate(liveContext).files[0].value as any;
294
- expect(opencode.model).toBe('freellmapi/auto');
295
- expect(Object.keys(opencode.provider.freellmapi.models)).toEqual(['auto', 'fast-coder', 'reasoning-model']);
296
- const crush = tools.find(tool => tool.id === 'crush')!.generate(liveContext).files[0].value as any;
297
- expect(crush.models.large.model).toBe('auto');
298
- expect(crush.providers.freellmapi.models[0].id).toBe('auto');
299
- const goose = tools.find(tool => tool.id === 'goose')!.generate(liveContext);
300
- const provider = goose.files.find(file => file.path.endsWith('freellmapi.json'))!.value as any;
301
- expect(provider.models[0].name).toBe('auto');
302
- // Qwen Code silently falls back to the first listed model when the selected
303
- // one is missing (it picked `fusion`); Kilo refuses to start outright.
304
- const qwen = tools.find(tool => tool.id === 'qwen')!.generate(liveContext).files[0].value as any;
305
- expect(qwen.modelProviders.openai.models[0].id).toBe('auto');
306
- const kilo = tools.find(tool => tool.id === 'kilo')!.generate(liveContext).files[0].value as any;
307
- expect(kilo.model).toBe('openai-compatible/auto');
308
- expect(Object.keys(kilo.provider['openai-compatible'].models)[0]).toBe('auto');
309
- });
310
-
311
- it('delivers the Continue secret through ~/.continue/.env', () => {
312
- const generation = tools.find(tool => tool.id === 'continue')!.generate(context);
313
- const env = generation.files.find(file => file.path.endsWith('.env'))!;
314
- expect(asPosix(env.path)).toBe('/home/tester/.continue/.env');
315
- expect(env.sensitive).toBe(true);
316
- expect(env.content).toBe('FREELLMAPI_API_KEY=freellmapi-test-key\n');
317
- const config = generation.files.find(file => file.path.endsWith('config.yaml'))!.content!;
318
- expect(config).not.toContain('freellmapi-test-key');
319
- });
320
-
321
- it('gives Roo an openai profile for the extension and a separate CLI import with an openrouter one', () => {
322
- const files = tools.find(tool => tool.id === 'roo')!.generate(context).files;
323
- const value = files[0].value as any;
324
- const configs = value.providerProfiles.apiConfigs;
325
- expect(value.providerProfiles.currentApiConfigName).toBe('freellmapi');
326
- // The CLI forces its provider onto the CURRENT profile of the file it
327
- // imports, so its file must make the openrouter-type profile current.
328
- const cli = files[1].value as any;
329
- expect(asPosix(files[1].path)).toBe('/home/tester/.roo/freellmapi-cli.json');
330
- expect(cli.providerProfiles.currentApiConfigName).toBe('freellmapi-cli');
331
- expect(cli.providerProfiles.apiConfigs['freellmapi-cli']).toEqual(configs['freellmapi-cli']);
332
- expect(asPosix(files[2].path)).toBe('/home/tester/.roo/cli-settings.json');
333
- expect(files[2].value).toEqual({ provider: 'openrouter', model: 'fast-coder' });
334
- expect(configs.freellmapi).toMatchObject({
335
- apiProvider: 'openai',
336
- openAiBaseUrl: 'http://localhost:3000/v1',
337
- openAiModelId: 'fast-coder',
338
- openAiCustomModelInfo: { contextWindow: 131072, maxTokens: 8192 },
339
- });
340
- expect(configs['freellmapi-cli']).toEqual({
341
- apiProvider: 'openrouter',
342
- openRouterBaseUrl: 'http://localhost:3000/v1',
343
- openRouterApiKey: 'freellmapi-test-key',
344
- openRouterModelId: 'fast-coder',
345
- });
346
- });
347
-
348
- it('declares a complete DeepSeek Harness route and claims the default model', () => {
349
- const dsh = tools.find(tool => tool.id === 'dsh')!;
350
- const generation = dsh.generate(context);
351
- const [settings, env] = generation.files;
352
- expect(asPosix(settings.path)).toBe('/home/tester/.dsh/settings.yaml');
353
- expect(settings.format).toBe('yaml');
354
- const value = settings.value as {
355
- 'llm-pi-ai': { providers: Record<string, { api: string; baseURL: string; apiKeyEnv: string; models: { id: string }[] }> };
356
- 'agent-default-model': { provider: string; model: string; reasoningEffort?: string };
357
- };
358
- const route = value['llm-pi-ai'].providers.freellmapi;
359
- // A hand-declared route must carry api, baseURL, and a non-empty models
360
- // list, or DSH refuses the whole section where it is written.
361
- expect(route.api).toBe('openai-completions');
362
- expect(route.baseURL).toBe('http://localhost:3000/v1');
363
- expect(route.apiKeyEnv).toBe('FREELLMAPI_API_KEY');
364
- expect(route.models.map(model => model.id)).toEqual(['fast-coder', 'reasoning-model']);
365
- expect(value['agent-default-model']).toEqual({
366
- provider: 'freellmapi',
367
- model: 'fast-coder',
368
- reasoningEffort: undefined,
369
- });
370
- expect('reasoningEffort' in value['agent-default-model']).toBe(true);
371
- // DSH loads $DSH_HOME/.env as its user environment layer, which is how
372
- // `apiKeyEnv` resolves without an export.
373
- expect({ ...env, path: asPosix(env.path) }).toMatchObject({
374
- path: '/home/tester/.dsh/.env',
375
- format: 'env',
376
- sensitive: true,
377
- content: 'FREELLMAPI_API_KEY=freellmapi-test-key\n',
378
- });
379
- });
380
-
381
- it('adds a named DeepSeek Harness profile as a second route without moving the default', () => {
382
- const dsh = tools.find(tool => tool.id === 'dsh')!;
383
- const value = dsh.generate({ ...context, profile: 'Work Laptop' }).files[0].value as Record<string, unknown>;
384
- const providers = (value['llm-pi-ai'] as { providers: Record<string, unknown> }).providers;
385
- expect(Object.keys(providers)).toEqual(['freellmapi-work-laptop']);
386
- expect(value['agent-default-model']).toBeUndefined();
387
- });
388
-
389
- it('writes MiMo Code a custom provider its own schema accepts', () => {
390
- const mimo = tools.find(tool => tool.id === 'mimo')!;
391
- const [config] = mimo.generate(context).files;
392
- // The global config directory is XDG-based, and `config.json` is the
393
- // weakest of the three names it merges, so a hand-written
394
- // `mimocode.json` still wins.
395
- expect(asPosix(config.path)).toBe('/home/tester/.config/mimocode/config.json');
396
- const value = config.value as {
397
- model: string;
398
- provider: {
399
- freellmapi: {
400
- npm: string;
401
- options: Record<string, string>;
402
- models: Record<string, { limit: Record<string, number> }>;
403
- };
404
- };
405
- };
406
- const provider = value.provider.freellmapi;
407
- expect(provider.npm).toBe('@ai-sdk/openai-compatible');
408
- expect(provider.options).toEqual({
409
- baseURL: 'http://localhost:3000/v1',
410
- apiKey: '{env:FREELLMAPI_API_KEY}',
411
- });
412
- // `provider.<id>.models.<id>.limit` requires context AND output.
413
- expect(provider.models['fast-coder'].limit).toEqual({ context: 131072, output: 8192 });
414
- // The default model has to name an entry that exists in that map.
415
- expect(value.model).toBe('freellmapi/fast-coder');
416
- expect(Object.keys(provider.models)).toContain(value.model.split('/')[1]);
417
- // MIMOCODE_API_KEY and MIMOCODE_BASE_URL do not exist.
418
- expect(JSON.stringify(mimo.generate(context))).not.toContain('MIMOCODE_');
419
- });
420
-
421
- it('keeps the MiMo Code default model in its own provider map when auto leads', () => {
422
- const liveContext: GenerateContext = {
423
- ...context,
424
- models: [
425
- { id: 'auto', name: 'Auto', available: true, context_window: 200_000 },
426
- ...context.models,
427
- ],
428
- };
429
- const value = tools.find(tool => tool.id === 'mimo')!
430
- .generate(liveContext).files[0].value as {
431
- model: string;
432
- provider: { freellmapi: { models: Record<string, unknown> } };
433
- };
434
- expect(value.model).toBe('freellmapi/auto');
435
- expect(Object.keys(value.provider.freellmapi.models)).toContain('auto');
436
- });
437
-
438
- it('writes OpenClaw as a custom provider plus the default model ref, key via its own .env', () => {
439
- // OpenClaw resolves `${VAR}` in openclaw.json from the global
440
- // ~/.openclaw/.env it loads itself, so the pair works with nothing
441
- // exported. A custom origin gets no attribution header from OpenClaw, so
442
- // the provider carries a static User-Agent the gateway can classify.
443
- const [config, env] = tools.find(tool => tool.id === 'openclaw')!.generate(context).files;
444
- expect(asPosix(config.path)).toBe('/home/tester/.openclaw/openclaw.json');
445
- expect(config.format).toBe('json');
446
- const value = config.value as {
447
- agents: { defaults: { model: { primary: string } } }
448
- models: { providers: Record<string, { baseUrl: string; apiKey: string; api: string; headers: Record<string, string>; models: { id: string }[] }> }
449
- };
450
- expect(value.agents.defaults.model.primary).toBe('freellmapi/fast-coder');
451
- const provider = value.models.providers.freellmapi;
452
- expect(provider.baseUrl).toBe('http://localhost:3000/v1');
453
- expect(provider.apiKey).toBe('${FREELLMAPI_API_KEY}');
454
- expect(provider.api).toBe('openai-completions');
455
- expect(provider.headers).toEqual({ 'User-Agent': 'openclaw' });
456
- expect(provider.models.map(model => model.id)).toEqual(['fast-coder', 'reasoning-model']);
457
- expect(asPosix(env.path)).toBe('/home/tester/.openclaw/.env');
458
- expect(env.sensitive).toBe(true);
459
- expect(env.content).toBe('FREELLMAPI_API_KEY=freellmapi-test-key\n');
460
- });
461
-
462
- it('gives a named OpenClaw profile its own provider without touching the default model', () => {
463
- const generation = tools.find(tool => tool.id === 'openclaw')!.generate({ ...context, profile: 'Work Box' });
464
- const value = generation.files[0].value as { agents?: unknown; models: { providers: Record<string, unknown> } };
465
- expect(value.agents).toBeUndefined();
466
- expect(Object.keys(value.models.providers)).toEqual(['freellmapi-work-box']);
467
- });
468
-
469
- it('honours OPENCLAW_CONFIG_PATH and OPENCLAW_STATE_DIR the way OpenClaw does', () => {
470
- vi.stubEnv('OPENCLAW_STATE_DIR', '/srv/claw');
471
- const [config, env] = tools.find(tool => tool.id === 'openclaw')!.generate(context).files;
472
- expect(asPosix(config.path)).toBe('/srv/claw/openclaw.json');
473
- expect(asPosix(env.path)).toBe('/srv/claw/.env');
474
- vi.stubEnv('OPENCLAW_CONFIG_PATH', '/etc/openclaw.json');
475
- expect(tools.find(tool => tool.id === 'openclaw')!.generate(context).files[0].path).toBe('/etc/openclaw.json');
476
- });
477
-
478
- it('writes Hermes Agent as a custom model block with the key routed through its .env', () => {
479
- // config.yaml is Hermes's single source of truth for the endpoint:
480
- // OPENAI_BASE_URL is ignored for non-OpenAI hosts and OPENAI_API_KEY is only
481
- // sent to OpenAI hosts, so both go in the `model` block, the key as the
482
- // `${VAR}` form Hermes expands from ~/.hermes/.env. Leftover key_env keys
483
- // from the wizard are retired so they cannot shadow api_key.
484
- const [config, env] = tools.find(tool => tool.id === 'hermes')!.generate(context).files;
485
- expect(asPosix(config.path)).toBe('/home/tester/.hermes/config.yaml');
486
- expect(config.format).toBe('yaml');
487
- expect(config.value).toEqual({
488
- model: {
489
- provider: 'custom',
490
- default: 'fast-coder',
491
- base_url: 'http://localhost:3000/v1',
492
- api_key: '${FREELLMAPI_API_KEY}',
493
- api_mode: 'chat_completions',
494
- context_length: 131072,
495
- default_headers: { 'User-Agent': 'hermes-agent' },
496
- key_env: undefined,
497
- api_key_env: undefined,
498
- },
499
- });
500
- expect(asPosix(env.path)).toBe('/home/tester/.hermes/.env');
501
- expect(env.sensitive).toBe(true);
502
- expect(env.content).toBe('FREELLMAPI_API_KEY=freellmapi-test-key\n');
503
- });
504
-
505
- it('gives a named Hermes profile a providers entry instead of the default model', () => {
506
- vi.stubEnv('HERMES_HOME', '/srv/hermes');
507
- const [config] = tools.find(tool => tool.id === 'hermes')!.generate({ ...context, profile: 'lab' }).files;
508
- expect(asPosix(config.path)).toBe('/srv/hermes/config.yaml');
509
- const value = config.value as { model?: unknown; providers: Record<string, { api: string; default_model: string }> };
510
- expect(value.model).toBeUndefined();
511
- expect(value.providers['freellmapi-lab'].api).toBe('http://localhost:3000/v1');
512
- expect(value.providers['freellmapi-lab'].default_model).toBe('fast-coder');
513
- });
514
-
515
- it('writes Pi as a models.json provider plus the startup default in settings.json', () => {
516
- // Pi has no .env of its own, so the key is literal in the 0600 models.json.
517
- // A provider entry only fills /model; defaultProvider + defaultModel in
518
- // settings.json is what a fresh `pi` starts on. A custom origin gets the
519
- // bare openai-node UA from Pi, so the provider names the client itself.
520
- const [models, settings] = tools.find(tool => tool.id === 'pi')!.generate(context).files;
521
- expect(asPosix(models.path)).toBe('/home/tester/.pi/agent/models.json');
522
- expect(models.format).toBe('json');
523
- expect(models.sensitive).toBe(true);
524
- const provider = (models.value as { providers: Record<string, any> }).providers.freellmapi;
525
- expect(provider).toMatchObject({
526
- name: 'FreeLLMAPI',
527
- baseUrl: 'http://localhost:3000/v1',
528
- api: 'openai-completions',
529
- apiKey: 'freellmapi-test-key',
530
- headers: { 'User-Agent': 'pi-coding-agent' },
531
- });
532
- expect(provider.models.map((model: { id: string }) => model.id)).toEqual(['fast-coder', 'reasoning-model']);
533
- expect(provider.models[0]).toEqual({
534
- id: 'fast-coder',
535
- name: 'Fast Coder',
536
- reasoning: false,
537
- input: ['text'],
538
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
539
- contextWindow: 131072,
540
- maxTokens: 8192,
541
- });
542
- expect(asPosix(settings.path)).toBe('/home/tester/.pi/agent/settings.json');
543
- expect(settings.sensitive).toBeUndefined();
544
- expect(settings.value).toEqual({ defaultProvider: 'freellmapi', defaultModel: 'fast-coder' });
545
- });
546
-
547
- it('keeps `auto` first in the Pi roster when it is the default', () => {
548
- const liveContext: GenerateContext = {
549
- ...context,
550
- models: [{ id: 'auto', name: 'Auto', available: true, context_window: 200_000 }, ...context.models],
551
- };
552
- const [models, settings] = tools.find(tool => tool.id === 'pi')!.generate(liveContext).files;
553
- const provider = (models.value as { providers: Record<string, { models: { id: string }[] }> }).providers.freellmapi;
554
- expect(provider.models.map(model => model.id)).toEqual(['auto', 'fast-coder', 'reasoning-model']);
555
- expect(settings.value).toEqual({ defaultProvider: 'freellmapi', defaultModel: 'auto' });
556
- });
557
-
558
- it('gives a named Pi profile its own provider and leaves the default model alone', () => {
559
- vi.stubEnv('PI_CODING_AGENT_DIR', '/srv/pi');
560
- const files = tools.find(tool => tool.id === 'pi')!.generate({ ...context, profile: 'Work Box' }).files;
561
- expect(files).toHaveLength(1);
562
- expect(asPosix(files[0].path)).toBe('/srv/pi/models.json');
563
- const providers = (files[0].value as { providers: Record<string, { name: string }> }).providers;
564
- expect(Object.keys(providers)).toEqual(['freellmapi-work-box']);
565
- expect(providers['freellmapi-work-box'].name).toBe('FreeLLMAPI (Work Box)');
566
- });
567
-
568
- it('writes Reasonix as a [[providers]] entry plus its key in the Reasonix .env', () => {
569
- // Reasonix names the key variable in config.toml and keeps the value in the
570
- // .env beside it, which it loads itself. `default_model` is provider/model
571
- // and must sit in the root region, above the array entry.
572
- const [config, env] = tools.find(tool => tool.id === 'reasonix')!.generate(context).files;
573
- expect(asPosix(config.path)).toBe('/home/tester/.reasonix/config.toml');
574
- expect(config.format).toBe('toml');
575
- expect(config.sensitive).toBeUndefined();
576
- const lines = (config.content ?? '').split('\n');
577
- expect(lines[0]).toBe('default_model = "freellmapi/fast-coder"');
578
- expect(lines.indexOf('[[providers]]')).toBeGreaterThan(0);
579
- expect(lines).toContain('name = "freellmapi"');
580
- expect(lines).toContain('kind = "openai"');
581
- expect(lines).toContain('base_url = "http://localhost:3000/v1"');
582
- expect(lines).toContain('models = ["fast-coder", "reasoning-model"]');
583
- expect(lines).toContain('default = "fast-coder"');
584
- expect(lines).toContain('api_key_env = "FREELLMAPI_API_KEY"');
585
- expect(lines).toContain('context_window = 131072');
586
- expect(config.content).not.toContain('freellmapi-test-key');
587
- expect({ ...env, path: asPosix(env.path) }).toEqual({
588
- path: '/home/tester/.reasonix/.env',
589
- format: 'env',
590
- sensitive: true,
591
- content: 'FREELLMAPI_API_KEY=freellmapi-test-key\n',
592
- });
593
- });
594
-
595
- it('keeps `auto` first in the Reasonix roster when it is the default', () => {
596
- const liveContext: GenerateContext = {
597
- ...context,
598
- models: [{ id: 'auto', name: 'Auto', available: true, context_window: 200_000 }, ...context.models],
599
- };
600
- const [config] = tools.find(tool => tool.id === 'reasonix')!.generate(liveContext).files;
601
- expect(config.content).toContain('default_model = "freellmapi/auto"');
602
- expect(config.content).toContain('models = ["auto", "fast-coder", "reasoning-model"]');
603
- });
604
-
605
- it('gives a named Reasonix profile its own provider and leaves the default model alone', () => {
606
- vi.stubEnv('REASONIX_HOME', '/srv/reasonix');
607
- const [config, env] = tools.find(tool => tool.id === 'reasonix')!.generate({ ...context, profile: 'Work Box' }).files;
608
- expect(asPosix(config.path)).toBe('/srv/reasonix/config.toml');
609
- expect(asPosix(env.path)).toBe('/srv/reasonix/.env');
610
- expect(config.content).not.toContain('default_model');
611
- expect(config.content!.split('\n')[0]).toBe('[[providers]]');
612
- expect(config.content).toContain('name = "freellmapi-work-box"');
613
- expect(config.content).toContain('display_name = "FreeLLMAPI (Work Box)"');
614
- });
615
-
616
- it('writes ZCode as a custom provider in ~/.zcode/v2/provider_config.json', () => {
617
- // ZCode has no env lookup for custom providers — the key has to live in
618
- // the file, which the writer then protects with 0600 (sensitive: true).
619
- const [config] = tools.find(tool => tool.id === 'zcode')!.generate(context).files;
620
- expect(asPosix(config.path)).toBe('/home/tester/.zcode/v2/provider_config.json');
621
- expect(config.format).toBe('json');
622
- expect(config.sensitive).toBe(true);
623
- const value = config.value as {
624
- schemaVersion: number;
625
- config: {
626
- providerConfigRules: { providerRules: {
627
- providerId: string; providerName: string;
628
- config: { access: { type: string; apiKey: string }; api: { type: string; baseUrl: string }; personalModelIds: string[] };
629
- }[] };
630
- modelConfigRules: {
631
- providerModelRules: { providerId: string; modelId: string; config: { properties: { contextWindow: number }; optionSpecs: { maxOutputTokens: { max: number; map: string } } } }[];
632
- manualProviderModelRules: unknown[];
633
- };
634
- providerOrder: string[];
635
- defaultModelSelection: { providerId: string; modelId: string };
636
- };
637
- };
638
- expect(value.schemaVersion).toBe(1);
639
- const [provider] = value.config.providerConfigRules.providerRules;
640
- expect(provider.providerId).toBe('freellmapi');
641
- expect(provider.providerName).toBe('FreeLLMAPI');
642
- expect(provider.config.access).toEqual({ type: 'api-key', apiKey: 'freellmapi-test-key' });
643
- expect(provider.config.api).toEqual({ type: 'openai-chat-completions', baseUrl: 'http://localhost:3000/v1' });
644
- expect(provider.config.personalModelIds).toEqual(['fast-coder', 'reasoning-model']);
645
- const rules = value.config.modelConfigRules.providerModelRules;
646
- expect(rules.map(rule => rule.modelId)).toEqual(['fast-coder', 'reasoning-model']);
647
- expect(rules[0].config.properties.contextWindow).toBe(131072);
648
- expect(rules[0].config.optionSpecs.maxOutputTokens.map).toBe('{"max_tokens": maxOutputTokens}');
649
- expect(value.config.modelConfigRules.manualProviderModelRules).toEqual([]);
650
- expect(value.config.defaultModelSelection).toEqual({ providerId: 'freellmapi', modelId: 'fast-coder' });
651
- // The rule arrays are merged per provider, never replaced whole.
652
- expect(config.arrays?.['config.providerConfigRules.providerRules']).toEqual({ ownedBy: { providerId: 'freellmapi' } });
653
- });
654
-
655
- it('follows ZCODE_PERSONAL_PROVIDER_CONFIG_FILE for ZCode', () => {
656
- vi.stubEnv('ZCODE_PERSONAL_PROVIDER_CONFIG_FILE', '/srv/zcode/provider_config.json');
657
- const [config] = tools.find(tool => tool.id === 'zcode')!.generate(context).files;
658
- expect(asPosix(config.path)).toBe('/srv/zcode/provider_config.json');
659
- });
660
-
661
- it('gives a named ZCode profile its own provider entry', () => {
662
- const [config] = tools.find(tool => tool.id === 'zcode')!.generate({ ...context, profile: 'Work Box' }).files;
663
- const value = config.value as { config: { providerConfigRules: { providerRules: { providerId: string; providerName: string }[] } } };
664
- const [provider] = value.config.providerConfigRules.providerRules;
665
- expect(provider.providerId).toBe('freellmapi-work-box');
666
- expect(provider.providerName).toBe('FreeLLMAPI (Work Box)');
667
- });
668
-
669
- it('writes AtomCode as default_provider plus a typed [providers.freellmapi] table', () => {
670
- // AtomCode ignores a bare `[provider]` table: it looks up the table named
671
- // by the root `default_provider` key, and only a `type = "openai"` table
672
- // speaks the OpenAI-compatible wire. `context_window` is its own key.
673
- const [config] = tools.find(tool => tool.id === 'atomcode')!.generate(context).files;
674
- expect(asPosix(config.path)).toBe('/home/tester/.atomcode/config.toml');
675
- expect(config.format).toBe('toml');
676
- expect(config.sensitive).toBe(true);
677
- const lines = (config.content ?? '').split('\n');
678
- expect(lines[0]).toBe('default_provider = "freellmapi"');
679
- expect(lines).toContain('[providers.freellmapi]');
680
- expect(lines.indexOf('[providers.freellmapi]')).toBeGreaterThan(0);
681
- expect(lines).toContain('type = "openai"');
682
- expect(lines).toContain('base_url = "http://localhost:3000/v1"');
683
- expect(lines).toContain('api_key = "freellmapi-test-key"');
684
- expect(lines).toContain('model = "fast-coder"');
685
- expect(lines).toContain('context_window = 131072');
686
- expect(config.content).not.toContain('[provider]');
687
- });
688
-
689
- it('uses /v1 for every OpenAI-compatible generated base URL', () => {
690
- for (const tool of tools.filter(entry => entry.protocol.startsWith('OpenAI'))) {
691
- expect(tool.baseUrlSupport, tool.id).toBe('/v1');
692
- }
693
- expect(tools.find(tool => tool.id === 'claude')!.baseUrlSupport).toBe('root');
694
- });
695
-
696
- it('keeps the dashboard metadata export in sync with the tool catalog', () => {
697
- const expected = tools.map(({ generate: _generate, ...tool }) => tool);
698
- const packageMetadata = JSON.parse(fs.readFileSync(
699
- path.resolve(import.meta.dirname, '../tools.json'),
700
- 'utf8',
701
- ));
702
- const dashboardMetadata = JSON.parse(fs.readFileSync(
703
- path.resolve(import.meta.dirname, '../../client/src/data/agent-tools.json'),
704
- 'utf8',
705
- ));
706
- expect(packageMetadata).toEqual(expected);
707
- expect(dashboardMetadata).toEqual(expected);
708
- });
709
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/src/tools.ts DELETED
@@ -1,1173 +0,0 @@
1
- import path from 'node:path';
2
- import { clientNotes, detectChatGptClient } from './detect.js';
3
- import type {
4
- CatalogModel,
5
- GenerateContext,
6
- Generation,
7
- ToolDefinition,
8
- } from './types.js';
9
-
10
- function rootUrl(url: string): string {
11
- return url.trim().replace(/\/+$/, '').replace(/\/v1$/i, '');
12
- }
13
-
14
- function v1Url(url: string): string {
15
- return `${rootUrl(url)}/v1`;
16
- }
17
-
18
- function primaryModel(models: CatalogModel[], requestedId?: string): CatalogModel {
19
- // An explicit --model wins over every heuristic below. It is validated
20
- // against the UNFILTERED catalog before we get here, so an id absent from
21
- // `models` (the available-only roster) is a real, registered model that is
22
- // merely out of quota right now — pin it anyway rather than silently writing
23
- // a different model into the user's config.
24
- if (requestedId) return models.find(model => model.id === requestedId) ?? { id: requestedId };
25
- // `auto` — the router picking the best model per request — is the whole
26
- // point of the gateway and the right default for a generated config. Never
27
- // fall back to `fusion` (multi-model fan-out) by accident.
28
- return models.find(model => model.id === 'auto')
29
- ?? models.find(model => model.id !== 'fusion' && model.available !== false)
30
- ?? models.find(model => model.id !== 'fusion')
31
- ?? { id: 'auto', name: 'Auto', context_window: 128_000 };
32
- }
33
-
34
- function catalogModels(models: CatalogModel[]): CatalogModel[] {
35
- const available = models.filter(model => model.id !== 'auto' && model.available !== false);
36
- if (available.length) return available;
37
- const nonAuto = models.filter(model => model.id !== 'auto');
38
- return nonAuto.length ? nonAuto : [primaryModel(models)];
39
- }
40
-
41
- function contextWindow(model: CatalogModel): number {
42
- return model.context_window ?? model.context_length ?? 128_000;
43
- }
44
-
45
- function outputLimit(model: CatalogModel): number {
46
- return Math.min(8192, contextWindow(model));
47
- }
48
-
49
- function yamlString(value: string): string {
50
- return JSON.stringify(value);
51
- }
52
-
53
- function claude(ctx: GenerateContext): Generation {
54
- const model = primaryModel(ctx.models, ctx.requestedModelId);
55
- const directory = ctx.profile === 'default'
56
- ? path.join(ctx.homeDir, '.claude')
57
- : path.join(ctx.homeDir, '.claude', 'profiles', ctx.profile);
58
- return {
59
- files: [{
60
- path: path.join(directory, 'settings.json'),
61
- format: 'json',
62
- sensitive: true,
63
- value: {
64
- env: {
65
- ANTHROPIC_BASE_URL: rootUrl(ctx.url),
66
- ANTHROPIC_AUTH_TOKEN: ctx.apiKey,
67
- ANTHROPIC_MODEL: model.id,
68
- ANTHROPIC_DEFAULT_OPUS_MODEL: model.id,
69
- ANTHROPIC_DEFAULT_SONNET_MODEL: model.id,
70
- ANTHROPIC_DEFAULT_HAIKU_MODEL: model.id,
71
- CLAUDE_CODE_AUTO_COMPACT_WINDOW: String(contextWindow(model)),
72
- CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: '1',
73
- },
74
- },
75
- }],
76
- notes: [
77
- ctx.profile === 'default'
78
- ? 'Claude Code will read this configuration automatically.'
79
- : `Launch with CLAUDE_CONFIG_DIR=${directory} claude`,
80
- 'For zero-persistence credentials, prefer: freellmapi launch',
81
- ],
82
- };
83
- }
84
-
85
- function codex(ctx: GenerateContext): Generation {
86
- const model = primaryModel(ctx.models, ctx.requestedModelId);
87
- const compact = Math.max(16_000, Math.floor(contextWindow(model) * 0.9));
88
- const providerTable = [
89
- '[model_providers.freellmapi]',
90
- 'name = "FreeLLMAPI"',
91
- `base_url = ${JSON.stringify(v1Url(ctx.url))}`,
92
- 'wire_api = "responses"',
93
- 'env_key = "FREELLMAPI_API_KEY"',
94
- 'requires_openai_auth = false',
95
- ];
96
- // Codex reads exactly one file, ~/.codex/config.toml. Named profiles are
97
- // `[profiles.NAME]` tables in that same file, selected with
98
- // `codex --profile NAME`; separate per-profile files are never read.
99
- const content = ctx.profile === 'default'
100
- ? [
101
- '# freellmapi:start',
102
- `model = ${JSON.stringify(model.id)}`,
103
- 'model_provider = "freellmapi"',
104
- `model_context_window = ${contextWindow(model)}`,
105
- `model_auto_compact_token_limit = ${compact}`,
106
- 'tool_output_token_limit = 20000',
107
- '',
108
- ...providerTable,
109
- '# freellmapi:end',
110
- '',
111
- ]
112
- : [
113
- '# freellmapi:start',
114
- ...providerTable,
115
- '',
116
- `[profiles.${/^[A-Za-z0-9_-]+$/.test(ctx.profile) ? ctx.profile : JSON.stringify(ctx.profile)}]`,
117
- `model = ${JSON.stringify(model.id)}`,
118
- 'model_provider = "freellmapi"',
119
- '# freellmapi:end',
120
- '',
121
- ];
122
- return {
123
- files: [{
124
- path: path.join(ctx.homeDir, '.codex', 'config.toml'),
125
- format: 'toml',
126
- content: content.join('\n'),
127
- }],
128
- notes: [
129
- ...clientNotes(ctx.detectedClient ?? detectChatGptClient()),
130
- 'Export FREELLMAPI_API_KEY before running codex; the key is not written to config.toml.',
131
- ...(ctx.profile === 'default'
132
- ? []
133
- : [`Activate this profile with: codex --profile ${ctx.profile}`]),
134
- `Selected ${model.id} with a ${contextWindow(model)} token context window.`,
135
- ],
136
- };
137
- }
138
-
139
- function cline(ctx: GenerateContext): Generation {
140
- const model = primaryModel(ctx.models, ctx.requestedModelId);
141
- return {
142
- files: [{
143
- path: path.join(ctx.homeDir, '.cline', 'data', 'settings', 'providers.json'),
144
- format: 'json',
145
- sensitive: true,
146
- value: {
147
- version: 1,
148
- lastUsedProvider: 'openai-compatible',
149
- providers: {
150
- 'openai-compatible': {
151
- settings: {
152
- provider: 'openai-compatible',
153
- protocol: 'openai-chat',
154
- client: 'openai-compatible',
155
- model: model.id,
156
- baseUrl: v1Url(ctx.url),
157
- apiKey: ctx.apiKey,
158
- contextWindow: contextWindow(model),
159
- capabilities: ['streaming', 'tools'],
160
- },
161
- // The field is required by Cline's persisted schema. Keeping it
162
- // deterministic makes repeated setup runs idempotent.
163
- updatedAt: '2026-07-27T00:00:00.000Z',
164
- tokenSource: 'manual',
165
- },
166
- },
167
- },
168
- }],
169
- notes: ['Cline will use the generated OpenAI Compatible provider immediately.'],
170
- };
171
- }
172
-
173
- function continueDev(ctx: GenerateContext): Generation {
174
- const model = primaryModel(ctx.models, ctx.requestedModelId);
175
- return {
176
- files: [{
177
- path: path.join(ctx.homeDir, '.continue', 'config.yaml'),
178
- format: 'yaml',
179
- content: [
180
- '# freellmapi:start',
181
- 'name: FreeLLMAPI',
182
- 'version: 1.0.0',
183
- 'schema: v1',
184
- 'models:',
185
- ' - name: FreeLLMAPI',
186
- ' provider: openai',
187
- ` model: ${yamlString(model.id)}`,
188
- ` apiBase: ${yamlString(v1Url(ctx.url))}`,
189
- ' apiKey: ${{ secrets.FREELLMAPI_API_KEY }}',
190
- ' capabilities:',
191
- ' - tool_use',
192
- ' defaultCompletionOptions:',
193
- ` contextLength: ${contextWindow(model)}`,
194
- '# freellmapi:end',
195
- '',
196
- ].join('\n'),
197
- },
198
- // `${{ secrets.NAME }}` is resolved, in order, from the process
199
- // environment, ~/.continue/.env, <cwd>/.continue/.env and <cwd>/.env
200
- // before Continue's Hub is consulted. The IDE extensions cannot see the
201
- // shell environment, so ~/.continue/.env is the one place that serves the
202
- // CLI and the extensions alike — and it keeps the raw key out of the YAML.
203
- {
204
- path: path.join(ctx.homeDir, '.continue', '.env'),
205
- format: 'env',
206
- sensitive: true,
207
- content: `FREELLMAPI_API_KEY=${ctx.apiKey}\n`,
208
- }],
209
- notes: [
210
- 'The key is in ~/.continue/.env (read by the Continue CLI and the IDE extensions); config.yaml references it as a secret.',
211
- 'One-shot check with the CLI (npm install -g @continuedev/cli): cn -p "Say hello"',
212
- ],
213
- };
214
- }
215
-
216
- function aider(ctx: GenerateContext): Generation {
217
- const model = primaryModel(ctx.models, ctx.requestedModelId);
218
- return {
219
- files: [{
220
- path: path.join(ctx.homeDir, '.aider.conf.yml'),
221
- format: 'yaml',
222
- sensitive: true,
223
- content: [
224
- '# freellmapi:start',
225
- `openai-api-base: ${yamlString(v1Url(ctx.url))}`,
226
- `openai-api-key: ${yamlString(ctx.apiKey)}`,
227
- `model: ${yamlString(`openai/${model.id}`)}`,
228
- '# freellmapi:end',
229
- '',
230
- ].join('\n'),
231
- }],
232
- notes: [
233
- `Environment-only alternative: OPENAI_API_BASE=${v1Url(ctx.url)} OPENAI_API_KEY=… aider --model openai/${model.id}`,
234
- ],
235
- };
236
- }
237
-
238
- // OpenCode resolves `provider/model` refs only against the ids a provider
239
- // declares, so the default model has to be in the `models` map — `auto`, the
240
- // usual default, is filtered out of the plain catalog roster, so it goes back
241
- // at the front. And a provider entry alone is inert: without a top-level
242
- // `model` OpenCode keeps whatever it used before (or nothing on a fresh
243
- // install), so the generated config names the default too.
244
- function opencode(ctx: GenerateContext): Generation {
245
- const model = primaryModel(ctx.models, ctx.requestedModelId);
246
- const roster = catalogModels(ctx.models);
247
- const modelEntries = Object.fromEntries(
248
- [model, ...roster.filter(entry => entry.id !== model.id)].map(entry => [entry.id, {
249
- name: entry.name ?? entry.id,
250
- limit: { context: contextWindow(entry), output: outputLimit(entry) },
251
- }]),
252
- );
253
- return {
254
- files: [{
255
- path: path.join(ctx.homeDir, '.config', 'opencode', 'opencode.json'),
256
- format: 'json',
257
- value: {
258
- $schema: 'https://opencode.ai/config.json',
259
- model: `freellmapi/${model.id}`,
260
- provider: {
261
- freellmapi: {
262
- npm: '@ai-sdk/openai-compatible',
263
- name: 'FreeLLMAPI',
264
- options: {
265
- baseURL: v1Url(ctx.url),
266
- apiKey: '{env:FREELLMAPI_API_KEY}',
267
- },
268
- models: modelEntries,
269
- },
270
- },
271
- },
272
- }],
273
- notes: [
274
- 'Export FREELLMAPI_API_KEY before starting OpenCode.',
275
- `freellmapi/${model.id} is now the default model.`,
276
- ],
277
- };
278
- }
279
-
280
- function goose(ctx: GenerateContext): Generation {
281
- const model = primaryModel(ctx.models, ctx.requestedModelId);
282
- // GOOSE_MODEL names the default, so it belongs in the provider's list too;
283
- // `auto` is filtered out of the plain roster and goes back at the front.
284
- const roster = catalogModels(ctx.models);
285
- const models = [model, ...roster.filter(entry => entry.id !== model.id)].map(entry => ({
286
- name: entry.id,
287
- context_limit: contextWindow(entry),
288
- }));
289
- return {
290
- files: [
291
- {
292
- path: path.join(
293
- ctx.homeDir,
294
- '.config',
295
- 'goose',
296
- 'custom_providers',
297
- 'freellmapi.json',
298
- ),
299
- format: 'json',
300
- value: {
301
- name: 'freellmapi',
302
- engine: 'openai',
303
- display_name: 'FreeLLMAPI',
304
- description: 'FreeLLMAPI OpenAI-compatible gateway',
305
- api_key_env: 'FREELLMAPI_API_KEY',
306
- base_url: v1Url(ctx.url),
307
- models,
308
- supports_streaming: true,
309
- requires_auth: true,
310
- dynamic_models: false,
311
- preserves_thinking: true,
312
- },
313
- },
314
- {
315
- path: path.join(ctx.homeDir, '.config', 'goose', 'config.yaml'),
316
- format: 'yaml',
317
- content: [
318
- '# freellmapi:start',
319
- 'GOOSE_PROVIDER: freellmapi',
320
- `GOOSE_MODEL: ${yamlString(model.id)}`,
321
- '# freellmapi:end',
322
- '',
323
- ].join('\n'),
324
- },
325
- ],
326
- notes: ['Export FREELLMAPI_API_KEY before starting Goose.'],
327
- };
328
- }
329
-
330
- function qwen(ctx: GenerateContext): Generation {
331
- const model = primaryModel(ctx.models, ctx.requestedModelId);
332
- const dir = path.join(ctx.homeDir, '.qwen');
333
- // Qwen Code looks the selected model up in the provider list and, finding
334
- // nothing, silently falls back to the FIRST listed model — with `auto`
335
- // filtered out of the roster that was `fusion`, a multi-model fan-out. The
336
- // default goes first so the lookup always succeeds.
337
- const roster = catalogModels(ctx.models);
338
- const models = [model, ...roster.filter(entry => entry.id !== model.id)].map(entry => ({
339
- id: entry.id,
340
- name: entry.name ?? entry.id,
341
- envKey: 'FREELLMAPI_API_KEY',
342
- baseUrl: v1Url(ctx.url),
343
- generationConfig: {
344
- contextWindowSize: contextWindow(entry),
345
- },
346
- }));
347
- return {
348
- files: [
349
- {
350
- path: path.join(dir, 'settings.json'),
351
- format: 'json',
352
- value: {
353
- model: { name: model.id },
354
- modelProviders: {
355
- openai: {
356
- protocol: 'openai',
357
- models,
358
- },
359
- },
360
- security: { auth: { selectedType: 'openai' } },
361
- },
362
- },
363
- {
364
- path: path.join(dir, '.env'),
365
- format: 'env',
366
- sensitive: true,
367
- content: `FREELLMAPI_API_KEY=${ctx.apiKey}\n`,
368
- },
369
- ],
370
- notes: [
371
- `Native Gemini mode is also available at ${rootUrl(ctx.url)}/v1beta with GEMINI_API_KEY.`,
372
- ],
373
- };
374
- }
375
-
376
- // Roo Code imports a settings file named by `roo-cline.autoImportSettingsPath`
377
- // and makes that file's `currentApiConfigName` the active profile. The VS Code
378
- // extension can use an `openai`-type profile (Roo's "OpenAI Compatible"), but
379
- // the Roo CLI only starts with a provider from its own short list and then
380
- // forces `apiProvider: openrouter` plus the --model onto whatever profile is
381
- // CURRENT — so the CLI is served by a separate import file whose current
382
- // profile is an `openrouter`-type one with the base URL overridden. The two
383
- // stores never meet: the extension reads VS Code settings, the CLI reads
384
- // ~/.vscode-mock/global-storage/global-state.json.
385
- function roo(ctx: GenerateContext): Generation {
386
- const model = primaryModel(ctx.models, ctx.requestedModelId);
387
- const importPath = path.join(ctx.homeDir, '.roo', 'freellmapi.json');
388
- const cliImportPath = path.join(ctx.homeDir, '.roo', 'freellmapi-cli.json');
389
- const cliProfile = {
390
- apiProvider: 'openrouter',
391
- openRouterBaseUrl: v1Url(ctx.url),
392
- openRouterApiKey: ctx.apiKey,
393
- openRouterModelId: model.id,
394
- };
395
- return {
396
- files: [
397
- {
398
- path: importPath,
399
- format: 'json',
400
- sensitive: true,
401
- value: {
402
- providerProfiles: {
403
- currentApiConfigName: 'freellmapi',
404
- apiConfigs: {
405
- freellmapi: {
406
- apiProvider: 'openai',
407
- openAiBaseUrl: v1Url(ctx.url),
408
- openAiApiKey: ctx.apiKey,
409
- openAiModelId: model.id,
410
- openAiStreamingEnabled: true,
411
- openAiCustomModelInfo: {
412
- contextWindow: contextWindow(model),
413
- maxTokens: outputLimit(model),
414
- supportsPromptCache: false,
415
- },
416
- },
417
- 'freellmapi-cli': cliProfile,
418
- },
419
- },
420
- globalSettings: {},
421
- },
422
- },
423
- {
424
- path: cliImportPath,
425
- format: 'json',
426
- sensitive: true,
427
- value: {
428
- providerProfiles: {
429
- currentApiConfigName: 'freellmapi-cli',
430
- apiConfigs: { 'freellmapi-cli': cliProfile },
431
- },
432
- globalSettings: {},
433
- },
434
- },
435
- // The CLI's own defaults file. `provider` is honoured (it guards against
436
- // the CLI defaulting to Roo Cloud when a Roo token exists); `model` is
437
- // shadowed in Roo CLI 0.1.x by the -m flag's built-in default, so -m is
438
- // still needed on the command line until Roo fixes that.
439
- {
440
- path: path.join(ctx.homeDir, '.roo', 'cli-settings.json'),
441
- format: 'json',
442
- value: { provider: 'openrouter', model: model.id },
443
- },
444
- ],
445
- notes: [
446
- `VS Code: add "roo-cline.autoImportSettingsPath": "${importPath}" to settings.json and reload (or Roo Settings → Import); the freellmapi profile becomes current.`,
447
- `Roo CLI: merge {"roo-cline.autoImportSettingsPath": "${cliImportPath}"} into ~/.vscode-mock/global-storage/global-state.json (create it if missing), then:`,
448
- ` export OPENROUTER_API_KEY=<unified-key> # the CLI refuses to start without it, even with the key in the profile`,
449
- ` roo -m ${model.id} "Say hello" # -m is required: the CLI's built-in default model shadows cli-settings.json`,
450
- ],
451
- };
452
- }
453
-
454
- function kilo(ctx: GenerateContext): Generation {
455
- const model = primaryModel(ctx.models, ctx.requestedModelId);
456
- // Kilo refuses to start (`Model not found: openai-compatible/auto`) unless
457
- // the selected model is in the provider's map, so the default goes first.
458
- const roster = catalogModels(ctx.models);
459
- const models = Object.fromEntries([model, ...roster.filter(entry => entry.id !== model.id)].map(entry => [
460
- entry.id,
461
- {
462
- name: entry.name ?? entry.id,
463
- tool_call: true,
464
- limit: {
465
- context: contextWindow(entry),
466
- output: outputLimit(entry),
467
- },
468
- },
469
- ]));
470
- return {
471
- files: [{
472
- path: path.join(ctx.homeDir, '.config', 'kilo', 'kilo.jsonc'),
473
- format: 'json',
474
- value: {
475
- $schema: 'https://app.kilo.ai/config.json',
476
- model: `openai-compatible/${model.id}`,
477
- provider: {
478
- 'openai-compatible': {
479
- options: {
480
- apiKey: '{env:FREELLMAPI_API_KEY}',
481
- baseURL: v1Url(ctx.url),
482
- },
483
- models,
484
- },
485
- },
486
- },
487
- }],
488
- notes: [
489
- 'Export FREELLMAPI_API_KEY before starting Kilo; global config is trusted for {env:…} expansion.',
490
- `One-shot check: kilo run "Say hello" — openai-compatible/${model.id} is the default model.`,
491
- ],
492
- };
493
- }
494
-
495
- // Crush picks its provider by the top-level `models.large` / `models.small`
496
- // selection, and with neither set it auto-detects from whatever credentials
497
- // are on the machine (an AWS profile, ANTHROPIC_API_KEY, a Charm login) — a
498
- // provider entry alone never gets used. Both slots are pointed at the chosen
499
- // model, which therefore has to be in the provider's list; `auto` is filtered
500
- // out of the plain roster, so it goes back at the front.
501
- function crush(ctx: GenerateContext): Generation {
502
- const model = primaryModel(ctx.models, ctx.requestedModelId);
503
- const roster = catalogModels(ctx.models);
504
- const models = [model, ...roster.filter(entry => entry.id !== model.id)].map(entry => ({
505
- id: entry.id,
506
- name: entry.name ?? entry.id,
507
- cost_per_1m_in: 0,
508
- cost_per_1m_out: 0,
509
- cost_per_1m_in_cached: 0,
510
- cost_per_1m_out_cached: 0,
511
- context_window: contextWindow(entry),
512
- default_max_tokens: outputLimit(entry),
513
- can_reason: false,
514
- supports_attachments: false,
515
- }));
516
- return {
517
- files: [{
518
- path: path.join(ctx.homeDir, '.config', 'crush', 'crush.json'),
519
- format: 'json',
520
- value: {
521
- $schema: 'https://charm.land/crush.json',
522
- models: {
523
- large: { provider: 'freellmapi', model: model.id },
524
- small: { provider: 'freellmapi', model: model.id },
525
- },
526
- providers: {
527
- freellmapi: {
528
- name: 'FreeLLMAPI',
529
- type: 'openai-compat',
530
- base_url: v1Url(ctx.url),
531
- api_key: '$FREELLMAPI_API_KEY',
532
- models,
533
- },
534
- },
535
- },
536
- }],
537
- notes: [
538
- 'Export FREELLMAPI_API_KEY before starting Crush.',
539
- `freellmapi/${model.id} is now the large and small model.`,
540
- ],
541
- };
542
- }
543
-
544
- // DeepSeek Harness (dsh) reads one YAML settings document, $DSH_HOME/settings.yaml
545
- // (default ~/.dsh). Every provider is a route under `llm-pi-ai.providers`;
546
- // a route pi-ai's installed catalog does not ship must spell out `api`,
547
- // `baseURL`, and a non-empty `models` list, which is exactly what a gateway
548
- // with a per-user live catalog is. The key travels through `apiKeyEnv`:
549
- // DSH loads $DSH_HOME/.env as its user environment layer, so writing the key
550
- // there (0600) makes the route work on the next request without an export.
551
- // No `compat` switches: the gateway already maps `developer` → `system` and
552
- // honours `max_completion_tokens`, the two things pi-ai sends to an endpoint
553
- // it cannot recognize.
554
- function dsh(ctx: GenerateContext): Generation {
555
- const model = primaryModel(ctx.models, ctx.requestedModelId);
556
- // DSH_HOME relocates the whole harness home; nothing else about the
557
- // layout changes, so honour it the way dsh itself does.
558
- const home = process.env.DSH_HOME?.trim() || path.join(ctx.homeDir, '.dsh');
559
- // A route id is permanent in DSH (sessions, defaults, and credential refs
560
- // name it) and must be lowercase; a named profile becomes a second route
561
- // beside the default one rather than replacing it.
562
- const route = ctx.profile === 'default'
563
- ? 'freellmapi'
564
- : `freellmapi-${ctx.profile.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')}`;
565
- const roster = catalogModels(ctx.models);
566
- const entries = [model, ...roster.filter(entry => entry.id !== model.id)]
567
- .map(entry => ({
568
- id: entry.id,
569
- name: entry.name ?? entry.id,
570
- contextWindow: contextWindow(entry),
571
- maxTokens: outputLimit(entry),
572
- }));
573
- return {
574
- files: [
575
- {
576
- path: path.join(home, 'settings.yaml'),
577
- format: 'yaml',
578
- value: {
579
- 'llm-pi-ai': {
580
- providers: {
581
- [route]: {
582
- displayName: ctx.profile === 'default' ? 'FreeLLMAPI' : `FreeLLMAPI (${ctx.profile})`,
583
- apiKeyEnv: 'FREELLMAPI_API_KEY',
584
- api: 'openai-completions',
585
- baseURL: v1Url(ctx.url),
586
- models: entries,
587
- },
588
- },
589
- },
590
- // The default model is only claimed for the default profile; a
591
- // named route is an extra option in the picker, not a takeover.
592
- // A previous default's `reasoningEffort` must go with it: DSH
593
- // refuses a request naming a level the selected model cannot
594
- // take, and a hand-declared model declares none.
595
- ...(ctx.profile === 'default'
596
- ? {
597
- 'agent-default-model': {
598
- provider: route,
599
- model: model.id,
600
- reasoningEffort: undefined,
601
- },
602
- }
603
- : {}),
604
- },
605
- },
606
- {
607
- path: path.join(home, '.env'),
608
- format: 'env',
609
- sensitive: true,
610
- content: `FREELLMAPI_API_KEY=${ctx.apiKey}\n`,
611
- },
612
- ],
613
- notes: [
614
- `Start DeepSeek Harness with: npx @deepseek-ai/dsh web — ${route}/${model.id} is ${ctx.profile === 'default' ? 'the default model' : 'in the model picker'}.`,
615
- 'One-shot check: npx @deepseek-ai/dsh --profile headless "Say hello"',
616
- 'Settings are hot-reloaded, so a running dsh picks this up on its next request.',
617
- `Models are declared text-only; give a vision model \`input: [text, image]\` under ${route}.models in settings.yaml to send it images.`,
618
- ],
619
- };
620
- }
621
-
622
- // MiMo Code is an OpenCode derivative, so the config is the same shape as the
623
- // OpenCode one above: a custom `provider` entry backed by the AI SDK's
624
- // openai-compatible package, with credentials as `options.apiKey` /
625
- // `options.baseURL` (mimo.xiaomi.com/mimocode/models-provider). Two things
626
- // differ from OpenCode and both matter:
627
- // * the file lives in MiMo's own global config directory. That is
628
- // `$XDG_CONFIG_HOME/mimocode` (`~/.config/mimocode` on macOS and Linux),
629
- // relocated wholesale to `$MIMOCODE_HOME/config` when that is set. The
630
- // directory accepts `config.json`, `mimocode.json` and `mimocode.jsonc`
631
- // and merges them in that order, so writing `config.json` — the first and
632
- // weakest layer — leaves a hand-written `mimocode.json` in charge.
633
- // * `provider.<id>.models.<id>.limit` requires BOTH `context` and `output`
634
- // in MiMo's schema, the same as OpenCode's (https://opencode.ai/config.json).
635
- // There is no MIMOCODE_API_KEY or MIMOCODE_BASE_URL: MiMo's environment
636
- // variables locate resources and toggle features, they are not a fallback for
637
- // config fields. The key travels through the config file's own `{env:VAR}`
638
- // substitution instead, which keeps it off disk.
639
- function mimo(ctx: GenerateContext): Generation {
640
- const model = primaryModel(ctx.models, ctx.requestedModelId);
641
- const configDir = process.env.MIMOCODE_HOME?.trim()
642
- ? path.join(process.env.MIMOCODE_HOME.trim(), 'config')
643
- : path.join(
644
- process.env.XDG_CONFIG_HOME?.trim() || path.join(ctx.homeDir, '.config'),
645
- 'mimocode',
646
- );
647
- // The default model is named as `freellmapi/<id>`, so it has to exist in the
648
- // provider's own `models` map — `auto`, the usual default, is filtered out
649
- // of the plain catalog roster, so put the chosen model back at the front.
650
- const roster = catalogModels(ctx.models);
651
- const modelEntries = Object.fromEntries(
652
- [model, ...roster.filter(entry => entry.id !== model.id)].map(entry => [entry.id, {
653
- name: entry.name ?? entry.id,
654
- limit: { context: contextWindow(entry), output: outputLimit(entry) },
655
- }]),
656
- );
657
- return {
658
- files: [{
659
- path: path.join(configDir, 'config.json'),
660
- format: 'json',
661
- value: {
662
- $schema: 'https://mimo.xiaomi.com/mimocode/config.json',
663
- provider: {
664
- freellmapi: {
665
- npm: '@ai-sdk/openai-compatible',
666
- name: 'FreeLLMAPI',
667
- options: {
668
- baseURL: v1Url(ctx.url),
669
- apiKey: '{env:FREELLMAPI_API_KEY}',
670
- },
671
- models: modelEntries,
672
- },
673
- },
674
- model: `freellmapi/${model.id}`,
675
- },
676
- }],
677
- notes: [
678
- 'Install MiMo Code with: curl -fsSL https://mimo.xiaomi.com/install | bash',
679
- 'Export FREELLMAPI_API_KEY before starting MiMo Code.',
680
- `Start it with \`mimo\` — freellmapi/${model.id} is the default model.`,
681
- 'One-shot check: mimo run "Say hello"',
682
- ],
683
- };
684
- }
685
-
686
- // OpenClaw reads one JSON5 document, $OPENCLAW_CONFIG_PATH (default
687
- // ~/.openclaw/openclaw.json, the state dir being relocatable through
688
- // OPENCLAW_STATE_DIR / OPENCLAW_HOME). Every model endpoint is an entry under
689
- // `models.providers`, and a provider its bundled catalog does not know must
690
- // spell out `baseUrl`, `api` and a non-empty `models` list — exactly what a
691
- // gateway with a per-user live catalog is. `api: openai-completions` is the
692
- // adapter for a /v1/chat/completions backend; OpenClaw already strips the
693
- // developer role and attribution headers for a custom origin, so no `compat`
694
- // switches are needed. The key travels as `${FREELLMAPI_API_KEY}`, OpenClaw's
695
- // own env substitution, and the value lands in $OPENCLAW_STATE_DIR/.env (0600),
696
- // the global env file OpenClaw loads on its own — so the route works with
697
- // nothing exported. The default model is `freellmapi/<id>` under
698
- // `agents.defaults.model.primary`; the patch keeps any `fallbacks` already
699
- // declared beside it.
700
- function openclawStateDir(homeDir: string): string {
701
- return process.env.OPENCLAW_STATE_DIR?.trim()
702
- || path.join(process.env.OPENCLAW_HOME?.trim() || homeDir, '.openclaw');
703
- }
704
-
705
- function openclaw(ctx: GenerateContext): Generation {
706
- const model = primaryModel(ctx.models, ctx.requestedModelId);
707
- const stateDir = openclawStateDir(ctx.homeDir);
708
- const configPath = process.env.OPENCLAW_CONFIG_PATH?.trim()
709
- || path.join(stateDir, 'openclaw.json');
710
- // A provider id is referenced by every model ref (`<provider>/<model>`) and
711
- // by session state, so it is permanent; a named profile becomes a second
712
- // provider beside the default one rather than replacing it.
713
- const provider = ctx.profile === 'default'
714
- ? 'freellmapi'
715
- : `freellmapi-${ctx.profile.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')}`;
716
- const roster = catalogModels(ctx.models);
717
- const entries = [model, ...roster.filter(entry => entry.id !== model.id)]
718
- .map(entry => ({
719
- id: entry.id,
720
- name: entry.name ?? entry.id,
721
- reasoning: false,
722
- input: ['text'],
723
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
724
- contextWindow: contextWindow(entry),
725
- maxTokens: outputLimit(entry),
726
- }));
727
- return {
728
- files: [
729
- {
730
- path: configPath,
731
- format: 'json',
732
- value: {
733
- ...(ctx.profile === 'default'
734
- ? { agents: { defaults: { model: { primary: `${provider}/${model.id}` } } } }
735
- : {}),
736
- models: {
737
- providers: {
738
- [provider]: {
739
- baseUrl: v1Url(ctx.url),
740
- apiKey: '${FREELLMAPI_API_KEY}',
741
- api: 'openai-completions',
742
- // OpenClaw attaches its own `openclaw/<version>` identity only
743
- // to endpoints it recognises; a custom origin gets the bare
744
- // openai-node SDK user agent, which the gateway's analytics
745
- // would file under "openai-sdk". A static provider header
746
- // (verified to reach chat requests) names the client instead.
747
- headers: { 'User-Agent': 'openclaw' },
748
- models: entries,
749
- },
750
- },
751
- },
752
- },
753
- },
754
- {
755
- path: path.join(stateDir, '.env'),
756
- format: 'env',
757
- sensitive: true,
758
- content: `FREELLMAPI_API_KEY=${ctx.apiKey}\n`,
759
- },
760
- ],
761
- notes: [
762
- 'Install OpenClaw with: npm install -g openclaw@latest --allow-scripts=openclaw',
763
- `Try it without the gateway daemon: openclaw agent exec --model ${provider}/${model.id} "Say hello"`,
764
- ctx.profile === 'default'
765
- ? `${provider}/${model.id} is the default model; a running \`openclaw gateway\` needs a restart to pick the change up.`
766
- : `${provider}/${model.id} is in the model picker; the default model is unchanged.`,
767
- `Models are declared text-only; give a vision model \`input: ["text", "image"]\` under models.providers.${provider} to send it images.`,
768
- ],
769
- };
770
- }
771
-
772
- // Hermes Agent (Nous Research) reads one YAML document, $HERMES_HOME/config.yaml
773
- // (default ~/.hermes), and treats it as the single source of truth for the
774
- // endpoint: OPENAI_BASE_URL is deliberately ignored for anything but
775
- // api.openai.com, and OPENAI_API_KEY is only sent to OpenAI hosts. So the
776
- // gateway goes into the `model` block as `provider: custom` with `base_url`,
777
- // and the key travels as `api_key: "${FREELLMAPI_API_KEY}"` — Hermes's own
778
- // substitution — with the value in $HERMES_HOME/.env (0600), the file Hermes
779
- // loads on its own, so nothing needs exporting. A fresh install ships
780
- // `model: ""` (a "not configured" sentinel); replacing it with the mapping is
781
- // exactly what `hermes setup` would do, and it is what lets a headless first
782
- // run skip the wizard. A named profile becomes an entry in the `providers`
783
- // dict instead — picked with `/model custom:<name>:<model>` — leaving the
784
- // default model alone.
785
- function hermes(ctx: GenerateContext): Generation {
786
- const model = primaryModel(ctx.models, ctx.requestedModelId);
787
- const home = process.env.HERMES_HOME?.trim() || path.join(ctx.homeDir, '.hermes');
788
- const provider = `freellmapi-${ctx.profile.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')}`;
789
- // Hermes only identifies itself to hosts it knows; a custom endpoint gets the
790
- // bare openai-python user agent. `default_headers` is its documented way to
791
- // override that, and it is what lets the gateway's analytics name the client.
792
- const headers = { 'User-Agent': 'hermes-agent' };
793
- const value: Record<string, unknown> = ctx.profile === 'default'
794
- ? {
795
- model: {
796
- provider: 'custom',
797
- default: model.id,
798
- base_url: v1Url(ctx.url),
799
- api_key: '${FREELLMAPI_API_KEY}',
800
- api_mode: 'chat_completions',
801
- context_length: contextWindow(model),
802
- default_headers: headers,
803
- // The wizard strips these when it writes api_key; a leftover would
804
- // point the key lookup at a variable this route never sets.
805
- key_env: undefined,
806
- api_key_env: undefined,
807
- },
808
- }
809
- : {
810
- providers: {
811
- [provider]: {
812
- name: `FreeLLMAPI (${ctx.profile})`,
813
- api: v1Url(ctx.url),
814
- api_key: '${FREELLMAPI_API_KEY}',
815
- transport: 'chat_completions',
816
- default_model: model.id,
817
- context_length: contextWindow(model),
818
- extra_headers: headers,
819
- },
820
- },
821
- };
822
- return {
823
- files: [
824
- { path: path.join(home, 'config.yaml'), format: 'yaml', value },
825
- {
826
- path: path.join(home, '.env'),
827
- format: 'env',
828
- sensitive: true,
829
- content: `FREELLMAPI_API_KEY=${ctx.apiKey}\n`,
830
- },
831
- ],
832
- notes: [
833
- 'Install Hermes Agent with: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash -s -- --skip-setup',
834
- ctx.profile === 'default'
835
- ? `Try it with: hermes -z "Say hello" — custom/${model.id} is the default model.`
836
- : `Pick it inside a chat with: /model custom:${provider}:${model.id} — the default model is unchanged.`,
837
- 'A running `hermes gateway` (Telegram, Discord, …) needs a restart to pick the change up.',
838
- ],
839
- };
840
- }
841
-
842
- // Pi (pi.dev, @earendil-works/pi-coding-agent) keeps user configuration in its
843
- // agent directory, $PI_CODING_AGENT_DIR (default ~/.pi/agent). An endpoint Pi
844
- // does not ship is a provider entry in models.json — `baseUrl`, `api` and the
845
- // `models` it serves — and `api: openai-completions` is the adapter for a
846
- // /v1/chat/completions backend. Pi does not load a .env file of its own, so the
847
- // key is written literally (the file is created 0600); its `$NAME` form would
848
- // need the variable exported in every shell that starts Pi. A provider entry
849
- // alone only adds models to `/model`: the startup choice is `defaultProvider`
850
- // plus `defaultModel` in settings.json, which a named profile leaves alone.
851
- function piAgentDir(homeDir: string): string {
852
- return process.env.PI_CODING_AGENT_DIR?.trim() || path.join(homeDir, '.pi', 'agent');
853
- }
854
-
855
- function pi(ctx: GenerateContext): Generation {
856
- const model = primaryModel(ctx.models, ctx.requestedModelId);
857
- const dir = piAgentDir(ctx.homeDir);
858
- const provider = ctx.profile === 'default'
859
- ? 'freellmapi'
860
- : `freellmapi-${ctx.profile.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')}`;
861
- const roster = catalogModels(ctx.models);
862
- const entries = [model, ...roster.filter(entry => entry.id !== model.id)]
863
- .map(entry => ({
864
- id: entry.id,
865
- name: entry.name ?? entry.id,
866
- // The gateway picks the upstream per request, so no model can promise a
867
- // thinking API; Pi then sends no reasoning effort at all.
868
- reasoning: false,
869
- input: ['text'],
870
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
871
- contextWindow: contextWindow(entry),
872
- maxTokens: outputLimit(entry),
873
- }));
874
- const files: Generation['files'] = [{
875
- path: path.join(dir, 'models.json'),
876
- format: 'json',
877
- sensitive: true,
878
- value: {
879
- providers: {
880
- [provider]: {
881
- name: ctx.profile === 'default' ? 'FreeLLMAPI' : `FreeLLMAPI (${ctx.profile})`,
882
- baseUrl: v1Url(ctx.url),
883
- api: 'openai-completions',
884
- apiKey: ctx.apiKey,
885
- // Pi names itself only to a few hosts it knows; a custom endpoint gets
886
- // the bare openai-node SDK user agent, which the gateway's analytics
887
- // would file under "openai-sdk". This is the UA Pi already sends to
888
- // Cloudflare, so analytics can name the client.
889
- headers: { 'User-Agent': 'pi-coding-agent' },
890
- models: entries,
891
- },
892
- },
893
- },
894
- }];
895
- if (ctx.profile === 'default') {
896
- files.push({
897
- path: path.join(dir, 'settings.json'),
898
- format: 'json',
899
- value: { defaultProvider: provider, defaultModel: model.id },
900
- });
901
- }
902
- return {
903
- files,
904
- notes: [
905
- 'Install Pi with: npm install -g @earendil-works/pi-coding-agent (or curl -fsSL https://pi.dev/install.sh | sh)',
906
- ctx.profile === 'default'
907
- ? `Try it with: pi -p "Say hello" — ${provider}/${model.id} is the default model.`
908
- : `Try it with: pi --model ${provider}/${model.id} -p "Say hello" — the default model is unchanged.`,
909
- 'Every catalog model is in /model; a running Pi session picks the change up when /model is opened.',
910
- `Models are declared text-only; give a vision model \`input: ["text", "image"]\` under providers.${provider} in models.json to send it images.`,
911
- ],
912
- };
913
- }
914
-
915
- // Reasonix (reasonix.io, esengine/DeepSeek-Reasonix) reads one global TOML
916
- // document, <Reasonix home>/config.toml — ~/.reasonix, %APPDATA%\reasonix on
917
- // Windows, or $REASONIX_HOME when set. Every endpoint is a `[[providers]]`
918
- // entry; `kind = "openai"` posts to `<base_url>/chat/completions`, and a
919
- // `models` list exposes the whole catalog under one connection. The entry only
920
- // names its key variable (`api_key_env`); Reasonix keeps the value in the .env
921
- // beside config.toml (0600) and reads it on its own, so nothing needs
922
- // exporting. `default_model` is `provider/model`. Reasonix already sends
923
- // `User-Agent: Reasonix/<version>` to every endpoint, so no header is needed.
924
- function reasonixHome(homeDir: string): string {
925
- if (process.env.REASONIX_HOME?.trim()) return process.env.REASONIX_HOME.trim();
926
- if (process.platform === 'win32') {
927
- return path.join(process.env.APPDATA?.trim() || path.join(homeDir, 'AppData', 'Roaming'), 'reasonix');
928
- }
929
- return path.join(homeDir, '.reasonix');
930
- }
931
-
932
- function reasonix(ctx: GenerateContext): Generation {
933
- const model = primaryModel(ctx.models, ctx.requestedModelId);
934
- const home = reasonixHome(ctx.homeDir);
935
- // A provider name is what every `provider/model` ref and saved session points
936
- // at, so a named profile becomes a second entry rather than replacing it.
937
- const provider = ctx.profile === 'default'
938
- ? 'freellmapi'
939
- : `freellmapi-${ctx.profile.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')}`;
940
- const roster = catalogModels(ctx.models);
941
- const models = [model, ...roster.filter(entry => entry.id !== model.id)].map(entry => entry.id);
942
- return {
943
- files: [
944
- {
945
- path: path.join(home, 'config.toml'),
946
- format: 'toml',
947
- content: [
948
- ...(ctx.profile === 'default' ? [`default_model = ${JSON.stringify(`${provider}/${model.id}`)}`, ''] : []),
949
- '[[providers]]',
950
- `name = ${JSON.stringify(provider)}`,
951
- `display_name = ${JSON.stringify(ctx.profile === 'default' ? 'FreeLLMAPI' : `FreeLLMAPI (${ctx.profile})`)}`,
952
- 'kind = "openai"',
953
- `base_url = ${JSON.stringify(v1Url(ctx.url))}`,
954
- `models = [${models.map(id => JSON.stringify(id)).join(', ')}]`,
955
- `default = ${JSON.stringify(model.id)}`,
956
- 'api_key_env = "FREELLMAPI_API_KEY"',
957
- `context_window = ${contextWindow(model)}`,
958
- // Without a price Reasonix bills unknown models at a guessed rate;
959
- // the gateway's models are free.
960
- 'price = { cache_hit = 0, input = 0, output = 0, currency = "$" }',
961
- ].join('\n'),
962
- },
963
- {
964
- path: path.join(home, '.env'),
965
- format: 'env',
966
- sensitive: true,
967
- content: `FREELLMAPI_API_KEY=${ctx.apiKey}\n`,
968
- },
969
- ],
970
- notes: [
971
- 'Install Reasonix with: npm install -g reasonix (or brew install esengine/reasonix/reasonix)',
972
- ctx.profile === 'default'
973
- ? `Try it with: reasonix -p "Say hello" — ${provider}/${model.id} is the default model.`
974
- : `Try it with: reasonix --model ${provider}/${model.id} -p "Say hello" — the default model is unchanged.`,
975
- `Every catalog model is in /model as ${provider}/<id>; other [[providers]] entries in config.toml are kept.`,
976
- `Reasonix Studio lists only the providers in [desktop].provider_access when that list is set; add "${provider}" there, or under Settings → Model → Access.`,
977
- ],
978
- };
979
- }
980
-
981
- // ZCode (zcode.z.ai, Z.ai's coding agent). The Desktop app and the CLI share
982
- // one provider registry, ~/.zcode/v2/provider_config.json (underscore), which
983
- // ZCODE_PERSONAL_PROVIDER_CONFIG_FILE can relocate. A custom provider is an
984
- // entry in config.providerConfigRules.providerRules with an `api-key` access
985
- // block and an `openai-chat-completions` endpoint; each model gets a "smart"
986
- // rule in modelConfigRules.providerModelRules that pins only its context and
987
- // output limits. Those are arrays, so the merge replaces only the entries this
988
- // provider owns and keeps every other provider and rule. ZCode has no
989
- // environment-variable lookup for a custom provider's key, so the key lives in
990
- // the file, which the writer keeps at 0600. Live checked against the ZCode
991
- // runtime 0.16.9 (zcode-app-cli 3.15.3): ~/.zcode/v2/config.json and
992
- // ~/.zcode/cli/config.json are legacy files it reads once, for migration.
993
- function zcodeProviderFile(homeDir: string): string {
994
- const override = process.env.ZCODE_PERSONAL_PROVIDER_CONFIG_FILE?.trim();
995
- if (override && path.isAbsolute(override)) return override;
996
- return path.join(homeDir, '.zcode', 'v2', 'provider_config.json');
997
- }
998
-
999
- function zcode(ctx: GenerateContext): Generation {
1000
- const model = primaryModel(ctx.models, ctx.requestedModelId);
1001
- // Like every other generator, a named profile is a second provider entry so
1002
- // both routes coexist in ZCode's model picker.
1003
- const provider = ctx.profile === 'default'
1004
- ? 'freellmapi'
1005
- : `freellmapi-${ctx.profile.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')}`;
1006
- const ids = [model, ...catalogModels(ctx.models).filter(entry => entry.id !== model.id)];
1007
- return {
1008
- files: [{
1009
- path: zcodeProviderFile(ctx.homeDir),
1010
- format: 'json',
1011
- sensitive: true,
1012
- arrays: {
1013
- 'config.providerConfigRules.providerRules': { ownedBy: { providerId: provider } },
1014
- 'config.modelConfigRules.providerModelRules': { ownedBy: { providerId: provider } },
1015
- 'config.modelConfigRules.manualProviderModelRules': { ownedBy: { providerId: provider } },
1016
- 'config.providerOrder': { union: true },
1017
- },
1018
- value: {
1019
- schemaVersion: 1,
1020
- config: {
1021
- providerConfigRules: {
1022
- providerRules: [{
1023
- providerId: provider,
1024
- templateId: null,
1025
- providerName: ctx.profile === 'default' ? 'FreeLLMAPI' : `FreeLLMAPI (${ctx.profile})`,
1026
- enabled: true,
1027
- config: {
1028
- group: 'standard-personal',
1029
- access: { type: 'api-key', apiKey: ctx.apiKey },
1030
- api: { type: 'openai-chat-completions', baseUrl: v1Url(ctx.url) },
1031
- personalModelIds: ids.map(entry => entry.id),
1032
- modelOrder: ids.map(entry => entry.id),
1033
- visibility: 'visible',
1034
- },
1035
- }],
1036
- },
1037
- modelConfigRules: {
1038
- providerModelRules: ids.map(entry => ({
1039
- providerId: provider,
1040
- modelId: entry.id,
1041
- config: {
1042
- enabled: true,
1043
- properties: { contextWindow: contextWindow(entry) },
1044
- optionSpecs: {
1045
- maxOutputTokens: { max: outputLimit(entry), map: '{"max_tokens": maxOutputTokens}' },
1046
- },
1047
- },
1048
- })),
1049
- // Present but empty: ZCode expects both rule arrays, and the merge
1050
- // drops any manual rule this provider had so a model never sits in both.
1051
- manualProviderModelRules: [],
1052
- },
1053
- providerOrder: [provider],
1054
- defaultModelSelection: { providerId: provider, modelId: model.id },
1055
- },
1056
- },
1057
- }],
1058
- notes: [
1059
- 'Install ZCode from https://zcode.z.ai (or the community terminal client: npm i -g zcode-app-cli).',
1060
- 'Quit ZCode Desktop before running this so it does not save its in-memory registry over the file.',
1061
- `${provider}/${model.id} is now the default model; pick another under ${provider} in the model picker (or /model in the CLI). Other providers are kept.`,
1062
- 'The API key lives in the provider file (written 0600): ZCode has no env lookup for custom providers.',
1063
- ],
1064
- };
1065
- }
1066
-
1067
- function cursor(_ctx: GenerateContext): Generation {
1068
- return {
1069
- files: [],
1070
- notes: [
1071
- 'Cursor sends model traffic through its cloud service, so localhost is not reachable from Cursor.',
1072
- `Expose the gateway through a trusted HTTPS tunnel, then open Cursor Settings → Models, enable Override OpenAI Base URL, and enter <public-url>/v1.`,
1073
- 'Cursor only documents custom keys for standard chat models; custom base-URL overrides may not support Responses-based or built-in models.',
1074
- 'The override affects Cursor globally while enabled, so disable it before switching back to built-in providers.',
1075
- 'Use a separately revocable URL token if the client cannot set an Authorization header.',
1076
- ],
1077
- };
1078
- }
1079
-
1080
- function atomcode(ctx: GenerateContext): Generation {
1081
- const model = primaryModel(ctx.models, ctx.requestedModelId);
1082
- const configDir = path.join(ctx.homeDir, '.atomcode');
1083
- // AtomCode picks its provider by name: a root `default_provider` key names
1084
- // one `[providers.<id>]` table, and `type = "openai"` is what makes that
1085
- // table speak the OpenAI-compatible wire. Root key first, table second, so
1086
- // mergeToml can slot the key above any tables already in the file.
1087
- return {
1088
- files: [{
1089
- path: path.join(configDir, 'config.toml'),
1090
- format: 'toml',
1091
- sensitive: true,
1092
- content: [
1093
- 'default_provider = "freellmapi"',
1094
- '',
1095
- '[providers.freellmapi]',
1096
- 'type = "openai"',
1097
- `base_url = ${JSON.stringify(v1Url(ctx.url))}`,
1098
- `api_key = ${JSON.stringify(ctx.apiKey)}`,
1099
- `model = ${JSON.stringify(model.id)}`,
1100
- `context_window = ${contextWindow(model)}`,
1101
- ].join('\n'),
1102
- }],
1103
- notes: [
1104
- 'AtomCode reads ~/.atomcode/config.toml; other [providers.*] tables in it are kept.',
1105
- `default_provider now points at [providers.freellmapi] with ${model.id} as its model.`,
1106
- 'Point base_url at the unified /v1 endpoint; api_key is the unified key shown on the Agents page.',
1107
- 'One-shot check: atomcode -p "Say hello" (telemetry is on by default: atomcode telemetry disable).',
1108
- ],
1109
- };
1110
- }
1111
-
1112
- function generic(ctx: GenerateContext): Generation {
1113
- const model = primaryModel(ctx.models, ctx.requestedModelId);
1114
- return {
1115
- files: [],
1116
- notes: [
1117
- `OPENAI_BASE_URL=${v1Url(ctx.url)}`,
1118
- `OPENAI_API_KEY=${ctx.apiKey || '<unified-key>'}`,
1119
- `OPENAI_MODEL=${model.id}`,
1120
- `curl ${v1Url(ctx.url)}/chat/completions -H "Authorization: Bearer $OPENAI_API_KEY" -H "Content-Type: application/json" -d '{"model":"${model.id}","messages":[{"role":"user","content":"Hello"}]}'`,
1121
- ],
1122
- };
1123
- }
1124
-
1125
- const metadata = [
1126
- ['claude', 'Claude Code', 'code', 'file', 'Anthropic Messages', 'root', 'setup-claude', 'https://docs.anthropic.com/en/docs/claude-code', claude],
1127
- ['codex', 'Codex CLI', 'code', 'file', 'OpenAI Responses', '/v1', 'setup-codex', 'https://developers.openai.com/codex', codex],
1128
- ['cline', 'Cline', 'code', 'file', 'OpenAI Chat', '/v1', 'setup-cline', 'https://docs.cline.bot', cline],
1129
- ['continue', 'Continue', 'code', 'file', 'OpenAI Chat', '/v1', 'setup-continue', 'https://docs.continue.dev', continueDev],
1130
- ['aider', 'Aider', 'code', 'file', 'OpenAI Chat', '/v1', 'setup-aider', 'https://aider.chat/docs', aider],
1131
- ['opencode', 'OpenCode', 'code', 'file', 'OpenAI Chat', '/v1', 'setup-opencode', 'https://opencode.ai/docs', opencode],
1132
- ['goose', 'Goose', 'agent', 'file', 'OpenAI Chat', '/v1', 'setup-goose', 'https://block.github.io/goose', goose],
1133
- ['qwen', 'Qwen Code', 'code', 'file', 'OpenAI or Gemini', '/v1', 'setup-qwen', 'https://qwenlm.github.io/qwen-code-docs', qwen],
1134
- ['roo', 'Roo Code', 'code', 'file', 'OpenAI Chat', '/v1', 'setup-roo', 'https://docs.roocode.com', roo],
1135
- ['kilo', 'Kilo Code', 'code', 'file', 'OpenAI Chat', '/v1', 'setup-kilo', 'https://kilocode.ai/docs', kilo],
1136
- ['crush', 'Crush', 'code', 'file', 'OpenAI Chat', '/v1', 'setup-crush', 'https://github.com/charmbracelet/crush', crush],
1137
- ['dsh', 'DeepSeek Harness', 'agent', 'file', 'OpenAI Chat', '/v1', 'setup-dsh', 'https://github.com/deepseek-ai/deepseek-harness', dsh],
1138
- ['mimo', 'MiMo Code', 'code', 'file', 'OpenAI Chat', '/v1', 'setup-mimo', 'https://mimo.xiaomi.com/mimocode', mimo],
1139
- ['atomcode', 'AtomCode', 'code', 'file', 'OpenAI Chat', '/v1', 'setup-atomcode', 'https://atomcode.atomgit.com/docs/en/', atomcode],
1140
- ['openclaw', 'OpenClaw', 'agent', 'file', 'OpenAI Chat', '/v1', 'setup-openclaw', 'https://docs.openclaw.ai/gateway/config-tools/custom-providers', openclaw],
1141
- ['hermes', 'Hermes Agent', 'agent', 'file', 'OpenAI Chat', '/v1', 'setup-hermes', 'https://hermes-agent.nousresearch.com/docs/', hermes],
1142
- ['pi', 'Pi', 'code', 'file', 'OpenAI Chat', '/v1', 'setup-pi', 'https://pi.dev/docs/latest/models', pi],
1143
- ['reasonix', 'Reasonix', 'code', 'file', 'OpenAI Chat', '/v1', 'setup-reasonix', 'https://github.com/esengine/DeepSeek-Reasonix/blob/studio/docs/CLI.md#configure-providers', reasonix],
1144
- ['zcode', 'ZCode', 'code', 'file', 'OpenAI Chat', '/v1', 'setup-zcode', 'https://zcode.z.ai/en/docs/configuration', zcode],
1145
- ['cursor', 'Cursor', 'code', 'guide', 'OpenAI Chat', '/v1', 'setup-cursor', 'https://docs.cursor.com', cursor],
1146
- ['generic', 'Generic OpenAI client', 'agent', 'guide', 'OpenAI Chat', '/v1', 'setup-generic', 'https://github.com/tashfeenahmed/freellmapi', generic],
1147
- ] as const;
1148
-
1149
- export const tools: ToolDefinition[] = metadata.map(([
1150
- id,
1151
- name,
1152
- category,
1153
- configType,
1154
- protocol,
1155
- baseUrlSupport,
1156
- command,
1157
- docsUrl,
1158
- generate,
1159
- ]) => ({
1160
- id,
1161
- name,
1162
- category,
1163
- configType,
1164
- protocol,
1165
- baseUrlSupport,
1166
- command,
1167
- docsUrl,
1168
- generate,
1169
- }));
1170
-
1171
- export function getTool(id: string): ToolDefinition | undefined {
1172
- return tools.find(tool => tool.id === id);
1173
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/src/types.ts DELETED
@@ -1,59 +0,0 @@
1
- import type { DetectedClient } from './detect.js';
2
-
3
- export interface CatalogModel {
4
- id: string;
5
- name?: string;
6
- context_window?: number | null;
7
- context_length?: number | null;
8
- available?: boolean;
9
- }
10
-
11
- export interface GeneratedFile {
12
- path: string;
13
- format: 'json' | 'toml' | 'yaml' | 'env';
14
- /** Structured patch, deep-merged into the existing document (json, yaml). */
15
- value?: Record<string, unknown>;
16
- /** Literal text, merged as a marked `# freellmapi:start/end` block (toml, yaml, env). */
17
- content?: string;
18
- sensitive?: boolean;
19
- /** json only: arrays merged item by item instead of replaced whole, keyed by
20
- * the array's dotted path. `ownedBy` drops the existing items whose fields
21
- * all match it, then appends the patch's items; `union` keeps the existing
22
- * values and appends the patch's missing ones. */
23
- arrays?: Record<string, JsonArrayMerge>;
24
- }
25
-
26
- export type JsonArrayMerge = { ownedBy: Record<string, string> } | { union: true };
27
-
28
- export interface GenerateContext {
29
- url: string;
30
- apiKey: string;
31
- profile: string;
32
- models: CatalogModel[];
33
- homeDir: string;
34
- /** An explicit `--model`. Overrides each generator's default-model
35
- * heuristic; validated against the unfiltered catalog by the caller. */
36
- requestedModelId?: string;
37
- /** Result of `detectChatGptClient()`. Injected by the CLI entry point;
38
- * when the property is absent generators probe the real machine, which
39
- * golden-output tests must avoid (the snapshot must not depend on the
40
- * host's installed clients). */
41
- detectedClient?: DetectedClient;
42
- }
43
-
44
- export interface Generation {
45
- files: GeneratedFile[];
46
- notes: string[];
47
- }
48
-
49
- export interface ToolDefinition {
50
- id: string;
51
- name: string;
52
- category: 'code' | 'agent';
53
- configType: 'env' | 'file' | 'guide';
54
- protocol: string;
55
- baseUrlSupport: 'root' | '/v1';
56
- command: string;
57
- docsUrl: string;
58
- generate(ctx: GenerateContext): Generation;
59
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/tools.json DELETED
@@ -1,23 +0,0 @@
1
- [
2
- {"id":"claude","name":"Claude Code","category":"code","configType":"file","protocol":"Anthropic Messages","baseUrlSupport":"root","command":"setup-claude","docsUrl":"https://docs.anthropic.com/en/docs/claude-code"},
3
- {"id":"codex","name":"Codex CLI","category":"code","configType":"file","protocol":"OpenAI Responses","baseUrlSupport":"/v1","command":"setup-codex","docsUrl":"https://developers.openai.com/codex"},
4
- {"id":"cline","name":"Cline","category":"code","configType":"file","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-cline","docsUrl":"https://docs.cline.bot"},
5
- {"id":"continue","name":"Continue","category":"code","configType":"file","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-continue","docsUrl":"https://docs.continue.dev"},
6
- {"id":"aider","name":"Aider","category":"code","configType":"file","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-aider","docsUrl":"https://aider.chat/docs"},
7
- {"id":"opencode","name":"OpenCode","category":"code","configType":"file","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-opencode","docsUrl":"https://opencode.ai/docs"},
8
- {"id":"goose","name":"Goose","category":"agent","configType":"file","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-goose","docsUrl":"https://block.github.io/goose"},
9
- {"id":"qwen","name":"Qwen Code","category":"code","configType":"file","protocol":"OpenAI or Gemini","baseUrlSupport":"/v1","command":"setup-qwen","docsUrl":"https://qwenlm.github.io/qwen-code-docs"},
10
- {"id":"roo","name":"Roo Code","category":"code","configType":"file","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-roo","docsUrl":"https://docs.roocode.com"},
11
- {"id":"kilo","name":"Kilo Code","category":"code","configType":"file","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-kilo","docsUrl":"https://kilocode.ai/docs"},
12
- {"id":"crush","name":"Crush","category":"code","configType":"file","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-crush","docsUrl":"https://github.com/charmbracelet/crush"},
13
- {"id":"dsh","name":"DeepSeek Harness","category":"agent","configType":"file","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-dsh","docsUrl":"https://github.com/deepseek-ai/deepseek-harness"},
14
- {"id":"mimo","name":"MiMo Code","category":"code","configType":"file","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-mimo","docsUrl":"https://mimo.xiaomi.com/mimocode"},
15
- {"id":"atomcode","name":"AtomCode","category":"code","configType":"file","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-atomcode","docsUrl":"https://atomcode.atomgit.com/docs/en/"},
16
- {"id":"openclaw","name":"OpenClaw","category":"agent","configType":"file","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-openclaw","docsUrl":"https://docs.openclaw.ai/gateway/config-tools/custom-providers"},
17
- {"id":"hermes","name":"Hermes Agent","category":"agent","configType":"file","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-hermes","docsUrl":"https://hermes-agent.nousresearch.com/docs/"},
18
- {"id":"pi","name":"Pi","category":"code","configType":"file","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-pi","docsUrl":"https://pi.dev/docs/latest/models"},
19
- {"id":"reasonix","name":"Reasonix","category":"code","configType":"file","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-reasonix","docsUrl":"https://github.com/esengine/DeepSeek-Reasonix/blob/studio/docs/CLI.md#configure-providers"},
20
- {"id":"zcode","name":"ZCode","category":"code","configType":"file","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-zcode","docsUrl":"https://zcode.z.ai/en/docs/configuration"},
21
- {"id":"cursor","name":"Cursor","category":"code","configType":"guide","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-cursor","docsUrl":"https://docs.cursor.com"},
22
- {"id":"generic","name":"Generic OpenAI client","category":"agent","configType":"guide","protocol":"OpenAI Chat","baseUrlSupport":"/v1","command":"setup-generic","docsUrl":"https://github.com/tashfeenahmed/freellmapi"}
23
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cli/tsconfig.json DELETED
@@ -1,17 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2022",
4
- "module": "NodeNext",
5
- "moduleResolution": "NodeNext",
6
- "outDir": "dist",
7
- "rootDir": "src",
8
- "strict": true,
9
- "esModuleInterop": true,
10
- "skipLibCheck": true,
11
- "resolveJsonModule": true,
12
- "declaration": true,
13
- "types": ["node"]
14
- },
15
- "include": ["src/**/*.ts"],
16
- "exclude": ["src/**/*.test.ts", "src/**/__snapshots__/**"]
17
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/.gitignore DELETED
@@ -1,24 +0,0 @@
1
- # Logs
2
- logs
3
- *.log
4
- npm-debug.log*
5
- yarn-debug.log*
6
- yarn-error.log*
7
- pnpm-debug.log*
8
- lerna-debug.log*
9
-
10
- node_modules
11
- dist
12
- dist-ssr
13
- *.local
14
-
15
- # Editor directories and files
16
- .vscode/*
17
- !.vscode/extensions.json
18
- .idea
19
- .DS_Store
20
- *.suo
21
- *.ntvs*
22
- *.njsproj
23
- *.sln
24
- *.sw?
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/README.md DELETED
@@ -1,73 +0,0 @@
1
- # React + TypeScript + Vite
2
-
3
- This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
4
-
5
- Currently, two official plugins are available:
6
-
7
- - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
8
- - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
9
-
10
- ## React Compiler
11
-
12
- The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
13
-
14
- ## Expanding the ESLint configuration
15
-
16
- If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
17
-
18
- ```js
19
- export default defineConfig([
20
- globalIgnores(['dist']),
21
- {
22
- files: ['**/*.{ts,tsx}'],
23
- extends: [
24
- // Other configs...
25
-
26
- // Remove tseslint.configs.recommended and replace with this
27
- tseslint.configs.recommendedTypeChecked,
28
- // Alternatively, use this for stricter rules
29
- tseslint.configs.strictTypeChecked,
30
- // Optionally, add this for stylistic rules
31
- tseslint.configs.stylisticTypeChecked,
32
-
33
- // Other configs...
34
- ],
35
- languageOptions: {
36
- parserOptions: {
37
- project: ['./tsconfig.node.json', './tsconfig.app.json'],
38
- tsconfigRootDir: import.meta.dirname,
39
- },
40
- // other options...
41
- },
42
- },
43
- ])
44
- ```
45
-
46
- You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
47
-
48
- ```js
49
- // eslint.config.js
50
- import reactX from 'eslint-plugin-react-x'
51
- import reactDom from 'eslint-plugin-react-dom'
52
-
53
- export default defineConfig([
54
- globalIgnores(['dist']),
55
- {
56
- files: ['**/*.{ts,tsx}'],
57
- extends: [
58
- // Other configs...
59
- // Enable lint rules for React
60
- reactX.configs['recommended-typescript'],
61
- // Enable lint rules for React DOM
62
- reactDom.configs.recommended,
63
- ],
64
- languageOptions: {
65
- parserOptions: {
66
- project: ['./tsconfig.node.json', './tsconfig.app.json'],
67
- tsconfigRootDir: import.meta.dirname,
68
- },
69
- // other options...
70
- },
71
- },
72
- ])
73
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/components.json DELETED
@@ -1,25 +0,0 @@
1
- {
2
- "$schema": "https://ui.shadcn.com/schema.json",
3
- "style": "base-nova",
4
- "rsc": false,
5
- "tsx": true,
6
- "tailwind": {
7
- "config": "",
8
- "css": "src/index.css",
9
- "baseColor": "neutral",
10
- "cssVariables": true,
11
- "prefix": ""
12
- },
13
- "iconLibrary": "lucide",
14
- "rtl": false,
15
- "aliases": {
16
- "components": "@/components",
17
- "utils": "@/lib/utils",
18
- "ui": "@/components/ui",
19
- "lib": "@/lib",
20
- "hooks": "@/hooks"
21
- },
22
- "menuColor": "default",
23
- "menuAccent": "subtle",
24
- "registries": {}
25
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/dev/mockApi.ts DELETED
@@ -1,152 +0,0 @@
1
- import type { Plugin } from 'vite'
2
-
3
- // Dev-only in-memory mock of the /api surface the Fallback page needs, so the
4
- // frontend can be exercised without a running backend. Enabled only when the
5
- // dev server is started with MOCK_API=1 (see vite.config.ts) — never bundled.
6
-
7
- const PRESETS: Record<string, { reliability: number; speed: number; intelligence: number }> = {
8
- balanced: { reliability: 0.5, speed: 0.25, intelligence: 0.25 },
9
- smartest: { reliability: 0.35, speed: 0.1, intelligence: 0.55 },
10
- fastest: { reliability: 0.35, speed: 0.55, intelligence: 0.1 },
11
- reliable: { reliability: 0.7, speed: 0.15, intelligence: 0.15 },
12
- }
13
-
14
- interface MockModel {
15
- modelDbId: number
16
- platform: string
17
- modelId: string
18
- displayName: string
19
- sizeLabel: string
20
- intelligenceRank: number
21
- speedRank: number
22
- monthlyTokenBudget: string
23
- supportsVision: boolean
24
- rpmLimit: number | null
25
- rpdLimit: number | null
26
- enabled: boolean
27
- priority: number
28
- reliability: number
29
- speed: number
30
- intelligence: number
31
- headroom: number
32
- rateLimit: number
33
- totalRequests: number
34
- }
35
-
36
- let strategy = 'balanced'
37
- // User-tuned vector for the 'custom' strategy (kept normalized, like the server).
38
- let customWeights = { ...PRESETS.balanced }
39
-
40
- function activeWeights() {
41
- if (strategy === 'custom') return customWeights
42
- return PRESETS[strategy] ?? PRESETS.balanced
43
- }
44
-
45
- const models: MockModel[] = [
46
- { modelDbId: 1, platform: 'google', modelId: 'gemini-2.5-pro', displayName: 'Gemini 2.5 Pro', sizeLabel: 'Frontier', intelligenceRank: 1, speedRank: 8, monthlyTokenBudget: '~12M', supportsVision: true, rpmLimit: 5, rpdLimit: 100, enabled: true, priority: 1, reliability: 0.94, speed: 0.55, intelligence: 1.0, headroom: 1, rateLimit: 1, totalRequests: 412 },
47
- { modelDbId: 2, platform: 'groq', modelId: 'openai/gpt-oss-120b', displayName: 'GPT-OSS 120B', sizeLabel: 'Frontier', intelligenceRank: 6, speedRank: 2, monthlyTokenBudget: '~6M', supportsVision: false, rpmLimit: 30, rpdLimit: 1000, enabled: true, priority: 2, reliability: 0.9, speed: 0.98, intelligence: 0.72, headroom: 1, rateLimit: 0.7, totalRequests: 833 },
48
- { modelDbId: 3, platform: 'cerebras', modelId: 'llama-3.3-70b', displayName: 'Llama 3.3 70B', sizeLabel: 'Large', intelligenceRank: 4, speedRank: 1, monthlyTokenBudget: '~50M', supportsVision: false, rpmLimit: 30, rpdLimit: 14400, enabled: true, priority: 3, reliability: 0.88, speed: 1.0, intelligence: 0.5, headroom: 1, rateLimit: 1, totalRequests: 256 },
49
- { modelDbId: 4, platform: 'google', modelId: 'gemini-2.5-flash', displayName: 'Gemini 2.5 Flash', sizeLabel: 'Large', intelligenceRank: 4, speedRank: 5, monthlyTokenBudget: '~3M', supportsVision: true, rpmLimit: 10, rpdLimit: 20, enabled: true, priority: 4, reliability: 0.97, speed: 0.78, intelligence: 0.52, headroom: 0.45, rateLimit: 1, totalRequests: 90 },
50
- { modelDbId: 5, platform: 'nvidia', modelId: 'llama-4-scout', displayName: 'Llama 4 Scout', sizeLabel: 'Medium', intelligenceRank: 7, speedRank: 4, monthlyTokenBudget: '~30M', supportsVision: true, rpmLimit: 40, rpdLimit: null, enabled: true, priority: 5, reliability: 0.7, speed: 0.83, intelligence: 0.33, headroom: 1, rateLimit: 1, totalRequests: 47 },
51
- { modelDbId: 6, platform: 'openrouter', modelId: 'deepseek/deepseek-v3.1:free', displayName: 'DeepSeek V3.1', sizeLabel: 'Frontier', intelligenceRank: 2, speedRank: 10, monthlyTokenBudget: '~6M', supportsVision: false, rpmLimit: 20, rpdLimit: 200, enabled: false, priority: 6, reliability: 0.5, speed: 0.4, intelligence: 0.67, headroom: 1, rateLimit: 1, totalRequests: 0 },
52
- { modelDbId: 7, platform: 'mistral', modelId: 'mistral-large', displayName: 'Mistral Large', sizeLabel: 'Large', intelligenceRank: 5, speedRank: 6, monthlyTokenBudget: '~15M', supportsVision: false, rpmLimit: 60, rpdLimit: 500, enabled: true, priority: 7, reliability: 0.82, speed: 0.6, intelligence: 0.45, headroom: 1, rateLimit: 1, totalRequests: 178 },
53
- ]
54
-
55
- function budgetTokens(label: string): number {
56
- const m = label.match(/~?([\d.]+)(?:-([\d.]+))?([MK])?/)
57
- if (!m) return 0
58
- const n = parseFloat(m[2] ?? m[1])
59
- const unit = m[3] === 'M' ? 1_000_000 : m[3] === 'K' ? 1_000 : 1
60
- return n * unit
61
- }
62
-
63
- function score(m: MockModel): number {
64
- const w = activeWeights()
65
- const base = w.reliability * m.reliability + w.speed * m.speed + w.intelligence * m.intelligence
66
- return base * m.headroom * m.rateLimit
67
- }
68
-
69
- function readBody(req: any): Promise<any> {
70
- return new Promise(resolve => {
71
- let data = ''
72
- req.on('data', (c: any) => { data += c })
73
- req.on('end', () => { try { resolve(JSON.parse(data || '{}')) } catch { resolve({}) } })
74
- })
75
- }
76
-
77
- export function mockApiPlugin(): Plugin {
78
- return {
79
- name: 'freellmapi-dev-mock',
80
- configureServer(server) {
81
- server.middlewares.use(async (req: any, res: any, next: any) => {
82
- const url = (req.url || '').split('?')[0]
83
- if (!url.startsWith('/api/')) return next()
84
- const send = (obj: any, status = 200) => {
85
- res.statusCode = status
86
- res.setHeader('Content-Type', 'application/json')
87
- res.end(JSON.stringify(obj))
88
- }
89
-
90
- // Auth gate — always "logged in" in mock mode.
91
- if (url === '/api/auth/status') return send({ needsSetup: false, authenticated: true, email: 'dev@local' })
92
- if (url === '/api/ping') return send({ status: 'ok', timestamp: new Date().toISOString() })
93
-
94
- if (url === '/api/fallback' && req.method === 'GET') {
95
- const rows = [...models].sort((a, b) => a.priority - b.priority).map(m => ({
96
- modelDbId: m.modelDbId, priority: m.priority, effectivePriority: m.priority,
97
- penalty: m.rateLimit < 1 ? Math.round((1 - m.rateLimit) * 10) : 0,
98
- rateLimitHits: m.rateLimit < 1 ? 3 : 0,
99
- enabled: m.enabled, platform: m.platform, modelId: m.modelId, displayName: m.displayName,
100
- intelligenceRank: m.intelligenceRank, speedRank: m.speedRank, sizeLabel: m.sizeLabel,
101
- rpmLimit: m.rpmLimit, rpdLimit: m.rpdLimit, monthlyTokenBudget: m.monthlyTokenBudget,
102
- supportsVision: m.supportsVision, keyCount: 3,
103
- }))
104
- return send(rows)
105
- }
106
-
107
- if (url === '/api/fallback' && req.method === 'PUT') {
108
- const body = await readBody(req)
109
- for (const e of body as any[]) {
110
- const m = models.find(x => x.modelDbId === e.modelDbId)
111
- if (m) { m.priority = e.priority; m.enabled = e.enabled }
112
- }
113
- return send({ success: true })
114
- }
115
-
116
- if (url === '/api/fallback/routing' && req.method === 'GET') {
117
- const scores = [...models]
118
- .map(m => ({
119
- modelDbId: m.modelDbId, platform: m.platform, modelId: m.modelId, displayName: m.displayName,
120
- enabled: m.enabled, reliability: m.reliability, speed: m.speed, intelligence: m.intelligence,
121
- headroom: m.headroom, rateLimit: m.rateLimit, score: score(m), totalRequests: m.totalRequests,
122
- }))
123
- .sort((a, b) => b.score - a.score)
124
- return send({ strategy, weights: strategy === 'priority' ? null : activeWeights(), customWeights, scores })
125
- }
126
-
127
- if (url === '/api/fallback/routing' && req.method === 'PUT') {
128
- const body = await readBody(req)
129
- if (typeof body.strategy === 'string') strategy = body.strategy
130
- if (body.weights && typeof body.weights === 'object') {
131
- const { reliability = 0, speed = 0, intelligence = 0 } = body.weights
132
- const sum = reliability + speed + intelligence
133
- if (sum > 0) {
134
- customWeights = { reliability: reliability / sum, speed: speed / sum, intelligence: intelligence / sum }
135
- }
136
- }
137
- return send({ strategy, presets: PRESETS, customWeights })
138
- }
139
-
140
- if (url === '/api/fallback/token-usage') {
141
- const withKeys = models
142
- const modelBudgets = withKeys.map(m => ({ displayName: m.displayName, platform: m.platform, budget: budgetTokens(m.monthlyTokenBudget) }))
143
- const totalBudget = modelBudgets.reduce((s, m) => s + m.budget, 0)
144
- return send({ totalBudget, totalUsed: Math.round(totalBudget * 0.18), models: modelBudgets })
145
- }
146
-
147
- // Anything else under /api → empty 200 so pages don't hard-crash.
148
- return send({})
149
- })
150
- },
151
- }
152
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/eslint.config.js DELETED
@@ -1,23 +0,0 @@
1
- import js from '@eslint/js'
2
- import globals from 'globals'
3
- import reactHooks from 'eslint-plugin-react-hooks'
4
- import reactRefresh from 'eslint-plugin-react-refresh'
5
- import tseslint from 'typescript-eslint'
6
- import { defineConfig, globalIgnores } from 'eslint/config'
7
-
8
- export default defineConfig([
9
- globalIgnores(['dist']),
10
- {
11
- files: ['**/*.{ts,tsx}'],
12
- extends: [
13
- js.configs.recommended,
14
- tseslint.configs.recommended,
15
- reactHooks.configs.flat.recommended,
16
- reactRefresh.configs.vite,
17
- ],
18
- languageOptions: {
19
- ecmaVersion: 2020,
20
- globals: globals.browser,
21
- },
22
- },
23
- ])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/index.html DELETED
@@ -1,36 +0,0 @@
1
- <!doctype html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8" />
5
- <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
6
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
- <script>
8
- try {
9
- // Mirrors the ThemeProvider's resolution: 'system' (or nothing stored)
10
- // follows the OS preference. Keep in sync with src/theme.tsx.
11
- const theme = localStorage.getItem('theme')
12
- const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
13
- const dark = theme === 'dark' || (theme !== 'light' && prefersDark)
14
- if (dark) {
15
- document.documentElement.classList.add('dark')
16
- }
17
- document.documentElement.style.colorScheme = dark ? 'dark' : 'light'
18
- document.documentElement.dataset.themeChoice =
19
- theme === 'dark' || theme === 'light' ? theme : 'system'
20
- // Same idea for text direction; keep in sync with RTL_LOCALES in
21
- // src/i18n/locale-config.ts.
22
- const locale = localStorage.getItem('freellmapi.locale')
23
- if (locale && ['ar', 'he', 'fa', 'ur'].includes(locale)) {
24
- document.documentElement.dir = 'rtl'
25
- }
26
- } catch {
27
- // Keep the initial render working if localStorage is unavailable.
28
- }
29
- </script>
30
- <title>FreeLLMAPI · Unified LLM Router</title>
31
- </head>
32
- <body>
33
- <div id="root"></div>
34
- <script type="module" src="/src/main.tsx"></script>
35
- </body>
36
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/package.json DELETED
@@ -1,59 +0,0 @@
1
- {
2
- "name": "@freellmapi/client",
3
- "private": true,
4
- "version": "0.0.0",
5
- "type": "module",
6
- "scripts": {
7
- "dev": "vite",
8
- "build": "tsc -b && vite build",
9
- "lint": "eslint .",
10
- "test": "vitest run && npm run check:i18n",
11
- "check:i18n": "node scripts/check-i18n.mjs",
12
- "preview": "vite preview"
13
- },
14
- "dependencies": {
15
- "@base-ui/react": "^1.3.0",
16
- "@dnd-kit/core": "^6.3.1",
17
- "@dnd-kit/sortable": "^10.0.0",
18
- "@dnd-kit/utilities": "^3.2.2",
19
- "@fontsource-variable/geist": "^5.2.8",
20
- "@fontsource-variable/geist-mono": "^5.2.7",
21
- "@tailwindcss/vite": "^4.2.2",
22
- "@tanstack/react-query": "^5.97.0",
23
- "class-variance-authority": "^0.7.1",
24
- "clsx": "^2.1.1",
25
- "highlight.js": "^11.12.0",
26
- "liquid-gooey": "^0.2.1",
27
- "lucide-react": "^1.8.0",
28
- "react": "^19.2.4",
29
- "react-dom": "^19.2.4",
30
- "react-markdown": "^10.1.0",
31
- "react-router-dom": "^7.14.0",
32
- "recharts": "^3.8.1",
33
- "remark-gfm": "^4.0.1",
34
- "shadcn": "^4.2.0",
35
- "simple-icons": "^16.31.0",
36
- "tailwind-merge": "^3.5.0",
37
- "tailwindcss": "^4.2.2",
38
- "tw-animate-css": "^1.4.0"
39
- },
40
- "devDependencies": {
41
- "@eslint/js": "^9.39.4",
42
- "@types/node": "^24.12.2",
43
- "@types/react": "^19.2.14",
44
- "@types/react-dom": "^19.2.3",
45
- "@vitejs/plugin-react": "^6.0.1",
46
- "eslint": "^9.39.4",
47
- "eslint-plugin-react-hooks": "^7.0.1",
48
- "eslint-plugin-react-refresh": "^0.5.2",
49
- "globals": "^17.4.0",
50
- "typescript": "~6.0.2",
51
- "typescript-eslint": "^8.58.0",
52
- "vite": "^8.0.4",
53
- "vitest": "^3.1.3"
54
- },
55
- "engines": {
56
- "node": ">=20.18.0 <25.0.0",
57
- "npm": ">=10.0.0"
58
- }
59
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/public/favicon.svg DELETED
client/public/icons.svg DELETED
client/scripts/check-i18n.mjs DELETED
@@ -1,88 +0,0 @@
1
- import { readdir, readFile } from 'node:fs/promises'
2
- import path from 'node:path'
3
- import { fileURLToPath } from 'node:url'
4
-
5
- const localeDirectory = path.resolve(
6
- path.dirname(fileURLToPath(import.meta.url)),
7
- '../src/i18n/locales',
8
- )
9
- const expectedLocales = [
10
- 'en', 'zh-CN', 'es', 'fr', 'pt-BR', 'it', 'hi', 'ar', 'bn', 'ru',
11
- 'ur', 'id', 'de', 'ja', 'sw', 'mr', 'te', 'tr', 'ta', 'vi',
12
- 'ko', 'fa', 'th', 'gu', 'pl', 'uk', 'kn', 'ml', 'or', 'my',
13
- 'pa', 'ro', 'nl', 'ms', 'tl', 'ha', 'yo', 'ig', 'am', 'uz',
14
- 'az', 'si', 'ne', 'km', 'el', 'cs', 'hu', 'sv', 'he', 'da',
15
- 'fi', 'no', 'sk', 'bg', 'hr', 'sr', 'lt', 'zh-TW', 'pt-PT', 'ka',
16
- ]
17
-
18
- function flatten(value, prefix = '', output = new Map()) {
19
- if (value && typeof value === 'object' && !Array.isArray(value)) {
20
- for (const [key, child] of Object.entries(value)) {
21
- flatten(child, prefix ? `${prefix}.${key}` : key, output)
22
- }
23
- } else {
24
- output.set(prefix, value)
25
- }
26
- return output
27
- }
28
-
29
- function placeholders(value) {
30
- if (typeof value !== 'string') return []
31
- return [...value.matchAll(/\{(\w+)\}/g)].map(match => match[1]).sort()
32
- }
33
-
34
- const fileNames = (await readdir(localeDirectory))
35
- .filter(fileName => fileName.endsWith('.json'))
36
- .sort()
37
- const actualLocales = fileNames.map(fileName => fileName.slice(0, -5))
38
- const missingFiles = expectedLocales.filter(locale => !actualLocales.includes(locale))
39
- const unexpectedFiles = actualLocales.filter(locale => !expectedLocales.includes(locale))
40
- const errors = []
41
-
42
- if (missingFiles.length) errors.push(`Missing locale files: ${missingFiles.join(', ')}`)
43
- if (unexpectedFiles.length) errors.push(`Unexpected locale files: ${unexpectedFiles.join(', ')}`)
44
-
45
- const english = JSON.parse(await readFile(path.join(localeDirectory, 'en.json'), 'utf8'))
46
- const englishEntries = flatten(english)
47
- const englishKeys = new Set(englishEntries.keys())
48
-
49
- for (const locale of actualLocales) {
50
- const dictionary = JSON.parse(
51
- await readFile(path.join(localeDirectory, `${locale}.json`), 'utf8'),
52
- )
53
- const entries = flatten(dictionary)
54
- const keys = new Set(entries.keys())
55
- const missingKeys = [...englishKeys].filter(key => !keys.has(key))
56
- const extraKeys = [...keys].filter(key => !englishKeys.has(key))
57
-
58
- if (missingKeys.length) {
59
- errors.push(`${locale}: missing keys: ${missingKeys.join(', ')}`)
60
- }
61
- if (extraKeys.length) {
62
- errors.push(`${locale}: extra keys: ${extraKeys.join(', ')}`)
63
- }
64
-
65
- for (const [key, englishValue] of englishEntries) {
66
- if (!entries.has(key)) continue
67
- const localizedValue = entries.get(key)
68
- if (typeof localizedValue !== typeof englishValue) {
69
- errors.push(`${locale}:${key}: expected ${typeof englishValue}, got ${typeof localizedValue}`)
70
- continue
71
- }
72
- const expectedPlaceholders = placeholders(englishValue)
73
- const actualPlaceholders = placeholders(localizedValue)
74
- if (expectedPlaceholders.join(',') !== actualPlaceholders.join(',')) {
75
- errors.push(
76
- `${locale}:${key}: placeholders {${actualPlaceholders.join(', ')}} do not match {${expectedPlaceholders.join(', ')}}`,
77
- )
78
- }
79
- }
80
- }
81
-
82
- if (errors.length) {
83
- console.error(`i18n validation failed with ${errors.length} error(s):`)
84
- for (const error of errors) console.error(`- ${error}`)
85
- process.exitCode = 1
86
- } else {
87
- console.log(`i18n validation passed for ${actualLocales.length} locales and ${englishKeys.size} keys`)
88
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/src/App.test.ts DELETED
@@ -1,38 +0,0 @@
1
- import { readFileSync } from 'node:fs'
2
- import path from 'node:path'
3
- import { fileURLToPath } from 'node:url'
4
- import { describe, expect, it } from 'vitest'
5
-
6
- // The Playground only scrolls inside its transcript pane if every ancestor
7
- // between <body> and that pane carries a definite height. One unconditional
8
- // `min-h-screen` on the shell breaks it: min-height is a floor, not a ceiling,
9
- // so the shell grows with the chat and the document scrolls instead. The
10
- // contract lives in a couple of class strings in App.tsx
11
- // and regresses silently, so it is pinned here like the chain manager pins
12
- // its routing.
13
- const here = path.dirname(fileURLToPath(import.meta.url))
14
- const app = readFileSync(path.join(here, 'App.tsx'), 'utf8')
15
- const playground = readFileSync(path.join(here, 'pages/PlaygroundPage.tsx'), 'utf8')
16
-
17
- describe('app shell heights', () => {
18
- it('pins full-bleed routes to the viewport, padded routes to the document', () => {
19
- // h-dvh gives the shell a definite height so the flex chain below can
20
- // constrain the transcript; overflow-hidden stops the document itself
21
- // from scrolling. Padded routes keep plain min-height and scroll as a
22
- // document — clipping them under h-dvh would leave long pages with no
23
- // scrollbar at all.
24
- expect(app).toMatch(/fullBleed \? 'h-dvh overflow-hidden' : 'min-h-screen'/)
25
- })
26
-
27
- it('passes a definite height down the flex chain to the page', () => {
28
- // Dropping min-h-0/flex-1 anywhere between the shell and the page lets
29
- // the content size its ancestors again, which is the original bug by
30
- // another route.
31
- expect(app).toContain("'flex min-h-0 flex-1 flex-col'")
32
- expect(playground).toContain('flex min-h-0 flex-1 overflow-hidden')
33
- })
34
-
35
- it('keeps /playground in the full-bleed set', () => {
36
- expect(app).toMatch(/FULL_BLEED_ROUTES = new Set\(\[[^\]]*'\/playground'[^\]]*\]\)/)
37
- })
38
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/src/App.tsx DELETED
@@ -1,522 +0,0 @@
1
- import { useEffect, useState, type ReactNode } from 'react'
2
- import { BrowserRouter, Routes, Route, Navigate, NavLink, Link, useLocation, useNavigate } from 'react-router-dom'
3
- import { MutationCache, QueryClient, QueryClientProvider } from '@tanstack/react-query'
4
- import { ChevronDown, KeyRound, LogOut, Menu, MoreHorizontal, RefreshCw, Search, Settings, Sparkles } from 'lucide-react'
5
- import { buttonVariants } from '@/components/ui/button'
6
- import {
7
- DropdownMenu,
8
- DropdownMenuContent,
9
- DropdownMenuGroup,
10
- DropdownMenuItem,
11
- DropdownMenuSeparator,
12
- DropdownMenuSub,
13
- DropdownMenuSubContent,
14
- DropdownMenuSubTrigger,
15
- DropdownMenuTrigger,
16
- } from '@/components/ui/dropdown-menu'
17
- import { AuthGate, ChangeCredentialsModal } from '@/components/auth-gate'
18
- import { CommandPalette } from '@/components/command-palette'
19
- import { openCommandPalette } from '@/components/command-palette-state'
20
- import { ErrorBoundary } from '@/components/error-boundary'
21
- import { SettingsDialog } from '@/components/settings-dialog'
22
- import { UpdatesDialog } from '@/components/updates-dialog'
23
- import { OPEN_UPDATES_EVENT } from '@/lib/updates'
24
- import { Toaster } from '@/components/toaster'
25
- import { UpdateReminder } from '@/components/update-reminder'
26
- import { NewBuildPrompt } from '@/components/new-build-prompt'
27
- import { usePremium } from '@/hooks/use-premium'
28
- import { I18nProvider, useI18n } from '@/i18n'
29
- import { logout } from '@/lib/api'
30
- import { toast } from '@/lib/toast'
31
- import { ThemeProvider } from '@/theme'
32
- import KeysPage from '@/pages/KeysPage'
33
- import PlaygroundPage from '@/pages/PlaygroundPage'
34
- import FallbackPage from '@/pages/FallbackPage'
35
- import ModelDetailPage from '@/pages/ModelDetailPage'
36
- import FusionPage from '@/pages/FusionPage'
37
- import EmbeddingsPage from '@/pages/EmbeddingsPage'
38
- import ImagePage from '@/pages/ImagePage'
39
- import VideoPage from '@/pages/VideoPage'
40
- import AudioPage from '@/pages/AudioPage'
41
- import SearchPage from '@/pages/SearchPage'
42
- import DecisionPage from '@/pages/DecisionPage'
43
- import MediaDetailPage from '@/pages/MediaDetailPage'
44
- import EmbeddingDetailPage from '@/pages/EmbeddingDetailPage'
45
- import AnalyticsPage from '@/pages/AnalyticsPage'
46
- import LogsPage from '@/pages/LogsPage'
47
- import PremiumPage from '@/pages/PremiumPage'
48
- import NotFoundPage from '@/pages/NotFoundPage'
49
- import AgentsPage from '@/pages/AgentsPage'
50
-
51
- // Every failed mutation surfaces as an error toast, so no action fails
52
- // silently. A page that already shows the failure inline can opt out with
53
- // `meta: { silenceToast: true }` on the mutation.
54
- const queryClient = new QueryClient({
55
- // staleTime dedupes the mount storm (#1047) and keeps page-to-page
56
- // navigation off the network: the Models page alone mounts ~13 queries,
57
- // several of them the same endpoint from different components, and
58
- // staleTime 0 refetched every one of them on every navigation and window
59
- // focus. Cached data renders immediately either way; this only decides
60
- // whether a background refetch follows. Thirty seconds is shorter than any
61
- // poller here (refetchInterval still fires on its own clock), and mutations
62
- // invalidate explicitly, so nothing user-visible goes stale.
63
- defaultOptions: { queries: { staleTime: 30_000 } },
64
- mutationCache: new MutationCache({
65
- onError: (error, _variables, _context, mutation) => {
66
- if (mutation.meta?.silenceToast) return
67
- toast.error(error instanceof Error ? error.message : String(error))
68
- },
69
- }),
70
- })
71
-
72
- const navItems = [
73
- { to: '/models', labelKey: 'nav.models' },
74
- { to: '/playground', labelKey: 'nav.playground' },
75
- { to: '/keys', labelKey: 'nav.keys' },
76
- { to: '/agents', labelKey: 'nav.agents' },
77
- { to: '/analytics', labelKey: 'nav.analytics' },
78
- { to: '/premium', labelKey: 'nav.premium' },
79
- ]
80
-
81
- // The modality pages behind "Models"; surfaced in the nav dropdown and
82
- // the mobile submenu so Fusion/Embeddings/Image/Audio are discoverable without
83
- // first landing on the chat table.
84
- const modelItems = [
85
- { to: '/models/chat', labelKey: 'models.chatModelsTab' },
86
- { to: '/models/image', labelKey: 'models.imageTab' },
87
- { to: '/models/video', labelKey: 'models.videoTab' },
88
- { to: '/models/audio', labelKey: 'models.audioTab' },
89
- { to: '/models/embeddings', labelKey: 'models.embeddingsTab' },
90
- { to: '/models/decision', labelKey: 'decision.tab' },
91
- { to: '/models/search', labelKey: 'search.tab' },
92
- { to: '/models/fusion', labelKey: 'models.fusionTab' },
93
- ]
94
-
95
- // The pages that hang off "Analytics". Logs is reachable only from here — it is
96
- // deliberately kept out of navItems so the top bar does not grow a seventh entry.
97
- const analyticsItems = [
98
- { to: '/analytics', labelKey: 'nav.analytics' },
99
- { to: '/logs', labelKey: 'nav.logs' },
100
- ]
101
-
102
- // Nav entries rendered as a split control: the label still navigates, and a
103
- // chevron (desktop) / submenu (mobile) reveals the pages behind it. Keyed by the
104
- // nav entry's `to` so both branches below stay one lookup, not two hardcoded
105
- // special cases.
106
- const navMenus: Record<
107
- string,
108
- { ariaKey: string; items: { to: string; labelKey: string }[]; isActive: (pathname: string) => boolean }
109
- > = {
110
- '/models': {
111
- ariaKey: 'nav.modelsMenu',
112
- items: modelItems,
113
- isActive: (pathname) => pathname.startsWith('/models'),
114
- },
115
- '/analytics': {
116
- ariaKey: 'nav.analyticsMenu',
117
- items: analyticsItems,
118
- isActive: (pathname) => pathname.startsWith('/analytics') || pathname.startsWith('/logs'),
119
- },
120
- }
121
-
122
- const isMac = typeof navigator !== 'undefined' && /mac/i.test(navigator.platform)
123
-
124
- function NavItem({ to, children }: { to: string; children: React.ReactNode }) {
125
- return (
126
- <NavLink
127
- to={to}
128
- className={({ isActive }) =>
129
- `relative text-sm px-1 py-4 transition-colors ${
130
- isActive
131
- ? 'text-foreground after:absolute after:inset-x-0 after:-bottom-px after:h-px after:bg-foreground'
132
- : 'text-muted-foreground hover:text-foreground'
133
- }`
134
- }
135
- >
136
- {children}
137
- </NavLink>
138
- )
139
- }
140
-
141
- function Brand() {
142
- return (
143
- <Link to="/" className="flex items-center gap-2 transition-opacity hover:opacity-70">
144
- <span className="inline-block size-2 rounded-full bg-foreground" />
145
- <span className="font-semibold tracking-tight text-sm">FreeLLMAPI</span>
146
- </Link>
147
- )
148
- }
149
-
150
- // True when the dashboard runs inside the desktop shell (Electron preload
151
- // sets this). The navbar then doubles as the window title bar: draggable,
152
- // padded for the macOS traffic lights, and without the web-only Sign out.
153
- const isDesktopApp = typeof window !== 'undefined'
154
- && (window as Window & { __FREEAPI_DESKTOP__?: boolean }).__FREEAPI_DESKTOP__ === true
155
-
156
- const desktopPlatform = typeof window !== 'undefined'
157
- ? (window as Window & { __FREEAPI_PLATFORM__?: string }).__FREEAPI_PLATFORM__
158
- : undefined
159
-
160
- const isMacDesktop = isDesktopApp && (
161
- desktopPlatform ? desktopPlatform === 'darwin' : (typeof navigator !== 'undefined' && /Macintosh|Mac OS X/.test(navigator.userAgent))
162
- )
163
-
164
- // The preload's own early classList.add can be lost (it may run before this
165
- // document exists), so the client claims the class itself at module load —
166
- // before the first React paint — keeping html.desktop CSS (transparent body,
167
- // glass backdrop on macOS) reliable.
168
- if (isDesktopApp) {
169
- document.documentElement.classList.add('desktop')
170
- if (isMacDesktop) {
171
- document.documentElement.classList.add('desktop-mac')
172
- }
173
- }
174
-
175
- function AccountMenuItems({
176
- showUpgrade,
177
- upgradeLabel,
178
- settingsLabel,
179
- updatesLabel,
180
- signOutLabel,
181
- changeEmailLabel,
182
- changePasswordLabel,
183
- onUpgrade,
184
- onOpenSettings,
185
- onOpenUpdates,
186
- onChangeEmail,
187
- onChangePassword,
188
- }: {
189
- showUpgrade: boolean
190
- upgradeLabel: string
191
- settingsLabel: string
192
- updatesLabel: string
193
- signOutLabel: string
194
- changeEmailLabel: string
195
- changePasswordLabel: string
196
- onUpgrade: () => void
197
- onOpenSettings: () => void
198
- onOpenUpdates: () => void
199
- onChangeEmail: () => void
200
- onChangePassword: () => void
201
- }) {
202
- return (
203
- <>
204
- {showUpgrade && (
205
- <DropdownMenuItem onClick={onUpgrade}>
206
- <Sparkles />
207
- {upgradeLabel}
208
- </DropdownMenuItem>
209
- )}
210
- <DropdownMenuItem onClick={onOpenSettings}>
211
- <Settings />
212
- {settingsLabel}
213
- </DropdownMenuItem>
214
- <DropdownMenuItem onClick={onOpenUpdates}>
215
- <RefreshCw />
216
- {updatesLabel}
217
- </DropdownMenuItem>
218
- {/* Desktop signs in with a hidden local account, so it has no credentials
219
- to change and no session to end. */}
220
- {!isDesktopApp && (
221
- <>
222
- <DropdownMenuSeparator />
223
- <DropdownMenuItem onClick={onChangeEmail}>
224
- <span className="flex size-4 items-center justify-center font-serif text-xs font-bold">@</span>
225
- {changeEmailLabel}
226
- </DropdownMenuItem>
227
- <DropdownMenuItem onClick={onChangePassword}>
228
- <KeyRound />
229
- {changePasswordLabel}
230
- </DropdownMenuItem>
231
- <DropdownMenuItem onClick={() => logout()}>
232
- <LogOut />
233
- {signOutLabel}
234
- </DropdownMenuItem>
235
- </>
236
- )}
237
- </>
238
- )
239
- }
240
-
241
- function Navbar() {
242
- const { t } = useI18n()
243
- const location = useLocation()
244
- const navigate = useNavigate()
245
- const [settingsOpen, setSettingsOpen] = useState(false)
246
- const [updatesOpen, setUpdatesOpen] = useState(false)
247
- // The update pill lives outside the navbar; it asks for this dialog by event.
248
- useEffect(() => {
249
- const open = () => setUpdatesOpen(true)
250
- window.addEventListener(OPEN_UPDATES_EVENT, open)
251
- return () => window.removeEventListener(OPEN_UPDATES_EVENT, open)
252
- }, [])
253
- const [credentialsMode, setCredentialsMode] = useState<'password' | 'email' | null>(null)
254
- const { data: premium, licensed, isLoading: premiumLoading, isError: premiumError } = usePremium()
255
- const showUpgrade = Boolean(premium) && !licensed && !premiumLoading && !premiumError
256
-
257
- return (
258
- <>
259
- <header
260
- // In macOS desktop shell the window carries vibrancy blur, so a lighter wash (45%)
261
- // lets it read as glass. Everywhere else (Windows/Linux/browser), use solid wash (80%)
262
- // so text and contrast stay sharp and readable.
263
- className={`sticky top-0 z-40 border-b backdrop-blur ${isMacDesktop ? 'bg-background/45' : 'bg-background/80'}`}
264
- style={isDesktopApp ? ({ WebkitAppRegion: 'drag' } as React.CSSProperties) : undefined}
265
- >
266
- <div
267
- // Physical pl: reserves macOS traffic lights only on macOS. On Windows and Linux,
268
- // standard window controls sit on the top-right, so no left padding is needed.
269
- className={`mx-auto flex max-w-6xl items-center px-4 sm:px-6 ${isMacDesktop ? 'pl-20 sm:pl-20' : ''}`}
270
- style={isMacDesktop ? { minHeight: 52 } : undefined}
271
- >
272
- <Brand />
273
- <nav
274
- className="ms-10 hidden items-center gap-6 md:flex"
275
- style={isDesktopApp ? ({ WebkitAppRegion: 'no-drag' } as React.CSSProperties) : undefined}
276
- >
277
- {navItems.map((item) => {
278
- const menu = navMenus[item.to]
279
- return menu ? (
280
- // Split control: the label navigates, the chevron reveals the
281
- // pages hiding behind it.
282
- <div key={item.to} className="flex items-center gap-0.5">
283
- <NavItem to={item.to}>{t(item.labelKey)}</NavItem>
284
- <DropdownMenu>
285
- <DropdownMenuTrigger
286
- aria-label={t(menu.ariaKey)}
287
- className="rounded-md p-1 text-muted-foreground transition-colors hover:text-foreground"
288
- >
289
- <ChevronDown className="size-3.5" />
290
- </DropdownMenuTrigger>
291
- <DropdownMenuContent align="start" className="w-44">
292
- {menu.items.map((entry) => (
293
- <DropdownMenuItem key={entry.to} onClick={() => navigate(entry.to)}>
294
- {t(entry.labelKey)}
295
- </DropdownMenuItem>
296
- ))}
297
- </DropdownMenuContent>
298
- </DropdownMenu>
299
- </div>
300
- ) : (
301
- <NavItem key={item.to} to={item.to}>
302
- {t(item.labelKey)}
303
- </NavItem>
304
- )
305
- })}
306
- </nav>
307
- <div
308
- className="ms-auto hidden items-center gap-1 md:flex"
309
- style={isDesktopApp ? ({ WebkitAppRegion: 'no-drag' } as React.CSSProperties) : undefined}
310
- >
311
- <button
312
- type="button"
313
- onClick={openCommandPalette}
314
- aria-label={t('palette.title')}
315
- className={buttonVariants({ variant: 'ghost', size: 'sm' })}
316
- >
317
- <Search className="size-3.5" />
318
- <kbd className="text-[10px] text-muted-foreground">{isMac ? '⌘K' : 'Ctrl K'}</kbd>
319
- </button>
320
- <DropdownMenu>
321
- <DropdownMenuTrigger
322
- className={buttonVariants({ variant: 'ghost', size: 'icon' })}
323
- aria-label={t('nav.openMenu')}
324
- >
325
- <MoreHorizontal />
326
- </DropdownMenuTrigger>
327
- <DropdownMenuContent align="end" className="w-48">
328
- <AccountMenuItems
329
- showUpgrade={showUpgrade}
330
- upgradeLabel={t('nav.upgrade')}
331
- settingsLabel={t('nav.settings')}
332
- updatesLabel={t('settings.checkForUpdates')}
333
- signOutLabel={t('nav.signOut')}
334
- changeEmailLabel={t('auth.changeEmail')}
335
- changePasswordLabel={t('auth.changePassword')}
336
- onUpgrade={() => navigate('/premium')}
337
- onOpenSettings={() => setSettingsOpen(true)}
338
- onOpenUpdates={() => setUpdatesOpen(true)}
339
- onChangeEmail={() => setCredentialsMode('email')}
340
- onChangePassword={() => setCredentialsMode('password')}
341
- />
342
- </DropdownMenuContent>
343
- </DropdownMenu>
344
- </div>
345
- <div className="ms-auto md:hidden">
346
- <DropdownMenu>
347
- <DropdownMenuTrigger
348
- className={buttonVariants({ variant: 'ghost', size: 'icon' })}
349
- aria-label={t('nav.openMenu')}
350
- >
351
- <Menu />
352
- </DropdownMenuTrigger>
353
- <DropdownMenuContent align="end" className="w-52">
354
- <DropdownMenuGroup>
355
- {navItems.map((item) => {
356
- const menu = navMenus[item.to]
357
- return menu ? (
358
- <DropdownMenuSub key={item.to}>
359
- <DropdownMenuSubTrigger
360
- className={menu.isActive(location.pathname) ? 'bg-accent text-accent-foreground font-medium' : undefined}
361
- >
362
- {t(item.labelKey)}
363
- </DropdownMenuSubTrigger>
364
- <DropdownMenuSubContent>
365
- {menu.items.map((entry) => (
366
- <DropdownMenuItem key={entry.to} onClick={() => navigate(entry.to)}>
367
- {t(entry.labelKey)}
368
- </DropdownMenuItem>
369
- ))}
370
- </DropdownMenuSubContent>
371
- </DropdownMenuSub>
372
- ) : (
373
- <DropdownMenuItem
374
- key={item.to}
375
- onClick={() => navigate(item.to)}
376
- className={location.pathname === item.to ? 'bg-accent text-accent-foreground font-medium' : undefined}
377
- >
378
- {t(item.labelKey)}
379
- </DropdownMenuItem>
380
- )
381
- })}
382
- </DropdownMenuGroup>
383
- <DropdownMenuSeparator />
384
- <AccountMenuItems
385
- showUpgrade={showUpgrade}
386
- upgradeLabel={t('nav.upgrade')}
387
- settingsLabel={t('nav.settings')}
388
- updatesLabel={t('settings.checkForUpdates')}
389
- signOutLabel={t('nav.signOut')}
390
- changeEmailLabel={t('auth.changeEmail')}
391
- changePasswordLabel={t('auth.changePassword')}
392
- onUpgrade={() => navigate('/premium')}
393
- onOpenSettings={() => setSettingsOpen(true)}
394
- onOpenUpdates={() => setUpdatesOpen(true)}
395
- onChangeEmail={() => setCredentialsMode('email')}
396
- onChangePassword={() => setCredentialsMode('password')}
397
- />
398
- </DropdownMenuContent>
399
- </DropdownMenu>
400
- </div>
401
- </div>
402
- </header>
403
- <SettingsDialog open={settingsOpen} onOpenChange={setSettingsOpen} />
404
- <UpdatesDialog open={updatesOpen} onOpenChange={setUpdatesOpen} />
405
- {credentialsMode && (
406
- <ChangeCredentialsModal mode={credentialsMode} onClose={() => setCredentialsMode(null)} />
407
- )}
408
- </>
409
- )
410
- }
411
-
412
- // Keyed by pathname so navigating away from a crashed page resets the boundary.
413
- function PageBoundary({ children }: { children: ReactNode }) {
414
- const location = useLocation()
415
- return <ErrorBoundary key={location.pathname}>{children}</ErrorBoundary>
416
- }
417
-
418
- // Routes that own the whole viewport instead of sitting in the shell's centred,
419
- // padded column. Only the Playground so far: its three columns run edge to edge
420
- // and the transcript scrolls inside its own pane, so the page must be exactly
421
- // as tall as what is left under the navbar — not a centred card with margins.
422
- const FULL_BLEED_ROUTES = new Set(['/playground'])
423
-
424
- // The shell's content container. A full-bleed route drops the max-width and the
425
- // padding and becomes a flex child that fills the rest of the screen; every
426
- // other route gets a centred column that is always exactly max-w-6xl wide.
427
- //
428
- // `w-full` is load-bearing, not decoration. This <main> is an item of a COLUMN
429
- // flex container, so its cross axis is the horizontal one — and flexbox only
430
- // stretches an item across the cross axis when neither cross-axis margin is
431
- // auto (CSS Flexbox §9.6). `mx-auto` sets both, so without an explicit width
432
- // the column shrink-to-fits its content instead: the page is only ever as wide
433
- // as the widest thing that has finished rendering. On a page that fills in from
434
- // several independent queries — Analytics fires ten — that turns every arriving
435
- // response into a visible horizontal jump as the column re-fits, and pages
436
- // whose content never reaches 72rem (Analytics, Premium) settle narrower than
437
- // they were designed to be. A definite width makes the column 72rem from the
438
- // first paint, and `mx-auto` goes back to only centring it.
439
- function PageContainer({ children }: { children: ReactNode }) {
440
- const location = useLocation()
441
- const fullBleed = FULL_BLEED_ROUTES.has(location.pathname)
442
- return (
443
- <main className={fullBleed ? 'flex min-h-0 flex-1 flex-col' : 'mx-auto w-full max-w-6xl px-6 py-8'}>
444
- {children}
445
- </main>
446
- )
447
- }
448
-
449
- // The shell column. Padded routes keep `min-h-screen` and scroll as a document;
450
- // a full-bleed route pins the shell to the dynamic viewport instead, because
451
- // min-height alone is a floor, not a ceiling: with an indefinite shell height
452
- // every flex-1 container below grows with its content and the document scrolls
453
- // rather than the one pane (the Playground transcript) that means to.
454
- function AppShell({ children }: { children: ReactNode }) {
455
- const location = useLocation()
456
- const fullBleed = FULL_BLEED_ROUTES.has(location.pathname)
457
- return (
458
- <div className={`flex flex-col ${fullBleed ? 'h-dvh overflow-hidden' : 'min-h-screen'} ${isMacDesktop ? 'desktop-backdrop' : 'bg-background'}`}>
459
- {children}
460
- </div>
461
- )
462
- }
463
-
464
- function App() {
465
- return (
466
- <QueryClientProvider client={queryClient}>
467
- <ThemeProvider>
468
- <I18nProvider>
469
- <BrowserRouter basename={import.meta.env.BASE_URL}>
470
- <AuthGate>
471
- {/* Column, so a full-bleed route can claim the height the navbar
472
- leaves without anyone having to know how tall the navbar is.
473
- Fixed-position children (toaster, palette, reminder) are out of
474
- flow, and a padded route stretches to nothing it can show. */}
475
- <AppShell>
476
- <Navbar />
477
- <PageContainer>
478
- <PageBoundary>
479
- <Routes>
480
- <Route path="/" element={<Navigate to="/models/chat" replace />} />
481
- <Route path="/models" element={<Navigate to="/models/chat" replace />} />
482
- <Route path="/models/chat" element={<FallbackPage />} />
483
- <Route path="/models/chat/:id" element={<ModelDetailPage />} />
484
- <Route path="/models/fusion" element={<FusionPage />} />
485
- <Route path="/models/embeddings" element={<EmbeddingsPage />} />
486
- <Route path="/models/embeddings/:id" element={<EmbeddingDetailPage />} />
487
- <Route path="/models/image" element={<ImagePage />} />
488
- <Route path="/models/image/:id" element={<MediaDetailPage modality="image" />} />
489
- <Route path="/models/video" element={<VideoPage />} />
490
- <Route path="/models/video/:id" element={<MediaDetailPage modality="video" />} />
491
- <Route path="/models/audio" element={<AudioPage />} />
492
- <Route path="/models/audio/:id" element={<MediaDetailPage modality="audio" />} />
493
- <Route path="/models/transcription/:id" element={<MediaDetailPage modality="transcription" />} />
494
- <Route path="/models/search" element={<SearchPage />} />
495
- <Route path="/models/decision" element={<DecisionPage />} />
496
- <Route path="/playground" element={<PlaygroundPage />} />
497
- <Route path="/keys" element={<KeysPage />} />
498
- <Route path="/agents" element={<AgentsPage />} />
499
- <Route path="/fallback" element={<Navigate to="/models/chat" replace />} />
500
- <Route path="/analytics" element={<AnalyticsPage />} />
501
- <Route path="/logs" element={<LogsPage />} />
502
- <Route path="/premium" element={<PremiumPage />} />
503
- <Route path="/test" element={<Navigate to="/playground" replace />} />
504
- <Route path="/health" element={<Navigate to="/keys" replace />} />
505
- <Route path="*" element={<NotFoundPage />} />
506
- </Routes>
507
- </PageBoundary>
508
- </PageContainer>
509
- <Toaster />
510
- <CommandPalette />
511
- <UpdateReminder />
512
- <NewBuildPrompt />
513
- </AppShell>
514
- </AuthGate>
515
- </BrowserRouter>
516
- </I18nProvider>
517
- </ThemeProvider>
518
- </QueryClientProvider>
519
- )
520
- }
521
-
522
- export default App
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/src/assets/vite.svg DELETED
client/src/components/agent-icons.tsx DELETED
@@ -1,391 +0,0 @@
1
- import type { ReactNode, SVGProps } from 'react'
2
- import { cn } from '@/lib/utils'
3
-
4
- // Brand marks for the tools listed on the Agents page. Every mark below is the
5
- // tool's own published logo, taken verbatim from the source in the table and
6
- // changed in only two ways: it is scaled and centred onto the shared 24px grid
7
- // used by the rest of the icons, and it is painted in that brand's own colour
8
- // for the tile it sits on. No mark is redrawn, recomposed or restyled.
9
- //
10
- // The marks identify tools this server is compatible with. They remain the
11
- // trademarks of their respective owners and imply no affiliation or endorsement.
12
- //
13
- // COLOUR RULE — one rule for the whole set, applied in this order:
14
- // 1. Use the brand's own artwork colour. Where a brand publishes separate
15
- // artwork for light and dark backgrounds (most of these do) the matching
16
- // variant is used verbatim on each tile — that is the `published pair`
17
- // treatment below.
18
- // 2. Where a brand publishes one value only and it falls under 3:1 against
19
- // the tile it has to sit on, that value is moved in OKLCH lightness only:
20
- // hue is held exactly, chroma is held and clamped to the sRGB gamut, and
21
- // lightness stops at the first step that clears 3:1. The mark still reads
22
- // as that brand's colour. Only claude, aider, kilo and reasonix need this,
23
- // and only on one tile each; the untouched brand hex is kept on the other
24
- // tile.
25
- // 3. `generic` is not a brand — it stays `currentColor`.
26
- //
27
- // Contrast is measured against the tile itself, `bg-muted`, which resolves to
28
- // #F5F5F5 in light and #1B1B1B in dark. Ratios are in the second table.
29
- //
30
- // id tool source licence
31
- // claude Claude Code simple-icons `claude` (claude.ai; the code.claude.com mark) CC0-1.0
32
- // codex Codex CLI developers.openai.com/codex site header (OpenAI's own asset) OpenAI TM, nominative use
33
- // cline Cline simple-icons `cline`; colours from cline.bot/assets/branding/ CC0-1.0 + Cline TM
34
- // logos/cline-wordmark-{black,white}.svg
35
- // continue Continue continuedev/continue `docs/logo/{light,dark}.svg` Apache-2.0
36
- // aider Aider Aider-AI/aider `aider/website/assets/icons/safari-pinned-tab.svg`; Apache-2.0
37
- // colours sampled from `android-chrome-192x192.png` (only raster)
38
- // opencode OpenCode anomalyco/opencode `packages/identity/mark{,-light}.svg` MIT
39
- // goose Goose block/goose `documentation/static/img/goose.svg`, with the Apache-2.0
40
- // published `goose-logo-white.png` as the dark variant
41
- // qwen Qwen Code simple-icons `qwen` (qwen.ai) CC0-1.0
42
- // roo Roo Code RooCodeInc/Roo-Code `src/assets/icons/icon.svg`; colours from Apache-2.0
43
- // docs `img/roo-code-logo-{dark,white}.svg`
44
- // kilo Kilo Code Kilo-Org/kilocode `packages/kilo-console/public/kilo-logo.svg` MIT
45
- // cursor Cursor cursor.com/brand asset pack, `Cube/SVG/CUBE_2D_{LIGHT,DARK}.svg` Cursor TM, nominative use
46
- // crush Crush no vector published; hue sampled from the official Charm TM, nominative use
47
- // stuff.charm.sh/crush/charm-crush.png (Charm's `charple`)
48
- // dsh DeepSeek lettermark only: DSH's brand guidelines ask third parties not DeepSeek TM, nominative use
49
- // Harness to reuse official artwork; tinted with DeepSeek's brand blue
50
- // mimo MiMo Code lettermark only: no vector published, only the 32px favicon Xiaomi TM, nominative use
51
- // at cdn.cnbj1.fds.api.mi-img.com/.../mimo.ico, which is flat black
52
- // atomcode AtomCode lettermark only: no vector published; hue sampled from the AtomGit TM, nominative use
53
- // app icon cdn-news.gitcode.com/news/atomcode-icon1.png (the
54
- // gradient's dominant blue, at two of its four corners)
55
- // openclaw OpenClaw openclaw.ai/favicon.svg (the lobster mark: body, claws and MIT (openclaw/openclaw)
56
- // antennae); the eyes are dropped with the gradient, as every
57
- // mark here is painted flat in one brand colour
58
- // hermes Hermes Agent lettermark only: the published mark (NousResearch/hermes-agent Nous Research TM, nominative use
59
- // website/static/img/logo.png) is a raster portrait and the SVG
60
- // favicon is a text glyph, so neither fits the 24px grid
61
- // pi Pi pi.dev/favicon.svg (the monochrome mark; the press kit's Earendil TM, nominative use
62
- // three-colour logo is the same geometry)
63
- // reasonix Reasonix esengine/DeepSeek-Reasonix `docs/logo.svg` (the ◈ brand mark: MIT
64
- // three concentric diamonds, without the wordmark)
65
- //
66
- // id light tile ratio dark tile ratio dark-mode treatment
67
- // claude #D37152 3.08 #D97757 5.52 brand #D97757 on dark; light tile is
68
- // the same hue tuned down (rule 2, 2.86→3.08)
69
- // codex #000000 19.26 #FFFFFF 17.22 published pair (OpenAI paints the mark in
70
- // currentColor: black on light, white on dark)
71
- // cline #18181B 16.25 #FAFAFA 16.50 published pair (black/white wordmarks)
72
- // continue #000000 19.26 #FFFFFF 17.22 published pair (logo/light.svg, logo/dark.svg)
73
- // aider #07A160 3.07 #02F191 11.48 brand green on dark; light tile is the same
74
- // hue tuned down (rule 2, 1.38→3.07)
75
- // opencode #17181C + #E6E5E6 16.27 #FFFFFF + #5A5858 17.22 published pair; the second value is the
76
- // mark's own inner block, a depth fill that is
77
- // deliberately near-invisible in the brand's
78
- // own artwork too (1.15 / 2.44) — the frame
79
- // carries the legibility
80
- // goose #101010 17.45 #FFFFFF 17.22 published pair (black mark / white logo)
81
- // qwen #6950EF 4.82 #6950EF 3.28 brand hex unchanged; it clears 3:1 on both
82
- // tiles, so no tuning is applied
83
- // roo #000000 19.26 #FFFFFF 17.22 published pair (logo-dark.svg/logo-white.svg)
84
- // kilo #949107 3.05 #FAF74F 15.16 brand yellow on dark; light tile is the same
85
- // hue tuned down (rule 2, 1.04→3.05) — #FAF74F
86
- // is oklch(0.95 0.18 108.4) and the tuned value
87
- // is oklch(0.638 0.136 108.4), the most
88
- // saturated yellow that clears 3:1 there
89
- // cursor #26251E 14.10 #EDECEC 14.61 published pair (CUBE_2D_LIGHT/DARK)
90
- // crush #6B50FF 4.57 #6B50FF 3.46 brand purple unchanged; clears on both tiles
91
- // dsh #4D6BFE 3.97 #4D6BFE 3.98 brand blue unchanged; clears on both tiles
92
- // mimo #000000 19.26 #FFFFFF 17.22 published pair (the favicon is black artwork on
93
- // transparent, so it inverts on the dark tile)
94
- // atomcode #3C82F6 3.37 #3C82F6 4.69 icon blue unchanged; clears on both tiles
95
- // openclaw #991B1B 7.62 #FF4D4D 5.27 published pair: the mark is a gradient from
96
- // #FF4D4D to #991B1B, and each tile takes the
97
- // stop that clears on it (the light stop is
98
- // 3.00 on the light tile, right at the line)
99
- // hermes #000000 19.26 #FFFFFF 17.22 published pair (the logo is flat black artwork
100
- // on white, so it inverts on the dark tile)
101
- // pi #111111 17.32 #F6F6F6 15.94 published pair (the favicon's own light and
102
- // dark-scheme fills)
103
- // reasonix #6191C6 3.02 #93C5FD 9.55 the mark's gradient midpoint #93C5FD on dark;
104
- // light tile is the same hue tuned down (rule 2,
105
- // 1.65→3.02): oklch(0.809 0.096 251.8) →
106
- // oklch(0.645 0.096 251.8)
107
- // generic currentColor — currentColor — not a brand mark
108
- //
109
- // Cursor also publishes a 2.5D cube in five warm greys (#43413c #55544f #72716d
110
- // #d6d5d2 #fff). It is not used: at 20px the facets stop resolving, and its
111
- // darkest and lightest faces drop out on the dark and light tile respectively.
112
- // The 2D cube is an official mark in its own right, not a flattening of that one.
113
- //
114
- // OpenCode's mark is the only two-tone one. Its inner block was dropped while
115
- // the set was monochrome — it would have merged with the frame — and is restored
116
- // here from the same published artwork, so the mark keeps both of its layers.
117
- //
118
- // Aider's and Kilo Code's logos are published as light artwork knocked out of a
119
- // dark plate; both are used here as the plain letterform the plate carries, which
120
- // is the same geometry with the background dropped for the colour swap.
121
- //
122
- // Crush has no published vector mark (charmbracelet/crush ships the icon as a
123
- // PNG only), so it keeps the lettermark fallback below rather than an invented
124
- // symbol; it is tinted with Charm's own purple so it sits in the coloured row.
125
- // `generic` is not a brand: it is our own terminal glyph, on the same lucide grid
126
- // and weight as the icons used elsewhere in the app.
127
-
128
- type Brand = {
129
- // Tailwind arbitrary properties set `--mk` (and `--mk2` for the one two-tone
130
- // mark) on the tile. The `dark:` half swaps in the dark-tile value, so the
131
- // whole colour scheme is CSS — no theme hook, no flash on first paint.
132
- tint: string
133
- // Optical size correction, applied about the centre on top of the geometry
134
- // already fitted to the grid; omitted means the mark is used at its fitted
135
- // size. A bright saturated fill blooms next to a near-black or white one, so
136
- // aider's #02F191 and kilo's #FAF74F — the two most luminous colours in the
137
- // set, both on blocky marks — are pulled in slightly. Measured on the
138
- // rendered tile as perceptual ink coverage, both sat ~1.5 points above the
139
- // set's median and land on it at these values. Nothing is scaled up: every
140
- // other mark already fills 21–24 of the 24-unit grid, so there is no room.
141
- scale?: number
142
- art?: ReactNode
143
- }
144
-
145
- const brands: Record<string, Brand> = {
146
- claude: {
147
- tint: '[--mk:#D37152] dark:[--mk:#D97757]',
148
- art: (
149
- <path
150
- d="m4.67 15.8 4.67-2.62 0.08-0.23-0.08-0.13h-0.23l-0.78-0.05-2.67-0.07-2.31-0.1-2.24-0.12-0.56-0.12-0.53-0.7 0.05-0.35 0.47-0.32 0.68 0.06 1.5 0.1 2.25 0.16 1.63 0.1 2.42 0.25h0.38l0.05-0.16-0.13-0.1-0.1-0.1L6.89 9.98l-2.52-1.67-1.32-0.96-0.72-0.49-0.36-0.46-0.16-1 0.65-0.72 0.87 0.06 0.22 0.06 0.88 0.68 1.89 1.46 2.46 1.82 0.36 0.3 0.14-0.1 0.02-0.07-0.16-0.27-1.34-2.42-1.43-2.46-0.64-1.02-0.17-0.61c-0.06-0.25-0.1-0.46-0.1-0.72L6.22 0.37 6.62 0.24l0.99 0.13 0.41 0.36 0.61 1.4 0.99 2.21 1.54 3 0.45 0.89 0.24 0.82 0.09 0.25h0.16v-0.14l0.13-1.69 0.23-2.07 0.23-2.67 0.08-0.75 0.37-0.9 0.74-0.49 0.58 0.28 0.47 0.68-0.07 0.44-0.28 1.83-0.55 2.87-0.36 1.92h0.21l0.24-0.24 0.97-1.29 1.63-2.04 0.72-0.81 0.84-0.9 0.54-0.43h1.02l0.75 1.12-0.34 1.15-1.05 1.33-0.87 1.13-1.25 1.68-0.78 1.35 0.07 0.11 0.19-0.02 2.82-0.6 1.53-0.28 1.82-0.31 0.82 0.38 0.09 0.39-0.32 0.8-1.95 0.48-2.28 0.46-3.4 0.81-0.04 0.03 0.05 0.06 1.53 0.14 0.66 0.04h1.6l2.99 0.22 0.78 0.52 0.47 0.63-0.08 0.48-1.2 0.61-1.62-0.38-3.79-0.9-1.3-0.32h-0.18v0.11l1.08 1.06 1.98 1.79 2.48 2.31 0.13 0.57-0.32 0.45-0.34-0.05-2.18-1.64-0.84-0.74-1.91-1.6h-0.13v0.17l0.44 0.64 2.32 3.49 0.12 1.07-0.17 0.35-0.6 0.21-0.66-0.12-1.36-1.91L14.23 18.02l-1.13-1.92-0.14 0.08-0.67 7.18-0.31 0.37-0.72 0.28-0.6-0.46-0.32-0.74 0.32-1.46 0.38-1.91 0.31-1.51 0.28-1.88 0.17-0.63-0.01-0.04-0.14 0.02-1.42 1.95-2.16 2.92-1.71 1.83-0.41 0.16-0.71-0.37 0.07-0.66 0.4-0.58 2.36-3.01 1.42-1.86 0.92-1.08-0.01-0.16h-0.05l-6.28 4.08-1.12 0.14-0.48-0.45 0.06-0.74 0.23-0.24 1.89-1.3Z"
151
- />
152
- ),
153
- },
154
- codex: {
155
- tint: '[--mk:#000000] dark:[--mk:#FFFFFF]',
156
- art: (
157
- <path
158
- d="M9.46 9.06v-2.07c0-0.17 0.07-0.31 0.22-0.39l4.16-2.4c0.57-0.33 1.24-0.48 1.94-0.48 2.62 0 4.27 2.03 4.27 4.19 0 0.15 0 0.33-0.02 0.5L15.72 5.87c-0.26-0.15-0.52-0.15-0.78 0L9.46 9.06Zm9.72 8.07V12.18c0-0.31-0.13-0.52-0.39-0.68L13.32 8.32l1.79-1.02c0.15-0.09 0.28-0.09 0.44 0l4.16 2.4c1.2 0.7 2.01 2.18 2.01 3.62 0 1.66-0.98 3.18-2.53 3.82Zm-11.01-4.36-1.79-1.05c-0.15-0.09-0.22-0.22-0.22-0.39V6.53c0-2.33 1.79-4.1 4.21-4.1 0.92 0 1.77 0.31 2.49 0.85l-4.3 2.49c-0.26 0.15-0.39 0.37-0.39 0.68v6.32ZM12.02 14.99l-2.56-1.44V10.5L12.02 9.06l2.56 1.44v3.05L12.02 14.99Zm1.65 6.63c-0.92 0-1.77-0.31-2.49-0.85l4.3-2.49c0.26-0.15 0.39-0.37 0.39-0.68V11.28l1.81 1.05c0.15 0.09 0.22 0.22 0.22 0.39v4.8c0 2.33-1.81 4.1-4.23 4.1v0Zm-5.17-4.86-4.16-2.4c-1.2-0.7-2.01-2.18-2.01-3.62 0-1.68 1-3.18 2.55-3.82v4.97c0 0.31 0.13 0.52 0.39 0.68l5.45 3.16-1.79 1.02c-0.15 0.09-0.28 0.09-0.44 0ZM8.26 20.33c-2.46 0-4.27-1.85-4.27-4.14 0-0.17 0.02-0.35 0.04-0.52L8.33 18.15c0.26 0.15 0.52 0.15 0.78 0l5.47-3.16v2.07c0 0.17-0.07 0.31-0.22 0.39L10.2 19.85c-0.57 0.33-1.24 0.48-1.94 0.48h0Zm5.41 2.59c2.64 0 4.84-1.88 5.34-4.36C21.45 17.93 23.02 15.64 23.02 13.31c0-1.53-0.65-3.01-1.83-4.08 0.11-0.46 0.17-0.92 0.17-1.37 0-3.12-2.53-5.45-5.45-5.45-0.59 0-1.16 0.09-1.72 0.28C13.21 1.73 11.86 1.12 10.38 1.12c-2.64 0-4.84 1.88-5.34 4.36C2.59 6.11 1.02 8.4 1.02 10.74c0 1.53 0.65 3.01 1.83 4.08-0.11 0.46-0.17 0.92-0.17 1.37 0 3.12 2.53 5.45 5.45 5.45 0.59 0 1.16-0.09 1.72-0.28 0.98 0.96 2.33 1.57 3.82 1.57Z"
159
- />
160
- ),
161
- },
162
- cline: {
163
- tint: '[--mk:#18181B] dark:[--mk:#FAFAFA]',
164
- art: (
165
- <path
166
- d="m18.42 10.69-1.14-2.28V8.97c0-2.18-1.75-3.94-3.91-3.94h-1.94c0.14-0.29 0.22-0.61 0.22-0.96A2.18 2.18 0 0 0 12.2 1.88a2.18 2.18 0 0 0-2.18 2.19c0 0.34 0.08 0.67 0.22 0.96H8.3c-2.16 0-3.91 1.76-3.91 3.94v1.31L3.23 12.57c-0.12 0.23-0.12 0.5 0 0.73l1.16 2.25v1.31C4.39 19.04 6.14 20.8 8.3 20.8h7.81c2.16 0 3.91-1.76 3.91-3.94V15.55l1.14-2.26c0.11-0.23 0.11-0.49 0-0.72m-10.13 1.86a1.79 1.79 0 0 1-1.78 1.79 1.79 1.79 0 0 1-1.78-1.79v-3.19A1.79 1.79 0 0 1 9.23 9.45a1.79 1.79 0 0 1 1.78 1.79zm5.74 0a1.79 1.79 0 0 1-1.78 1.79 1.79 1.79 0 0 1-1.78-1.79v-3.19A1.79 1.79 0 0 1 14.97 9.45a1.79 1.79 0 0 1 1.78 1.79z"
167
- />
168
- ),
169
- },
170
- continue: {
171
- tint: '[--mk:#000000] dark:[--mk:#FFFFFF]',
172
- art: (
173
- <path
174
- d="M19.28 4.39L18.05 6.52L21.15 11.88C21.17 11.92 21.19 11.97 21.19 12.01C21.19 12.06 21.17 12.11 21.15 12.15L18.05 17.51L19.28 19.64L23.68 12.01L19.28 4.39V4.39ZM17.58 6.24L18.8 4.12H16.35L15.13 6.24H17.58H17.58ZM15.13 6.79L17.99 11.74H20.44L17.58 6.79H15.13ZM17.58 17.24L20.44 12.29H17.99L15.13 17.24H17.58ZM15.13 17.79L16.35 19.91H18.8L17.58 17.79H15.12H15.13ZM6.82 20.43C6.77 20.43 6.73 20.42 6.69 20.4C6.65 20.37 6.61 20.34 6.59 20.3L3.49 14.93H1.04L5.44 22.55H14.24L13.01 20.43H6.83H6.82ZM13.49 20.16L14.71 22.28L15.94 20.15L14.71 18.03L13.49 20.15V20.16ZM14.24 17.76H8.53L7.3 19.88H13.01L14.24 17.76ZM8.05 17.49L5.19 12.53L3.96 14.66L6.82 19.61L8.05 17.49ZM1.03 14.38H3.48L4.71 12.26H2.26L1.03 14.38ZM6.57 3.74C6.6 3.7 6.63 3.67 6.67 3.65C6.71 3.62 6.76 3.61 6.81 3.61H13.01L14.23 1.48H5.42L1.02 9.11H3.47L6.56 3.75L6.57 3.74ZM4.71 11.78L3.48 9.66H1.03L2.26 11.78H4.71ZM6.81 4.43L3.96 9.38L5.18 11.51L8.04 6.56L6.81 4.43ZM13.01 4.16H7.29L8.51 6.28H14.23L13.01 4.16ZM14.71 6L15.93 3.88L14.71 1.76L13.49 3.88L14.71 6Z"
175
- />
176
- ),
177
- },
178
- aider: {
179
- tint: '[--mk:#07A160] dark:[--mk:#02F191]',
180
- scale: 0.96,
181
- art: (
182
- <path
183
- d="M14.78 0.67c0.12 0.12 0.17 0.72 0.18 2.38l0.01 1.82 1.29 0.03c0.71 0.02 1.3 0.05 1.33 0.07 0.02 0.02 0.06 0.28 0.09 0.57 0.03 0.29 0.1 0.75 0.15 1.03 0.1 0.51 0.1 0.48-0.1 1.39-0.08 0.4-0.08 2.18 0.01 2.62 0.13 0.6 0.13 0.95 0.03 1.48-0.14 0.73-0.14 2.17 0.01 2.74 0.14 0.53 0.14 1.27 0.01 1.97-0.05 0.29-0.1 0.65-0.1 0.79l0 0.26 1.21 0c0.66 0 1.24 0.02 1.29 0.05 0.06 0.04 0.11 0.3 0.16 0.89 0.05 0.45 0.1 0.91 0.12 1 0.04 0.23-0.14 2.16-0.22 2.31-0.06 0.11-0.13 0.11-1.28 0.1-0.81-0.01-1.24-0.04-1.29-0.08-0.13-0.13-0.2-1.8-0.13-3 0.04-0.61 0.05-1.13 0.03-1.16-0.05-0.08-2.49-0.07-2.58 0.01-0.07 0.07-0.05 0.87 0.05 1.56 0.05 0.33 0.05 0.57 0.01 0.84-0.04 0.21-0.08 0.59-0.1 0.86-0.05 0.74-0.08 0.84-0.25 0.92-0.11 0.05-1.3 0.07-4.06 0.07l-3.91 0-0.07-0.2c-0.19-0.58-0.26-2.01-0.16-3.19 0.03-0.33 0.04-0.68 0.01-0.77l-0.04-0.16-1.16 0c-1.26 0-1.51-0.02-1.56-0.17-0.07-0.2-0.1-2.34-0.04-3.12 0.09-1.11-0.01-1.04 1.55-1.08 0.69-0.02 1.27-0.05 1.3-0.07 0.02-0.02 0.01-0.31-0.03-0.63-0.04-0.32-0.1-0.78-0.13-1-0.04-0.33-0.03-0.54 0.07-1.02 0.06-0.33 0.13-0.78 0.16-0.99 0.02-0.22 0.06-0.43 0.09-0.47 0.04-0.07 0.77-0.09 3.98-0.11l3.93-0.03 0.05-0.18c0.03-0.11 0.02-0.43-0.02-0.78-0.07-0.69-0.04-2.07 0.07-2.72 0.06-0.36 0.06-0.45-0.01-0.49-0.05-0.03-1.79-0.05-3.89-0.05l-3.8 0-0.16-0.15c-0.11-0.1-0.16-0.2-0.16-0.34 0-0.11-0.03-0.52-0.06-0.91-0.06-0.77 0.03-2.69 0.13-2.82 0.03-0.04 0.16-0.08 0.28-0.09 0.47-0.04 7.66-0.02 7.7 0.02z"
184
- />
185
- ),
186
- },
187
- opencode: {
188
- tint: '[--mk:#17181C] [--mk2:#E6E5E6] dark:[--mk:#FFFFFF] dark:[--mk2:#5A5858]',
189
- art: (
190
- <>
191
- <path fill="var(--mk2)" d="M15.68 10.26v7.04H8.35v-7.04z" />
192
- <path d="M19.35 20.82H4.68V3.22h14.67zM15.68 6.74H8.35v10.56h7.33z" />
193
- </>
194
- ),
195
- },
196
- goose: {
197
- tint: '[--mk:#101010] dark:[--mk:#FFFFFF]',
198
- art: (
199
- <path
200
- d="M23.8 21.2L21.9 19.7C20.9 18.9 20 17.9 19.3 16.7 18.4 15.2 17.1 13.8 15.5 12.9L14.8 12.4C14.5 12.2 14.3 12 14.3 11.6 14.3 11.4 14.3 11.3 14.5 11.1 14.9 10.5 17 8.2 17.4 7.9 17.8 7.5 18.4 7.2 18.9 6.8 19 6.8 19 6.7 19.1 6.7 19.3 6.5 19.4 6.4 19.5 6.2 20.1 5.6 20.1 5 20.1 5 20 4.8 19.8 4.4 19.4 4.2 19.8 4.1 20.2 4.3 20.4 4.5 20.7 4.1 20.8 3.9 21.1 3.4 21.1 3.3 21.2 3.2 21 3 20.9 2.9 20.7 2.9 20.6 3 20 3.3 19.5 3.6 19 3.9 19 3.9 18.5 3.9 17.8 4.5 17.6 4.6 17.5 4.8 17.4 4.9 17.3 5 17.2 5.1 17.2 5.1 16.8 5.6 16.5 6.2 16.1 6.7 15.8 7 13.5 9.2 12.9 9.6 12.8 9.7 12.6 9.7 12.4 9.7 12.1 9.7 11.8 9.5 11.6 9.2L11.2 8.5C10.2 6.9 8.9 5.6 7.3 4.7 6.2 4 5.2 3.2 4.3 2.1L2.8 0.3C2.7 0.2 2.6 0.2 2.5 0.3 2.3 0.6 2 1.4 1.7 2.3 1.7 2.3 1.7 2.4 1.7 2.4 2.1 2.8 2.8 3.6 3.7 4.3 3.7 4.4 3.7 4.5 3.6 4.5 2.9 4.3 2.1 3.9 1.6 3.7 1.5 3.6 1.5 3.7 1.5 3.7 1.4 4.4 1.4 5.2 1.4 6 1.4 6 1.5 6 1.5 6 2.1 6.3 3.1 6.7 4.2 6.9 4.3 7 4.3 7.1 4.2 7.1 3.4 7.2 2.5 7.3 1.8 7.3 1.7 7.3 1.7 7.3 1.7 7.4 1.9 7.9 2.1 8.4 2.3 8.9 2.4 9.1 2.5 9.3 2.6 9.5 2.7 9.6 2.7 9.6 2.7 9.6 3.3 9.6 4 9.5 4.7 9.4 4.8 9.4 4.9 9.5 4.8 9.6 4.3 9.9 3.8 10.2 3.4 10.4 3.3 10.4 3.3 10.5 3.3 10.6 3.6 11 3.9 11.3 4.2 11.7 4.2 11.7 5.9 13.4 5.9 13.5 6.9 12.5 8.5 11.4 10.2 10.5 7.9 12.4 6.6 13.8 5.9 14.6L5.5 15.2C5.2 15.6 5 15.9 4.8 16.3 4.3 17.5 3.3 20.1 3.3 20.1 3.2 20.3 3.3 20.5 3.4 20.6 3.6 20.7 3.8 20.8 4 20.7 4 20.7 6.5 19.8 7.7 19.2 8.1 19 8.5 18.8 8.8 18.6L9.5 18C9.9 17.8 10.4 17.8 10.7 18.2L12.4 19.8C12.7 20.1 13.1 20.4 13.4 20.7 13.5 20.8 13.6 20.7 13.6 20.7 13.8 20.2 14.1 19.7 14.4 19.2 14.5 19.1 14.7 19.2 14.6 19.3 14.5 20 14.5 20.7 14.4 21.3 14.4 21.3 14.4 21.4 14.5 21.4 14.7 21.5 14.9 21.6 15.2 21.7 15.7 22 16.2 22.2 16.7 22.3 16.7 22.3 16.8 22.3 16.8 22.2 16.8 21.5 16.8 20.7 16.9 19.8 17 19.8 17.1 19.8 17.1 19.8 17.3 20.9 17.7 21.9 18 22.5 18 22.6 18 22.6 18.1 22.6 18.9 22.7 19.6 22.7 20.3 22.6 20.4 22.6 20.4 22.5 20.4 22.5 20.1 21.9 19.8 21.2 19.5 20.4 19.5 20.3 19.6 20.3 19.7 20.3 20.4 21.2 21.2 22 21.6 22.3 21.7 22.3 21.7 22.3 21.7 22.3 22.7 22 23.4 21.7 23.7 21.5 23.8 21.5 23.9 21.3 23.8 21.3L23.8 21.2Z"
201
- />
202
- ),
203
- },
204
- qwen: {
205
- tint: '[--mk:#6950EF] dark:[--mk:#6950EF]',
206
- art: (
207
- <path
208
- d="M22.73 14.3 19.94 9.48l1.32-2.29a0.5 0.5 0 0 0 0-0.51l-1.47-2.54a0.51 0.51 0 0 0-0.44-0.25h-5.58L12.46 1.6a0.51 0.51 0 0 0-0.44-0.26H9.09a0.5 0.5 0 0 0-0.44 0.26L5.86 6.43h-2.64a0.5 0.5 0 0 0-0.44 0.26L1.31 9.22a0.5 0.5 0 0 0 0 0.51L4.1 14.56l-1.32 2.29a0.5 0.5 0 0 0 0 0.51l1.47 2.54a0.51 0.51 0 0 0 0.44 0.25h5.57l1.32 2.29a0.51 0.51 0 0 0 0.44 0.26h2.93a0.51 0.51 0 0 0 0.44-0.26l2.79-4.83h2.64a0.51 0.51 0 0 0 0.44-0.25l1.47-2.54a0.49 0.49 0 0 0 0-0.51M9.09 1.85l1.47 2.54-1.47 2.54H20.83L19.36 9.48H7.91L6.3 6.68Zm1.17 17.79-5.57 0 1.47-2.54h2.93L3.22 6.94h2.93q2.86 4.96 5.72 9.91zm9.09-5.08L17.89 12.02l-5.87 10.16-1.47-2.54c1.91-3.3 3.82-6.6 5.73-9.91h3.23l2.79 4.83z"
209
- />
210
- ),
211
- },
212
- roo: {
213
- tint: '[--mk:#000000] dark:[--mk:#FFFFFF]',
214
- art: (
215
- <path
216
- d="M19.48 5.42l-0.43 1.56c-0.02 0.08-0.11 0.13-0.19 0.1l-7.01-2.17c-0.05-0.01-0.1 0-0.14 0.03l-7.21 5.79c-0.02 0.02-0.04 0.03-0.07 0.03l-4.3 0.66c-0.08 0.01-0.13 0.08-0.13 0.16l0.03 0.62c0 0.08 0.06 0.14 0.14 0.14l5 0.31c0.03 0 0.05 0 0.08-0.01l3.65-1.84c0.05-0.03 0.11-0.02 0.16 0.01l2.34 1.75c0.04 0.03 0.06 0.07 0.06 0.12l-0.02 2.9c0 0.03 0.01 0.06 0.03 0.09l3.67 5.27c0.03 0.04 0.07 0.06 0.12 0.06h1.25c0.11 0 0.19-0.12 0.13-0.22l-2.71-4.96c-0.02-0.04-0.02-0.1 0-0.14l1.37-2.61c0.01-0.03 0.04-0.05 0.06-0.06l4.87-2.47c0.05-0.02 0.11-0.02 0.15 0.01l1.4 0.93c0.02 0.02 0.05 0.02 0.08 0.02h1.28c0.12 0 0.19-0.13 0.13-0.23l-3.54-5.86c-0.07-0.11-0.24-0.09-0.28 0.04Z"
217
- />
218
- ),
219
- },
220
- kilo: {
221
- tint: '[--mk:#949107] dark:[--mk:#FAF74F]',
222
- scale: 0.95,
223
- art: (
224
- <path
225
- d="M16.43 19.72H19.95V22.53H15.52L13.61 20.62V16.2H16.43V19.72ZM22.76 15.29L20.85 13.38H16.43V16.2L19.95 16.2V19.72H22.76V15.29ZM10.79 13.38H7.98V16.2H10.79V13.38ZM1.64 20.62L3.55 22.53H10.79V19.72H4.46V13.38H1.64V20.62ZM19.57 7.75V3.33L17.66 1.41H13.61V4.23H16.76V7.75H13.61V10.57H22.76V7.75H19.57ZM4.46 1.41H1.64V10.57H4.46V7.4H7.98V10.57H10.79V7.4L7.98 4.58H4.46V1.41ZM10.79 1.41H7.98V4.58H10.79V1.41Z"
226
- />
227
- ),
228
- },
229
- cursor: {
230
- tint: '[--mk:#26251E] dark:[--mk:#EDECEC]',
231
- art: (
232
- <path
233
- d="M11.83 2.32 4.08 6.79a0.68 0.68 0 0 0-0.34 0.59v9.03c0 0.24 0.13 0.46 0.34 0.58l7.75 4.48a0.81 0.81 0 0 0 0.81 0l7.75-4.48a0.68 0.68 0 0 0 0.34-0.58V7.38a0.68 0.68 0 0 0-0.34-0.59L12.63 2.32a0.81 0.81 0 0 0-0.8 0M4.69 7.32h14.96c0.21 0 0.35 0.23 0.24 0.42L12.42 20.7c-0.05 0.09-0.18 0.05-0.18-0.05V12.16a0.48 0.48 0 0 0-0.24-0.41l-7.35-4.24c-0.09-0.05-0.05-0.19 0.05-0.19"
234
- />
235
- ),
236
- },
237
- // No vector mark exists, so the lettermark fallback stands in — tinted with
238
- // Charm's own purple so the tile still carries the brand.
239
- crush: {
240
- tint: '[--mk:#6B50FF] dark:[--mk:#6B50FF]',
241
- },
242
- // DeepSeek Harness asks third parties not to reuse its official artwork
243
- // (BRAND_GUIDELINES.md), so the lettermark stands in, in DeepSeek's blue.
244
- dsh: {
245
- tint: '[--mk:#4D6BFE] dark:[--mk:#4D6BFE]',
246
- },
247
- // Xiaomi publishes no vector mark for MiMo Code — the only artwork on
248
- // mimo.xiaomi.com is the 32px favicon — so the lettermark stands in. That
249
- // favicon is drawn in flat black on transparent, which is the published
250
- // pair treatment: black on the light tile, white on the dark one.
251
- mimo: {
252
- tint: '[--mk:#000000] dark:[--mk:#FFFFFF]',
253
- },
254
- // AtomGit publishes AtomCode's icon only as a raster (the app icon the site
255
- // header uses: an atom orbit on a cyan-to-violet gradient), so the lettermark
256
- // stands in. It is tinted with the gradient's dominant blue, sampled from
257
- // that PNG, which clears 3:1 on both tiles as published.
258
- atomcode: {
259
- tint: '[--mk:#3C82F6] dark:[--mk:#3C82F6]',
260
- },
261
- // openclaw.ai/favicon.svg, drawn on a 120-unit box: the body and the two
262
- // claws are filled paths, the antennae stroked. Scaled 0.2 and centred onto
263
- // the 24 grid. The published mark paints the shell in a red gradient with
264
- // dark eyes; here the shell is one flat brand red, like every other mark.
265
- openclaw: {
266
- tint: '[--mk:#991B1B] dark:[--mk:#FF4D4D]',
267
- art: (
268
- <g transform="translate(0 0) scale(0.2)">
269
- <path d="M60 10 C30 10 15 35 15 55 C15 75 30 95 45 100 L45 110 L55 110 L55 100 C55 100 60 102 65 100 L65 110 L75 110 L75 100 C90 95 105 75 105 55 C105 35 90 10 60 10Z" />
270
- <path d="M20 45 C5 40 0 50 5 60 C10 70 20 65 25 55 C28 48 25 45 20 45Z" />
271
- <path d="M100 45 C115 40 120 50 115 60 C110 70 100 65 95 55 C92 48 95 45 100 45Z" />
272
- <path d="M45 15 Q35 5 30 8" fill="none" stroke="var(--mk, currentColor)" strokeWidth={3} strokeLinecap="round" />
273
- <path d="M75 15 Q85 5 90 8" fill="none" stroke="var(--mk, currentColor)" strokeWidth={3} strokeLinecap="round" />
274
- </g>
275
- ),
276
- },
277
- // Nous Research publishes the Hermes Agent mark only as a raster portrait,
278
- // so the lettermark stands in. The artwork is flat black on white, which is
279
- // the published pair treatment: black on the light tile, white on the dark.
280
- hermes: {
281
- tint: '[--mk:#000000] dark:[--mk:#FFFFFF]',
282
- },
283
- // pi.dev/favicon.svg, drawn on a 560-unit box with three solid blocks.
284
- // Scaled 0.0375 and centred, so it spans 21 units: a mark that fills its
285
- // whole square reads heavier than the set's outlined marks at full size.
286
- pi: {
287
- tint: '[--mk:#111111] dark:[--mk:#F6F6F6]',
288
- art: (
289
- <g transform="translate(1.5 1.5) scale(0.0375)">
290
- <path d="M420 280H280V140H0V0H420V280Z" />
291
- <path d="M560 560H420V280H560V560Z" />
292
- <path d="M140 560H0V140H140V280H280V420H140V560Z" />
293
- </g>
294
- ),
295
- },
296
- // esengine/DeepSeek-Reasonix docs/logo.svg: the ◈ mark is three concentric
297
- // diamonds on a 92-unit box — two stroked, the inner one filled. Scaled
298
- // 0.21 about the centre, so it spans 19.3 units. The published artwork
299
- // pulses the strokes between 3.5 and 5.5; the peak width is used so the
300
- // outlines survive at 20px. The cyan-to-violet gradient becomes one flat
301
- // colour, its midpoint stop.
302
- reasonix: {
303
- tint: '[--mk:#6191C6] dark:[--mk:#93C5FD]',
304
- art: (
305
- <g transform="translate(12 12) scale(0.21)" stroke="var(--mk, currentColor)" strokeLinejoin="round">
306
- <path d="M0-46 46 0 0 46-46 0Z" fill="none" strokeWidth={5.5} />
307
- <path d="M0-26 26 0 0 26-26 0Z" fill="none" strokeWidth={3.5} />
308
- <path d="M0-11 11 0 0 11-11 0Z" strokeWidth={0} />
309
- </g>
310
- ),
311
- },
312
- // ZCode (Z.ai): its app icon is a white Z on a near-black rounded square,
313
- // drawn here as the square with the Z knocked out so it reads on both tiles.
314
- zcode: {
315
- tint: '[--mk:#2B2B2B] dark:[--mk:#E5E5E5]',
316
- art: (
317
- <path
318
- fill="var(--mk, currentColor)"
319
- fillRule="evenodd"
320
- d="M7 3h10a4 4 0 0 1 4 4v10a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V7a4 4 0 0 1 4-4ZM7 7v2.4h6.6L7 14.6V17h10v-2.4h-6.6L17 9.4V7Z"
321
- />
322
- ),
323
- },
324
- // Any other OpenAI-compatible client: our own terminal glyph, not a brand
325
- // mark, so it keeps the page foreground colour on both tiles.
326
- generic: {
327
- tint: '',
328
- art: (
329
- <g fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
330
- <rect x="2.8" y="4.3" width="18.4" height="15.4" rx="3.6" />
331
- <path d="M7.6 10.4 10.1 12.9 7.6 15.4" />
332
- <path d="M12.6 15.4h4.4" />
333
- </g>
334
- ),
335
- },
336
- }
337
-
338
- function Mark({
339
- scale,
340
- children,
341
- ...props
342
- }: SVGProps<SVGSVGElement> & { scale?: number; children: ReactNode }) {
343
- return (
344
- // `--mk` is set by the tile below; the fallback keeps an untinted mark on
345
- // the page foreground colour rather than leaving it unpainted.
346
- <svg viewBox="0 0 24 24" fill="var(--mk, currentColor)" aria-hidden="true" {...props}>
347
- {scale
348
- ? <g transform={`translate(12 12) scale(${scale}) translate(-12 -12)`}>{children}</g>
349
- : children}
350
- </svg>
351
- )
352
- }
353
-
354
- // Letters for a tool with no mark yet, so a catalog entry added later still
355
- // gets a badge of the same size and weight instead of an empty tile.
356
- function lettermark(name: string): string {
357
- return name.replace(/[^A-Za-z0-9]/g, '').slice(0, 2).toUpperCase()
358
- }
359
-
360
- export function AgentIcon({
361
- id,
362
- name,
363
- className,
364
- }: {
365
- id: string
366
- name: string
367
- className?: string
368
- }) {
369
- const brand = brands[id]
370
- return (
371
- <span
372
- aria-hidden="true"
373
- className={cn(
374
- 'flex size-9 shrink-0 items-center justify-center rounded-xl bg-muted text-foreground',
375
- brand?.tint,
376
- className,
377
- )}
378
- >
379
- {brand?.art
380
- ? <Mark className="size-5" scale={brand.scale}>{brand.art}</Mark>
381
- : (
382
- <span
383
- className="font-mono text-[11px] font-semibold"
384
- style={{ color: 'var(--mk, currentColor)' }}
385
- >
386
- {lettermark(name)}
387
- </span>
388
- )}
389
- </span>
390
- )
391
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/src/components/api-usage.tsx DELETED
@@ -1,26 +0,0 @@
1
- import { CopyButton } from '@/components/copy-button'
2
- import { useI18n } from '@/i18n'
3
-
4
- // The /v1 base URL for ready-to-run snippets, derived the same way as the chat
5
- // model page + Keys page: the dev server port in DEV, the page origin in a
6
- // packaged/hosted build.
7
- export function apiBaseUrl(): string {
8
- return import.meta.env.DEV
9
- ? `http://${window.location.hostname}:${__SERVER_PORT__}/v1`
10
- : `${window.location.origin}/v1`
11
- }
12
-
13
- // A copy-able "ways to use the API" code block, matching the chat detail page's
14
- // snippet card so every modality's detail page looks the same.
15
- export function ApiUsageBlock({ snippet }: { snippet: string }) {
16
- const { t } = useI18n()
17
- return (
18
- <div className="overflow-hidden rounded-2xl border bg-card">
19
- <div className="flex items-center gap-2 border-b px-3 py-2">
20
- <CopyButton text={snippet} className="size-7 shrink-0" label={t('common.copy')} />
21
- <span className="text-xs font-medium">{t('models.codeSnippetHeading')}</span>
22
- </div>
23
- <pre className="overflow-x-auto px-4 py-3 text-[11px] leading-relaxed"><code className="font-mono">{snippet}</code></pre>
24
- </div>
25
- )
26
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/src/components/auth-gate.desktop-browser.test.tsx DELETED
@@ -1,93 +0,0 @@
1
- // @vitest-environment jsdom
2
- //
3
- // #1399: the desktop app's dashboard opened in a normal browser tab has no
4
- // preload bridge. When the server reports `desktop: true` (a desktop install,
5
- // a request from this computer) the gate fetches a session from
6
- // /api/auth/desktop-session and never shows the Sign In form. Without the flag
7
- // (web and Docker installs) the form stays.
8
- import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
9
- import { act } from 'react'
10
- import { createRoot, type Root } from 'react-dom/client'
11
- import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
12
- import { I18nProvider } from '@/i18n'
13
- import { AuthGate } from './auth-gate'
14
-
15
- const MINTED = 'minted-desktop-session'
16
-
17
- let root: Root
18
- let container: HTMLDivElement
19
- let desktopFlag: boolean
20
- let sessionCalls: number
21
-
22
- function json(body: unknown, status = 200): Response {
23
- return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
24
- }
25
-
26
- async function flush() {
27
- for (let i = 0; i < 6; i++) {
28
- await act(async () => { await new Promise(r => setTimeout(r, 0)) })
29
- }
30
- }
31
-
32
- function mount() {
33
- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
34
- act(() => {
35
- root.render(
36
- <QueryClientProvider client={client}>
37
- <I18nProvider initialLocale="en">
38
- <AuthGate><div data-testid="app">dashboard</div></AuthGate>
39
- </I18nProvider>
40
- </QueryClientProvider>,
41
- )
42
- })
43
- }
44
-
45
- beforeAll(() => {
46
- ;(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true
47
- })
48
-
49
- beforeEach(() => {
50
- container = document.createElement('div')
51
- document.body.appendChild(container)
52
- root = createRoot(container)
53
- desktopFlag = true
54
- sessionCalls = 0
55
- vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
56
- const url = String(input)
57
- if (url.endsWith('/api/auth/desktop-session')) {
58
- sessionCalls++
59
- return desktopFlag ? json({ token: MINTED }) : json({ error: { message: 'forbidden' } }, 403)
60
- }
61
- if (url.endsWith('/api/auth/status')) {
62
- const ok = new Headers(init?.headers).get('Authorization') === `Bearer ${MINTED}`
63
- return json({ needsSetup: false, authenticated: ok, email: ok ? 'desktop@localhost' : null, desktop: desktopFlag })
64
- }
65
- return json({ error: { message: `unexpected ${url}` } }, 404)
66
- }))
67
- })
68
-
69
- afterEach(() => {
70
- act(() => root.unmount())
71
- container.remove()
72
- localStorage.clear()
73
- vi.unstubAllGlobals()
74
- })
75
-
76
- describe('AuthGate in a browser tab on a desktop install (#1399)', () => {
77
- it('signs in through the server and never shows the Sign In form', async () => {
78
- mount()
79
- await flush()
80
- expect(sessionCalls).toBe(1)
81
- expect(container.querySelector('[data-testid="app"]')).not.toBeNull()
82
- expect(container.querySelector('input[type="password"]')).toBeNull()
83
- })
84
-
85
- it('keeps the Sign In form when the server does not report a desktop install', async () => {
86
- desktopFlag = false
87
- mount()
88
- await flush()
89
- expect(sessionCalls).toBe(0)
90
- expect(container.querySelector('[data-testid="app"]')).toBeNull()
91
- expect(container.querySelector('input[type="password"]')).not.toBeNull()
92
- })
93
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/src/components/auth-gate.desktop.test.tsx DELETED
@@ -1,182 +0,0 @@
1
- // @vitest-environment jsdom
2
- //
3
- // The desktop shell signs the dashboard in as a hidden machine account whose
4
- // password is random and never shown (desktop/src/server-host.ts). If that
5
- // session is ever rejected — expired after a month of uptime, cleared by a
6
- // 401 — the gate must ask the shell for a fresh one, never show a login form
7
- // nobody can fill in. This mounts the real AuthGate against a stubbed
8
- // /api/auth/status and checks exactly that.
9
- import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
10
- import { act } from 'react'
11
- import { createRoot, type Root } from 'react-dom/client'
12
- import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
13
- import { I18nProvider } from '@/i18n'
14
- import { AuthGate } from './auth-gate'
15
-
16
- type DesktopWindow = Window & {
17
- __FREEAPI_DESKTOP__?: boolean
18
- __FREEAPI_SESSION__?: () => Promise<string>
19
- }
20
-
21
- const FRESH = 'fresh-session-token'
22
- const TOKEN_KEY = 'freellmapi_dashboard_token'
23
-
24
- let root: Root
25
- let container: HTMLDivElement
26
- let accepted: Set<string>
27
- let statusCalls: string[]
28
-
29
- function json(body: unknown, status = 200): Response {
30
- return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
31
- }
32
-
33
- async function flush() {
34
- for (let i = 0; i < 6; i++) {
35
- await act(async () => { await new Promise(r => setTimeout(r, 0)) })
36
- }
37
- }
38
-
39
- function mount() {
40
- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
41
- act(() => {
42
- root.render(
43
- <QueryClientProvider client={client}>
44
- <I18nProvider initialLocale="en">
45
- <AuthGate><div data-testid="app">dashboard</div></AuthGate>
46
- </I18nProvider>
47
- </QueryClientProvider>,
48
- )
49
- })
50
- }
51
-
52
- beforeAll(() => {
53
- ;(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true
54
- })
55
-
56
- beforeEach(() => {
57
- container = document.createElement('div')
58
- document.body.appendChild(container)
59
- root = createRoot(container)
60
- accepted = new Set()
61
- statusCalls = []
62
- localStorage.setItem(TOKEN_KEY, 'stale-token')
63
- vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
64
- const url = String(input)
65
- if (!url.endsWith('/api/auth/status')) return json({ error: { message: `unexpected ${url}` } }, 404)
66
- const auth = new Headers(init?.headers).get('Authorization') ?? ''
67
- statusCalls.push(auth)
68
- const ok = accepted.has(auth.replace(/^Bearer /, ''))
69
- return json({ needsSetup: false, authenticated: ok, email: ok ? 'desktop@localhost' : null })
70
- }))
71
- })
72
-
73
- afterEach(() => {
74
- act(() => root.unmount())
75
- container.remove()
76
- localStorage.clear()
77
- vi.unstubAllGlobals()
78
- const w = window as DesktopWindow
79
- delete w.__FREEAPI_DESKTOP__
80
- delete w.__FREEAPI_SESSION__
81
- })
82
-
83
- const passwordField = () => container.querySelector('input[type="password"]')
84
-
85
- describe('AuthGate inside the desktop shell', () => {
86
- it('replaces a rejected session through the shell and never shows the login form', async () => {
87
- const w = window as DesktopWindow
88
- w.__FREEAPI_DESKTOP__ = true
89
- const bridge = vi.fn(async () => {
90
- accepted.add(FRESH)
91
- return FRESH
92
- })
93
- w.__FREEAPI_SESSION__ = bridge
94
-
95
- mount()
96
- await flush()
97
-
98
- expect(bridge).toHaveBeenCalledTimes(1)
99
- expect(localStorage.getItem(TOKEN_KEY)).toBe(FRESH)
100
- expect(statusCalls.at(-1)).toBe(`Bearer ${FRESH}`)
101
- expect(container.querySelector('[data-testid="app"]')?.textContent).toBe('dashboard')
102
- expect(passwordField()).toBeNull()
103
- })
104
-
105
- it('shows the recovery message, not a password prompt, when the fresh session is rejected too', async () => {
106
- const w = window as DesktopWindow
107
- w.__FREEAPI_DESKTOP__ = true
108
- const bridge = vi.fn(async () => 'still-rejected')
109
- w.__FREEAPI_SESSION__ = bridge
110
-
111
- mount()
112
- await flush()
113
-
114
- expect(bridge).toHaveBeenCalledTimes(1)
115
- expect(passwordField()).toBeNull()
116
- expect(container.querySelector('[data-testid="app"]')).toBeNull()
117
- expect(container.textContent).toContain('Quit FreeLLMAPI and open it again')
118
- })
119
-
120
- // The recovery message is the whole screen: a screen reader that has already
121
- // announced "loading" must be told the wait ended in a failure.
122
- it('announces the recovery message as an alert', async () => {
123
- const w = window as DesktopWindow
124
- w.__FREEAPI_DESKTOP__ = true
125
- w.__FREEAPI_SESSION__ = vi.fn(async () => 'still-rejected')
126
-
127
- mount()
128
- await flush()
129
-
130
- const alert = container.querySelector('[role="alert"]')
131
- expect(alert).not.toBeNull()
132
- expect(alert?.textContent?.trim()).not.toBe('')
133
- })
134
- })
135
-
136
- describe('AuthGate in a browser', () => {
137
- it('still shows the sign-in form when the session is rejected', async () => {
138
- mount()
139
- await flush()
140
-
141
- expect(passwordField()).not.toBeNull()
142
- expect(container.querySelector('[data-testid="app"]')).toBeNull()
143
- })
144
-
145
- // Assertions are on the wiring, not the wording: the copy comes from t() and
146
- // is free to change, but a validation error nobody's input points at is
147
- // silent to a screen reader.
148
- it('ties each validation error to the field it describes', async () => {
149
- mount()
150
- await flush()
151
-
152
- const form = container.querySelector('form')!
153
- await act(async () => {
154
- form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
155
- })
156
-
157
- for (const id of ['auth-email', 'auth-password']) {
158
- const input = container.querySelector<HTMLInputElement>(`#${id}`)!
159
- const describedBy = input.getAttribute('aria-describedby')
160
- expect(describedBy).not.toBeNull()
161
- expect(input.getAttribute('aria-invalid')).toBe('true')
162
- const error = container.querySelector(`#${describedBy}`)!
163
- expect(error).not.toBeNull()
164
- expect(error.getAttribute('role')).toBe('alert')
165
- expect(error.textContent?.trim()).not.toBe('')
166
- }
167
- })
168
-
169
- it('gives every field a label pointing at it', async () => {
170
- mount()
171
- await flush()
172
-
173
- const inputs = [...container.querySelectorAll('input')]
174
- expect(inputs.length).toBeGreaterThan(0)
175
- for (const input of inputs) {
176
- expect(input.id).not.toBe('')
177
- const label = container.querySelector(`label[for="${input.id}"]`)
178
- expect(label, `no label for #${input.id}`).not.toBeNull()
179
- expect(label?.textContent?.trim()).not.toBe('')
180
- }
181
- })
182
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/src/components/auth-gate.login-identifier.test.tsx DELETED
@@ -1,121 +0,0 @@
1
- // @vitest-environment jsdom
2
- //
3
- // The desktop app seeds a hidden account named `desktop@localhost`. The login
4
- // route accepts that identifier on purpose, but the form used to reject it
5
- // client-side ("Enter a valid email address") before any request was sent, so
6
- // a desktop user who opened the dashboard in a browser could reset the
7
- // password and still never sign in (#1250). Setup keeps the strict check.
8
- import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
9
- import { act } from 'react'
10
- import { createRoot, type Root } from 'react-dom/client'
11
- import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
12
- import { I18nProvider } from '@/i18n'
13
- import { AuthGate } from './auth-gate'
14
-
15
- let root: Root
16
- let container: HTMLDivElement
17
- let needsSetup: boolean
18
- let posts: { url: string; body: Record<string, string> }[]
19
-
20
- function json(body: unknown, status = 200): Response {
21
- return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
22
- }
23
-
24
- async function flush() {
25
- for (let i = 0; i < 6; i++) {
26
- await act(async () => { await new Promise(r => setTimeout(r, 0)) })
27
- }
28
- }
29
-
30
- function mount() {
31
- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
32
- act(() => {
33
- root.render(
34
- <QueryClientProvider client={client}>
35
- <I18nProvider initialLocale="en">
36
- <AuthGate><div data-testid="app">dashboard</div></AuthGate>
37
- </I18nProvider>
38
- </QueryClientProvider>,
39
- )
40
- })
41
- }
42
-
43
- function type(selector: string, value: string) {
44
- const input = container.querySelector<HTMLInputElement>(selector)!
45
- const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!
46
- act(() => {
47
- setter.call(input, value)
48
- input.dispatchEvent(new Event('input', { bubbles: true }))
49
- })
50
- }
51
-
52
- async function submit() {
53
- const form = container.querySelector('form')!
54
- act(() => { form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })) })
55
- await flush()
56
- }
57
-
58
- beforeAll(() => {
59
- ;(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true
60
- })
61
-
62
- beforeEach(() => {
63
- container = document.createElement('div')
64
- document.body.appendChild(container)
65
- root = createRoot(container)
66
- needsSetup = false
67
- posts = []
68
- vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
69
- const url = String(input)
70
- if (url.endsWith('/api/auth/status')) return json({ needsSetup, authenticated: false, email: null })
71
- if (init?.method === 'POST') {
72
- posts.push({ url, body: JSON.parse(String(init.body)) })
73
- return json({ error: { message: 'Invalid email or password' } }, 401)
74
- }
75
- return json({ error: { message: `unexpected ${url}` } }, 404)
76
- }))
77
- })
78
-
79
- afterEach(() => {
80
- act(() => root.unmount())
81
- container.remove()
82
- localStorage.clear()
83
- vi.unstubAllGlobals()
84
- })
85
-
86
- describe('AuthGate login identifier', () => {
87
- it('sends the desktop account identifier to the login route instead of blocking it', async () => {
88
- mount()
89
- await flush()
90
- type('#auth-email', 'desktop@localhost')
91
- type('#auth-password', 'a-new-password')
92
- await submit()
93
-
94
- expect(posts).toHaveLength(1)
95
- expect(posts[0].url.endsWith('/api/auth/login')).toBe(true)
96
- expect(posts[0].body.email).toBe('desktop@localhost')
97
- expect(container.querySelector('#auth-email-error')).toBeNull()
98
- })
99
-
100
- it('still requires something in the email field on login', async () => {
101
- mount()
102
- await flush()
103
- type('#auth-password', 'a-new-password')
104
- await submit()
105
-
106
- expect(posts).toHaveLength(0)
107
- expect(container.querySelector('#auth-email-error')).not.toBeNull()
108
- })
109
-
110
- it('keeps the strict email check when creating the first account', async () => {
111
- needsSetup = true
112
- mount()
113
- await flush()
114
- type('#auth-email', 'desktop@localhost')
115
- type('#auth-password', 'a-long-enough-password')
116
- await submit()
117
-
118
- expect(posts).toHaveLength(0)
119
- expect(container.querySelector('#auth-email-error')?.textContent).toContain('valid email')
120
- })
121
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/src/components/auth-gate.reset-signs-in.test.tsx DELETED
@@ -1,124 +0,0 @@
1
- // @vitest-environment jsdom
2
- //
3
- // A password reset used to end on "Please sign in", but the login form needs
4
- // the account email, which an operator who forgot the password may not
5
- // remember either (#1477). The server now signs them in after a valid reset
6
- // code; the form must store that session and open the dashboard.
7
- import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
8
- import { act } from 'react'
9
- import { createRoot, type Root } from 'react-dom/client'
10
- import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
11
- import { I18nProvider } from '@/i18n'
12
- import { AuthGate } from './auth-gate'
13
- import { getToken } from '@/lib/api'
14
-
15
- let root: Root
16
- let container: HTMLDivElement
17
- let authenticated: boolean
18
- let resetResponse: { status: number; body: unknown }
19
- let posts: { url: string; body: Record<string, string> | null }[]
20
-
21
- function json(body: unknown, status = 200): Response {
22
- return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
23
- }
24
-
25
- async function flush() {
26
- for (let i = 0; i < 6; i++) {
27
- await act(async () => { await new Promise(r => setTimeout(r, 0)) })
28
- }
29
- }
30
-
31
- function mount() {
32
- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
33
- act(() => {
34
- root.render(
35
- <QueryClientProvider client={client}>
36
- <I18nProvider initialLocale="en">
37
- <AuthGate><div data-testid="app">dashboard</div></AuthGate>
38
- </I18nProvider>
39
- </QueryClientProvider>,
40
- )
41
- })
42
- }
43
-
44
- function type(selector: string, value: string) {
45
- const input = container.querySelector<HTMLInputElement>(selector)!
46
- const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!
47
- act(() => {
48
- setter.call(input, value)
49
- input.dispatchEvent(new Event('input', { bubbles: true }))
50
- })
51
- }
52
-
53
- async function clickButton(label: string) {
54
- const button = [...container.querySelectorAll('button')].find(b => b.textContent === label)!
55
- act(() => { button.click() })
56
- await flush()
57
- }
58
-
59
- async function resetWithCode() {
60
- mount()
61
- await flush()
62
- await clickButton('Forgot password?')
63
- await clickButton('Send reset code')
64
- type('#reset-code', 'ABCDEFGHIJ')
65
- type('#reset-new-password', 'brand-new-password')
66
- const form = container.querySelector('form')!
67
- act(() => { form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })) })
68
- await flush()
69
- }
70
-
71
- beforeAll(() => {
72
- ;(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true
73
- })
74
-
75
- beforeEach(() => {
76
- container = document.createElement('div')
77
- document.body.appendChild(container)
78
- root = createRoot(container)
79
- authenticated = false
80
- posts = []
81
- resetResponse = { status: 200, body: { success: true, token: 'session-after-reset', email: 'owner@example.test' } }
82
- vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
83
- const url = String(input)
84
- if (url.endsWith('/api/auth/status')) {
85
- return json({ needsSetup: false, authenticated, email: authenticated ? 'owner@example.test' : null })
86
- }
87
- if (init?.method === 'POST') {
88
- posts.push({ url, body: init.body ? JSON.parse(String(init.body)) : null })
89
- if (url.endsWith('/api/auth/forgot-password')) return json({ success: true })
90
- if (url.endsWith('/api/auth/reset-password')) {
91
- if (resetResponse.status === 200) authenticated = true
92
- return json(resetResponse.body, resetResponse.status)
93
- }
94
- }
95
- return json({ error: { message: `unexpected ${url}` } }, 404)
96
- }))
97
- })
98
-
99
- afterEach(() => {
100
- act(() => root.unmount())
101
- container.remove()
102
- localStorage.clear()
103
- vi.unstubAllGlobals()
104
- })
105
-
106
- describe('AuthGate password reset', () => {
107
- it('signs in with the session the reset returns instead of asking for the email', async () => {
108
- await resetWithCode()
109
-
110
- expect(posts.map(p => p.url.replace(/^.*\/api/, '/api'))).toEqual(['/api/auth/forgot-password', '/api/auth/reset-password'])
111
- expect(posts[1].body).toEqual({ resetCode: 'ABCDEFGHIJ', newPassword: 'brand-new-password' })
112
- expect(getToken()).toBe('session-after-reset')
113
- expect(container.querySelector('[data-testid="app"]')).not.toBeNull()
114
- })
115
-
116
- it('stays on the reset form with the error when the code is wrong', async () => {
117
- resetResponse = { status: 403, body: { error: { message: 'Invalid or expired reset code' } } }
118
- await resetWithCode()
119
-
120
- expect(getToken()).toBeNull()
121
- expect(container.querySelector('[data-testid="app"]')).toBeNull()
122
- expect(container.textContent).toContain('Invalid or expired reset code')
123
- })
124
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/src/components/auth-gate.tsx DELETED
@@ -1,547 +0,0 @@
1
- import { useEffect, useRef, useState, type ReactNode } from 'react'
2
- import { useQuery, useQueryClient } from '@tanstack/react-query'
3
- import { Loader2 } from 'lucide-react'
4
- import { apiFetch, setToken, UNAUTHORIZED_EVENT, type ApiError } from '@/lib/api'
5
- import { Button } from '@/components/ui/button'
6
- import { FieldError } from '@/components/ui/field-error'
7
- import { Input } from '@/components/ui/input'
8
- import { PasswordInput } from '@/components/ui/password-input'
9
- import { Label } from '@/components/ui/label'
10
- import { isEmail } from '@/lib/validate'
11
- import { useI18n } from '@/i18n'
12
- import { toast } from '@/lib/toast'
13
-
14
- // Matches the server rule (routes/auth.ts zod schema).
15
- const PASSWORD_MIN = 8
16
-
17
- // Inside the desktop shell the dashboard runs as a hidden machine account with
18
- // a random password nobody knows (desktop/src/server-host.ts). There are no
19
- // credentials to type, so the gate never shows a login form there: when the
20
- // seeded session is gone (expired after a month of uptime, or cleared by a
21
- // 401) it asks the shell for a fresh one through the preload bridge.
22
- type DesktopWindow = Window & {
23
- __FREEAPI_DESKTOP__?: boolean
24
- __FREEAPI_SESSION__?: () => Promise<string>
25
- }
26
- function desktopSessionBridge(): (() => Promise<string>) | null {
27
- if (typeof window === 'undefined') return null
28
- const w = window as DesktopWindow
29
- return w.__FREEAPI_DESKTOP__ === true && typeof w.__FREEAPI_SESSION__ === 'function'
30
- ? w.__FREEAPI_SESSION__
31
- : null
32
- }
33
-
34
- // The same dashboard opened in a normal browser tab on a desktop install has no
35
- // preload bridge, so the server mints the session instead (#1399). It only
36
- // does so for a request from this computer, and says so through `desktop` on
37
- // /api/auth/status; web and Docker installs never set it and keep their login.
38
- async function browserDesktopSession(): Promise<string> {
39
- const res = await apiFetch<{ token: string }>('/api/auth/desktop-session', { method: 'POST' })
40
- return res.token
41
- }
42
-
43
- interface AuthStatus {
44
- needsSetup: boolean
45
- authenticated: boolean
46
- email: string | null
47
- desktop?: boolean
48
- }
49
-
50
- function Centered({ children }: { children: ReactNode }) {
51
- // dvh, not vh: on mobile the collapsing URL bar and the software keyboard both
52
- // change the viewport, and 100vh leaves the card parked mid-scroll.
53
- return (
54
- <main className="min-h-dvh flex items-center justify-center bg-background px-4 py-10">
55
- <div className="w-full max-w-sm">{children}</div>
56
- </main>
57
- )
58
- }
59
-
60
- function AuthForm({ mode, onAuthed }: { mode: 'setup' | 'login'; onAuthed: () => void }) {
61
- const { t } = useI18n()
62
- const [email, setEmail] = useState('')
63
- const [password, setPassword] = useState('')
64
- const [setupCode, setSetupCode] = useState('')
65
- // Revealed only after the server asks for it (remote first-run setup). A
66
- // browser on the same machine as the server never sees this field.
67
- const [codeRequired, setCodeRequired] = useState(false)
68
- const [error, setError] = useState('')
69
- const [busy, setBusy] = useState(false)
70
- const [attempted, setAttempted] = useState(false)
71
- const [showForgot, setShowForgot] = useState(false)
72
-
73
- const isSetup = mode === 'setup'
74
-
75
- // Inline field feedback; the server stays authoritative. Only the setup form
76
- // enforces the password minimum client-side (an existing password of any
77
- // length must still be able to log in). The same goes for the email shape:
78
- // the desktop app's hidden account is `desktop@localhost` (no TLD), which
79
- // the login route accepts on purpose (server/src/routes/auth.ts), so a
80
- // browser tab must be able to submit it after a password reset (#1250).
81
- const emailError = !email.trim()
82
- ? t('validation.required')
83
- : isSetup && !isEmail(email)
84
- ? t('validation.email')
85
- : null
86
- const passwordError = !password
87
- ? t('validation.required')
88
- : isSetup && password.length < PASSWORD_MIN
89
- ? t('validation.passwordMin', { min: PASSWORD_MIN })
90
- : null
91
-
92
- const showEmailError = attempted && !!emailError
93
- const showPasswordError = attempted && !!passwordError
94
-
95
- async function submit(e: React.FormEvent) {
96
- e.preventDefault()
97
- if (emailError || passwordError) {
98
- setAttempted(true)
99
- return
100
- }
101
- setBusy(true)
102
- setError('')
103
- try {
104
- const payload: Record<string, string> = { email, password }
105
- // Only the setup flow carries a code, and only once the server has asked
106
- // for it. The server ignores it for local (loopback) setup.
107
- if (isSetup && setupCode) payload.setupCode = setupCode.trim()
108
- const res = await apiFetch<{ token: string }>(isSetup ? '/api/auth/setup' : '/api/auth/login', {
109
- method: 'POST',
110
- body: JSON.stringify(payload),
111
- })
112
- setToken(res.token)
113
- onAuthed()
114
- } catch (err) {
115
- // The server gates remote first-run setup behind a one-time code; reveal
116
- // the field so the operator can paste the code from the server logs.
117
- if (isSetup && (err as ApiError).code === 'setup_code_required') {
118
- setCodeRequired(true)
119
- }
120
- setError((err as Error).message)
121
- } finally {
122
- setBusy(false)
123
- }
124
- }
125
-
126
- if (showForgot && !isSetup) {
127
- return <ForgotPasswordForm onBack={() => setShowForgot(false)} onAuthed={onAuthed} />
128
- }
129
-
130
- return (
131
- <Centered>
132
- <div className="mb-6 flex items-center gap-2">
133
- <span className="inline-block size-2 rounded-full bg-foreground" />
134
- <span className="font-semibold tracking-tight text-sm">FreeLLMAPI</span>
135
- </div>
136
- <div className="rounded-3xl border bg-card p-6">
137
- <h1 className="text-lg font-semibold tracking-tight">{isSetup ? t('auth.createYourAccount') : t('auth.signIn')}</h1>
138
- <p className="text-sm text-muted-foreground mt-1.5 mb-6">
139
- {isSetup
140
- ? t('auth.setupDescription')
141
- : t('auth.loginDescription')}
142
- </p>
143
- <form onSubmit={submit} className="space-y-4" noValidate>
144
- <div className="space-y-1.5">
145
- <Label className="text-xs" htmlFor="auth-email">{t('auth.email')}</Label>
146
- <Input
147
- id="auth-email"
148
- type="email"
149
- autoComplete="username"
150
- autoFocus
151
- value={email}
152
- onChange={e => setEmail(e.target.value)}
153
- placeholder={t('auth.emailPlaceholder')}
154
- aria-invalid={showEmailError}
155
- aria-describedby={showEmailError ? 'auth-email-error' : undefined}
156
- />
157
- {attempted && <FieldError id="auth-email-error" error={emailError} />}
158
- </div>
159
- <div className="space-y-1.5">
160
- <Label className="text-xs" htmlFor="auth-password">{t('auth.password')}</Label>
161
- <PasswordInput
162
- id="auth-password"
163
- autoComplete={isSetup ? 'new-password' : 'current-password'}
164
- value={password}
165
- onChange={e => setPassword(e.target.value)}
166
- placeholder={isSetup ? t('auth.passwordPlaceholderSetup') : t('auth.passwordPlaceholderLogin')}
167
- aria-invalid={showPasswordError}
168
- aria-describedby={showPasswordError ? 'auth-password-error' : undefined}
169
- />
170
- {attempted && <FieldError id="auth-password-error" error={passwordError} />}
171
- </div>
172
- {isSetup && codeRequired && (
173
- <div className="space-y-1.5">
174
- <Label className="text-xs" htmlFor="auth-setup-code">{t('auth.setupCode')}</Label>
175
- <Input
176
- id="auth-setup-code"
177
- type="text"
178
- autoComplete="off"
179
- value={setupCode}
180
- onChange={e => setSetupCode(e.target.value)}
181
- placeholder={t('auth.setupCodePlaceholder')}
182
- aria-describedby="auth-setup-code-hint"
183
- />
184
- <p id="auth-setup-code-hint" className="text-xs text-muted-foreground">{t('auth.setupCodeHint')}</p>
185
- </div>
186
- )}
187
- {/* A server rejection is the one error nobody can predict; it gets the same
188
- announcement and the same visual weight as the inline field errors. */}
189
- {error && (
190
- <p role="alert" className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive">
191
- {error}
192
- </p>
193
- )}
194
- <Button type="submit" className="w-full h-10" disabled={busy}>
195
- {busy && <Loader2 className="animate-spin" aria-hidden />}
196
- {busy ? (isSetup ? t('auth.creating') : t('auth.signingIn')) : isSetup ? t('auth.createAccount') : t('auth.signIn')}
197
- </Button>
198
- </form>
199
- {!isSetup && (
200
- <button
201
- type="button"
202
- onClick={() => setShowForgot(true)}
203
- className="mt-3 w-full text-center text-xs text-muted-foreground hover:text-foreground transition-colors"
204
- >
205
- {t('auth.forgotPassword')}
206
- </button>
207
- )}
208
- </div>
209
- </Centered>
210
- )
211
- }
212
-
213
- // Forgot / Reset password flow
214
-
215
- type ForgotStep = 'request' | 'reset' | 'done'
216
-
217
- function ForgotPasswordForm({ onBack, onAuthed }: { onBack: () => void; onAuthed: () => void }) {
218
- const { t } = useI18n()
219
- const [step, setStep] = useState<ForgotStep>('request')
220
- const [resetCode, setResetCode] = useState('')
221
- const [newPassword, setNewPassword] = useState('')
222
- const [error, setError] = useState('')
223
- const [busy, setBusy] = useState(false)
224
- const [attempted, setAttempted] = useState(false)
225
-
226
- const passwordError = !newPassword
227
- ? t('validation.required')
228
- : newPassword.length < PASSWORD_MIN
229
- ? t('validation.passwordMin', { min: PASSWORD_MIN })
230
- : null
231
- const codeError = !resetCode.trim() ? t('validation.required') : null
232
-
233
- async function requestCode() {
234
- setBusy(true)
235
- setError('')
236
- try {
237
- await apiFetch('/api/auth/forgot-password', { method: 'POST' })
238
- setStep('reset')
239
- } catch (err) {
240
- setError((err as Error).message)
241
- } finally {
242
- setBusy(false)
243
- }
244
- }
245
-
246
- async function submitReset(e: React.FormEvent) {
247
- e.preventDefault()
248
- if (codeError || passwordError) {
249
- setAttempted(true)
250
- return
251
- }
252
- setBusy(true)
253
- setError('')
254
- try {
255
- const res = await apiFetch<{ token?: string }>('/api/auth/reset-password', {
256
- method: 'POST',
257
- body: JSON.stringify({ resetCode: resetCode.trim(), newPassword }),
258
- })
259
- // The server signs the operator in after a reset, so nobody has to
260
- // remember which email the account uses (#1477).
261
- if (res.token) {
262
- setToken(res.token)
263
- onAuthed()
264
- return
265
- }
266
- setStep('done')
267
- } catch (err) {
268
- setError((err as Error).message)
269
- } finally {
270
- setBusy(false)
271
- }
272
- }
273
-
274
- return (
275
- <Centered>
276
- <div className="mb-6 flex items-center gap-2">
277
- <span className="inline-block size-2 rounded-full bg-foreground" />
278
- <span className="font-semibold tracking-tight text-sm">FreeLLMAPI</span>
279
- </div>
280
- <div className="rounded-3xl border bg-card p-6">
281
- <h1 className="text-base font-medium">{t('auth.forgotPassword')}</h1>
282
-
283
- {step === 'request' && (
284
- <div className="mt-1 space-y-3">
285
- <p className="text-xs text-muted-foreground mb-4">{t('auth.forgotPasswordDescription')}</p>
286
- {error && <p className="text-destructive text-xs">{error}</p>}
287
- <Button className="w-full" disabled={busy} onClick={requestCode}>
288
- {busy ? t('auth.requestingResetCode') : t('auth.requestResetCode')}
289
- </Button>
290
- </div>
291
- )}
292
-
293
- {step === 'reset' && (
294
- <form onSubmit={submitReset} className="space-y-3 mt-4" noValidate>
295
- <p className="text-xs text-muted-foreground">{t('auth.resetCodeHint')}</p>
296
- <p className="text-xs text-muted-foreground">{t('auth.resetCodeDockerHint')}</p>
297
- <div className="space-y-1.5">
298
- <Label className="text-xs" htmlFor="reset-code">{t('auth.resetCode')}</Label>
299
- <Input
300
- id="reset-code"
301
- type="text"
302
- autoComplete="off"
303
- value={resetCode}
304
- onChange={e => setResetCode(e.target.value)}
305
- placeholder={t('auth.resetCodePlaceholder')}
306
- aria-invalid={attempted && !!codeError}
307
- />
308
- {attempted && <FieldError error={codeError} />}
309
- </div>
310
- <div className="space-y-1.5">
311
- <Label className="text-xs" htmlFor="reset-new-password">{t('auth.newPassword')}</Label>
312
- <PasswordInput
313
- id="reset-new-password"
314
- autoComplete="new-password"
315
- value={newPassword}
316
- onChange={e => setNewPassword(e.target.value)}
317
- placeholder={t('auth.passwordPlaceholderSetup')}
318
- aria-invalid={attempted && !!passwordError}
319
- />
320
- {attempted && <FieldError error={passwordError} />}
321
- </div>
322
- {error && <p className="text-destructive text-xs">{error}</p>}
323
- <Button type="submit" className="w-full" disabled={busy}>
324
- {busy ? t('auth.resettingPassword') : t('auth.resetPassword')}
325
- </Button>
326
- </form>
327
- )}
328
-
329
- {step === 'done' && (
330
- <p className="text-xs text-muted-foreground mt-1 mb-4">{t('auth.passwordReset')}</p>
331
- )}
332
-
333
- <button
334
- type="button"
335
- onClick={onBack}
336
- className="mt-3 w-full text-center text-xs text-muted-foreground hover:text-foreground transition-colors"
337
- >
338
- {t('auth.backToLogin')}
339
- </button>
340
- </div>
341
- </Centered>
342
- )
343
- }
344
-
345
- // Change-credentials modal (rendered inside the authenticated shell)
346
-
347
- interface ChangeCredentialsModalProps {
348
- mode: 'password' | 'email'
349
- onClose: () => void
350
- }
351
-
352
- export function ChangeCredentialsModal({ mode, onClose }: ChangeCredentialsModalProps) {
353
- const { t } = useI18n()
354
- const [currentPassword, setCurrentPassword] = useState('')
355
- const [newValue, setNewValue] = useState('')
356
- const [error, setError] = useState('')
357
- const [busy, setBusy] = useState(false)
358
- const [attempted, setAttempted] = useState(false)
359
-
360
- const isPassword = mode === 'password'
361
-
362
- const newValueError = !newValue.trim()
363
- ? t('validation.required')
364
- : isPassword && newValue.length < PASSWORD_MIN
365
- ? t('validation.passwordMin', { min: PASSWORD_MIN })
366
- : !isPassword && !isEmail(newValue)
367
- ? t('validation.email')
368
- : null
369
- const currentPwError = !currentPassword ? t('validation.required') : null
370
-
371
- async function submit(e: React.FormEvent) {
372
- e.preventDefault()
373
- if (newValueError || currentPwError) {
374
- setAttempted(true)
375
- return
376
- }
377
- setBusy(true)
378
- setError('')
379
- try {
380
- if (isPassword) {
381
- await apiFetch('/api/auth/change-password', {
382
- method: 'POST',
383
- body: JSON.stringify({ currentPassword, newPassword: newValue }),
384
- })
385
- toast.success(t('auth.passwordChanged'))
386
- } else {
387
- await apiFetch('/api/auth/change-email', {
388
- method: 'POST',
389
- body: JSON.stringify({ currentPassword, newEmail: newValue }),
390
- })
391
- toast.success(t('auth.emailChanged'))
392
- }
393
- onClose()
394
- } catch (err) {
395
- setError((err as Error).message)
396
- } finally {
397
- setBusy(false)
398
- }
399
- }
400
-
401
- return (
402
- <div
403
- className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4"
404
- onClick={e => { if (e.target === e.currentTarget) onClose() }}
405
- >
406
- <div className="w-full max-w-sm rounded-3xl border bg-card p-6 shadow-xl">
407
- <h2 className="text-base font-medium mb-1">
408
- {isPassword ? t('auth.changePassword') : t('auth.changeEmail')}
409
- </h2>
410
- <form onSubmit={submit} className="space-y-3 mt-4" noValidate>
411
- <div className="space-y-1.5">
412
- <Label className="text-xs" htmlFor="cred-current-password">{t('auth.currentPassword')}</Label>
413
- <PasswordInput
414
- id="cred-current-password"
415
- autoComplete="current-password"
416
- value={currentPassword}
417
- onChange={e => setCurrentPassword(e.target.value)}
418
- placeholder={t('auth.passwordPlaceholderLogin')}
419
- aria-invalid={attempted && !!currentPwError}
420
- />
421
- {attempted && <FieldError error={currentPwError} />}
422
- </div>
423
- <div className="space-y-1.5">
424
- <Label className="text-xs" htmlFor="cred-new-value">
425
- {isPassword ? t('auth.newPassword') : t('auth.newEmail')}
426
- </Label>
427
- {isPassword ? <PasswordInput
428
- id="cred-new-value"
429
- autoComplete="new-password"
430
- value={newValue}
431
- onChange={e => setNewValue(e.target.value)}
432
- placeholder={t('auth.passwordPlaceholderSetup')}
433
- aria-invalid={attempted && !!newValueError}
434
- /> : <Input
435
- id="cred-new-value"
436
- type="email"
437
- autoComplete="email"
438
- value={newValue}
439
- onChange={e => setNewValue(e.target.value)}
440
- placeholder={t('auth.emailPlaceholder')}
441
- aria-invalid={attempted && !!newValueError}
442
- />}
443
- {attempted && <FieldError error={newValueError} />}
444
- </div>
445
- {error && <p className="text-destructive text-xs">{error}</p>}
446
- <div className="flex gap-2 pt-1">
447
- <Button type="button" variant="outline" className="flex-1" onClick={onClose} disabled={busy}>
448
- {t('common.cancel')}
449
- </Button>
450
- <Button type="submit" className="flex-1" disabled={busy}>
451
- {busy
452
- ? (isPassword ? t('auth.changingPassword') : t('auth.changingEmail'))
453
- : t('common.save')}
454
- </Button>
455
- </div>
456
- </form>
457
- </div>
458
- </div>
459
- )
460
- }
461
-
462
- export function AuthGate({ children }: { children: ReactNode }) {
463
- const { t } = useI18n()
464
- const queryClient = useQueryClient()
465
- const { data, isLoading, isError, refetch } = useQuery<AuthStatus>({
466
- queryKey: ['auth-status'],
467
- queryFn: () => apiFetch('/api/auth/status'),
468
- retry: false,
469
- })
470
-
471
- useEffect(() => {
472
- const handler = () => { refetch() }
473
- window.addEventListener(UNAUTHORIZED_EVENT, handler)
474
- return () => window.removeEventListener(UNAUTHORIZED_EVENT, handler)
475
- }, [refetch])
476
-
477
- // Desktop self-repair: one attempt at a time, and none after the shell has
478
- // handed back a session the server still rejects — a broken install shows a
479
- // message instead of looping.
480
- const desktopSession = desktopSessionBridge() ?? (data?.desktop ? browserDesktopSession : null)
481
- const desktopNeedsSession = !!desktopSession && !!data && (data.needsSetup || !data.authenticated)
482
- const repairing = useRef(false)
483
- const [repairFailed, setRepairFailed] = useState(false)
484
- useEffect(() => {
485
- if (!desktopNeedsSession || !desktopSession || repairing.current || repairFailed) return
486
- repairing.current = true
487
- ;(async () => {
488
- try {
489
- const token = await desktopSession()
490
- if (!token) throw new Error('empty session token')
491
- setToken(token)
492
- queryClient.invalidateQueries()
493
- const next = await refetch()
494
- if (!next.data?.authenticated) setRepairFailed(true)
495
- } catch (err) {
496
- console.error('[auth-gate] desktop session repair failed', err)
497
- setRepairFailed(true)
498
- } finally {
499
- repairing.current = false
500
- }
501
- })()
502
- }, [desktopNeedsSession, desktopSession, repairFailed, queryClient, refetch])
503
-
504
- function onAuthed() {
505
- // New session: drop any cached (unauthenticated) data and re-check status.
506
- queryClient.invalidateQueries()
507
- refetch()
508
- }
509
-
510
- if (isLoading) {
511
- return (
512
- <Centered>
513
- <p className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
514
- <Loader2 className="size-3.5 animate-spin" aria-hidden />
515
- {t('auth.loading')}
516
- </p>
517
- </Centered>
518
- )
519
- }
520
- if (isError || !data) {
521
- return (
522
- <Centered>
523
- <div role="alert" className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2.5 text-xs text-destructive">
524
- {t('auth.serverUnreachableBefore')}<code className="font-mono">npm run dev</code>{t('auth.serverUnreachableAfter')}
525
- </div>
526
- </Centered>
527
- )
528
- }
529
-
530
- if (desktopNeedsSession) {
531
- if (repairFailed) {
532
- return (
533
- <Centered>
534
- <div role="alert" className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2.5 text-xs text-destructive">
535
- {t('auth.desktopSessionFailed')}
536
- </div>
537
- </Centered>
538
- )
539
- }
540
- return <Centered><p className="flex items-center justify-center gap-2 text-sm text-muted-foreground"><Loader2 className="size-3.5 animate-spin" aria-hidden />{t('auth.loading')}</p></Centered>
541
- }
542
- if (data.needsSetup) return <AuthForm mode="setup" onAuthed={onAuthed} />
543
- if (!data.authenticated) return <AuthForm mode="login" onAuthed={onAuthed} />
544
-
545
- return <>{children}</>
546
- }
547
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/src/components/chain-manager.test.ts DELETED
@@ -1,116 +0,0 @@
1
- import { readdirSync, readFileSync } from 'node:fs'
2
- import path from 'node:path'
3
- import { fileURLToPath } from 'node:url'
4
- import { describe, expect, it } from 'vitest'
5
-
6
- // The chain manager is the dashboard surface for named fallback chains
7
- // (#960/#895). Two things about it are easy to break by accident and are
8
- // pinned here: every string it renders has to exist in all 60 locales, and it
9
- // has to stay a secondary panel on the Fallback page rather than growing into
10
- // its own nav entry — one chain is all most installs ever use.
11
- const here = path.dirname(fileURLToPath(import.meta.url))
12
- const localeDir = path.join(here, '../i18n/locales')
13
- const source = readFileSync(path.join(here, 'chain-manager.tsx'), 'utf8')
14
- const fallbackPage = readFileSync(path.join(here, '../pages/FallbackPage.tsx'), 'utf8')
15
- const app = readFileSync(path.join(here, '../App.tsx'), 'utf8')
16
- const playground = readFileSync(path.join(here, '../pages/PlaygroundPage.tsx'), 'utf8')
17
-
18
- function locale(name: string): Record<string, unknown> {
19
- return JSON.parse(readFileSync(path.join(localeDir, `${name}.json`), 'utf8'))
20
- }
21
-
22
- function lookup(dictionary: Record<string, unknown>, key: string): unknown {
23
- return key.split('.').reduce<unknown>(
24
- (node, part) => (node && typeof node === 'object' ? (node as Record<string, unknown>)[part] : undefined),
25
- dictionary,
26
- )
27
- }
28
-
29
- const locales = readdirSync(localeDir)
30
- .filter(name => name.endsWith('.json'))
31
- .map(name => name.slice(0, -5))
32
-
33
- // Every t('...') the component actually calls.
34
- const usedKeys = [...source.matchAll(/\bt\('([^']+)'/g)].map(match => match[1])
35
-
36
- describe('chain manager', () => {
37
- it('calls only keys that exist in every locale', () => {
38
- expect(usedKeys.length).toBeGreaterThan(5)
39
- expect(usedKeys).toContain('chains.title')
40
- expect(locales.length).toBeGreaterThan(50)
41
-
42
- for (const name of locales) {
43
- const dictionary = locale(name)
44
- for (const key of usedKeys) {
45
- expect(typeof lookup(dictionary, key), `${name} is missing ${key}`).toBe('string')
46
- }
47
- }
48
- })
49
-
50
- it('keeps the {name} and {count} placeholders in every locale', () => {
51
- for (const name of locales) {
52
- const dictionary = locale(name)
53
- expect(lookup(dictionary, 'chains.deleteConfirm'), `${name}.chains.deleteConfirm`)
54
- .toContain('{name}')
55
- expect(lookup(dictionary, 'chains.count'), `${name}.chains.count`).toContain('{count}')
56
- }
57
- })
58
-
59
- it('lives on the Fallback page as a collapsible panel, not a nav entry', () => {
60
- expect(fallbackPage).toContain("import { ChainManager } from '@/components/chain-manager'")
61
- expect(fallbackPage).toContain('<ChainManager />')
62
- // Collapsed by default and remembered per browser, like the penalty
63
- // inspector next to it — the routing table is what the page is for.
64
- expect(source).toContain('aria-expanded')
65
- expect(source).toMatch(/stored === null \? true : stored === '1'/)
66
- // No route or nav destination of its own.
67
- expect(app).not.toContain('chain-manager')
68
- expect(app).not.toContain('ChainManager')
69
- })
70
-
71
- it('surfaces the server error when a chain name is rejected', () => {
72
- // POST /api/profiles enforces length, character set, reserved words and
73
- // uniqueness. Swallowing that 400/409 leaves a button that does nothing.
74
- expect(source).toContain('onError')
75
- expect(source).toContain('setCreateError')
76
- })
77
-
78
- it('renames a chain through the profile update endpoint, with a confirm (#1179)', () => {
79
- // A chain's name is the address clients route with (auto:<name>), so the
80
- // rename goes through PUT /api/profiles/:id — where the creation rules
81
- // are enforced and protected chains get a real 403 — and must warn about
82
- // in-flight auto:<old-name> callers before committing.
83
- expect(source).toMatch(/api\/profiles\/\$\{profileId\}`, \{ method: 'PUT'/)
84
- expect(source).not.toContain('/rename')
85
- expect(source).toContain('chains.renameConfirm')
86
- expect(source).toContain('chains.renameFailed')
87
- // Only custom chains get the pencil, matching the delete affordance.
88
- expect(source).toMatch(/!isProtected[\s\S]*?chains\.renameHint/)
89
- })
90
- })
91
-
92
- // Switching the active chain has to change what the rest of the dashboard is
93
- // looking at (#1021). Both of these were silently wrong: the routing table read
94
- // one unscoped cache entry, so a switch re-rendered the previous chain's rows
95
- // and a save wrote them into the new chain; and the Playground could only ever
96
- // send 'auto', so a chain you had just built was untestable from the dashboard.
97
- describe('chains reach the rest of the dashboard (#1021)', () => {
98
- it('scopes the fallback table and its staged edits to the active chain', () => {
99
- expect(fallbackPage).toContain("queryKey: ['profiles', 'active']")
100
- expect(fallbackPage).toContain("queryKey: ['fallback', 'chain', activeProfileId]")
101
- // Staged edits remember which chain they were made against instead of
102
- // following whichever one happens to be active at save time.
103
- expect(fallbackPage).toMatch(/staged\.profileId === activeProfileId/)
104
- })
105
-
106
- it('offers every custom chain in the playground picker as auto:<name>', () => {
107
- expect(playground).toContain("queryKey: ['profiles']")
108
- // The id has to be derived exactly as the server derives it in
109
- // routes/proxy.ts, or the picker offers models /v1/models never listed.
110
- expect(playground).toContain('`auto:${c.name.toLowerCase()}`')
111
- expect(playground).toContain('...chainOptions,')
112
- // A chain is server-picked like plain auto, so the "can't see images" hint
113
- // must not fire on one.
114
- expect(playground).toContain("!selectedModel.startsWith('auto:')")
115
- })
116
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/src/components/chain-manager.tsx DELETED
@@ -1,328 +0,0 @@
1
- import { useState } from 'react'
2
- import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
3
- import { Check, ChevronDown, Layers, Pencil, Plus, Trash2 } from 'lucide-react'
4
- import { useI18n } from '@/i18n'
5
- import { apiFetch, type ApiError } from '@/lib/api'
6
- import { Button } from '@/components/ui/button'
7
- import { Input } from '@/components/ui/input'
8
- import { Badge } from '@/components/ui/badge'
9
- import { Tooltip } from '@/components/tooltip'
10
-
11
- // Named fallback chains (#960/#895). The backend /api/profiles CRUD is
12
- // complete and every chain is listed as an `auto:<name>` model in /v1/models;
13
- // this panel is the missing dashboard surface: list chains, create new ones,
14
- // switch the active chain (the fallback table below then edits that chain),
15
- // and delete custom ones.
16
- //
17
- // Deliberately a secondary, collapsed-by-default accordion on the Fallback
18
- // page rather than its own nav entry: most installs use one chain forever, and
19
- // the routing table below is what the page is for.
20
-
21
- const COLLAPSED_KEY = 'freellmapi.chainManager.collapsed'
22
-
23
- function readCollapsed(): boolean {
24
- try {
25
- const stored = localStorage.getItem(COLLAPSED_KEY)
26
- return stored === null ? true : stored === '1'
27
- } catch {
28
- return true
29
- }
30
- }
31
-
32
- export interface Chain {
33
- id: number
34
- name: string
35
- emoji: string
36
- color: string
37
- type: 'default' | 'builtin' | 'custom'
38
- is_favorite: number
39
- sort_order: number
40
- auto_sort: string | null
41
- layout_config: string | null
42
- // 0 once the chain opts out of the catalog-sync backfill (#895), which is
43
- // what an empty-created chain does — it stays exactly as hand-built.
44
- auto_include_new_models: number
45
- created_at: string
46
- }
47
-
48
- export function ChainManager() {
49
- const { t } = useI18n()
50
- const queryClient = useQueryClient()
51
- const [newName, setNewName] = useState('')
52
- const [startEmpty, setStartEmpty] = useState(true)
53
- const [createError, setCreateError] = useState('')
54
- const [collapsed, setCollapsed] = useState<boolean>(readCollapsed)
55
- // Inline rename (#1179): one row is editable at a time, like the Playground
56
- // conversation list. Renaming is safe mid-flight — routing resolves the name
57
- // at request time — but in-flight auto:<old-name> requests fail, so the
58
- // confirm step says so.
59
- const [renamingId, setRenamingId] = useState<number | null>(null)
60
- const [renameDraft, setRenameDraft] = useState('')
61
- const [renameError, setRenameError] = useState('')
62
-
63
- const { data: chains = [] } = useQuery<Chain[]>({
64
- queryKey: ['profiles'],
65
- queryFn: () => apiFetch('/api/profiles'),
66
- })
67
- const { data: active } = useQuery<{ activeProfileId: number | null }>({
68
- queryKey: ['profiles', 'active'],
69
- queryFn: () => apiFetch('/api/profiles/active'),
70
- })
71
-
72
- const invalidate = async () => {
73
- // Resolve WHICH chain is active before refreshing anything keyed on it
74
- // (#1047): invalidating ['fallback'] first refetched the chain table under
75
- // the old profile id — a wasted full-catalog round trip, and the write that
76
- // poisoned the old chain's cache entry with the new chain's rows.
77
- await queryClient.refetchQueries({ queryKey: ['profiles', 'active'], exact: true })
78
- queryClient.invalidateQueries({ queryKey: ['profiles'] })
79
- // The fallback table renders the active chain; refresh it too. The prefix
80
- // covers the chain, routing, token-usage and rate-limit queries.
81
- queryClient.invalidateQueries({ queryKey: ['fallback'] })
82
- }
83
-
84
- const createChain = useMutation({
85
- mutationFn: (payload: { name: string; empty: boolean }) =>
86
- apiFetch('/api/profiles', { method: 'POST', body: JSON.stringify(payload) }),
87
- onSuccess: () => {
88
- invalidate()
89
- setNewName('')
90
- setCreateError('')
91
- },
92
- // Names are validated server-side (max 20 chars, Latin/digits/-/_ only, a
93
- // list of reserved words, no duplicates). Say which rule was broken rather
94
- // than swallowing the 400/409.
95
- onError: (error: ApiError) => setCreateError(error.message || t('chains.createFailed')),
96
- })
97
- const setActive = useMutation({
98
- mutationFn: (profileId: number) =>
99
- apiFetch('/api/profiles/active', { method: 'POST', body: JSON.stringify({ profileId }) }),
100
- onSuccess: invalidate,
101
- })
102
- const deleteChain = useMutation({
103
- mutationFn: (profileId: number) =>
104
- apiFetch(`/api/profiles/${profileId}`, { method: 'DELETE' }),
105
- onSuccess: invalidate,
106
- })
107
- const renameChain = useMutation({
108
- mutationFn: ({ profileId, name }: { profileId: number; name: string }) =>
109
- apiFetch(`/api/profiles/${profileId}`, { method: 'PUT', body: JSON.stringify({ name }) }),
110
- onSuccess: () => {
111
- invalidate()
112
- setRenamingId(null)
113
- setRenameError('')
114
- },
115
- // Same server rules as create (charset, length, reserved, taken); show
116
- // which one fired instead of leaving the row stuck in edit mode.
117
- onError: (error: ApiError) => setRenameError(error.message || t('chains.renameFailed')),
118
- })
119
-
120
- if (chains.length === 0) return null
121
-
122
- const activeId = active?.activeProfileId ?? null
123
-
124
- function toggle() {
125
- setCollapsed(prev => {
126
- const next = !prev
127
- try { localStorage.setItem(COLLAPSED_KEY, next ? '1' : '0') } catch { /* ignore */ }
128
- return next
129
- })
130
- }
131
-
132
- return (
133
- <section className="rounded-lg border bg-card">
134
- <button
135
- type="button"
136
- onClick={toggle}
137
- aria-expanded={!collapsed}
138
- aria-label={collapsed ? t('common.show') : t('common.hide')}
139
- className={`flex w-full flex-wrap items-center justify-between gap-2 px-4 py-3 text-left ${collapsed ? '' : 'border-b'}`}
140
- >
141
- <div className="flex items-center gap-2">
142
- <Layers className="size-4 text-muted-foreground" />
143
- <div>
144
- <h2 className="text-sm font-medium">{t('chains.title')}</h2>
145
- <p className="text-xs text-muted-foreground">{t('chains.description')}</p>
146
- </div>
147
- </div>
148
- <div className="flex items-center gap-2">
149
- <span className="rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground tabular-nums">
150
- {t('chains.count', { count: chains.length })}
151
- </span>
152
- <ChevronDown className={`size-4 text-muted-foreground transition-transform ${collapsed ? '-rotate-90' : ''}`} />
153
- </div>
154
- </button>
155
-
156
- {!collapsed && (
157
- <div className="p-4">
158
- <div className="space-y-2">
159
- {chains.map(chain => {
160
- const isActive = chain.id === activeId
161
- const isProtected = chain.type === 'default' || chain.type === 'builtin'
162
- const isRenaming = renamingId === chain.id
163
- if (isRenaming) {
164
- return (
165
- <form
166
- key={chain.id}
167
- className="flex items-center gap-2 rounded-xl border border-foreground/25 bg-muted/50 px-3 py-2"
168
- onSubmit={e => {
169
- e.preventDefault()
170
- const name = renameDraft.trim()
171
- if (!name || renameChain.isPending) return
172
- if (name !== chain.name
173
- && !window.confirm(t('chains.renameConfirm', { oldName: chain.name, name }))) return
174
- renameChain.mutate({ profileId: chain.id, name })
175
- }}
176
- >
177
- <Input
178
- autoFocus
179
- value={renameDraft}
180
- onChange={e => {
181
- setRenameDraft(e.target.value)
182
- setRenameError('')
183
- }}
184
- onKeyDown={e => { if (e.key === 'Escape') { e.preventDefault(); setRenamingId(null); setRenameError('') } }}
185
- aria-label={t('chains.renamePlaceholder')}
186
- placeholder={t('chains.renamePlaceholder')}
187
- className="h-7 max-w-48 text-sm"
188
- />
189
- <Button type="submit" size="sm" variant="secondary" className="h-7 px-2 text-xs" disabled={!renameDraft.trim() || renameChain.isPending}>
190
- {t('common.save')}
191
- </Button>
192
- <Button type="button" size="sm" variant="ghost" className="h-7 px-2 text-xs" onClick={() => { setRenamingId(null); setRenameError('') }}>
193
- {t('common.cancel')}
194
- </Button>
195
- {renameError && <span className="text-xs text-rose-600 dark:text-rose-400">{renameError}</span>}
196
- </form>
197
- )
198
- }
199
- return (
200
- <div
201
- key={chain.id}
202
- className={`flex flex-wrap items-center gap-2 rounded-xl border px-3 py-2 ${
203
- isActive ? 'border-foreground/25 bg-muted/50' : 'border-transparent hover:bg-muted/40'
204
- }`}
205
- >
206
- <span className="flex items-center gap-1.5 text-sm font-medium" title={chain.name}>
207
- {chain.emoji || <Layers className="size-3.5 text-muted-foreground" />}
208
- <span className="truncate">{chain.name}</span>
209
- </span>
210
- {/* The id a client sends to pick this chain per request. */}
211
- <code className="rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground">
212
- auto:{chain.name.toLowerCase()}
213
- </code>
214
- {isActive && (
215
- <Badge variant="secondary" className="gap-1">
216
- <Check className="size-3" />
217
- {t('chains.active')}
218
- </Badge>
219
- )}
220
- {isProtected && !isActive && (
221
- <span className="text-[11px] text-muted-foreground">{t('chains.default')}</span>
222
- )}
223
- {chain.auto_include_new_models === 0 && (
224
- <Tooltip text={t('chains.curatedHint')}>
225
- <span className="cursor-help text-[11px] text-muted-foreground underline decoration-dotted underline-offset-2">
226
- {t('chains.curated')}
227
- </span>
228
- </Tooltip>
229
- )}
230
- <span className="flex-1" />
231
- {!isActive && (
232
- <Tooltip text={t('chains.activateHint')}>
233
- <Button
234
- variant="ghost"
235
- size="sm"
236
- className="h-7 px-2 text-xs"
237
- disabled={setActive.isPending}
238
- onClick={() => setActive.mutate(chain.id)}
239
- >
240
- {t('chains.activate')}
241
- </Button>
242
- </Tooltip>
243
- )}
244
- {!isProtected && (
245
- <Tooltip text={t('chains.renameHint')}>
246
- <Button
247
- variant="ghost"
248
- size="sm"
249
- className="h-7 px-2 text-xs text-muted-foreground"
250
- aria-label={t('chains.renameHint')}
251
- disabled={renameChain.isPending}
252
- onClick={() => {
253
- setRenamingId(chain.id)
254
- setRenameDraft(chain.name)
255
- setRenameError('')
256
- }}
257
- >
258
- <Pencil className="size-3.5" />
259
- </Button>
260
- </Tooltip>
261
- )}
262
- {!isProtected && (
263
- <Tooltip text={t('chains.deleteHint')}>
264
- <Button
265
- variant="ghost"
266
- size="sm"
267
- className="h-7 px-2 text-xs text-muted-foreground hover:text-rose-600"
268
- aria-label={t('chains.deleteHint')}
269
- disabled={deleteChain.isPending}
270
- onClick={() => {
271
- if (window.confirm(t('chains.deleteConfirm', { name: chain.name }))) {
272
- deleteChain.mutate(chain.id)
273
- }
274
- }}
275
- >
276
- <Trash2 className="size-3.5" />
277
- </Button>
278
- </Tooltip>
279
- )}
280
- </div>
281
- )
282
- })}
283
- </div>
284
-
285
- <form
286
- className="mt-3 flex gap-2"
287
- onSubmit={e => {
288
- e.preventDefault()
289
- const name = newName.trim()
290
- if (name && !createChain.isPending) createChain.mutate({ name, empty: startEmpty })
291
- }}
292
- >
293
- <Input
294
- value={newName}
295
- onChange={e => {
296
- setNewName(e.target.value)
297
- setCreateError('')
298
- }}
299
- placeholder={t('chains.createPlaceholder')}
300
- aria-label={t('chains.createPlaceholder')}
301
- className="h-8"
302
- />
303
- <Button type="submit" size="sm" className="h-8" disabled={!newName.trim() || createChain.isPending}>
304
- <Plus className="size-3.5" />
305
- {t('chains.create')}
306
- </Button>
307
- </form>
308
- <label className="mt-2 flex items-center gap-2 text-xs text-muted-foreground">
309
- <input
310
- type="checkbox"
311
- checked={startEmpty}
312
- onChange={e => setStartEmpty(e.target.checked)}
313
- className="size-3.5 accent-foreground"
314
- />
315
- <span>{t('chains.startEmpty')}</span>
316
- <Tooltip text={t('chains.startEmptyHint')}>
317
- <span className="cursor-help underline decoration-dotted underline-offset-2">?</span>
318
- </Tooltip>
319
- </label>
320
-
321
- {createError
322
- ? <p className="mt-1.5 text-xs text-rose-600 dark:text-rose-400">{createError}</p>
323
- : <p className="mt-1.5 text-xs text-muted-foreground">{t('chains.nameRules')}</p>}
324
- </div>
325
- )}
326
- </section>
327
- )
328
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/src/components/code-block.tsx DELETED
@@ -1,24 +0,0 @@
1
- import { useMemo } from 'react'
2
- import { cn } from '@/lib/utils'
3
- import { highlightCode } from '@/lib/highlight'
4
-
5
- // Highlighted source: the reply code blocks and the artifact panel's Code tab.
6
- // highlightCode returns escaped HTML with hljs-* spans, so injecting it is
7
- // safe; the token colours live in index.css under `.code-highlight`.
8
-
9
- export interface CodeBlockProps {
10
- code: string
11
- language?: string | null
12
- className?: string
13
- }
14
-
15
- export function CodeBlock({ code, language, className }: CodeBlockProps) {
16
- const { html, language: applied } = useMemo(() => highlightCode(code, language), [code, language])
17
- return (
18
- <code
19
- className={cn('code-highlight block font-mono text-[12.5px] leading-relaxed whitespace-pre', className)}
20
- data-language={applied ?? undefined}
21
- dangerouslySetInnerHTML={{ __html: html }}
22
- />
23
- )
24
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
client/src/components/command-palette-state.ts DELETED
@@ -1,5 +0,0 @@
1
- export const COMMAND_PALETTE_EVENT = 'freellmapi:command-palette'
2
-
3
- export function openCommandPalette() {
4
- window.dispatchEvent(new CustomEvent(COMMAND_PALETTE_EVENT))
5
- }