@mumbrane/arrakis 0.1.0 → 0.3.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.
package/src/client.js ADDED
@@ -0,0 +1,101 @@
1
+ // Minimal client for OpenAI-compatible /chat/completions with streaming and tool calls.
2
+ import { getProvider, normalizeModels } from './providers.js';
3
+
4
+ function headers(config) {
5
+ const h = { 'content-type': 'application/json' };
6
+ if (config.apiKey) h.authorization = `Bearer ${config.apiKey}`;
7
+ return h;
8
+ }
9
+
10
+ async function request(config, pathname, init, { retries = 3, extraHeaders } = {}) {
11
+ const url = `${config.baseUrl}${pathname}`;
12
+ for (let attempt = 0; ; attempt++) {
13
+ let res;
14
+ try {
15
+ res = await fetch(url, { ...init, headers: extraHeaders ? { 'content-type': 'application/json', ...extraHeaders } : headers(config) });
16
+ } catch (err) {
17
+ if (err.name === 'AbortError') throw err;
18
+ if (attempt < retries) {
19
+ await sleep(500 * 2 ** attempt, init.signal);
20
+ continue;
21
+ }
22
+ const e = new Error(`Could not reach ${config.baseUrl} (${err.cause?.code || err.message}).`);
23
+ e.unreachable = true;
24
+ throw e;
25
+ }
26
+ if (res.ok) return res;
27
+ const retryable = res.status === 429 || res.status >= 500;
28
+ if (retryable && attempt < retries) {
29
+ await res.text().catch(() => {});
30
+ await sleep(1000 * 2 ** attempt, init.signal);
31
+ continue;
32
+ }
33
+ const body = await res.text().catch(() => '');
34
+ const e = new Error(`API error ${res.status} from ${url}: ${body.slice(0, 500)}`);
35
+ e.status = res.status;
36
+ throw e;
37
+ }
38
+ }
39
+
40
+ function sleep(ms, signal) {
41
+ return new Promise((resolve, reject) => {
42
+ const t = setTimeout(resolve, ms);
43
+ signal?.addEventListener('abort', () => {
44
+ clearTimeout(t);
45
+ reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
46
+ }, { once: true });
47
+ });
48
+ }
49
+
50
+ export async function* streamChat({ config, messages, tools, signal }) {
51
+ const body = { model: config.model, messages, stream: true };
52
+ if (tools?.length) body.tools = tools;
53
+ if (config.maxTokens) body.max_tokens = config.maxTokens;
54
+ const res = await request(config, '/chat/completions', { method: 'POST', body: JSON.stringify(body), signal });
55
+
56
+ const decoder = new TextDecoder();
57
+ let buf = '';
58
+ for await (const chunk of res.body) {
59
+ buf += decoder.decode(chunk, { stream: true });
60
+ let nl;
61
+ while ((nl = buf.indexOf('\n')) >= 0) {
62
+ const line = buf.slice(0, nl).trim();
63
+ buf = buf.slice(nl + 1);
64
+ if (!line.startsWith('data:')) continue;
65
+ const data = line.slice(5).trim();
66
+ if (data === '[DONE]') return;
67
+ let event;
68
+ try {
69
+ event = JSON.parse(data);
70
+ } catch {
71
+ continue;
72
+ }
73
+ if (event.error) throw new Error(`API error: ${event.error.message || JSON.stringify(event.error)}`);
74
+ yield event;
75
+ }
76
+ }
77
+ }
78
+
79
+ // Collect a full text response (used for summaries).
80
+ export async function completeText({ config, messages, signal }) {
81
+ let text = '';
82
+ for await (const event of streamChat({ config, messages, signal })) {
83
+ text += event.choices?.[0]?.delta?.content ?? '';
84
+ }
85
+ return text;
86
+ }
87
+
88
+ // List the chat models the provider offers, newest first when it says.
89
+ export async function listModels(config) {
90
+ const provider = getProvider(config.provider);
91
+ const extraHeaders = provider?.modelsHeaders && config.apiKey ? provider.modelsHeaders(config.apiKey) : undefined;
92
+ const res = await request(config, `/models${provider?.modelsQuery ?? ''}`, { method: 'GET' }, { retries: 1, extraHeaders });
93
+ return normalizeModels(await res.json());
94
+ }
95
+
96
+ export async function resolveModel(config) {
97
+ if (config.model) return config.model;
98
+ const models = await listModels(config);
99
+ if (!models.length) throw new Error(`No model configured and ${config.baseUrl}/models listed none. Pick one with: arrakis setup`);
100
+ return models[0].id;
101
+ }
package/src/config.js ADDED
@@ -0,0 +1,133 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { getProvider } from './providers.js';
5
+
6
+ export const HOME_DIR = process.env.ARRAKIS_HOME || path.join(os.homedir(), '.arrakis');
7
+ export const CONFIG_PATH = path.join(HOME_DIR, 'config.json');
8
+ export const SESSIONS_DIR = path.join(HOME_DIR, 'sessions');
9
+
10
+ // Config file shape:
11
+ // {
12
+ // "provider": "anthropic",
13
+ // "providers": { "anthropic": { "apiKey": "...", "model": "...", "contextWindow": 1000000 } },
14
+ // "maxTokens": 0
15
+ // }
16
+ // Each provider keeps its own key and last-used model, so switching back is instant.
17
+
18
+ export const CONFIG_KEYS = {
19
+ provider: { env: 'ARRAKIS_PROVIDER', help: 'Active provider id (see: arrakis setup)', global: true },
20
+ baseUrl: { env: 'ARRAKIS_BASE_URL', help: 'API base URL (custom provider)' },
21
+ apiKey: { env: 'ARRAKIS_API_KEY', help: 'API key for the active provider', secret: true },
22
+ model: { env: 'ARRAKIS_MODEL', help: 'Model name' },
23
+ contextWindow: { env: 'ARRAKIS_CONTEXT_WINDOW', help: 'Context window in tokens; history is compacted near 80%', number: true },
24
+ maxTokens: { env: 'ARRAKIS_MAX_TOKENS', help: 'Max output tokens per response (0 = provider default)', number: true, global: true },
25
+ };
26
+
27
+ const DEFAULT_CONTEXT = 128000;
28
+
29
+ export function readConfigFile() {
30
+ let file;
31
+ try {
32
+ file = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
33
+ } catch {
34
+ return { providers: {} };
35
+ }
36
+ file.providers ??= {};
37
+ // Migrate the flat 0.2 format ({ baseUrl, apiKey, model }) to a custom provider.
38
+ if (!file.provider && file.baseUrl) {
39
+ file.providers.custom = { baseUrl: file.baseUrl, apiKey: file.apiKey, model: file.model, contextWindow: file.contextWindow };
40
+ file.provider = 'custom';
41
+ }
42
+ delete file.baseUrl;
43
+ delete file.apiKey;
44
+ delete file.model;
45
+ delete file.contextWindow;
46
+ return file;
47
+ }
48
+
49
+ function writeConfigFile(file) {
50
+ fs.mkdirSync(HOME_DIR, { recursive: true });
51
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(file, null, 2) + '\n', { mode: 0o600 });
52
+ fs.chmodSync(CONFIG_PATH, 0o600);
53
+ }
54
+
55
+ export function loadConfig(overrides = {}) {
56
+ const file = readConfigFile();
57
+ const env = process.env;
58
+ let providerId = overrides.provider || env.ARRAKIS_PROVIDER || file.provider || null;
59
+ // A base URL from the environment or flags without a provider means a custom API.
60
+ if (!providerId && (env.ARRAKIS_BASE_URL || overrides.baseUrl)) providerId = 'custom';
61
+ const provider = providerId ? getProvider(providerId) : null;
62
+ if (providerId && !provider) throw new Error(`Unknown provider "${providerId}". Run: arrakis setup`);
63
+ const saved = (providerId && file.providers[providerId]) || {};
64
+
65
+ const config = {
66
+ provider: providerId,
67
+ providerName: provider?.name ?? '',
68
+ baseUrl: saved.baseUrl || provider?.baseUrl || '',
69
+ apiKey: saved.apiKey || '',
70
+ model: saved.model || '',
71
+ contextWindow: Number(saved.contextWindow) || provider?.contextWindow || DEFAULT_CONTEXT,
72
+ maxTokens: Number(file.maxTokens) || provider?.maxTokens || 0,
73
+ };
74
+ if (env.ARRAKIS_BASE_URL) config.baseUrl = env.ARRAKIS_BASE_URL;
75
+ if (env.ARRAKIS_API_KEY) config.apiKey = env.ARRAKIS_API_KEY;
76
+ if (env.ARRAKIS_MODEL) config.model = env.ARRAKIS_MODEL;
77
+ if (Number(env.ARRAKIS_CONTEXT_WINDOW)) config.contextWindow = Number(env.ARRAKIS_CONTEXT_WINDOW);
78
+ if (Number(env.ARRAKIS_MAX_TOKENS)) config.maxTokens = Number(env.ARRAKIS_MAX_TOKENS);
79
+ if (overrides.baseUrl) config.baseUrl = overrides.baseUrl;
80
+ if (overrides.model) config.model = overrides.model;
81
+ config.baseUrl = String(config.baseUrl).replace(/\/+$/, '');
82
+ config.configured = Boolean(config.provider && config.baseUrl && (config.apiKey || provider?.noKey || provider?.custom || env.ARRAKIS_BASE_URL));
83
+ return config;
84
+ }
85
+
86
+ // Save settings for one provider and (by default) make it the active one.
87
+ export function saveProvider(providerId, patch, { activate = true } = {}) {
88
+ const file = readConfigFile();
89
+ const current = file.providers[providerId] ?? {};
90
+ const next = { ...current, ...patch };
91
+ for (const k of Object.keys(next)) if (next[k] === undefined || next[k] === '') delete next[k];
92
+ file.providers[providerId] = next;
93
+ if (activate) file.provider = providerId;
94
+ writeConfigFile(file);
95
+ }
96
+
97
+ export function savedProviderSettings(providerId) {
98
+ return readConfigFile().providers[providerId] ?? {};
99
+ }
100
+
101
+ // `arrakis config set <key> <value>`
102
+ export function setConfigValue(key, value) {
103
+ const spec = CONFIG_KEYS[key];
104
+ if (!spec) throw new Error(`Unknown config key "${key}". Keys: ${Object.keys(CONFIG_KEYS).join(', ')}`);
105
+ const file = readConfigFile();
106
+ const v = value === undefined || value === '' ? undefined : spec.number ? Number(value) : value;
107
+ if (key === 'provider') {
108
+ if (v && !getProvider(v)) throw new Error(`Unknown provider "${v}".`);
109
+ if (v) file.provider = v;
110
+ else delete file.provider;
111
+ } else if (spec.global) {
112
+ if (v === undefined) delete file[key];
113
+ else file[key] = v;
114
+ } else {
115
+ const id = file.provider ?? 'custom';
116
+ file.provider = id;
117
+ file.providers[id] ??= {};
118
+ if (v === undefined) delete file.providers[id][key];
119
+ else file.providers[id][key] = v;
120
+ }
121
+ writeConfigFile(file);
122
+ }
123
+
124
+ export function removeProviderKeys() {
125
+ const file = readConfigFile();
126
+ for (const p of Object.values(file.providers)) delete p.apiKey;
127
+ writeConfigFile(file);
128
+ }
129
+
130
+ export function maskSecret(value) {
131
+ if (!value) return '(not set)';
132
+ return value.length <= 10 ? '****' : `${value.slice(0, 6)}…${value.slice(-4)}`;
133
+ }
@@ -0,0 +1,17 @@
1
+ // Modes: 'ask' prompts for each write/command; 'yolo' allows everything;
2
+ // 'deny' refuses anything that needs permission (non-interactive default).
3
+ export class Permissions {
4
+ constructor({ ui, mode = 'ask', allow = [] }) {
5
+ this.ui = ui;
6
+ this.mode = mode;
7
+ this.allowed = new Set(allow);
8
+ }
9
+
10
+ async check(toolName, preview) {
11
+ if (this.mode === 'yolo' || this.allowed.has(toolName)) return true;
12
+ if (this.mode === 'deny') return false;
13
+ const answer = await this.ui.confirm(preview);
14
+ if (answer === 'always') this.allowed.add(toolName);
15
+ return answer !== 'no';
16
+ }
17
+ }
package/src/prompt.js ADDED
@@ -0,0 +1,81 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { HOME_DIR } from './config.js';
5
+
6
+ const INSTRUCTION_FILES = ['ARRAKIS.md', 'AGENTS.md'];
7
+
8
+ function findUp(start, name) {
9
+ let dir = start;
10
+ while (true) {
11
+ if (fs.existsSync(path.join(dir, name))) return dir;
12
+ const parent = path.dirname(dir);
13
+ if (parent === dir) return null;
14
+ dir = parent;
15
+ }
16
+ }
17
+
18
+ // Instruction files from the global config dir, then from the filesystem root
19
+ // down to the working directory (closer files come later and take precedence).
20
+ export function loadProjectInstructions(cwd) {
21
+ const found = [];
22
+ for (const name of INSTRUCTION_FILES) {
23
+ const global = path.join(HOME_DIR, name);
24
+ if (fs.existsSync(global)) found.push(global);
25
+ }
26
+ const chain = [];
27
+ let dir = cwd;
28
+ while (true) {
29
+ for (const name of INSTRUCTION_FILES) {
30
+ const f = path.join(dir, name);
31
+ if (fs.existsSync(f)) {
32
+ chain.unshift(f);
33
+ break; // one file per directory; ARRAKIS.md wins over AGENTS.md
34
+ }
35
+ }
36
+ const parent = path.dirname(dir);
37
+ if (parent === dir || dir === os.homedir()) break;
38
+ dir = parent;
39
+ }
40
+ return [...found, ...chain].map((file) => {
41
+ let text = '';
42
+ try {
43
+ text = fs.readFileSync(file, 'utf8').slice(0, 40000);
44
+ } catch {}
45
+ return { file, text };
46
+ });
47
+ }
48
+
49
+ export function buildSystemPrompt({ cwd, model }) {
50
+ const git = findUp(cwd, '.git');
51
+ const instructions = loadProjectInstructions(cwd).filter((i) => i.text.trim());
52
+ let prompt = `You are Arrakis, a coding agent built by Mumbrane that runs in the user's terminal. You help with software engineering: reading and changing code, running commands, debugging, and explaining.
53
+
54
+ # Environment
55
+ - Working directory: ${cwd}
56
+ - Git repository: ${git ? `yes (root: ${git})` : 'no'}
57
+ - Platform: ${process.platform} (${os.release()})
58
+ - Date: ${new Date().toISOString().slice(0, 10)}
59
+ - Model: ${model}
60
+
61
+ # How to work
62
+ - Understand before changing: use list_files, grep and read_file to find and read the relevant code.
63
+ - Make focused changes with edit_file. Read a file before editing it and copy old_string exactly, including indentation.
64
+ - Use write_file only for new files or full rewrites.
65
+ - Verify your work when you can: run the tests, the build, or the program with bash.
66
+ - Each bash call starts fresh in the working directory; use "cd dir && cmd" when needed. Commands get no stdin, so avoid interactive programs, editors and watch modes.
67
+ - Do what was asked. Don't make unrelated changes, add files nobody asked for, or commit unless told to.
68
+ - If the user denies a tool call, don't retry it; ask how they want to proceed.
69
+ - Never print or exfiltrate secrets such as API keys or tokens.
70
+
71
+ # Style
72
+ - Be concise and direct. Lead with the answer or result; skip preamble.
73
+ - Reference code as path:line.
74
+ - When done, say briefly what changed and anything left unverified.`;
75
+
76
+ if (instructions.length) {
77
+ prompt += `\n\n# Project instructions\nThese come from instruction files the user wrote. Follow them.\n`;
78
+ for (const { file, text } of instructions) prompt += `\n## ${file}\n${text.trim()}\n`;
79
+ }
80
+ return prompt;
81
+ }
package/src/prompts.js ADDED
@@ -0,0 +1,186 @@
1
+ // Interactive prompts: an arrow-key picker with type-to-search, masked secret
2
+ // input and plain text input. Without a TTY (piped input, CI) they fall back
3
+ // to numbered lists and plain line reads.
4
+ import readline from 'node:readline';
5
+ import { colors } from './ui.js';
6
+
7
+ const isTTY = () => Boolean(process.stdin.isTTY && process.stdout.isTTY && process.stdin.setRawMode);
8
+
9
+ // Read raw keypresses until done() is called. Hands stdin back afterwards.
10
+ function rawKeys(onKey) {
11
+ return new Promise((resolve) => {
12
+ const stdin = process.stdin;
13
+ readline.emitKeypressEvents(stdin);
14
+ const wasRaw = stdin.isRaw;
15
+ stdin.setRawMode(true);
16
+ stdin.resume();
17
+ const done = (value) => {
18
+ stdin.off('keypress', handler);
19
+ stdin.setRawMode(wasRaw);
20
+ stdin.pause();
21
+ resolve(value);
22
+ };
23
+ const handler = (str, key = {}) => onKey(str, key, done);
24
+ stdin.on('keypress', handler);
25
+ });
26
+ }
27
+
28
+ const printable = (str, key) => str && !key.ctrl && !key.meta && str.length >= 1 && !/[\x00-\x1f\x7f]/.test(str);
29
+
30
+ function truncateToWidth(s, width) {
31
+ // Strip ANSI for measuring; cut the visible text if it's too long.
32
+ const plain = s.replace(/\x1b\[[0-9;]*m/g, '');
33
+ if (plain.length <= width) return s;
34
+ return plain.slice(0, Math.max(0, width - 1)) + '…';
35
+ }
36
+
37
+ async function rawSelect({ title, items, initial = 0, pageSize = 10 }) {
38
+ const out = process.stdout;
39
+ const c = colors(out);
40
+ const searchable = items.length > 8;
41
+ let filter = '';
42
+ let cursor = Math.max(0, Math.min(initial, items.length - 1));
43
+ let rendered = 0;
44
+ const visible = () => {
45
+ if (!filter) return items;
46
+ const f = filter.toLowerCase();
47
+ return items.filter((i) => `${i.label} ${i.value} ${i.hint ?? ''}`.toLowerCase().includes(f));
48
+ };
49
+ const clear = () => {
50
+ if (!rendered) return;
51
+ readline.moveCursor(out, 0, -rendered);
52
+ readline.cursorTo(out, 0);
53
+ readline.clearScreenDown(out);
54
+ rendered = 0;
55
+ };
56
+ const render = () => {
57
+ clear();
58
+ const list = visible();
59
+ cursor = Math.max(0, Math.min(cursor, list.length - 1));
60
+ const width = (out.columns || 80) - 1;
61
+ const rows = [`${c.bold(title)} ${c.dim(searchable ? '↑↓ move · type to search · Enter select · Esc cancel' : '↑↓ move · Enter select · Esc cancel')}`];
62
+ if (searchable) rows.push(` ${c.dim('search:')} ${filter}${c.dim('▏')}`);
63
+ if (!list.length) rows.push(c.dim(' no matches'));
64
+ const start = Math.max(0, Math.min(cursor - Math.floor(pageSize / 2), list.length - pageSize));
65
+ list.slice(start, start + pageSize).forEach((item, i) => {
66
+ const selected = start + i === cursor;
67
+ const label = selected ? c.accent(c.bold(item.label)) : item.label;
68
+ rows.push(truncateToWidth(`${selected ? c.accent('❯') : ' '} ${label}${item.hint ? ' ' + c.dim(item.hint) : ''}`, width));
69
+ });
70
+ if (list.length > pageSize) rows.push(c.dim(` ${cursor + 1} of ${list.length}`));
71
+ out.write(rows.join('\n') + '\n');
72
+ rendered = rows.length;
73
+ };
74
+ out.write('\x1b[?25l');
75
+ render();
76
+ const result = await rawKeys((str, key, done) => {
77
+ const list = visible();
78
+ if (key.ctrl && key.name === 'c') return done(null);
79
+ if (key.name === 'escape') {
80
+ if (filter) {
81
+ filter = '';
82
+ cursor = 0;
83
+ return render();
84
+ }
85
+ return done(null);
86
+ }
87
+ if (key.name === 'return' || key.name === 'enter') return done(list[cursor] ?? null);
88
+ if (key.name === 'up') cursor = cursor > 0 ? cursor - 1 : list.length - 1;
89
+ else if (key.name === 'down') cursor = cursor < list.length - 1 ? cursor + 1 : 0;
90
+ else if (key.name === 'pageup') cursor = Math.max(0, cursor - pageSize);
91
+ else if (key.name === 'pagedown') cursor = Math.min(list.length - 1, cursor + pageSize);
92
+ else if (key.name === 'backspace') {
93
+ filter = filter.slice(0, -1);
94
+ cursor = 0;
95
+ } else if (searchable && printable(str, key)) {
96
+ filter += str;
97
+ cursor = 0;
98
+ } else return;
99
+ render();
100
+ });
101
+ clear();
102
+ out.write('\x1b[?25h');
103
+ out.write(`${c.bold(title)} ${result ? c.accent(result.label) : c.dim('cancelled')}\n`);
104
+ return result ? result.value : null;
105
+ }
106
+
107
+ async function rawSecret(label) {
108
+ const out = process.stdout;
109
+ const c = colors(out);
110
+ let value = '';
111
+ const draw = () => {
112
+ readline.cursorTo(out, 0);
113
+ readline.clearLine(out, 1);
114
+ const dots = '•'.repeat(Math.min(value.length, 32)) + (value.length > 32 ? c.dim(` +${value.length - 32}`) : '');
115
+ out.write(`${label}${dots}`);
116
+ };
117
+ draw();
118
+ const result = await rawKeys((str, key, done) => {
119
+ if (key.ctrl && key.name === 'c') return done(null);
120
+ if (key.name === 'escape') return done(null);
121
+ if (key.name === 'return' || key.name === 'enter') return done(value);
122
+ if (key.name === 'backspace') value = value.slice(0, -1);
123
+ else if (key.ctrl && key.name === 'u') value = '';
124
+ else if (printable(str, key)) value += str;
125
+ else return;
126
+ draw();
127
+ });
128
+ out.write('\n');
129
+ return result === null ? null : result.trim();
130
+ }
131
+
132
+ export function createPrompts(ui) {
133
+ return {
134
+ // items: [{ label, value, hint? }]. Resolves to the chosen value, or null.
135
+ async select({ title, items, initial = 0 }) {
136
+ if (isTTY()) {
137
+ ui.suspend();
138
+ try {
139
+ return await rawSelect({ title, items, initial });
140
+ } finally {
141
+ ui.resume();
142
+ }
143
+ }
144
+ return numberedSelect(ui, { title, items, initial });
145
+ },
146
+
147
+ async secret(label) {
148
+ if (isTTY()) {
149
+ ui.suspend();
150
+ try {
151
+ return await rawSecret(label);
152
+ } finally {
153
+ ui.resume();
154
+ }
155
+ }
156
+ const line = await ui.readLine(label);
157
+ return line === null ? null : line.trim();
158
+ },
159
+
160
+ async input(label) {
161
+ const line = await ui.readLine(label);
162
+ return line === null ? null : line.trim();
163
+ },
164
+ };
165
+ }
166
+
167
+ async function numberedSelect(ui, { title, items, initial }) {
168
+ const c = ui.c;
169
+ const shown = items.slice(0, 40);
170
+ ui.write(ui.out, `${c.bold(title)}\n`);
171
+ shown.forEach((item, i) => ui.write(ui.out, ` ${String(i + 1).padStart(2)}. ${item.label}${item.hint ? ' ' + c.dim(item.hint) : ''}\n`));
172
+ if (items.length > shown.length) ui.write(ui.out, c.dim(` … ${items.length - shown.length} more (type a name to pick one)\n`));
173
+ while (true) {
174
+ const answer = await ui.readLine(`Choose 1-${shown.length} ${c.dim(`[${initial + 1}]`)}: `);
175
+ if (answer === null) return null;
176
+ const a = answer.trim();
177
+ if (!a) return items[initial]?.value ?? null;
178
+ const n = Number(a);
179
+ if (Number.isInteger(n) && n >= 1 && n <= shown.length) return shown[n - 1].value;
180
+ const exact = items.find((i) => i.value === a || i.label.toLowerCase() === a.toLowerCase());
181
+ if (exact) return exact.value;
182
+ const partial = items.filter((i) => `${i.label} ${i.value}`.toLowerCase().includes(a.toLowerCase()));
183
+ if (partial.length === 1) return partial[0].value;
184
+ ui.write(ui.out, c.dim(partial.length ? ` ${partial.length} matches; be more specific.\n` : ' No match.\n'));
185
+ }
186
+ }
@@ -0,0 +1,60 @@
1
+ // Built-in providers. Every one speaks the OpenAI-compatible /chat/completions
2
+ // API. To add one (for example your own hosted model), add an entry here.
3
+ //
4
+ // id stable key used in config and ARRAKIS_PROVIDER
5
+ // name shown in the picker
6
+ // baseUrl API base URL (without /chat/completions)
7
+ // keyUrl where users create an API key
8
+ // noKey true for local servers that don't need a key
9
+ // custom true: the user enters the base URL
10
+ // defaultModel highlighted first in the model picker, if the provider lists it
11
+ // contextWindow fallback when the models API doesn't report one
12
+ // maxTokens max output tokens to request (some APIs require it)
13
+ // modelsHeaders headers for GET /models when they differ from Bearer auth
14
+
15
+ export const PROVIDERS = [
16
+ {
17
+ id: 'anthropic',
18
+ name: 'Anthropic (Claude)',
19
+ baseUrl: 'https://api.anthropic.com/v1',
20
+ keyUrl: 'https://platform.claude.com/settings/keys',
21
+ defaultModel: 'claude-opus-5-5',
22
+ contextWindow: 1000000,
23
+ maxTokens: 32000,
24
+ modelsHeaders: (key) => ({ 'x-api-key': key, 'anthropic-version': '2023-06-01' }),
25
+ modelsQuery: '?limit=1000',
26
+ },
27
+ { id: 'openai', name: 'OpenAI', baseUrl: 'https://api.openai.com/v1', keyUrl: 'https://platform.openai.com/api-keys' },
28
+ { id: 'google', name: 'Google Gemini', baseUrl: 'https://generativelanguage.googleapis.com/v1beta/openai', keyUrl: 'https://aistudio.google.com/apikey', contextWindow: 1000000 },
29
+ { id: 'openrouter', name: 'OpenRouter (hundreds of models)', baseUrl: 'https://openrouter.ai/api/v1', keyUrl: 'https://openrouter.ai/keys' },
30
+ { id: 'xai', name: 'xAI (Grok)', baseUrl: 'https://api.x.ai/v1', keyUrl: 'https://console.x.ai' },
31
+ { id: 'deepseek', name: 'DeepSeek', baseUrl: 'https://api.deepseek.com/v1', keyUrl: 'https://platform.deepseek.com/api_keys' },
32
+ { id: 'mistral', name: 'Mistral', baseUrl: 'https://api.mistral.ai/v1', keyUrl: 'https://console.mistral.ai/api-keys' },
33
+ { id: 'groq', name: 'Groq', baseUrl: 'https://api.groq.com/openai/v1', keyUrl: 'https://console.groq.com/keys' },
34
+ { id: 'together', name: 'Together AI', baseUrl: 'https://api.together.xyz/v1', keyUrl: 'https://api.together.ai/settings/api-keys' },
35
+ { id: 'ollama', name: 'Ollama (local models, no key)', baseUrl: 'http://localhost:11434/v1', noKey: true },
36
+ { id: 'custom', name: 'Other OpenAI-compatible API', custom: true },
37
+ ];
38
+
39
+ export const getProvider = (id) => PROVIDERS.find((p) => p.id === id) ?? null;
40
+
41
+ // Models that can't chat (embeddings, audio, images, moderation…).
42
+ const NON_CHAT = /(embed|whisper|tts|dall-e|moderation|transcribe|audio|realtime|image|imagen|veo|sora|davinci|babbage|rerank|aqa|guard)/i;
43
+
44
+ export function normalizeModels(json) {
45
+ const raw = Array.isArray(json) ? json : json?.data ?? json?.models ?? [];
46
+ const models = raw
47
+ .map((m) => {
48
+ const id = String(m.id ?? m.name ?? '').replace(/^models\//, '');
49
+ const created = typeof m.created === 'number' ? m.created * 1000 : m.created_at ? Date.parse(m.created_at) : 0;
50
+ return {
51
+ id,
52
+ name: m.display_name ?? m.displayName ?? (m.name && m.name !== m.id ? m.name : ''),
53
+ created: Number.isFinite(created) ? created : 0,
54
+ contextWindow: Number(m.max_input_tokens ?? m.context_length ?? m.context_window ?? m.inputTokenLimit ?? 0) || 0,
55
+ };
56
+ })
57
+ .filter((m) => m.id && !NON_CHAT.test(m.id));
58
+ if (models.some((m) => m.created)) models.sort((a, b) => b.created - a.created);
59
+ return models;
60
+ }