apihub-auto-setup 0.1.0 → 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.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/install.mjs +88 -8
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -22,7 +22,7 @@ npx apihub-auto-setup
22
22
 
23
23
  - **Claude Code.** Запустите `claude`.
24
24
  - **Codex.** Запустите `codex`. Установщик сохранит токен в локальных настройках провайдера APIHub.
25
- - **OpenCode.** Если вы раньше выбрали модель другого провайдера, переключитесь на APIHub через `/models`.
25
+ - **OpenCode.** Запустите `opencode`.
26
26
  - **Cursor, Continue, Aider и Cline.** Перезапустите свой инструмент, чтобы он перечитал настройки.
27
27
 
28
28
  Перед записью Go-настройщик сохраняет копии существующих настроек. Описание параметров и восстановления есть в [репозитории apihub-setup](https://github.com/streeboga/apihub-setup?utm_source=github&utm_medium=readme&utm_campaign=apihub-auto-setup).
package/install.mjs CHANGED
@@ -1,12 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawnSync } from 'node:child_process';
3
3
  import { createHash } from 'node:crypto';
4
- import { mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
4
+ import { access, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
5
5
  import { homedir, tmpdir } from 'node:os';
6
6
  import { join } from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
7
8
  import { createInterface } from 'node:readline';
8
9
  import { Writable } from 'node:stream';
9
- import { defaultGateway, replaceSettings } from './src/setup.mjs';
10
+ import { defaultGateway, gatewayBase, replaceSettings } from './src/setup.mjs';
10
11
 
11
12
  const release = 'https://github.com/streeboga/apihub-setup/releases/download/v0.1.0';
12
13
  const checksums = {
@@ -37,15 +38,39 @@ async function askForToken() {
37
38
  }
38
39
  }
39
40
 
40
- async function saveCodexToken(token) {
41
- let path;
41
+ async function existingSettings(...parts) {
42
42
  try {
43
- path = await realpath(join(homedir(), '.codex', 'config.toml'));
43
+ return await realpath(join(homedir(), ...parts));
44
44
  } catch (error) {
45
- if (error.code === 'ENOENT') return;
45
+ if (error.code === 'ENOENT') return undefined;
46
46
  throw error;
47
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
+ }
48
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;
49
74
  const original = await readFile(path, 'utf8');
50
75
  // This is the provider block emitted by the pinned Go release.
51
76
  const envKey = 'env_key = "APIHUB_API_KEY"';
@@ -61,7 +86,59 @@ async function saveCodexToken(token) {
61
86
  if (updated === original) {
62
87
  throw new Error('Настройщик не подтвердил подключение Codex к APIHub.');
63
88
  }
64
- await replaceSettings(path, original, updated, 'Codex');
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');
65
142
  }
66
143
 
67
144
  async function install() {
@@ -71,6 +148,7 @@ async function install() {
71
148
  if (!digest) throw new Error('Для этой системы нет готового установщика.');
72
149
 
73
150
  const token = await askForToken();
151
+ const adapter = await openCodeAdapter();
74
152
  const name = `apihub-setup-${platform}-${arch}${platform === 'windows' ? '.exe' : ''}`;
75
153
  const response = await fetch(`${release}/${name}`, { signal: AbortSignal.timeout(60_000) });
76
154
  if (!response.ok) throw new Error(`Не удалось скачать установщик (HTTP ${response.status}).`);
@@ -89,7 +167,9 @@ async function install() {
89
167
  });
90
168
  if (result.error) throw result.error;
91
169
  if (result.status !== 0) throw new Error('Не удалось завершить настройку агентов.');
92
- await saveCodexToken(token);
170
+ await finishClaudeCode(token);
171
+ await finishCodex(token);
172
+ await finishOpenCode(token, adapter);
93
173
  } finally {
94
174
  await rm(dir, { recursive: true, force: true });
95
175
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apihub-auto-setup",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Connect Claude Code, Codex, OpenCode, and other coding agents to APIHub.",
5
5
  "repository": {
6
6
  "type": "git",