apihub-auto-setup 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 streeboga
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.
package/README.md CHANGED
@@ -1,3 +1,30 @@
1
- # Temporary Holding Version
1
+ # APIHub для кодинг-агентов
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Подключите модели APIHub к своему Claude Code, Codex или OpenCode. Продолжайте работать в привычном агенте и оплачивайте запросы с одного баланса APIHub.
4
+
5
+ ## Быстрый старт
6
+
7
+ 1. [Зарегистрируйтесь в APIHub](https://hub.gnzs.pro/register?utm_source=github&utm_medium=readme&utm_campaign=apihub-auto-setup). Первые запросы можно оплатить стартовым бонусом, который APIHub начисляет при регистрации.
8
+ 2. [Создайте и скопируйте токен](https://hub.gnzs.pro/app/tokens?utm_source=github&utm_medium=readme&utm_campaign=apihub-auto-setup).
9
+ 3. Запустите команду ниже. Когда терминал попросит токен, вставьте его и нажмите Enter. Настройщик найдёт поддерживаемые приложения по их файлам настроек и подключит их к APIHub. Откройте новую сессию в агенте.
10
+
11
+ Можно попросить об этом агента, в котором вы уже работаете. Отправьте ему ссылку на этот README и сообщение.
12
+
13
+ > Подключи APIHub по инструкции из README. Покажи команду для моего терминала и подскажи, как запустить мой агент после настройки. Токен я введу в терминале.
14
+
15
+ Команда для macOS, Linux и Windows (x64). Нужен Node.js 22.19 или новее.
16
+
17
+ ```sh
18
+ npx apihub-auto-setup
19
+ ```
20
+
21
+ ## После настройки
22
+
23
+ - **Claude Code.** Запустите `claude`.
24
+ - **Codex.** Запустите `codex`. Установщик сохранит токен в локальных настройках провайдера APIHub.
25
+ - **OpenCode.** Запустите `opencode`.
26
+ - **Cursor, Continue, Aider и Cline.** Перезапустите свой инструмент, чтобы он перечитал настройки.
27
+
28
+ Перед записью Go-настройщик сохраняет копии существующих настроек. Описание параметров и восстановления есть в [репозитории apihub-setup](https://github.com/streeboga/apihub-setup?utm_source=github&utm_medium=readme&utm_campaign=apihub-auto-setup).
29
+
30
+ [Открыть APIHub](https://hub.gnzs.pro/?utm_source=github&utm_medium=readme&utm_campaign=apihub-auto-setup)
package/install.mjs ADDED
@@ -0,0 +1,190 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from 'node:child_process';
3
+ import { createHash } from 'node:crypto';
4
+ import { access, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
5
+ import { homedir, tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+ import { createInterface } from 'node:readline';
9
+ import { Writable } from 'node:stream';
10
+ import { defaultGateway, gatewayBase, replaceSettings } from './src/setup.mjs';
11
+
12
+ const release = 'https://github.com/streeboga/apihub-setup/releases/download/v0.1.0';
13
+ const checksums = {
14
+ 'darwin-arm64': '4d6a670fc46b07d5bb0ab687bfb037a36707e851d751e433ebc43f1c99a1439c',
15
+ 'darwin-x64': 'f908c12156c22c9883ae72e343f57cd1458e93101735454a8733476b3b0c97c0',
16
+ 'linux-arm64': 'a87d93c5f8c58ce17eaa972f82a88125ed6356efbb743adf0e668afefe39968e',
17
+ 'linux-x64': 'b0eddf6cdc09c6832c02260b2fa756e0519bc0b6ae348f04dde2189883f60cf2',
18
+ 'win32-x64': '6597807cec37fad107ead231df1e752df9278d94677d9669e22b557ae8806c85',
19
+ };
20
+
21
+ async function askForToken() {
22
+ if (!process.stdin.isTTY) {
23
+ throw new Error('Запустите установщик в терминале, чтобы ввести токен APIHub.');
24
+ }
25
+ const muted = new Writable({ write(_chunk, _encoding, done) { done(); } });
26
+ const input = createInterface({ input: process.stdin, output: muted, terminal: true, historySize: 0 });
27
+ process.stderr.write('Вставьте токен APIHub и нажмите Enter: ');
28
+ try {
29
+ for await (const line of input) {
30
+ const token = line.trim();
31
+ if (/^[!-~]+$/.test(token)) return token;
32
+ break;
33
+ }
34
+ throw new Error('Для настройки нужен токен APIHub.');
35
+ } finally {
36
+ input.close();
37
+ process.stderr.write('\n');
38
+ }
39
+ }
40
+
41
+ async function existingSettings(...parts) {
42
+ try {
43
+ return await realpath(join(homedir(), ...parts));
44
+ } catch (error) {
45
+ if (error.code === 'ENOENT') return undefined;
46
+ throw error;
47
+ }
48
+ }
49
+
50
+ async function finishClaudeCode(token) {
51
+ const path = await existingSettings('.claude', 'settings.json');
52
+ if (!path) return;
53
+ const original = await readFile(path, 'utf8');
54
+ const settings = JSON.parse(original);
55
+ const env = settings.env;
56
+ if (env?.ANTHROPIC_AUTH_TOKEN !== token || env.ANTHROPIC_BASE_URL !== defaultGateway) {
57
+ throw new Error('Настройщик не подтвердил подключение Claude Code к APIHub.');
58
+ }
59
+
60
+ const haiku = 'claude-haiku-4.5';
61
+ settings.model = haiku;
62
+ // The Anthropic client appends /v1/messages to this base.
63
+ env.ANTHROPIC_BASE_URL = gatewayBase(defaultGateway);
64
+ env.ANTHROPIC_DEFAULT_HAIKU_MODEL = haiku;
65
+ env.ANTHROPIC_SMALL_FAST_MODEL = haiku;
66
+ env.ANTHROPIC_DEFAULT_SONNET_MODEL = 'claude-sonnet-4.6';
67
+ env.ANTHROPIC_DEFAULT_OPUS_MODEL = 'claude-opus-4.6';
68
+ await replaceSettings(path, original, JSON.stringify(settings, null, 2) + '\n');
69
+ }
70
+
71
+ async function finishCodex(token) {
72
+ const path = await existingSettings('.codex', 'config.toml');
73
+ if (!path) return;
74
+ const original = await readFile(path, 'utf8');
75
+ // This is the provider block emitted by the pinned Go release.
76
+ const envKey = 'env_key = "APIHUB_API_KEY"';
77
+ const provider = [
78
+ '[model_providers.apihub]',
79
+ 'name = "APIHUB"',
80
+ `base_url = "${defaultGateway}"`,
81
+ envKey,
82
+ '',
83
+ ].join('\n');
84
+ const updated = original.replace(provider, () =>
85
+ provider.replace(envKey, () => `experimental_bearer_token = ${JSON.stringify(token)}`));
86
+ if (updated === original) {
87
+ throw new Error('Настройщик не подтвердил подключение Codex к APIHub.');
88
+ }
89
+ // The Go installer can select a model that only supports Chat Completions.
90
+ const firstTable = updated.search(/^[ \t]*\[/m);
91
+ const root = updated.slice(0, firstTable);
92
+ const selection = 'model = "gpt-6.1-sol"';
93
+ const modelLine = /^[ \t]*model[ \t]*=[^\r\n]*/m;
94
+ const configured = modelLine.test(root) ? root.replace(modelLine, selection) : selection + '\n' + root;
95
+ await replaceSettings(path, original, configured + updated.slice(firstTable), 'Codex');
96
+ }
97
+
98
+ async function openCodeAdapter() {
99
+ if (!await existingSettings('.config', 'opencode', 'opencode.json')) return;
100
+ const version = spawnSync('opencode', ['--version'], {
101
+ encoding: 'utf8',
102
+ shell: process.platform === 'win32',
103
+ stdio: ['ignore', 'pipe', 'ignore'],
104
+ timeout: 5000,
105
+ }).stdout?.trim();
106
+ // OpenCode 1.0 expects the v2 streaming protocol supplied by SDK version 1.
107
+ if (!/^1\.0\.\d+$/.test(version ?? '')) return;
108
+ const sdk = '@ai-sdk/openai-compatible';
109
+ const sdkVersion = '1.0.63';
110
+ const prefix = join(homedir(), '.config', 'opencode', 'apihub-sdk-' + sdkVersion);
111
+ const entry = join(prefix, 'node_modules', sdk, 'dist', 'index.mjs');
112
+ try {
113
+ await access(entry);
114
+ } catch (error) {
115
+ if (error.code !== 'ENOENT') throw error;
116
+ const npm = process.env.npm_execpath;
117
+ if (!npm) throw new Error('Запустите установщик через npx, чтобы настроить OpenCode.');
118
+ const result = spawnSync(process.execPath, [
119
+ npm, 'install', '--prefix', prefix, '--ignore-scripts', '--no-audit', '--no-fund',
120
+ '--registry=https://registry.npmjs.org/', `${sdk}@${sdkVersion}`,
121
+ ], { stdio: ['ignore', 'inherit', 'inherit'] });
122
+ if (result.error) throw result.error;
123
+ if (result.status !== 0) throw new Error('Не удалось установить адаптер для OpenCode 1.0.');
124
+ await access(entry);
125
+ }
126
+ return pathToFileURL(entry).href;
127
+ }
128
+
129
+ async function finishOpenCode(token, adapter) {
130
+ const path = await existingSettings('.config', 'opencode', 'opencode.json');
131
+ if (!path) return;
132
+ const original = await readFile(path, 'utf8');
133
+ const settings = JSON.parse(original);
134
+ const provider = settings.provider?.apihub;
135
+ const model = 'gemini-3.1-flash-lite';
136
+ if (provider?.options?.apiKey !== token || provider.options.baseURL !== defaultGateway || !provider.models?.[model]) {
137
+ throw new Error('Настройщик не подтвердил подключение OpenCode к APIHub.');
138
+ }
139
+ settings.model = `apihub/${model}`;
140
+ if (adapter) provider.npm = adapter;
141
+ await replaceSettings(path, original, JSON.stringify(settings, null, 2) + '\n', 'OpenCode');
142
+ }
143
+
144
+ async function install() {
145
+ const platform = process.platform === 'win32' ? 'windows' : process.platform;
146
+ const arch = process.arch === 'x64' ? 'amd64' : process.arch;
147
+ const digest = checksums[`${process.platform}-${process.arch}`];
148
+ if (!digest) throw new Error('Для этой системы нет готового установщика.');
149
+
150
+ const token = await askForToken();
151
+ const adapter = await openCodeAdapter();
152
+ const name = `apihub-setup-${platform}-${arch}${platform === 'windows' ? '.exe' : ''}`;
153
+ const response = await fetch(`${release}/${name}`, { signal: AbortSignal.timeout(60_000) });
154
+ if (!response.ok) throw new Error(`Не удалось скачать установщик (HTTP ${response.status}).`);
155
+ const binary = Buffer.from(await response.arrayBuffer());
156
+ if (createHash('sha256').update(binary).digest('hex') !== digest) {
157
+ throw new Error('Контрольная сумма установщика не совпала.');
158
+ }
159
+
160
+ const dir = await mkdtemp(join(tmpdir(), 'apihub-install-'));
161
+ const executable = join(dir, name);
162
+ try {
163
+ await writeFile(executable, binary, { flag: 'wx', mode: 0o700 });
164
+ const result = spawnSync(executable, [], {
165
+ env: { ...process.env, APIHUB_TOKEN: token },
166
+ stdio: 'inherit',
167
+ });
168
+ if (result.error) throw result.error;
169
+ if (result.status !== 0) throw new Error('Не удалось завершить настройку агентов.');
170
+ await finishClaudeCode(token);
171
+ await finishCodex(token);
172
+ await finishOpenCode(token, adapter);
173
+ } finally {
174
+ await rm(dir, { recursive: true, force: true });
175
+ }
176
+ }
177
+
178
+ try {
179
+ const args = process.argv.slice(2);
180
+ if (args.length === 1 && ['--help', '-h'].includes(args[0])) {
181
+ console.log('Запустите без аргументов, чтобы подключить найденные агенты к APIHub.');
182
+ } else if (args.length === 0) {
183
+ await install();
184
+ } else {
185
+ throw new Error('Установщик запускается без аргументов.');
186
+ }
187
+ } catch (error) {
188
+ console.error(`APIHub: ${error.message}`);
189
+ process.exitCode = 1;
190
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "apihub-auto-setup",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Connect Claude Code, Codex, OpenCode, and other coding agents to APIHub.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/streeboga/apihub-auto-setup.git"
8
+ },
9
+ "type": "module",
10
+ "license": "MIT",
11
+ "engines": {
12
+ "node": ">=22.19.0"
13
+ },
14
+ "scripts": {
15
+ "test": "node --test"
16
+ },
17
+ "dependencies": {
18
+ "@earendil-works/pi-agent-core": "1.6.0",
19
+ "@earendil-works/pi-ai": "1.6.0"
20
+ },
21
+ "bin": {
22
+ "apihub-auto-setup": "./install.mjs"
23
+ },
24
+ "files": [
25
+ "install.mjs",
26
+ "setup.mjs",
27
+ "src/agent.mjs",
28
+ "src/setup.mjs"
29
+ ]
30
+ }
package/setup.mjs ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { run } from './src/setup.mjs';
3
+
4
+ try {
5
+ await run(process.argv.slice(2));
6
+ } catch (error) {
7
+ console.error(`APIHub Auto: ${error.message}`);
8
+ process.exitCode = 1;
9
+ }
package/src/agent.mjs ADDED
@@ -0,0 +1,83 @@
1
+ import { Agent } from '@earendil-works/pi-agent-core';
2
+ import { streamSimple } from '@earendil-works/pi-ai/api/anthropic-messages';
3
+ import { model, strategies } from './setup.mjs';
4
+
5
+ const toolName = 'select_claude_code_strategy';
6
+
7
+ export async function chooseStrategy(request, base, token) {
8
+ let selected;
9
+ let called = false;
10
+ const tool = {
11
+ name: toolName,
12
+ label: 'Select the Claude Code routing strategy',
13
+ description: 'Plan a Claude Code configuration with one APIHub Auto routing strategy.',
14
+ parameters: {
15
+ type: 'object',
16
+ properties: { strategy: { type: 'string', enum: strategies } },
17
+ required: ['strategy'],
18
+ additionalProperties: false,
19
+ },
20
+ execute: async (_id, { strategy }) => {
21
+ if (!strategies.includes(strategy)) throw new Error('Unknown strategy.');
22
+ if (selected !== undefined && selected !== strategy) {
23
+ selected = null;
24
+ } else {
25
+ selected = strategy;
26
+ }
27
+ return { content: [{ type: 'text', text: 'Strategy proposed.' }], details: {}, terminate: true };
28
+ },
29
+ };
30
+
31
+ const agent = new Agent({
32
+ initialState: {
33
+ systemPrompt: [
34
+ 'Interpret the user request for configuring Claude Code with the APIHub Auto virtual model.',
35
+ 'If supported, call select_claude_code_strategy once.',
36
+ 'Use optimal for balanced or unspecified, cheaper for lowest price, faster for speed, reliable for reliability.',
37
+ 'The only supported target is Claude Code CLI. Decline unsupported targets or actions.',
38
+ 'Never ask for credentials.',
39
+ ].join(' '),
40
+ model: {
41
+ id: model,
42
+ name: 'APIHub Auto',
43
+ api: 'anthropic-messages',
44
+ provider: 'apihub',
45
+ baseUrl: base,
46
+ input: ['text'],
47
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
48
+ contextWindow: 8192,
49
+ maxTokens: 512,
50
+ reasoning: false,
51
+ },
52
+ tools: [tool],
53
+ thinkingLevel: 'off',
54
+ },
55
+ toolExecution: 'sequential',
56
+ identity: { attribution: null },
57
+ streamFn: (agentModel, context, options) => {
58
+ if (called) throw new Error('Agent request budget exhausted.');
59
+ called = true;
60
+ return streamSimple(agentModel, context, {
61
+ ...options,
62
+ headers: { Authorization: `Bearer ${token}`, 'X-APIHub-Strategy': 'reliable' },
63
+ fetch: (input, init) => fetch(input, { ...init, redirect: 'error' }),
64
+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(30_000)].filter(Boolean)),
65
+ maxRetries: 0,
66
+ maxTokens: 512,
67
+ });
68
+ },
69
+ });
70
+
71
+ try {
72
+ await agent.prompt(request);
73
+ } catch {
74
+ throw new Error('Pi could not reach APIHub Auto. Check your key and gateway.');
75
+ }
76
+ if (agent.state.errorMessage) {
77
+ throw new Error('Pi could not get a response from APIHub Auto. Check your key and gateway.');
78
+ }
79
+ if (!selected) {
80
+ throw new Error('Pi did not propose a supported Claude Code configuration.');
81
+ }
82
+ return selected;
83
+ }
package/src/setup.mjs ADDED
@@ -0,0 +1,186 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { basename, dirname, join, resolve } from 'node:path';
5
+ import { parseArgs } from 'node:util';
6
+
7
+ export const model = 'apihub-auto';
8
+ export const defaultGateway = 'https://g.gnzs.pro/g/v1';
9
+ export const strategies = ['optimal', 'cheaper', 'faster', 'reliable'];
10
+ const strategyHeader = 'X-APIHub-Strategy';
11
+
12
+ export function gatewayBase(value) {
13
+ let url;
14
+ try {
15
+ url = new URL(value);
16
+ } catch {
17
+ throw new Error('Expected a gateway URL.');
18
+ }
19
+ if (url.username || url.password || url.search || url.hash) {
20
+ throw new Error('The gateway URL must be provided without credentials, query or fragment.');
21
+ }
22
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
23
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) {
24
+ throw new Error('The gateway URL must use HTTPS or loopback HTTP.');
25
+ }
26
+ return url.origin + url.pathname.replace(/\/+$/, '').replace(/\/v1$/, '');
27
+ }
28
+
29
+ async function readSettings(path) {
30
+ try {
31
+ return await readFile(path, 'utf8');
32
+ } catch (error) {
33
+ if (error.code === 'ENOENT') return undefined;
34
+ throw error;
35
+ }
36
+ }
37
+
38
+ function asObject(value, name) {
39
+ if (value === null || Array.isArray(value) || typeof value !== 'object') {
40
+ throw new Error(`${name} must be a JSON object.`);
41
+ }
42
+ return value;
43
+ }
44
+
45
+ async function settingsPath() {
46
+ const path = resolve(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'settings.json');
47
+ try {
48
+ return await realpath(path);
49
+ } catch (error) {
50
+ if (error.code === 'ENOENT') return path;
51
+ throw error;
52
+ }
53
+ }
54
+
55
+ export async function replaceSettings(path, original, content, client = 'Claude Code') {
56
+ const staged = join(dirname(path), `.apihub-settings-${randomUUID()}`);
57
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
58
+ try {
59
+ await writeFile(staged, content, { flag: 'wx', mode: 0o600 });
60
+ if (await readSettings(path) !== original) {
61
+ throw new Error(`${client} settings changed during setup. Retry the command.`);
62
+ }
63
+ await rename(staged, path);
64
+ } finally {
65
+ await rm(staged, { force: true });
66
+ }
67
+ }
68
+
69
+ export function requireToken() {
70
+ const token = process.env.APIHUB_TOKEN?.trim();
71
+ if (!token || /[\r\n]/.test(token)) {
72
+ throw new Error('Set APIHUB_TOKEN to your APIHub key.');
73
+ }
74
+ return token;
75
+ }
76
+
77
+ export async function applyClaudeCode(strategy, base, token) {
78
+ if (!strategies.includes(strategy)) {
79
+ throw new Error(`Choose a strategy from ${strategies.join(', ')}.`);
80
+ }
81
+ const path = await settingsPath();
82
+ const original = await readSettings(path);
83
+ let settings;
84
+ try {
85
+ settings = original === undefined ? {} : JSON.parse(original);
86
+ } catch {
87
+ throw new Error('Claude Code settings contain invalid JSON.');
88
+ }
89
+ asObject(settings, 'Claude Code settings');
90
+ const env = settings.env === undefined ? {} : asObject(settings.env, 'settings.env');
91
+ const existing = env.ANTHROPIC_CUSTOM_HEADERS ?? '';
92
+ if (typeof existing !== 'string') {
93
+ throw new Error('ANTHROPIC_CUSTOM_HEADERS must be a string.');
94
+ }
95
+ const headerName = (line) => line.split(':', 1)[0].trim().toLowerCase();
96
+ const lines = existing.split(/\r?\n/).filter((line) => line.trim());
97
+ const credentialHeaders = ['authorization', 'x-api-key', 'proxy-authorization', 'cookie'];
98
+ if (env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY || settings.apiKeyHelper ||
99
+ lines.some((line) => credentialHeaders.includes(headerName(line)))) {
100
+ throw new Error('Claude Code has a conflicting API credential or credential helper.');
101
+ }
102
+ const headers = lines.filter((line) => headerName(line) !== strategyHeader.toLowerCase());
103
+ headers.push(`${strategyHeader}: ${strategy}`);
104
+
105
+ settings.model = model;
106
+ settings.env = {
107
+ ...env,
108
+ ANTHROPIC_BASE_URL: base,
109
+ ANTHROPIC_AUTH_TOKEN: token,
110
+ ANTHROPIC_CUSTOM_MODEL_OPTION: model,
111
+ ANTHROPIC_CUSTOM_MODEL_OPTION_NAME: 'APIHub Auto',
112
+ ANTHROPIC_CUSTOM_HEADERS: headers.join('\n'),
113
+ };
114
+ const updated = JSON.stringify(settings, null, 2) + '\n';
115
+ if (updated === original) return { path, changed: false };
116
+
117
+ if (original !== undefined) {
118
+ const timestamp = new Date().toISOString().replaceAll(':', '-');
119
+ const backup = `${path}.bak.${timestamp}-${randomUUID()}`;
120
+ await writeFile(backup, original, { flag: 'wx', mode: 0o600 });
121
+ }
122
+ await replaceSettings(path, original, updated);
123
+ return { path, changed: true };
124
+ }
125
+
126
+ async function restoreClaudeCode() {
127
+ const path = await settingsPath();
128
+ const dir = dirname(path);
129
+ const prefix = basename(path) + '.bak.';
130
+ const backup = (await readdir(dir)).filter((name) => name.startsWith(prefix)).sort().pop();
131
+ if (!backup) throw new Error('No Claude Code settings backup found.');
132
+ await replaceSettings(path, await readSettings(path), await readFile(join(dir, backup), 'utf8'));
133
+ console.log(`Restored Claude Code settings in ${path}.`);
134
+ }
135
+
136
+ export async function run(args) {
137
+ const { values } = parseArgs({
138
+ args,
139
+ options: {
140
+ apply: { type: 'boolean' },
141
+ 'dry-run': { type: 'boolean' },
142
+ restore: { type: 'boolean' },
143
+ help: { type: 'boolean', short: 'h' },
144
+ strategy: { type: 'string' },
145
+ agent: { type: 'string' },
146
+ gateway: { type: 'string', default: defaultGateway },
147
+ },
148
+ });
149
+ if (values.help || !args.length) {
150
+ console.log('node setup.mjs (--dry-run | --apply | --restore) [--strategy optimal|cheaper|faster|reliable | --agent "REQUEST"]');
151
+ return;
152
+ }
153
+ if ([values.apply, values['dry-run'], values.restore].filter(Boolean).length !== 1) {
154
+ throw new Error('Select exactly one of --dry-run, --apply and --restore.');
155
+ }
156
+ if (values.restore) {
157
+ if (values.agent !== undefined) throw new Error('--restore cannot be combined with --agent.');
158
+ return restoreClaudeCode();
159
+ }
160
+ const base = gatewayBase(values.gateway);
161
+ let strategy = values.strategy ?? 'optimal';
162
+ if (values.agent !== undefined) {
163
+ if (values.strategy !== undefined || !values.agent.trim() || values.agent.length > 2000) {
164
+ throw new Error('Pass a nonempty --agent request up to 2000 characters without --strategy.');
165
+ }
166
+ const token = requireToken();
167
+ let chooseStrategy;
168
+ try {
169
+ ({ chooseStrategy } = await import('./agent.mjs'));
170
+ } catch (error) {
171
+ if (error.code !== 'ERR_MODULE_NOT_FOUND') throw error;
172
+ throw new Error('Install Pi with npm ci --ignore-scripts before using --agent.');
173
+ }
174
+ strategy = await chooseStrategy(values.agent, base, token);
175
+ }
176
+ if (!strategies.includes(strategy)) {
177
+ throw new Error(`Choose a strategy from ${strategies.join(', ')}.`);
178
+ }
179
+ if (values['dry-run']) {
180
+ console.log(`Claude Code → ${base}/v1/messages · model ${model} · strategy ${strategy}`);
181
+ return;
182
+ }
183
+ const result = await applyClaudeCode(strategy, base, requireToken());
184
+ console.log(`Claude Code uses ${model} (${strategy}) via ${base}.`);
185
+ console.log(`Settings ${result.changed ? 'updated' : 'already current'} in ${result.path}.`);
186
+ }