@saturn-universe/cli 0.0.0-stage → 0.1.0

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 (85) hide show
  1. package/LICENSE +661 -0
  2. package/dist/attach.d.ts +9 -0
  3. package/dist/attach.js +80 -0
  4. package/dist/auth-config.d.ts +31 -0
  5. package/dist/auth-config.js +285 -0
  6. package/dist/choice-menu.d.ts +13 -0
  7. package/dist/choice-menu.js +238 -0
  8. package/dist/cli-diagnostics.d.ts +23 -0
  9. package/dist/cli-diagnostics.js +42 -0
  10. package/dist/cli-help.d.ts +6 -0
  11. package/dist/cli-help.js +163 -0
  12. package/dist/client.d.ts +13 -0
  13. package/dist/client.js +90 -0
  14. package/dist/commands.d.ts +64 -0
  15. package/dist/commands.js +299 -0
  16. package/dist/compaction-command.d.ts +16 -0
  17. package/dist/compaction-command.js +16 -0
  18. package/dist/composer.d.ts +88 -0
  19. package/dist/composer.js +124 -0
  20. package/dist/config-cli.d.ts +1 -0
  21. package/dist/config-cli.js +47 -0
  22. package/dist/config-file.d.ts +1 -0
  23. package/dist/config-file.js +43 -0
  24. package/dist/config-lock.d.ts +5 -0
  25. package/dist/config-lock.js +45 -0
  26. package/dist/duration.d.ts +2 -0
  27. package/dist/duration.js +11 -0
  28. package/dist/export.d.ts +19 -0
  29. package/dist/export.js +66 -0
  30. package/dist/host-command.d.ts +40 -0
  31. package/dist/host-command.js +48 -0
  32. package/dist/host-launcher.d.ts +22 -0
  33. package/dist/host-launcher.js +300 -0
  34. package/dist/index.d.ts +2 -0
  35. package/dist/index.js +400 -0
  36. package/dist/markdown.d.ts +1 -0
  37. package/dist/markdown.js +118 -0
  38. package/dist/mcp-cli.d.ts +44 -0
  39. package/dist/mcp-cli.js +647 -0
  40. package/dist/menu.d.ts +7 -0
  41. package/dist/menu.js +91 -0
  42. package/dist/project-mcp-config.d.ts +9 -0
  43. package/dist/project-mcp-config.js +98 -0
  44. package/dist/provider-discovery.d.ts +26 -0
  45. package/dist/provider-discovery.js +138 -0
  46. package/dist/provider-pricing.d.ts +3 -0
  47. package/dist/provider-pricing.js +130 -0
  48. package/dist/provider.d.ts +16 -0
  49. package/dist/provider.js +370 -0
  50. package/dist/reconcile-command.d.ts +36 -0
  51. package/dist/reconcile-command.js +64 -0
  52. package/dist/renderer.d.ts +204 -0
  53. package/dist/renderer.js +1134 -0
  54. package/dist/repl-host.d.ts +22 -0
  55. package/dist/repl-host.js +51 -0
  56. package/dist/repl-run-observer.d.ts +27 -0
  57. package/dist/repl-run-observer.js +86 -0
  58. package/dist/repl.d.ts +12 -0
  59. package/dist/repl.js +1834 -0
  60. package/dist/results.d.ts +23 -0
  61. package/dist/results.js +1 -0
  62. package/dist/sandbox-cli.d.ts +39 -0
  63. package/dist/sandbox-cli.js +324 -0
  64. package/dist/session-history.d.ts +17 -0
  65. package/dist/session-history.js +76 -0
  66. package/dist/settings-menu.d.ts +2 -0
  67. package/dist/settings-menu.js +111 -0
  68. package/dist/skill-cli.d.ts +25 -0
  69. package/dist/skill-cli.js +355 -0
  70. package/dist/slash-commands.d.ts +66 -0
  71. package/dist/slash-commands.js +1449 -0
  72. package/dist/terminal-input.d.ts +24 -0
  73. package/dist/terminal-input.js +111 -0
  74. package/dist/terminal-selection.d.ts +21 -0
  75. package/dist/terminal-selection.js +72 -0
  76. package/dist/terminal-text.d.ts +38 -0
  77. package/dist/terminal-text.js +238 -0
  78. package/dist/tui.d.ts +170 -0
  79. package/dist/tui.js +2559 -0
  80. package/dist/usage.d.ts +13 -0
  81. package/dist/usage.js +46 -0
  82. package/dist/user-config.d.ts +48 -0
  83. package/dist/user-config.js +188 -0
  84. package/package.json +18 -3
  85. package/README.md +0 -3
package/dist/menu.js ADDED
@@ -0,0 +1,91 @@
1
+ import { createInterface } from 'node:readline/promises';
2
+ import { Writable } from 'node:stream';
3
+ import { AuthError } from './cli-diagnostics.js';
4
+ import { chooseInTerminal } from './choice-menu.js';
5
+ export function terminalPrompt(input, output) {
6
+ let hidden = false;
7
+ const display = new Writable({
8
+ write(chunk, _encoding, callback) {
9
+ if (hidden)
10
+ callback();
11
+ else
12
+ output.write(chunk, callback);
13
+ },
14
+ });
15
+ let cli;
16
+ let closed;
17
+ const open = () => {
18
+ if (cli)
19
+ return cli;
20
+ const active = createInterface({ input, output: display, terminal: true, historySize: 0 });
21
+ const signal = new AbortController();
22
+ active.on('SIGINT', () => active.close());
23
+ active.on('close', () => signal.abort());
24
+ closed = signal;
25
+ cli = active;
26
+ return active;
27
+ };
28
+ const close = () => {
29
+ cli?.close();
30
+ cli = undefined;
31
+ };
32
+ const supportsPicker = input.isTTY &&
33
+ output.isTTY &&
34
+ process.env.TERM !== 'dumb' &&
35
+ (output.columns || 80) >= 24 &&
36
+ (output.rows || 24) >= 6;
37
+ return {
38
+ async question(label, secret = false) {
39
+ const active = open();
40
+ hidden = secret;
41
+ if (secret)
42
+ output.write(label);
43
+ try {
44
+ return (await active.question(secret ? '' : label, { signal: closed.signal })).trim();
45
+ }
46
+ catch {
47
+ throw new AuthError('已取消设置。', 'USAGE');
48
+ }
49
+ finally {
50
+ hidden = false;
51
+ if (secret)
52
+ output.write('\n');
53
+ }
54
+ },
55
+ ...(supportsPicker
56
+ ? {
57
+ async choose(title, items) {
58
+ close();
59
+ return (await chooseInTerminal(input, output, title, items))[0];
60
+ },
61
+ async chooseMany(title, items) {
62
+ close();
63
+ return chooseInTerminal(input, output, title, items, true);
64
+ },
65
+ }
66
+ : {}),
67
+ close,
68
+ };
69
+ }
70
+ export async function askChoice(prompt, print, title, labels) {
71
+ if (!labels.length)
72
+ throw new AuthError('当前没有可选择的项目。');
73
+ print(title);
74
+ labels.forEach((label, i) => print(' ' + (i + 1) + '. ' + label));
75
+ for (;;) {
76
+ const answer = await prompt.question('编号: ');
77
+ const index = Number(answer) - 1;
78
+ if (Number.isInteger(index) && index >= 0 && index < labels.length)
79
+ return index;
80
+ print('请选择列表中的编号。');
81
+ }
82
+ }
83
+ export async function pickAction(title, labels) {
84
+ const prompt = terminalPrompt(process.stdin, process.stdout);
85
+ try {
86
+ return await askChoice(prompt, (line) => process.stdout.write(line + '\n'), title, labels.map((s) => s.replace(/[\x00-\x1f\x7f-\x9f]/g, ' ')));
87
+ }
88
+ finally {
89
+ prompt.close();
90
+ }
91
+ }
@@ -0,0 +1,9 @@
1
+ import type { NormalizedMcpServerConfig } from '@saturn-universe/protocol';
2
+ export declare function inspectProjectMcpConfig(workdir: string): Promise<{
3
+ readonly path: string;
4
+ readonly servers: Readonly<Record<string, NormalizedMcpServerConfig>>;
5
+ readonly parseError?: string;
6
+ }>;
7
+ export declare function writeProjectMcpServer(workdir: string, name: string, entry: Record<string, unknown>): Promise<string>;
8
+ export declare function updateProjectMcpServer(workdir: string, name: string, update: (current: unknown) => Record<string, unknown>): Promise<void>;
9
+ export declare function removeProjectMcpServer(workdir: string, name: string): Promise<string | undefined>;
@@ -0,0 +1,98 @@
1
+ import { readFile, stat } from 'node:fs/promises';
2
+ import { MAX_PROJECT_MCP_SERVERS, parseProjectMcpJson, projectMcpConfigPath, } from '@saturn-universe/protocol';
3
+ import { atomicWriteText } from './config-file.js';
4
+ import { withProjectMcpConfigLock } from './config-lock.js';
5
+ async function readOptionalText(filename) {
6
+ try {
7
+ return await readFile(filename, 'utf8');
8
+ }
9
+ catch (error) {
10
+ if (error.code === 'ENOENT')
11
+ return undefined;
12
+ throw error;
13
+ }
14
+ }
15
+ export async function inspectProjectMcpConfig(workdir) {
16
+ const filename = projectMcpConfigPath(workdir);
17
+ const text = await readOptionalText(filename);
18
+ if (text === undefined)
19
+ return { path: filename, servers: {} };
20
+ try {
21
+ return { path: filename, servers: parseProjectMcpJson(text) };
22
+ }
23
+ catch (error) {
24
+ return {
25
+ path: filename,
26
+ servers: {},
27
+ parseError: error instanceof Error ? error.message : 'Invalid .mcp.json',
28
+ };
29
+ }
30
+ }
31
+ function jsonObject(value) {
32
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
33
+ return value;
34
+ }
35
+ return undefined;
36
+ }
37
+ async function editProjectMcpDocument(workdir, filename, update) {
38
+ return withProjectMcpConfigLock(workdir, async () => {
39
+ const text = await readOptionalText(filename);
40
+ const next = update(text === undefined ? undefined : JSON.parse(text));
41
+ if (next === undefined)
42
+ return false;
43
+ await atomicWriteText(filename, JSON.stringify(next, null, 2) + '\n', 0o600);
44
+ return true;
45
+ });
46
+ }
47
+ export async function writeProjectMcpServer(workdir, name, entry) {
48
+ const filename = projectMcpConfigPath(workdir);
49
+ try {
50
+ await editProjectMcpDocument(workdir, filename, (current) => {
51
+ const root = current === undefined ? {} : jsonObject(current);
52
+ if (!root)
53
+ throw new Error('Invalid .mcp.json: expected a JSON object.');
54
+ const mcpServers = { ...jsonObject(root.mcpServers), [name]: entry };
55
+ if (Object.keys(mcpServers).length > MAX_PROJECT_MCP_SERVERS) {
56
+ throw new Error(`Project .mcp.json supports at most ${MAX_PROJECT_MCP_SERVERS} MCP servers.`);
57
+ }
58
+ return { ...root, mcpServers };
59
+ });
60
+ }
61
+ catch (error) {
62
+ throw error instanceof SyntaxError ? new Error('Invalid .mcp.json: malformed JSON.') : error;
63
+ }
64
+ return filename;
65
+ }
66
+ export async function updateProjectMcpServer(workdir, name, update) {
67
+ try {
68
+ await editProjectMcpDocument(workdir, projectMcpConfigPath(workdir), (current) => {
69
+ const root = jsonObject(current);
70
+ const servers = jsonObject(root?.mcpServers);
71
+ const entry = update(servers && Object.hasOwn(servers, name) ? servers[name] : undefined);
72
+ return { ...root, mcpServers: { ...servers, [name]: entry } };
73
+ });
74
+ }
75
+ catch (error) {
76
+ throw error instanceof SyntaxError ? new Error('Invalid .mcp.json: malformed JSON.') : error;
77
+ }
78
+ }
79
+ export async function removeProjectMcpServer(workdir, name) {
80
+ const filename = projectMcpConfigPath(workdir);
81
+ try {
82
+ await stat(filename);
83
+ }
84
+ catch (error) {
85
+ if (error.code === 'ENOENT')
86
+ return undefined;
87
+ throw error;
88
+ }
89
+ const changed = await editProjectMcpDocument(workdir, filename, (current) => {
90
+ const root = jsonObject(current);
91
+ const mcpServers = jsonObject(root?.mcpServers);
92
+ if (!mcpServers || !Object.hasOwn(mcpServers, name))
93
+ return undefined;
94
+ delete mcpServers[name];
95
+ return { ...root, mcpServers };
96
+ });
97
+ return changed ? filename : undefined;
98
+ }
@@ -0,0 +1,26 @@
1
+ import { type ModelPricing, type ProviderProtocol } from '@saturn-universe/protocol';
2
+ export interface DiscoveredModel {
3
+ readonly id: string;
4
+ readonly displayName?: string;
5
+ readonly contextWindow?: number;
6
+ readonly maxOutputTokens?: number;
7
+ readonly reasoningModel?: boolean;
8
+ readonly reasoningEfforts?: readonly string[];
9
+ readonly defaultReasoningEffort?: string;
10
+ readonly pricing?: ModelPricing;
11
+ readonly priceSource?: 'models.dev' | 'models.dev-estimate';
12
+ readonly textOutput?: boolean;
13
+ }
14
+ export interface ProviderDiscovery {
15
+ readonly protocol: ProviderProtocol;
16
+ readonly confidence: 'detected' | 'inferred' | 'unknown';
17
+ readonly models: readonly DiscoveredModel[];
18
+ readonly warning?: string;
19
+ }
20
+ export declare function inferProviderProtocol(baseUrl: string): ProviderProtocol;
21
+ export declare function textOutputFromModalities(value: unknown): boolean | undefined;
22
+ export declare function supportsTextModel(model: DiscoveredModel): boolean;
23
+ export declare function probeProviderEndpoint(baseUrl: string, apiKey: string, options?: {
24
+ readonly preferredProtocol?: ProviderProtocol;
25
+ readonly fetch?: typeof fetch;
26
+ }): Promise<ProviderDiscovery>;
@@ -0,0 +1,138 @@
1
+ import { lookupModelMetadata, normalizeProviderBaseUrl, } from '@saturn-universe/protocol';
2
+ function modelListProtocol(protocol) {
3
+ return protocol === 'openai-responses' || protocol === 'openai-chat' ? 'openai' : protocol;
4
+ }
5
+ export function inferProviderProtocol(baseUrl) {
6
+ const url = new URL(baseUrl);
7
+ if (url.hostname === 'generativelanguage.googleapis.com' || /\/v1beta(?:\/|$)/.test(url.pathname))
8
+ return 'gemini';
9
+ if (url.hostname === 'api.anthropic.com')
10
+ return 'anthropic';
11
+ if (url.hostname === 'api.deepseek.com')
12
+ return 'openai-chat';
13
+ return 'openai-responses';
14
+ }
15
+ function record(value) {
16
+ return value && typeof value === 'object' && !Array.isArray(value)
17
+ ? value
18
+ : undefined;
19
+ }
20
+ export function textOutputFromModalities(value) {
21
+ if (!Array.isArray(value))
22
+ return undefined;
23
+ if (value.includes('text'))
24
+ return true;
25
+ if (value.length && value.every((item) => ['image', 'video', 'audio', 'embedding', '3d'].includes(item)))
26
+ return false;
27
+ return undefined;
28
+ }
29
+ export function supportsTextModel(model) {
30
+ if (model.textOutput !== undefined)
31
+ return model.textOutput;
32
+ const id = model.id.toLowerCase().split('/').at(-1) ?? '';
33
+ return (!/^(?:doubao-(?:seedream|seedance|seed3d|embedding)|gpt-image|dall-e|imagen|veo|hitem3d|hyper3d|whisper|tts|(?:text-)?embedding)(?:[-.:]|$)/.test(id) && !/^(?:gemini-[\w.-]+-image|gemini-[\w.-]+-tts)(?:[-.:]|$)/.test(id));
34
+ }
35
+ function tokenLimit(...values) {
36
+ return values.find((value) => typeof value === 'number' && Number.isSafeInteger(value) && value > 0);
37
+ }
38
+ function modelList(value, protocol, apiKey) {
39
+ const body = record(value);
40
+ const items = protocol === 'gemini'
41
+ ? body?.models
42
+ : protocol === 'anthropic'
43
+ ? body?.data
44
+ : (body?.data ?? body?.models);
45
+ if (!Array.isArray(items))
46
+ return undefined;
47
+ const models = new Map();
48
+ for (const item of items) {
49
+ const row = record(item);
50
+ if (!row)
51
+ continue;
52
+ const gemini = protocol === 'gemini';
53
+ const rawId = gemini ? row.name : row.id;
54
+ if (typeof rawId !== 'string')
55
+ continue;
56
+ if (gemini &&
57
+ !(Array.isArray(row.supportedGenerationMethods) &&
58
+ row.supportedGenerationMethods.includes('generateContent')))
59
+ continue;
60
+ 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))
66
+ continue;
67
+ const metadata = lookupModelMetadata(id);
68
+ const topProvider = record(row.top_provider);
69
+ const contextWindow = tokenLimit(row.context_length, row.context_window, row.max_input_tokens, row.inputTokenLimit, topProvider?.context_length) ?? metadata?.contextWindow;
70
+ const maxOutputTokens = tokenLimit(row.max_output_tokens, row.max_tokens, row.outputTokenLimit, row.max_completion_tokens, topProvider?.max_completion_tokens) ?? metadata?.maxOutputTokens;
71
+ const architecture = record(row.architecture);
72
+ 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
+ models.set(id, {
78
+ id,
79
+ ...(displayName ? { displayName } : {}),
80
+ ...(textOutput === undefined ? {} : { textOutput }),
81
+ ...(contextWindow === undefined ? {} : { contextWindow }),
82
+ ...(maxOutputTokens === undefined ? {} : { maxOutputTokens }),
83
+ ...(metadata ? { reasoningEfforts: metadata.reasoningEfforts, pricing: metadata.pricing } : {}),
84
+ });
85
+ }
86
+ // An array with entries in a different protocol's shape is not evidence.
87
+ if (items.length && protocol === 'openai' && !items.some((item) => typeof record(item)?.id === 'string'))
88
+ return undefined;
89
+ return [...models.values()];
90
+ }
91
+ export async function probeProviderEndpoint(baseUrl, apiKey, options = {}) {
92
+ const endpoint = normalizeProviderBaseUrl(baseUrl);
93
+ const fallback = options.preferredProtocol ?? (endpoint ? inferProviderProtocol(endpoint) : 'openai-responses');
94
+ const unavailable = {
95
+ protocol: fallback,
96
+ confidence: 'unknown',
97
+ models: [],
98
+ warning: 'Could not discover models. Confirm the protocol and enter model IDs manually.',
99
+ };
100
+ if (!endpoint || !apiKey.trim())
101
+ return unavailable;
102
+ const request = options.fetch ?? fetch;
103
+ const signal = AbortSignal.timeout(8000);
104
+ const headersFor = {
105
+ openai: { Authorization: `Bearer ${apiKey}` },
106
+ anthropic: { 'x-api-key': apiKey, 'anthropic-version': '2023-06-01' },
107
+ gemini: { 'x-goog-api-key': apiKey },
108
+ };
109
+ const formats = new Set([modelListProtocol(fallback), 'openai', 'anthropic', 'gemini']);
110
+ for (const format of formats) {
111
+ if (signal.aborted)
112
+ break;
113
+ const suffix = format === 'gemini' ? '/models?pageSize=1000' : '/models';
114
+ let models;
115
+ try {
116
+ const response = await request(endpoint + suffix, {
117
+ headers: headersFor[format],
118
+ signal,
119
+ redirect: 'error',
120
+ });
121
+ if (!response.ok) {
122
+ await response.body?.cancel();
123
+ continue;
124
+ }
125
+ models = modelList(await response.json(), format, apiKey);
126
+ }
127
+ catch {
128
+ continue;
129
+ }
130
+ if (!models)
131
+ continue;
132
+ if (format !== 'openai')
133
+ return { protocol: format, confidence: 'detected', models };
134
+ const openaiFallback = fallback === 'openai-chat' ? fallback : 'openai-responses';
135
+ return { protocol: openaiFallback, confidence: 'inferred', models };
136
+ }
137
+ return unavailable;
138
+ }
@@ -0,0 +1,3 @@
1
+ import { type DiscoveredModel } from './provider-discovery.js';
2
+ export declare function modelAlias(id: string): string;
3
+ export declare function enrichPrices(baseUrl: string, models: readonly DiscoveredModel[], request?: typeof fetch): Promise<readonly DiscoveredModel[]>;
@@ -0,0 +1,130 @@
1
+ import { normalizeProviderBaseUrl, providerPresets } from '@saturn-universe/protocol';
2
+ import { textOutputFromModalities } from './provider-discovery.js';
3
+ function object(value) {
4
+ return value && typeof value === 'object' && !Array.isArray(value)
5
+ ? value
6
+ : {};
7
+ }
8
+ function rate(value) {
9
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
10
+ }
11
+ function reasoningMetadata(entry, model) {
12
+ if (typeof entry.reasoning !== 'boolean')
13
+ return {};
14
+ if (!entry.reasoning)
15
+ return { reasoningModel: false };
16
+ const options = Array.isArray(entry.reasoning_options) ? entry.reasoning_options.map(object) : [];
17
+ const effort = options.find((option) => option.type === 'effort');
18
+ const values = Array.isArray(effort?.values) ? effort.values : entry.reasoning_efforts;
19
+ const declared = Array.isArray(values)
20
+ ? [...new Set(values.filter((value) => typeof value === 'string' && !!value.trim()))]
21
+ : [];
22
+ const reasoningEfforts = declared.length
23
+ ? declared
24
+ : model.reasoningEfforts?.length
25
+ ? model.reasoningEfforts
26
+ : ['low', 'medium', 'high'];
27
+ const fallback = effort?.default ?? entry.default_reasoning_effort;
28
+ return {
29
+ reasoningModel: true,
30
+ reasoningEfforts,
31
+ ...(typeof fallback === 'string' && reasoningEfforts.includes(fallback)
32
+ ? { defaultReasoningEffort: fallback }
33
+ : {}),
34
+ };
35
+ }
36
+ export function modelAlias(id) {
37
+ return id
38
+ .toLowerCase()
39
+ .replace(/[-_.](?:\d{4}[-_.]\d{2}[-_.]\d{2}|\d{8}|\d{6}|latest)$/, '')
40
+ .replace(/[._\s]+/g, '-');
41
+ }
42
+ function priceIndex(entries) {
43
+ const byId = new Map();
44
+ const byAlias = new Map();
45
+ for (const [key, value] of Object.entries(entries)) {
46
+ const entry = object(value);
47
+ byId.set(key, entry);
48
+ const ids = typeof entry.id === 'string' ? [key, entry.id] : [key];
49
+ for (const id of ids) {
50
+ const alias = modelAlias(id);
51
+ const matches = byAlias.get(alias) ?? new Set();
52
+ matches.add(entry);
53
+ byAlias.set(alias, matches);
54
+ }
55
+ }
56
+ return (id) => {
57
+ const exact = byId.get(id);
58
+ if (exact)
59
+ return { entry: exact, exact: true };
60
+ const matches = byAlias.get(modelAlias(id));
61
+ if (matches?.size === 1)
62
+ return { entry: [...matches][0], exact: false };
63
+ return undefined;
64
+ };
65
+ }
66
+ // Only the public catalog URL is sent. Endpoint, credentials and model IDs stay local.
67
+ export async function enrichPrices(baseUrl, models, request = fetch) {
68
+ if (!models.length)
69
+ return models;
70
+ const endpoint = normalizeProviderBaseUrl(baseUrl);
71
+ const preset = providerPresets.find((p) => p.defaultBaseUrl && p.defaultBaseUrl === endpoint)?.id;
72
+ try {
73
+ const response = await request('https://models.dev/api.json', {
74
+ signal: AbortSignal.timeout(4000),
75
+ redirect: 'error',
76
+ });
77
+ if (!response.ok) {
78
+ await response.body?.cancel();
79
+ return models;
80
+ }
81
+ const catalog = object(await response.json());
82
+ const matchingProviders = Object.entries(catalog)
83
+ .filter(([, value]) => {
84
+ const api = object(value).api;
85
+ return (endpoint !== undefined && typeof api === 'string' && normalizeProviderBaseUrl(api) === endpoint);
86
+ })
87
+ .map(([id]) => id);
88
+ const provider = preset ?? (matchingProviders.length === 1 ? matchingProviders[0] : undefined);
89
+ const indexes = new Map();
90
+ return models.map((model) => {
91
+ const slash = model.id.indexOf('/');
92
+ const source = provider ?? (slash > 0 ? model.id.slice(0, slash) : undefined);
93
+ if (!source || !Object.hasOwn(catalog, source))
94
+ return model;
95
+ let lookup = indexes.get(source);
96
+ if (!lookup) {
97
+ lookup = priceIndex(object(object(catalog[source]).models));
98
+ indexes.set(source, lookup);
99
+ }
100
+ const id = provider ? model.id : model.id.slice(slash + 1);
101
+ const match = lookup(id);
102
+ if (!match)
103
+ return model;
104
+ const { entry, exact } = match;
105
+ const textOutput = model.textOutput ??
106
+ (provider ? textOutputFromModalities(object(entry.modalities).output) : undefined);
107
+ const enriched = {
108
+ ...model,
109
+ ...(textOutput === undefined ? {} : { textOutput }),
110
+ ...reasoningMetadata(entry, model),
111
+ };
112
+ const cost = object(entry.cost);
113
+ if (textOutput === false || !rate(cost.input) || !rate(cost.output))
114
+ return enriched;
115
+ const pricing = {
116
+ inputPerMillion: cost.input,
117
+ outputPerMillion: cost.output,
118
+ ...(rate(cost.cache_read) ? { cachedInputPerMillion: cost.cache_read } : {}),
119
+ };
120
+ return {
121
+ ...enriched,
122
+ pricing,
123
+ priceSource: provider && exact ? 'models.dev' : 'models.dev-estimate',
124
+ };
125
+ });
126
+ }
127
+ catch {
128
+ return models;
129
+ }
130
+ }
@@ -0,0 +1,16 @@
1
+ import { type AuthPrompt } from './menu.js';
2
+ import { enrichPrices } from './provider-pricing.js';
3
+ import { type ProviderProtocol } from '@saturn-universe/protocol';
4
+ import { probeProviderEndpoint } from './provider-discovery.js';
5
+ interface ProviderOptions {
6
+ readonly prices?: typeof enrichPrices;
7
+ readonly testModel?: typeof testModel;
8
+ readonly env?: NodeJS.ProcessEnv;
9
+ readonly root?: string;
10
+ readonly probe?: typeof probeProviderEndpoint;
11
+ readonly prompt?: AuthPrompt;
12
+ readonly writeLine?: (line: string) => void;
13
+ }
14
+ export declare function runProviderCommand(args: string[], options?: ProviderOptions): Promise<void>;
15
+ export declare function testModel(baseUrl: string, key: string, model: string, protocol?: ProviderProtocol): Promise<void>;
16
+ export {};