@mumbrane/arrakis 0.0.0-stage → 0.2.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/README.md CHANGED
@@ -1,3 +1,75 @@
1
- # Temporary Holding Version
1
+ # arrakis
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
+ A coding agent for your terminal, built by Mumbrane. It reads your code, edits files and runs commands, asking before anything that changes your machine.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install -g @mumbrane/arrakis
9
+ ```
10
+
11
+ Requires Node.js 18.17 or later.
12
+
13
+ ## Set up
14
+
15
+ Arrakis talks to any OpenAI-compatible `/chat/completions` API with tool calling (your own model server, vLLM, SGLang and similar).
16
+
17
+ ```bash
18
+ arrakis config set baseUrl https://api.example.com/v1
19
+ arrakis config set apiKey YOUR_KEY
20
+ arrakis config set model your-model-name
21
+ ```
22
+
23
+ If `model` isn't set, arrakis uses the first model listed at `/models`. Settings live in `~/.arrakis/config.json`. You can also set them with environment variables (`ARRAKIS_BASE_URL`, `ARRAKIS_API_KEY`, `ARRAKIS_MODEL`, `ARRAKIS_CONTEXT_WINDOW`), which take precedence over the file.
24
+
25
+ ## Use
26
+
27
+ ```bash
28
+ arrakis # interactive session in the current directory
29
+ arrakis "fix the failing test" # interactive, starting with a task
30
+ arrakis -p "explain src/app.ts" # one-shot: prints the answer and exits
31
+ arrakis -c # continue the last session in this directory
32
+ arrakis -r <id> # resume a specific session
33
+ arrakis sessions # list recent sessions
34
+ ```
35
+
36
+ In a session:
37
+
38
+ | Command | What it does |
39
+ |---|---|
40
+ | `/help` | List commands |
41
+ | `/status` | Session, model, context usage, permissions |
42
+ | `/compact` | Summarize history to free up context |
43
+ | `/model [name]` | Show or switch the model |
44
+ | `/clear` | Start a new session |
45
+ | `/yolo` | Toggle running tool calls without asking |
46
+ | `/exit` | Quit (or Ctrl-D) |
47
+
48
+ Ctrl-C interrupts the model mid-response. End a line with `\` to keep typing on the next line.
49
+
50
+ ## Tools
51
+
52
+ | Tool | Asks first |
53
+ |---|---|
54
+ | `read_file`, `grep`, `list_files` | No |
55
+ | `write_file`, `edit_file`, `bash` | Yes: answer `y`, `a` (always, for this session) or `n` |
56
+
57
+ `-p` mode denies tools that need permission unless you pass `--yolo` or `--allow edit_file,write_file,bash`.
58
+
59
+ ## Project instructions
60
+
61
+ Put an `ARRAKIS.md` (or `AGENTS.md`) in your repo to tell the agent how your project works: build commands, conventions, things to avoid. Arrakis reads these files from the current directory and its parents, plus `~/.arrakis/ARRAKIS.md` for global instructions.
62
+
63
+ ## Sessions
64
+
65
+ Every session is an append-only event log at `~/.arrakis/sessions/<id>.jsonl`, written to disk as each event happens. If arrakis crashes or the terminal closes, `arrakis -c` picks up where you left off. Unfinished tool calls are marked as interrupted, so the conversation stays valid. When the history nears the context window (`contextWindow`, default 128000 tokens), older turns are summarized automatically.
66
+
67
+ ## Development
68
+
69
+ ```bash
70
+ npm test # end-to-end tests against a mock model server
71
+ node test/mock-server.js 8765 # run the mock server locally
72
+ ARRAKIS_BASE_URL=http://localhost:8765/v1 node bin/arrakis.js
73
+ ```
74
+
75
+ Arrakis is also importable as a library: `import { Agent, Session, TOOLS } from '@mumbrane/arrakis'`.
package/bin/arrakis.js ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js';
3
+
4
+ main(process.argv.slice(2)).catch((err) => {
5
+ console.error(`arrakis: ${err?.message ?? err}`);
6
+ process.exit(1);
7
+ });
package/index.js ADDED
@@ -0,0 +1,8 @@
1
+ export { Agent } from './src/agent.js';
2
+ export { Session, listSessions } from './src/session.js';
3
+ export { Permissions } from './src/permissions.js';
4
+ export { TOOLS, toolSchemas, executeToolCall } from './src/tools.js';
5
+ export { loadConfig } from './src/config.js';
6
+ export { streamChat } from './src/client.js';
7
+ export { buildSystemPrompt } from './src/prompt.js';
8
+ export { VERSION } from './src/version.js';
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@mumbrane/arrakis",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Arrakis: a coding agent for your terminal, built by Mumbrane",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "exports": {
8
+ ".": "./index.js"
9
+ },
10
+ "bin": {
11
+ "arrakis": "./bin/arrakis.js"
12
+ },
13
+ "files": [
14
+ "index.js",
15
+ "bin",
16
+ "src"
17
+ ],
18
+ "engines": {
19
+ "node": ">=18.17"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/mumbrane/arrakis.git"
24
+ },
25
+ "license": "MIT",
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "scripts": {
30
+ "test": "node test/run.js"
31
+ },
32
+ "keywords": [
33
+ "ai",
34
+ "agent",
35
+ "coding-agent",
36
+ "cli",
37
+ "terminal"
38
+ ]
39
+ }
package/src/agent.js ADDED
@@ -0,0 +1,135 @@
1
+ import { streamChat, completeText } from './client.js';
2
+ import { toolSchemas, executeToolCall, truncate } from './tools.js';
3
+ import { buildSystemPrompt } from './prompt.js';
4
+
5
+ const MAX_STEPS = 200;
6
+ const COMPACT_AT = 0.8;
7
+ const KEEP_RECENT = 6;
8
+
9
+ export const estimateTokens = (messages) => Math.ceil(JSON.stringify(messages).length / 4);
10
+
11
+ export class Agent {
12
+ constructor({ config, session, ui, permissions, cwd }) {
13
+ this.config = config;
14
+ this.session = session;
15
+ this.ui = ui;
16
+ this.permissions = permissions;
17
+ this.cwd = cwd;
18
+ this.abort = null;
19
+ }
20
+
21
+ get busy() {
22
+ return this.abort !== null;
23
+ }
24
+
25
+ interrupt() {
26
+ if (!this.abort) return;
27
+ this.abort.abort();
28
+ this.ui.cancelRead();
29
+ }
30
+
31
+ // Run one user turn to completion. Returns true on success.
32
+ async send(text) {
33
+ this.session.add({ role: 'user', content: text });
34
+ this.abort = new AbortController();
35
+ const signal = this.abort.signal;
36
+ try {
37
+ for (let step = 0; step < MAX_STEPS; step++) {
38
+ await this.maybeCompact(signal);
39
+ const msg = await this.callModel(signal);
40
+ if (!msg.tool_calls?.length) return true;
41
+ for (const call of msg.tool_calls) {
42
+ const content = signal.aborted
43
+ ? 'Interrupted by the user before this tool ran.'
44
+ : await executeToolCall(call, { cwd: this.cwd, signal, ui: this.ui, permissions: this.permissions });
45
+ this.session.add({ role: 'tool', tool_call_id: call.id, content });
46
+ }
47
+ if (signal.aborted) throw new DOMException('Interrupted', 'AbortError');
48
+ }
49
+ this.ui.error(`Stopped after ${MAX_STEPS} steps.`);
50
+ return false;
51
+ } catch (err) {
52
+ if (err.name === 'AbortError') this.ui.info('Interrupted.');
53
+ else this.ui.error(err.message);
54
+ return false;
55
+ } finally {
56
+ this.ui.endText();
57
+ this.abort = null;
58
+ this.session.repair();
59
+ }
60
+ }
61
+
62
+ async callModel(signal) {
63
+ const messages = [{ role: 'system', content: buildSystemPrompt({ cwd: this.cwd, model: this.config.model }) }, ...this.session.messages];
64
+ let content = '';
65
+ const calls = [];
66
+ this.ui.startResponse();
67
+ try {
68
+ for await (const event of streamChat({ config: this.config, messages, tools: toolSchemas(), signal })) {
69
+ const delta = event.choices?.[0]?.delta;
70
+ if (!delta) continue;
71
+ const reasoning = delta.reasoning_content ?? delta.reasoning;
72
+ if (reasoning) this.ui.thinking(reasoning);
73
+ if (delta.content) {
74
+ content += delta.content;
75
+ this.ui.text(delta.content);
76
+ }
77
+ for (const tc of delta.tool_calls ?? []) {
78
+ const idx = tc.index ?? (tc.id ? calls.length : Math.max(0, calls.length - 1));
79
+ const c = (calls[idx] ??= { id: '', type: 'function', function: { name: '', arguments: '' } });
80
+ if (tc.id) c.id = tc.id;
81
+ if (tc.function?.name && !c.function.name) c.function.name = tc.function.name;
82
+ if (tc.function?.arguments) c.function.arguments += tc.function.arguments;
83
+ }
84
+ }
85
+ } finally {
86
+ this.ui.endText();
87
+ }
88
+ const toolCalls = calls.filter(Boolean).map((c, i) => ({ ...c, id: c.id || `call_${Date.now()}_${i}` }));
89
+ const msg = { role: 'assistant', content: content || (toolCalls.length ? null : '') };
90
+ if (toolCalls.length) msg.tool_calls = toolCalls;
91
+ this.session.add(msg);
92
+ return msg;
93
+ }
94
+
95
+ async maybeCompact(signal, force = false) {
96
+ const messages = this.session.messages;
97
+ if (!force && estimateTokens(messages) < this.config.contextWindow * COMPACT_AT) return false;
98
+ // Cut at a user message so tool calls stay paired with their results.
99
+ // A manual /compact keeps only the last exchange; automatic keeps a bit more.
100
+ const keep = force ? 2 : KEEP_RECENT;
101
+ let cut = -1;
102
+ for (let i = messages.length - 1; i > 0; i--) {
103
+ if (messages[i].role === 'user' && messages.length - i >= Math.min(keep, messages.length - 1)) {
104
+ cut = i;
105
+ break;
106
+ }
107
+ }
108
+ if (cut <= 0) {
109
+ for (let i = messages.length - 1; i > 0; i--) if (messages[i].role === 'user') { cut = i; break; }
110
+ }
111
+ if (cut <= 0) return false;
112
+ this.ui.info('Compacting conversation history…');
113
+ const transcript = messages.slice(0, cut).map(renderForSummary).join('\n\n');
114
+ const summary = await completeText({
115
+ config: this.config,
116
+ signal,
117
+ messages: [
118
+ { role: 'system', content: 'You summarize coding-agent conversations so the work can continue with less context.' },
119
+ {
120
+ role: 'user',
121
+ content: `Summarize this conversation between a user and a coding agent. Keep: the user's goals and instructions, decisions made, files read or changed (with paths), commands run and their important results, errors hit, and what is left to do. Be specific and concise.\n\n<conversation>\n${truncate(transcript, 400000)}\n</conversation>`,
122
+ },
123
+ ],
124
+ });
125
+ this.session.compact(summary.trim() || '(no summary produced)', cut);
126
+ return true;
127
+ }
128
+ }
129
+
130
+ function renderForSummary(m) {
131
+ if (m.role === 'tool') return `[tool result]\n${truncate(String(m.content ?? ''), 2000)}`;
132
+ let s = `[${m.role}]\n${m.content ?? ''}`;
133
+ for (const c of m.tool_calls ?? []) s += `\n(called ${c.function.name} ${truncate(c.function.arguments, 1000)})`;
134
+ return s;
135
+ }
package/src/cli.js ADDED
@@ -0,0 +1,247 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { loadConfig, setConfigValue, readConfigFile, maskSecret, CONFIG_KEYS, CONFIG_PATH } from './config.js';
3
+ import { resolveModel } from './client.js';
4
+ import { Session, listSessions } from './session.js';
5
+ import { Agent, estimateTokens } from './agent.js';
6
+ import { Permissions } from './permissions.js';
7
+ import { UI, colors } from './ui.js';
8
+ import { TOOLS } from './tools.js';
9
+ import { loadProjectInstructions } from './prompt.js';
10
+ import { VERSION } from './version.js';
11
+
12
+ const HELP = `arrakis ${VERSION} — a coding agent for your terminal
13
+
14
+ Usage
15
+ arrakis [prompt] Start an interactive session (optionally with a first message)
16
+ arrakis -p "prompt" Run one task non-interactively and print the answer
17
+ arrakis -c Continue the most recent session in this directory
18
+ arrakis -r <id> Resume a session by id (or id prefix)
19
+ arrakis sessions List recent sessions
20
+ arrakis config Show configuration
21
+ arrakis config set <key> <v> Set a config value (baseUrl, apiKey, model, contextWindow, maxTokens)
22
+
23
+ Options
24
+ -p, --print Non-interactive: print the response and exit (reads stdin if no prompt)
25
+ -m, --model <name> Model to use for this run
26
+ --base-url <url> API base URL for this run
27
+ -c, --continue Continue the latest session for this directory
28
+ -r, --resume <id> Resume a specific session
29
+ --yolo Allow every file write and command without asking
30
+ --allow <tools> Comma-separated tools to allow without asking (e.g. edit_file,write_file)
31
+ -v, --version Print version
32
+ -h, --help Show this help
33
+
34
+ Environment
35
+ ARRAKIS_BASE_URL, ARRAKIS_API_KEY, ARRAKIS_MODEL, ARRAKIS_CONTEXT_WINDOW, ARRAKIS_HOME`;
36
+
37
+ const SLASH_HELP = `/help Show commands
38
+ /clear Start a new session
39
+ /compact Summarize history to free up context
40
+ /model [name] Show or switch the model
41
+ /sessions List recent sessions
42
+ /status Session, model, context usage and permissions
43
+ /yolo Toggle allowing all tool calls without asking
44
+ /exit Quit (or Ctrl-D)
45
+
46
+ End a line with \\ to continue on the next line. Ctrl-C interrupts the model.`;
47
+
48
+ export async function main(argv) {
49
+ if (argv[0] === 'config') return configCommand(argv.slice(1));
50
+ if (argv[0] === 'sessions') return sessionsCommand();
51
+
52
+ const { values, positionals } = parseArgs({
53
+ args: argv,
54
+ allowPositionals: true,
55
+ options: {
56
+ print: { type: 'boolean', short: 'p' },
57
+ model: { type: 'string', short: 'm' },
58
+ 'base-url': { type: 'string' },
59
+ continue: { type: 'boolean', short: 'c' },
60
+ resume: { type: 'string', short: 'r' },
61
+ yolo: { type: 'boolean' },
62
+ allow: { type: 'string' },
63
+ version: { type: 'boolean', short: 'v' },
64
+ help: { type: 'boolean', short: 'h' },
65
+ },
66
+ });
67
+ if (values.version) return console.log(VERSION);
68
+ if (values.help) return console.log(HELP);
69
+
70
+ const print = !!values.print;
71
+ let prompt = positionals.join(' ').trim();
72
+ if (print && !prompt && !process.stdin.isTTY) prompt = (await readStdin()).trim();
73
+ if (print && !prompt) throw new Error('No prompt given. Usage: arrakis -p "your task"');
74
+
75
+ const cwd = process.cwd();
76
+ const config = loadConfig({ model: values.model, baseUrl: values['base-url'] });
77
+ config.model = await resolveModel(config);
78
+
79
+ let session;
80
+ if (values.resume) session = Session.load(values.resume);
81
+ else if (values.continue) {
82
+ session = Session.latest(cwd);
83
+ if (!session) throw new Error(`No previous session in ${cwd}. Start one with: arrakis`);
84
+ } else session = Session.create({ cwd, model: config.model });
85
+
86
+ const ui = new UI({ print });
87
+ const permissions = new Permissions({
88
+ ui,
89
+ mode: values.yolo ? 'yolo' : print ? 'deny' : 'ask',
90
+ allow: values.allow ? values.allow.split(',').map((s) => s.trim()).filter(Boolean) : [],
91
+ });
92
+ const agent = new Agent({ config, session, ui, permissions, cwd });
93
+
94
+ if (print) {
95
+ process.on('SIGINT', () => {
96
+ agent.interrupt();
97
+ process.exit(130);
98
+ });
99
+ const ok = await agent.send(prompt);
100
+ process.exitCode = ok ? 0 : 1;
101
+ return;
102
+ }
103
+ await interactive({ agent, ui, config, cwd, firstPrompt: prompt });
104
+ }
105
+
106
+ async function interactive({ agent, ui, config, cwd, firstPrompt }) {
107
+ const c = ui.c;
108
+ ui.start();
109
+ let armedExit = false;
110
+ ui.onInterrupt(() => {
111
+ if (agent.busy) return agent.interrupt();
112
+ if (armedExit) {
113
+ ui.write(ui.out, '\n');
114
+ process.exit(0);
115
+ }
116
+ armedExit = true;
117
+ ui.write(ui.out, `\n${c.dim('(Press Ctrl-C again to exit)')}\n`);
118
+ ui.rl?.prompt();
119
+ });
120
+
121
+ const instr = loadProjectInstructions(cwd).filter((i) => i.text.trim());
122
+ ui.write(ui.out, `\n${c.accent(c.bold(' ◆ arrakis'))} ${c.dim(`v${VERSION}`)}\n`);
123
+ ui.write(ui.out, c.dim(` model ${config.model} · ${cwd}\n`));
124
+ if (instr.length) ui.write(ui.out, c.dim(` instructions: ${instr.map((i) => i.file).join(', ')}\n`));
125
+ if (agent.session.messages.length) ui.write(ui.out, c.dim(` resumed session ${agent.session.id} (${agent.session.messages.length} messages)\n`));
126
+ ui.write(ui.out, c.dim(' /help for commands · Ctrl-C to interrupt · Ctrl-D to quit\n\n'));
127
+
128
+ if (firstPrompt) await agent.send(firstPrompt);
129
+ while (true) {
130
+ const line = await ui.prompt();
131
+ if (line === null) break;
132
+ armedExit = false;
133
+ const text = line.trim();
134
+ if (!text) continue;
135
+ if (text.startsWith('/')) {
136
+ if ((await slashCommand(text, { agent, ui, config, cwd })) === 'exit') break;
137
+ continue;
138
+ }
139
+ await agent.send(text);
140
+ ui.write(ui.out, '\n');
141
+ }
142
+ ui.close();
143
+ ui.write(ui.out, c.dim(`Session saved. Resume with: arrakis -r ${agent.session.id}\n`));
144
+ }
145
+
146
+ async function slashCommand(text, { agent, ui, config, cwd }) {
147
+ const [cmd, ...rest] = text.slice(1).split(/\s+/);
148
+ const arg = rest.join(' ');
149
+ const c = ui.c;
150
+ switch (cmd) {
151
+ case 'help':
152
+ ui.write(ui.out, SLASH_HELP + '\n');
153
+ break;
154
+ case 'exit':
155
+ case 'quit':
156
+ return 'exit';
157
+ case 'clear':
158
+ agent.session = Session.create({ cwd, model: config.model });
159
+ ui.info(`Started new session ${agent.session.id}.`);
160
+ break;
161
+ case 'compact': {
162
+ const ac = new AbortController();
163
+ agent.abort = ac;
164
+ try {
165
+ const done = await agent.maybeCompact(ac.signal, true);
166
+ ui.info(done ? `Compacted. ~${estimateTokens(agent.session.messages)} tokens of history.` : 'Nothing to compact yet.');
167
+ } catch (err) {
168
+ ui.error(err.name === 'AbortError' ? 'Interrupted.' : err.message);
169
+ } finally {
170
+ agent.abort = null;
171
+ }
172
+ break;
173
+ }
174
+ case 'model':
175
+ if (arg) {
176
+ config.model = arg;
177
+ ui.info(`Model set to ${arg} for this session. To make it the default: arrakis config set model ${arg}`);
178
+ } else ui.info(`Model: ${config.model}`);
179
+ break;
180
+ case 'sessions':
181
+ printSessions(ui.out, 10);
182
+ break;
183
+ case 'status': {
184
+ const used = estimateTokens(agent.session.messages);
185
+ ui.write(ui.out, [
186
+ `session ${agent.session.id}`,
187
+ `log ${agent.session.file}`,
188
+ `model ${config.model} @ ${config.baseUrl}`,
189
+ `context ~${used.toLocaleString()} / ${config.contextWindow.toLocaleString()} tokens (${Math.round((used / config.contextWindow) * 100)}%)`,
190
+ `permissions ${agent.permissions.mode}${agent.permissions.allowed.size ? ` (always allowed: ${[...agent.permissions.allowed].join(', ')})` : ''}`,
191
+ `tools ${TOOLS.map((t) => t.name).join(', ')}`,
192
+ ].join('\n') + '\n');
193
+ break;
194
+ }
195
+ case 'yolo':
196
+ agent.permissions.mode = agent.permissions.mode === 'yolo' ? 'ask' : 'yolo';
197
+ ui.info(agent.permissions.mode === 'yolo' ? 'YOLO on: tool calls run without asking.' : 'YOLO off: writes and commands ask first.');
198
+ break;
199
+ default:
200
+ ui.write(ui.out, c.red(`Unknown command /${cmd}. Try /help.\n`));
201
+ }
202
+ }
203
+
204
+ function configCommand(args) {
205
+ const [sub, key, ...rest] = args;
206
+ if (sub === 'set') {
207
+ if (!key) throw new Error('Usage: arrakis config set <key> <value>');
208
+ setConfigValue(key, rest.join(' '));
209
+ console.log(`Saved ${key} to ${CONFIG_PATH}`);
210
+ return;
211
+ }
212
+ if (sub === 'unset') {
213
+ setConfigValue(key, undefined);
214
+ console.log(`Removed ${key} from ${CONFIG_PATH}`);
215
+ return;
216
+ }
217
+ if (sub && sub !== 'show') throw new Error('Usage: arrakis config [show | set <key> <value> | unset <key>]');
218
+ const config = loadConfig();
219
+ const file = readConfigFile();
220
+ console.log(`Config file: ${CONFIG_PATH}\n`);
221
+ for (const [k, spec] of Object.entries(CONFIG_KEYS)) {
222
+ const source = process.env[spec.env] ? `env ${spec.env}` : file[k] !== undefined ? 'config file' : 'default';
223
+ const value = spec.secret ? maskSecret(config[k]) : config[k] || '(not set)';
224
+ console.log(`${k.padEnd(14)} ${String(value).padEnd(36)} ${source}`);
225
+ }
226
+ }
227
+
228
+ function sessionsCommand() {
229
+ printSessions(process.stdout, 20);
230
+ }
231
+
232
+ function printSessions(stream, limit) {
233
+ const c = colors(stream);
234
+ const sessions = listSessions().slice(0, limit);
235
+ if (!sessions.length) return stream.write('No sessions yet.\n');
236
+ for (const s of sessions) {
237
+ const when = new Date(s.updated).toLocaleString();
238
+ stream.write(`${c.bold(s.id)} ${c.dim(when)} ${c.dim(`${s.messages} msgs`)}\n ${s.title || c.dim('(empty)')}\n ${c.dim(s.cwd ?? '')}\n`);
239
+ }
240
+ stream.write(c.dim('\nResume with: arrakis -r <id>\n'));
241
+ }
242
+
243
+ async function readStdin() {
244
+ let data = '';
245
+ for await (const chunk of process.stdin) data += chunk;
246
+ return data;
247
+ }
package/src/client.js ADDED
@@ -0,0 +1,90 @@
1
+ // Minimal client for OpenAI-compatible /chat/completions with streaming and tool calls.
2
+
3
+ function headers(config) {
4
+ const h = { 'content-type': 'application/json' };
5
+ if (config.apiKey) h.authorization = `Bearer ${config.apiKey}`;
6
+ return h;
7
+ }
8
+
9
+ async function request(config, pathname, init, { retries = 3 } = {}) {
10
+ const url = `${config.baseUrl}${pathname}`;
11
+ for (let attempt = 0; ; attempt++) {
12
+ let res;
13
+ try {
14
+ res = await fetch(url, { ...init, headers: headers(config) });
15
+ } catch (err) {
16
+ if (err.name === 'AbortError') throw err;
17
+ if (attempt < retries) {
18
+ await sleep(500 * 2 ** attempt, init.signal);
19
+ continue;
20
+ }
21
+ throw new Error(`Could not reach ${config.baseUrl} (${err.cause?.code || err.message}). Check baseUrl with: arrakis config`);
22
+ }
23
+ if (res.ok) return res;
24
+ const retryable = res.status === 429 || res.status >= 500;
25
+ if (retryable && attempt < retries) {
26
+ await res.text().catch(() => {});
27
+ await sleep(1000 * 2 ** attempt, init.signal);
28
+ continue;
29
+ }
30
+ const body = await res.text().catch(() => '');
31
+ throw new Error(`API error ${res.status} from ${url}: ${body.slice(0, 500)}`);
32
+ }
33
+ }
34
+
35
+ function sleep(ms, signal) {
36
+ return new Promise((resolve, reject) => {
37
+ const t = setTimeout(resolve, ms);
38
+ signal?.addEventListener('abort', () => {
39
+ clearTimeout(t);
40
+ reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
41
+ }, { once: true });
42
+ });
43
+ }
44
+
45
+ export async function* streamChat({ config, messages, tools, signal }) {
46
+ const body = { model: config.model, messages, stream: true };
47
+ if (tools?.length) body.tools = tools;
48
+ if (config.maxTokens) body.max_tokens = config.maxTokens;
49
+ const res = await request(config, '/chat/completions', { method: 'POST', body: JSON.stringify(body), signal });
50
+
51
+ const decoder = new TextDecoder();
52
+ let buf = '';
53
+ for await (const chunk of res.body) {
54
+ buf += decoder.decode(chunk, { stream: true });
55
+ let nl;
56
+ while ((nl = buf.indexOf('\n')) >= 0) {
57
+ const line = buf.slice(0, nl).trim();
58
+ buf = buf.slice(nl + 1);
59
+ if (!line.startsWith('data:')) continue;
60
+ const data = line.slice(5).trim();
61
+ if (data === '[DONE]') return;
62
+ let event;
63
+ try {
64
+ event = JSON.parse(data);
65
+ } catch {
66
+ continue;
67
+ }
68
+ if (event.error) throw new Error(`API error: ${event.error.message || JSON.stringify(event.error)}`);
69
+ yield event;
70
+ }
71
+ }
72
+ }
73
+
74
+ // Collect a full text response (used for summaries).
75
+ export async function completeText({ config, messages, signal }) {
76
+ let text = '';
77
+ for await (const event of streamChat({ config, messages, signal })) {
78
+ text += event.choices?.[0]?.delta?.content ?? '';
79
+ }
80
+ return text;
81
+ }
82
+
83
+ export async function resolveModel(config) {
84
+ if (config.model) return config.model;
85
+ const res = await request(config, '/models', { method: 'GET' }, { retries: 1 });
86
+ const json = await res.json();
87
+ const id = json.data?.[0]?.id;
88
+ if (!id) throw new Error(`No model configured and ${config.baseUrl}/models listed none. Set one with: arrakis config set model <name>`);
89
+ return id;
90
+ }
package/src/config.js ADDED
@@ -0,0 +1,60 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+
5
+ export const HOME_DIR = process.env.ARRAKIS_HOME || path.join(os.homedir(), '.arrakis');
6
+ export const CONFIG_PATH = path.join(HOME_DIR, 'config.json');
7
+ export const SESSIONS_DIR = path.join(HOME_DIR, 'sessions');
8
+
9
+ export const CONFIG_KEYS = {
10
+ baseUrl: { env: 'ARRAKIS_BASE_URL', help: 'OpenAI-compatible API base URL, e.g. https://api.example.com/v1' },
11
+ apiKey: { env: 'ARRAKIS_API_KEY', help: 'API key, sent as a Bearer token', secret: true },
12
+ model: { env: 'ARRAKIS_MODEL', help: 'Model name (default: first model from /models)' },
13
+ contextWindow: { env: 'ARRAKIS_CONTEXT_WINDOW', help: 'Context window in tokens; history is compacted near 80%', number: true },
14
+ maxTokens: { env: 'ARRAKIS_MAX_TOKENS', help: 'Max output tokens per response (optional)', number: true },
15
+ };
16
+
17
+ const DEFAULTS = {
18
+ baseUrl: 'http://localhost:8000/v1',
19
+ apiKey: '',
20
+ model: '',
21
+ contextWindow: 128000,
22
+ maxTokens: 0,
23
+ };
24
+
25
+ export function readConfigFile() {
26
+ try {
27
+ return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
28
+ } catch {
29
+ return {};
30
+ }
31
+ }
32
+
33
+ export function loadConfig(overrides = {}) {
34
+ const file = readConfigFile();
35
+ const config = { ...DEFAULTS };
36
+ for (const [key, spec] of Object.entries(CONFIG_KEYS)) {
37
+ let value = config[key];
38
+ if (file[key] !== undefined && file[key] !== '') value = file[key];
39
+ if (process.env[spec.env]) value = process.env[spec.env];
40
+ if (overrides[key] !== undefined && overrides[key] !== '') value = overrides[key];
41
+ config[key] = spec.number ? Number(value) || 0 : value;
42
+ }
43
+ config.baseUrl = String(config.baseUrl).replace(/\/+$/, '');
44
+ if (!config.contextWindow) config.contextWindow = DEFAULTS.contextWindow;
45
+ return config;
46
+ }
47
+
48
+ export function setConfigValue(key, value) {
49
+ if (!CONFIG_KEYS[key]) throw new Error(`Unknown config key "${key}". Keys: ${Object.keys(CONFIG_KEYS).join(', ')}`);
50
+ const file = readConfigFile();
51
+ if (value === undefined || value === '') delete file[key];
52
+ else file[key] = CONFIG_KEYS[key].number ? Number(value) : value;
53
+ fs.mkdirSync(HOME_DIR, { recursive: true });
54
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(file, null, 2) + '\n', { mode: 0o600 });
55
+ }
56
+
57
+ export function maskSecret(value) {
58
+ if (!value) return '(not set)';
59
+ return value.length <= 8 ? '****' : `${value.slice(0, 4)}…${value.slice(-4)}`;
60
+ }