@saturn-universe/cli 0.1.1 → 0.1.2-dev.10

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/dist/attach.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import type { TerminalRunStatus } from '@saturn-universe/protocol';
2
2
  import type { RunProgressArguments } from './commands.js';
3
3
  import type { CliOutput } from './results.js';
4
- export declare function attach(root: string, args: RunProgressArguments, output: (frame: CliOutput) => void, signal: AbortSignal): Promise<{
4
+ export declare function attach(root: string, args: RunProgressArguments & {
5
+ readonly initialPollMs?: number;
6
+ }, output: (frame: CliOutput) => void, signal: AbortSignal): Promise<{
5
7
  cursor: string;
6
8
  status?: TerminalRunStatus | 'paused';
7
9
  pauseReason?: string;
package/dist/attach.js CHANGED
@@ -6,6 +6,7 @@ import { integer, runProgressCommand } from './commands.js';
6
6
  import { sendHostCommand } from './host-command.js';
7
7
  export async function attach(root, args, output, signal) {
8
8
  const pollMs = integer(args.values['poll-ms'], 250, 60000);
9
+ let nextPollMs = Math.min(args.initialPollMs ?? pollMs, pollMs);
9
10
  const rawTimeout = args.values['timeout-ms'];
10
11
  const unlimited = rawTimeout === '0';
11
12
  const timeoutMs = unlimited ? Infinity : integer(rawTimeout, 300000, 2147483647);
@@ -55,6 +56,7 @@ export async function attach(root, args, output, signal) {
55
56
  break;
56
57
  if (!(args.values.reconnect && reconnectable(error)))
57
58
  throw error;
59
+ nextPollMs = pollMs;
58
60
  if (last !== error.code)
59
61
  output({
60
62
  ok: false,
@@ -67,7 +69,8 @@ export async function attach(root, args, output, signal) {
67
69
  const remaining = deadline - performance.now();
68
70
  if (remaining <= 0)
69
71
  break;
70
- await delay(Math.min(pollMs, remaining), undefined, { signal: observation }).catch(() => { });
72
+ await delay(Math.min(nextPollMs, remaining), undefined, { signal: observation }).catch(() => { });
73
+ nextPollMs = Math.min(pollMs, nextPollMs * 2);
71
74
  }
72
75
  if (!signal.aborted)
73
76
  throw new CliError('HOST_TIMEOUT');
@@ -1,6 +1,6 @@
1
1
  import { readFile, rm } from 'node:fs/promises';
2
2
  import { parse, stringify } from 'smol-toml';
3
- import { credentialRefSchema, lookupModelMetadata, normalizeProviderBaseUrl, normalizeProviderProtocol, parseDotenvText, providerCredentialKey, resolveCredentialMap, userAuthCredentialsPath, userConfigPath, } from '@saturn-universe/protocol';
3
+ import { credentialRefSchema, lookupModelMetadata, normalizeProviderBaseUrl, normalizeProviderProtocol, parseDotenvText, providerCredentialKey, providerModelRouteSchema, providerPresets, resolveCredentialMap, userAuthCredentialsPath, userConfigPath, } from '@saturn-universe/protocol';
4
4
  import { AuthError } from './cli-diagnostics.js';
5
5
  import { atomicWriteText } from './config-file.js';
6
6
  import { withUserConfigLock } from './config-lock.js';
@@ -46,12 +46,25 @@ function configuredProfiles(config) {
46
46
  });
47
47
  for (const [providerId, value] of Object.entries(table(config.providers))) {
48
48
  const entry = table(value);
49
- if (!Array.isArray(entry.models) || !entry.models.length)
49
+ const modelTable = Array.isArray(entry.models) ? undefined : table(entry.models);
50
+ const models = modelTable ? Object.keys(modelTable) : entry.models;
51
+ if (!Array.isArray(models) || !models.length)
50
52
  throw new AuthError('Could not read provider models in config.toml.');
51
- for (const model of entry.models) {
53
+ const overrides = table(entry.model_overrides);
54
+ for (const model of models) {
52
55
  if (typeof model !== 'string')
53
56
  throw new AuthError('Could not read provider models in config.toml.');
54
- profiles.push(read(`${providerId}/${model.trim()}`, providerId, model, entry, true));
57
+ const modelId = model.trim();
58
+ const modelRoute = providerModelRouteSchema.safeParse({
59
+ ...table(own(overrides, modelId)),
60
+ ...(modelTable ? table(own(modelTable, model)) : {}),
61
+ });
62
+ if (!modelRoute.success)
63
+ throw new AuthError('Could not read provider models in config.toml.');
64
+ profiles.push({
65
+ ...read(providerId + '/' + modelId, providerId, modelId, entry, true),
66
+ modelRoute: modelRoute.data,
67
+ });
55
68
  }
56
69
  }
57
70
  return profiles;
@@ -145,43 +158,63 @@ export async function saveProviderLogin(input, env) {
145
158
  const providers = table(config.providers);
146
159
  const previous = table(own(providers, input.providerId));
147
160
  const priorOverrides = table(previous.model_overrides);
161
+ const priorModels = previous.models !== undefined && !Array.isArray(previous.models) ? table(previous.models) : undefined;
148
162
  const credentialKey = providerCredentialKey(input.providerId);
149
163
  const credentialRef = input.credentialRef ?? `env:${credentialKey}`;
164
+ const sharesOpenCodeKey = (id) => providerPresets.some((preset) => preset.id === id && preset.openCodeModelsUrl && credentialRef === 'env:' + preset.defaultEnvKey);
150
165
  if (configuredProfiles(config).some((p) => p.providerId !== input.providerId &&
151
- (p.credentialRef === credentialRef ||
166
+ ((p.credentialRef === credentialRef &&
167
+ !(sharesOpenCodeKey(input.providerId) && sharesOpenCodeKey(p.providerId))) ||
152
168
  (p.layered && providerCredentialKey(p.providerId) === credentialKey))))
153
169
  throw new AuthError('The credential name is already used by another provider.');
154
170
  const discovered = new Map(input.discovered.map((model) => [model.id, model]));
171
+ const useModelTable = priorModels || input.models.some((id) => discovered.get(id)?.protocol !== undefined);
155
172
  const overrides = Object.fromEntries(input.models.flatMap((id) => {
156
173
  const model = discovered.get(id);
157
174
  const metadata = lookupModelMetadata(id);
158
- const previous = table(own(priorOverrides, id));
175
+ const previous = {
176
+ ...table(own(priorOverrides, id)),
177
+ ...(priorModels ? table(own(priorModels, id)) : {}),
178
+ };
179
+ const pricing = model?.priceSource === 'models.dev' || model?.priceSource === 'opencode'
180
+ ? model.pricing
181
+ : undefined;
159
182
  const values = {
160
- ...(model?.contextWindow !== undefined && metadata?.contextWindow !== model.contextWindow
183
+ ...(model?.protocol === undefined ? {} : { protocol: model.protocol }),
184
+ ...(model?.baseUrl === undefined ? {} : { base_url: model.baseUrl }),
185
+ ...(model?.tools === undefined ? {} : { tools: model.tools }),
186
+ ...(model?.structuredOutput === undefined ? {} : { structured_output: model.structuredOutput }),
187
+ ...(model?.images === undefined ? {} : { images: model.images }),
188
+ ...(model?.contextWindow !== undefined &&
189
+ (model.protocol || metadata?.contextWindow !== model.contextWindow)
161
190
  ? { context_window: model.contextWindow }
162
191
  : {}),
163
- ...(model?.maxOutputTokens !== undefined && metadata?.maxOutputTokens !== model.maxOutputTokens
192
+ ...(model?.maxOutputTokens !== undefined &&
193
+ (model.protocol || metadata?.maxOutputTokens !== model.maxOutputTokens)
164
194
  ? { max_output_tokens: model.maxOutputTokens }
165
195
  : {}),
166
196
  ...(model?.reasoningModel !== undefined ? { reasoning_model: model.reasoningModel } : {}),
167
- ...(model?.reasoningModel !== false && model?.reasoningEfforts?.length
197
+ ...(model?.reasoningModel !== false &&
198
+ model?.reasoningEfforts &&
199
+ (model.protocol || model.reasoningEfforts.length)
168
200
  ? { reasoning_efforts: [...model.reasoningEfforts] }
169
201
  : {}),
170
202
  ...(model?.defaultReasoningEffort
171
203
  ? { default_reasoning_effort: model.defaultReasoningEffort }
172
204
  : {}),
173
- ...(model?.priceSource === 'models.dev' && model.pricing
205
+ ...previous,
206
+ ...(pricing
174
207
  ? {
175
208
  pricing: {
176
- input_per_million: model.pricing.inputPerMillion,
177
- output_per_million: model.pricing.outputPerMillion,
178
- ...(model.pricing.cachedInputPerMillion === undefined
209
+ input_per_million: pricing.inputPerMillion,
210
+ output_per_million: pricing.outputPerMillion,
211
+ ...(pricing.cachedInputPerMillion === undefined
179
212
  ? {}
180
- : { cached_input_per_million: model.pricing.cachedInputPerMillion }),
213
+ : { cached_input_per_million: pricing.cachedInputPerMillion }),
214
+ ...table(previous.pricing),
181
215
  },
182
216
  }
183
217
  : {}),
184
- ...previous,
185
218
  };
186
219
  return Object.keys(values).length ? [[id, values]] : [];
187
220
  }));
@@ -192,8 +225,8 @@ export async function saveProviderLogin(input, env) {
192
225
  base_url: input.baseUrl,
193
226
  protocol: input.protocol,
194
227
  credential_ref: credentialRef,
195
- models,
196
- ...(Object.keys(overrides).length ? { model_overrides: overrides } : {}),
228
+ models: useModelTable ? Object.fromEntries(models.map((id) => [id, own(overrides, id) ?? {}])) : models,
229
+ ...(!useModelTable && Object.keys(overrides).length ? { model_overrides: overrides } : {}),
197
230
  };
198
231
  config.providers = { ...providers, [input.providerId]: entry };
199
232
  const profiles = configuredProfiles(config);
@@ -281,5 +314,10 @@ export async function configuredEndpoint(profile, root, env) {
281
314
  const key = (await resolveCredentialMap(root, env)).values.get(item.credentialRef.slice(4));
282
315
  if (!key?.trim())
283
316
  throw new AuthError('尚未填写这个服务的密钥。');
284
- return { baseUrl: item.baseUrl, model: item.modelId, key, protocol: item.protocol };
317
+ return {
318
+ baseUrl: item.modelRoute?.base_url ?? item.baseUrl,
319
+ model: item.modelId,
320
+ key,
321
+ protocol: item.modelRoute?.protocol ?? item.protocol,
322
+ };
285
323
  }
package/dist/cli-help.js CHANGED
@@ -6,7 +6,7 @@ const topics = {
6
6
  summary: '配置 AI 服务和默认模型',
7
7
  actions: {
8
8
  add: [
9
- '[<provider>] [--base-url URL] [--protocol openai-responses|openai-chat|anthropic|gemini] [--models ID[,ID...]] [--default ID] [--api-key-stdin | --credential-ref env:NAME] [--no-probe] [--json]',
9
+ '[<provider>] [--base-url URL] [--protocol openai-responses|openai-chat|anthropic|gemini] [--models ID[,ID...]] [--default ID | --model ID] [--api-key-stdin | --credential-ref env:NAME] [--no-probe] [--json]',
10
10
  '连接服务商并选择默认模型。交互模式下可直接运行。',
11
11
  'saturn provider add',
12
12
  ],
@@ -2,6 +2,7 @@ import { parseArgs } from 'node:util';
2
2
  import { CliError } from './cli-diagnostics.js';
3
3
  import { workspaceRoot } from './client.js';
4
4
  import { sendHostCommand } from './host-command.js';
5
+ import { inspectHostModes } from './host-launcher.js';
5
6
  import { renderConfigCheck, renderConfigInit, renderConfigSummary } from './renderer.js';
6
7
  import { initUserConfig, inspectUserConfig } from './user-config.js';
7
8
  export async function runConfigCommand(configArgs) {
@@ -37,11 +38,22 @@ export async function runConfigCommand(configArgs) {
37
38
  }
38
39
  const workdir = await workspaceRoot(typeof parsed.values.workspace === 'string' ? parsed.values.workspace : process.cwd());
39
40
  const inspection = await inspectUserConfig(workdir);
40
- const status = await sendHostCommand(workdir, { type: 'host.status' }, { timeoutMs: 2000 }).catch(() => undefined);
41
+ const [status, availableModes] = await Promise.all([
42
+ sendHostCommand(workdir, { type: 'host.status' }, { timeoutMs: 2000 }).catch(() => undefined),
43
+ sub === 'check' ? inspectHostModes(workdir) : undefined,
44
+ ]);
41
45
  if (json) {
42
- process.stdout.write(JSON.stringify({ ok: true, result: { ...inspection, ...(status ? { host: status } : {}) } }) + '\n');
46
+ process.stdout.write(JSON.stringify({
47
+ ok: true,
48
+ result: {
49
+ ...inspection,
50
+ ...(status ? { host: status } : {}),
51
+ ...(availableModes ? { availableModes } : {}),
52
+ },
53
+ }) + '\n');
43
54
  return;
44
55
  }
45
- process.stdout.write((sub === 'check' ? renderConfigCheck(inspection, status) : renderConfigSummary(inspection, status)) +
46
- '\n');
56
+ process.stdout.write((sub === 'check'
57
+ ? renderConfigCheck(inspection, status, availableModes)
58
+ : renderConfigSummary(inspection, status)) + '\n');
47
59
  }
@@ -1,4 +1,4 @@
1
- import type { HostStatusSnapshot } from '@saturn-universe/protocol';
1
+ import type { HostStatusSnapshot, ModeSummary } from '@saturn-universe/protocol';
2
2
  export interface HostLaunchOptions {
3
3
  readonly config?: string;
4
4
  readonly profile?: string;
@@ -15,6 +15,7 @@ export interface ManagedHost {
15
15
  export declare const DEFAULT_HOST_READY_TIMEOUT_MS = 60000;
16
16
  export declare function resolveHostReadyTimeoutMs(env?: NodeJS.ProcessEnv): number;
17
17
  export declare function resolveHostEntry(): Promise<string>;
18
+ export declare function inspectHostModes(root: string): Promise<readonly ModeSummary[]>;
18
19
  export declare function shouldEnableEnvProxy(env: NodeJS.ProcessEnv): boolean;
19
20
  export declare function buildHostSpawnEnv(baseEnv?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
20
21
  export declare function ensureHost(root: string, options?: HostLaunchOptions): Promise<ManagedHost>;
@@ -1,10 +1,11 @@
1
- import { spawn } from 'node:child_process';
1
+ import { execFile, spawn } from 'node:child_process';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { access, realpath } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
  import { createRequire } from 'node:module';
6
6
  import { setTimeout as delay } from 'node:timers/promises';
7
7
  import { fileURLToPath } from 'node:url';
8
+ import { promisify } from 'node:util';
8
9
  import { matchesModeSelector, parseHostStatusResult } from '@saturn-universe/protocol';
9
10
  import { request } from './client.js';
10
11
  import { CliError, isHostConnectionError, safeCode } from './cli-diagnostics.js';
@@ -71,6 +72,20 @@ function parseHostStartupError(stderrText) {
71
72
  }
72
73
  return undefined;
73
74
  }
75
+ export async function inspectHostModes(root) {
76
+ const hostEntry = await resolveHostEntry();
77
+ try {
78
+ const { stdout } = await promisify(execFile)(process.execPath, [hostEntry, root, '--inspect-modes'], {
79
+ timeout: resolveHostReadyTimeoutMs(),
80
+ windowsHide: true,
81
+ });
82
+ return JSON.parse(stdout);
83
+ }
84
+ catch (error) {
85
+ const { stderr } = error;
86
+ throw (stderr && parseHostStartupError(stderr)) || new CliError('HOST_UNAVAILABLE');
87
+ }
88
+ }
74
89
  export function shouldEnableEnvProxy(env) {
75
90
  return (env.NODE_USE_ENV_PROXY === undefined &&
76
91
  Boolean(env.HTTPS_PROXY?.trim() || env.https_proxy?.trim() || env.HTTP_PROXY?.trim() || env.http_proxy?.trim()));
package/dist/menu.d.ts CHANGED
@@ -3,5 +3,5 @@ export interface AuthPrompt extends ChoicePrompt {
3
3
  close(): void;
4
4
  }
5
5
  export declare function terminalPrompt(input: NodeJS.ReadStream, output: NodeJS.WriteStream): AuthPrompt;
6
- export declare function askChoice(prompt: AuthPrompt, print: (s: string) => void, title: string, labels: readonly string[]): Promise<number>;
6
+ export declare function askChoice(prompt: AuthPrompt, print: (s: string) => void, title: string, labels: readonly string[], defaultIndex?: number): Promise<number>;
7
7
  export declare function pickAction(title: string, labels: readonly string[]): Promise<number>;
package/dist/menu.js CHANGED
@@ -67,14 +67,14 @@ export function terminalPrompt(input, output) {
67
67
  close,
68
68
  };
69
69
  }
70
- export async function askChoice(prompt, print, title, labels) {
70
+ export async function askChoice(prompt, print, title, labels, defaultIndex) {
71
71
  if (!labels.length)
72
72
  throw new AuthError('当前没有可选择的项目。');
73
73
  print(title);
74
74
  labels.forEach((label, i) => print(' ' + (i + 1) + '. ' + label));
75
75
  for (;;) {
76
76
  const answer = await prompt.question('编号: ');
77
- const index = Number(answer) - 1;
77
+ const index = answer.trim() === '' && defaultIndex !== undefined ? defaultIndex : Number(answer) - 1;
78
78
  if (Number.isInteger(index) && index >= 0 && index < labels.length)
79
79
  return index;
80
80
  print('请选择列表中的编号。');
@@ -1,6 +1,11 @@
1
1
  import { type ModelPricing, type ProviderProtocol } from '@saturn-universe/protocol';
2
2
  export interface DiscoveredModel {
3
3
  readonly id: string;
4
+ readonly protocol?: ProviderProtocol;
5
+ readonly baseUrl?: string;
6
+ readonly tools?: boolean;
7
+ readonly structuredOutput?: boolean;
8
+ readonly images?: boolean;
4
9
  readonly displayName?: string;
5
10
  readonly contextWindow?: number;
6
11
  readonly maxOutputTokens?: number;
@@ -8,7 +13,7 @@ export interface DiscoveredModel {
8
13
  readonly reasoningEfforts?: readonly string[];
9
14
  readonly defaultReasoningEffort?: string;
10
15
  readonly pricing?: ModelPricing;
11
- readonly priceSource?: 'models.dev' | 'models.dev-estimate';
16
+ readonly priceSource?: 'models.dev' | 'models.dev-estimate' | 'opencode';
12
17
  readonly textOutput?: boolean;
13
18
  }
14
19
  export interface ProviderDiscovery {
@@ -23,4 +28,5 @@ export declare function supportsTextModel(model: DiscoveredModel): boolean;
23
28
  export declare function probeProviderEndpoint(baseUrl: string, apiKey: string, options?: {
24
29
  readonly preferredProtocol?: ProviderProtocol;
25
30
  readonly fetch?: typeof fetch;
31
+ readonly signal?: AbortSignal;
26
32
  }): Promise<ProviderDiscovery>;
@@ -1,4 +1,4 @@
1
- import { lookupModelMetadata, normalizeProviderBaseUrl, } from '@saturn-universe/protocol';
1
+ import { lookupModelMetadata, normalizeProviderBaseUrl, openCodeClientHeaders, providerPresets, } from '@saturn-universe/protocol';
2
2
  function modelListProtocol(protocol) {
3
3
  return protocol === 'openai-responses' || protocol === 'openai-chat' ? 'openai' : protocol;
4
4
  }
@@ -35,6 +35,14 @@ export function supportsTextModel(model) {
35
35
  function tokenLimit(...values) {
36
36
  return values.find((value) => typeof value === 'number' && Number.isSafeInteger(value) && value > 0);
37
37
  }
38
+ function safeModelId(id, apiKey) {
39
+ return Boolean(id) && id.length <= 200 && !/[\u0000-\u001f\u007f-\u009f]/.test(id) && !id.includes(apiKey);
40
+ }
41
+ function safeDisplayName(value, apiKey) {
42
+ return typeof value === 'string' && !value.includes(apiKey)
43
+ ? value.replace(/[\u0000-\u001f\u007f-\u009f]/g, '').slice(0, 200) || undefined
44
+ : undefined;
45
+ }
38
46
  function modelList(value, protocol, apiKey) {
39
47
  const body = record(value);
40
48
  const items = protocol === 'gemini'
@@ -58,11 +66,7 @@ function modelList(value, protocol, apiKey) {
58
66
  row.supportedGenerationMethods.includes('generateContent')))
59
67
  continue;
60
68
  const id = (gemini ? rawId.replace(/^models\//, '') : rawId).trim();
61
- if (!id ||
62
- id.length > 200 ||
63
- /[\u0000-\u001f\u007f-\u009f]/.test(id) ||
64
- id.includes(apiKey) ||
65
- models.has(id))
69
+ if (!safeModelId(id, apiKey) || models.has(id))
66
70
  continue;
67
71
  const metadata = lookupModelMetadata(id);
68
72
  const topProvider = record(row.top_provider);
@@ -70,10 +74,7 @@ function modelList(value, protocol, apiKey) {
70
74
  const maxOutputTokens = tokenLimit(row.max_output_tokens, row.max_tokens, row.outputTokenLimit, row.max_completion_tokens, topProvider?.max_completion_tokens) ?? metadata?.maxOutputTokens;
71
75
  const architecture = record(row.architecture);
72
76
  const textOutput = textOutputFromModalities(row.output_modalities ?? architecture?.output_modalities ?? record(row.modalities)?.output);
73
- const name = row.display_name ?? row.displayName ?? row.name;
74
- const displayName = typeof name === 'string' && !name.includes(apiKey)
75
- ? name.replace(/[\u0000-\u001f\u007f-\u009f]/g, '').slice(0, 200)
76
- : undefined;
77
+ const displayName = safeDisplayName(row.display_name ?? row.displayName ?? row.name, apiKey);
77
78
  models.set(id, {
78
79
  id,
79
80
  ...(displayName ? { displayName } : {}),
@@ -88,9 +89,97 @@ function modelList(value, protocol, apiKey) {
88
89
  return undefined;
89
90
  return [...models.values()];
90
91
  }
92
+ const openCodeProtocols = {
93
+ 'chat-completions': 'openai-chat',
94
+ responses: 'openai-responses',
95
+ messages: 'anthropic',
96
+ 'generate-content': 'gemini',
97
+ };
98
+ function openCodePricing(value) {
99
+ const text = record(record(value)?.text);
100
+ const input = record(text?.input);
101
+ const inputPerMillion = input?.price;
102
+ const outputPerMillion = record(text?.output)?.price;
103
+ const cachedInputPerMillion = record(input?.cache)?.read;
104
+ const rate = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0;
105
+ if (!rate(inputPerMillion) || !rate(outputPerMillion))
106
+ return undefined;
107
+ return {
108
+ inputPerMillion,
109
+ outputPerMillion,
110
+ ...(rate(cachedInputPerMillion) ? { cachedInputPerMillion } : {}),
111
+ };
112
+ }
113
+ function openCodeModels(value, catalogUrl, apiKey) {
114
+ const rows = record(value)?.data;
115
+ if (!Array.isArray(rows))
116
+ return undefined;
117
+ const origin = new URL(catalogUrl).origin;
118
+ const models = new Map();
119
+ for (const item of rows) {
120
+ const row = record(item);
121
+ if (!row || typeof row.id !== 'string')
122
+ continue;
123
+ const id = row.id.trim();
124
+ if (!safeModelId(id, apiKey) || models.has(id))
125
+ continue;
126
+ const api = record(row.api);
127
+ if (!api)
128
+ continue;
129
+ const routes = Object.entries(openCodeProtocols).flatMap(([name, protocol]) => {
130
+ const rawUrl = record(api[name])?.base_url;
131
+ const baseUrl = typeof rawUrl === 'string' ? normalizeProviderBaseUrl(rawUrl) : undefined;
132
+ if (!baseUrl || new URL(baseUrl).origin !== origin || decodeURI(baseUrl).includes(apiKey))
133
+ return [];
134
+ return [{ name, protocol, baseUrl }];
135
+ });
136
+ const route = routes.find(({ name }) => name === row.recommended_api) ?? routes[0];
137
+ if (!route)
138
+ continue;
139
+ const capabilities = record(row.capabilities);
140
+ const limit = record(row.limit);
141
+ const reasoning = record(capabilities?.reasoning);
142
+ const effort = reasoning?.effort;
143
+ const reasoningEfforts = Array.isArray(effort)
144
+ ? [
145
+ ...new Set(effort.filter((value) => typeof value === 'string' && value.trim() === value && safeModelId(value, apiKey))),
146
+ ]
147
+ : [];
148
+ const tools = record(capabilities?.tools)?.supported;
149
+ const reasoningModel = reasoning?.supported;
150
+ const structuredOutput = capabilities?.structured_output;
151
+ const input = record(row.modalities)?.input;
152
+ const contextWindow = tokenLimit(limit?.context);
153
+ const maxOutputTokens = tokenLimit(limit?.output);
154
+ const pricing = openCodePricing(row.cost);
155
+ const displayName = safeDisplayName(row.name, apiKey);
156
+ models.set(id, {
157
+ id,
158
+ protocol: route.protocol,
159
+ baseUrl: route.baseUrl,
160
+ textOutput: true,
161
+ ...(displayName ? { displayName } : {}),
162
+ ...(contextWindow === undefined ? {} : { contextWindow }),
163
+ ...(maxOutputTokens === undefined ? {} : { maxOutputTokens }),
164
+ ...(typeof tools === 'boolean' ? { tools } : {}),
165
+ ...(typeof reasoningModel === 'boolean' ? { reasoningModel, reasoningEfforts } : {}),
166
+ ...(typeof structuredOutput === 'boolean' ? { structuredOutput } : {}),
167
+ ...(Array.isArray(input)
168
+ ? {
169
+ images: input.some((type) => typeof type === 'string' && (type === 'image' || type.startsWith('image/'))),
170
+ }
171
+ : {}),
172
+ ...(pricing ? { pricing, priceSource: 'opencode' } : {}),
173
+ });
174
+ }
175
+ return [...models.values()];
176
+ }
91
177
  export async function probeProviderEndpoint(baseUrl, apiKey, options = {}) {
92
178
  const endpoint = normalizeProviderBaseUrl(baseUrl);
93
- const fallback = options.preferredProtocol ?? (endpoint ? inferProviderProtocol(endpoint) : 'openai-responses');
179
+ const preset = providerPresets.find((preset) => preset.openCodeModelsUrl && preset.defaultBaseUrl === endpoint);
180
+ const fallback = options.preferredProtocol ??
181
+ preset?.defaultProtocol ??
182
+ (endpoint ? inferProviderProtocol(endpoint) : 'openai-responses');
94
183
  const unavailable = {
95
184
  protocol: fallback,
96
185
  confidence: 'unknown',
@@ -100,7 +189,26 @@ export async function probeProviderEndpoint(baseUrl, apiKey, options = {}) {
100
189
  if (!endpoint || !apiKey.trim())
101
190
  return unavailable;
102
191
  const request = options.fetch ?? fetch;
103
- const signal = AbortSignal.timeout(8000);
192
+ const timeout = AbortSignal.timeout(8000);
193
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
194
+ if (preset?.openCodeModelsUrl) {
195
+ try {
196
+ const response = await request(preset?.openCodeModelsUrl, {
197
+ headers: { Authorization: 'Bearer ' + apiKey, ...openCodeClientHeaders },
198
+ signal,
199
+ redirect: 'error',
200
+ });
201
+ if (!response.ok) {
202
+ await response.body?.cancel();
203
+ return unavailable;
204
+ }
205
+ const models = openCodeModels(await response.json(), preset?.openCodeModelsUrl, apiKey);
206
+ return models ? { protocol: fallback, confidence: 'detected', models } : unavailable;
207
+ }
208
+ catch {
209
+ return unavailable;
210
+ }
211
+ }
104
212
  const headersFor = {
105
213
  openai: { Authorization: `Bearer ${apiKey}` },
106
214
  anthropic: { 'x-api-key': apiKey, 'anthropic-version': '2023-06-01' },
@@ -1,3 +1,3 @@
1
1
  import { type DiscoveredModel } from './provider-discovery.js';
2
2
  export declare function modelAlias(id: string): string;
3
- export declare function enrichPrices(baseUrl: string, models: readonly DiscoveredModel[], request?: typeof fetch): Promise<readonly DiscoveredModel[]>;
3
+ export declare function enrichPrices(baseUrl: string, models: readonly DiscoveredModel[], request?: typeof fetch, signal?: AbortSignal): Promise<readonly DiscoveredModel[]>;
@@ -64,14 +64,18 @@ function priceIndex(entries) {
64
64
  };
65
65
  }
66
66
  // Only the public catalog URL is sent. Endpoint, credentials and model IDs stay local.
67
- export async function enrichPrices(baseUrl, models, request = fetch) {
67
+ export async function enrichPrices(baseUrl, models, request = fetch, signal) {
68
68
  if (!models.length)
69
69
  return models;
70
70
  const endpoint = normalizeProviderBaseUrl(baseUrl);
71
- const preset = providerPresets.find((p) => p.defaultBaseUrl && p.defaultBaseUrl === endpoint)?.id;
71
+ const matchedPreset = providerPresets.find((p) => p.defaultBaseUrl && p.defaultBaseUrl === endpoint);
72
+ if (matchedPreset?.openCodeModelsUrl)
73
+ return models;
74
+ const preset = matchedPreset?.id;
72
75
  try {
76
+ const timeout = AbortSignal.timeout(4000);
73
77
  const response = await request('https://models.dev/api.json', {
74
- signal: AbortSignal.timeout(4000),
78
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
75
79
  redirect: 'error',
76
80
  });
77
81
  if (!response.ok) {
@@ -0,0 +1,18 @@
1
+ import { type ProviderPreset, type ProviderProtocol } from '@saturn-universe/protocol';
2
+ export declare const customProtocols: readonly ["openai-chat", "openai-responses", "anthropic", "gemini"];
3
+ export declare const providerWizard: {
4
+ start(): void;
5
+ finish(profile: string, configPath: string): void;
6
+ cancel(error: unknown): void;
7
+ selectProvider(presets: readonly ProviderPreset[]): Promise<string>;
8
+ selectProtocol(): Promise<"openai-responses" | "openai-chat" | "anthropic" | "gemini">;
9
+ endpoint(protocol: ProviderProtocol | undefined): Promise<string>;
10
+ apiKey(): Promise<string>;
11
+ selectModel(options: {
12
+ value: string;
13
+ label: string;
14
+ hint: string;
15
+ }[]): Promise<string>;
16
+ manualModel(): Promise<string>;
17
+ fetchModels<T>(load: (signal: AbortSignal) => Promise<T>): Promise<T | undefined>;
18
+ };
@@ -0,0 +1,109 @@
1
+ import { autocomplete, CANCEL_SYMBOL, cancel, intro, isCancel, outro, password, select, settings, spinner, text, } from '@clack/prompts';
2
+ import { emitKeypressEvents } from 'node:readline';
3
+ import { styleText } from 'node:util';
4
+ import { normalizeProviderBaseUrl, } from '@saturn-universe/protocol';
5
+ export const customProtocols = ['openai-chat', 'openai-responses', 'anthropic', 'gemini'];
6
+ async function answer(prompt) {
7
+ const value = await prompt;
8
+ if (isCancel(value))
9
+ throw value;
10
+ return value;
11
+ }
12
+ export const providerWizard = {
13
+ start() {
14
+ const brand = styleText(['bgYellow', 'black', 'bold'], ' SATURN ');
15
+ intro(`${brand} ${styleText('bold', 'Provider Setup')}`);
16
+ },
17
+ finish(profile, configPath) {
18
+ outro(`Saved ${styleText('bold', profile)} to ${configPath}`);
19
+ },
20
+ cancel(error) {
21
+ if (!isCancel(error))
22
+ throw error;
23
+ cancel('Provider setup cancelled.');
24
+ },
25
+ selectProvider(presets) {
26
+ return answer(select({
27
+ message: 'Select provider',
28
+ options: presets.map((preset) => ({
29
+ value: preset.id,
30
+ label: preset.label,
31
+ ...(preset.defaultBaseUrl ? { hint: preset.defaultProtocol } : {}),
32
+ })),
33
+ }));
34
+ },
35
+ selectProtocol() {
36
+ return answer(select({
37
+ message: 'Select protocol',
38
+ initialValue: 'openai-chat',
39
+ options: customProtocols.map((value) => ({
40
+ value,
41
+ label: value,
42
+ ...(value === 'openai-chat' ? { hint: 'recommended' } : {}),
43
+ })),
44
+ }));
45
+ },
46
+ endpoint(protocol) {
47
+ return answer(text({
48
+ message: 'Enter endpoint URL',
49
+ placeholder: protocol === 'gemini' ? 'https://api.example.com/v1beta' : 'https://api.example.com/v1',
50
+ validate: (value) => normalizeProviderBaseUrl(value ?? '') ? undefined : 'Enter a complete HTTP or HTTPS URL.',
51
+ }));
52
+ },
53
+ apiKey() {
54
+ return answer(password({
55
+ message: 'Enter API key',
56
+ validate: (value) => (value?.trim() ? undefined : 'Enter an API key.'),
57
+ }));
58
+ },
59
+ selectModel(options) {
60
+ return answer(autocomplete({ message: 'Select default model', options, placeholder: 'Search models' }));
61
+ },
62
+ manualModel() {
63
+ return answer(text({
64
+ message: 'Enter model ID',
65
+ validate: (value) => (value?.trim() ? undefined : 'Enter a model ID.'),
66
+ }));
67
+ },
68
+ async fetchModels(load) {
69
+ const input = process.stdin;
70
+ const wasRaw = Boolean(input.isRaw);
71
+ const wasFlowing = input.readableFlowing === true;
72
+ const controller = new AbortController();
73
+ // The animated spinner otherwise handles these keys with process.exit(0).
74
+ // Let the wizard abort discovery and render its cancellation footer instead.
75
+ const cancelAliases = ['escape', '\x03'].filter((key) => settings.aliases.get(key) === 'cancel');
76
+ const progress = spinner({
77
+ onCancel: () => controller.abort(),
78
+ signal: controller.signal,
79
+ cancelMessage: 'Model discovery cancelled.',
80
+ });
81
+ const onKey = (_, key) => {
82
+ if (key?.name === 'escape' || (key?.ctrl && key.name === 'c'))
83
+ controller.abort();
84
+ };
85
+ for (const key of cancelAliases)
86
+ settings.aliases.delete(key);
87
+ try {
88
+ emitKeypressEvents(input);
89
+ input.setRawMode(true);
90
+ input.on('keypress', onKey);
91
+ input.resume();
92
+ progress.start('Fetching models...');
93
+ const result = await load(controller.signal).catch(() => undefined);
94
+ if (controller.signal.aborted)
95
+ throw CANCEL_SYMBOL;
96
+ progress.stop(result ? 'Model discovery finished' : 'Model list unavailable');
97
+ return result;
98
+ }
99
+ finally {
100
+ progress.clear();
101
+ input.off('keypress', onKey);
102
+ input.setRawMode(wasRaw);
103
+ if (!wasFlowing)
104
+ input.pause();
105
+ for (const key of cancelAliases)
106
+ settings.aliases.set(key, 'cancel');
107
+ }
108
+ },
109
+ };