@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/README.md CHANGED
@@ -1,21 +1,81 @@
1
- # @mumbrane/arrakis
1
+ # arrakis
2
+
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.
2
4
 
3
5
  ## Install
4
6
 
5
7
  ```bash
6
- npm install @mumbrane/arrakis
8
+ npm install -g @mumbrane/arrakis
7
9
  ```
8
10
 
9
- Or globally for the CLI:
11
+ Requires Node.js 18.17 or later.
12
+
13
+ ## Set up
14
+
15
+ Run `arrakis`. The first time, it walks you through setup:
16
+
17
+ 1. **Pick a provider** with the arrow keys: Anthropic (Claude), OpenAI, Google Gemini, OpenRouter, xAI, DeepSeek, Mistral, Groq, Together AI, Ollama (local) or any other OpenAI-compatible API.
18
+ 2. **Paste your API key.** It's hidden as you type, checked against the provider, and saved to `~/.arrakis/config.json` (readable only by you).
19
+ 3. **Pick a model** from the provider's live model list. Type to search.
20
+
21
+ That's it. Switch any time inside a session:
22
+
23
+ - `/model` picks another model from the same provider.
24
+ - `/provider` switches provider or updates your key. Each provider remembers its own key and model.
25
+
26
+ Outside a session: `arrakis setup` reruns setup, `arrakis models` lists models, `arrakis logout` removes saved keys.
27
+
28
+ For CI or scripts, skip setup with environment variables: `ARRAKIS_PROVIDER` (e.g. `anthropic`), `ARRAKIS_API_KEY`, `ARRAKIS_MODEL`, or `ARRAKIS_BASE_URL` for any OpenAI-compatible endpoint.
29
+
30
+ ## Use
10
31
 
11
32
  ```bash
12
- npm install -g @mumbrane/arrakis
13
- arrakis
33
+ arrakis # interactive session in the current directory
34
+ arrakis "fix the failing test" # interactive, starting with a task
35
+ arrakis -p "explain src/app.ts" # one-shot: prints the answer and exits
36
+ arrakis -c # continue the last session in this directory
37
+ arrakis -r <id> # resume a specific session
38
+ arrakis sessions # list recent sessions
14
39
  ```
15
40
 
16
- ## Use
41
+ In a session:
17
42
 
18
- ```js
19
- import { hello } from '@mumbrane/arrakis';
20
- console.log(hello('Paul'));
43
+ | Command | What it does |
44
+ |---|---|
45
+ | `/help` | List commands |
46
+ | `/status` | Session, model, context usage, permissions |
47
+ | `/compact` | Summarize history to free up context |
48
+ | `/model [name]` | Pick a model from your provider |
49
+ | `/provider` | Switch provider or update your API key |
50
+ | `/clear` | Start a new session |
51
+ | `/yolo` | Toggle running tool calls without asking |
52
+ | `/exit` | Quit (or Ctrl-D) |
53
+
54
+ Ctrl-C interrupts the model mid-response. End a line with `\` to keep typing on the next line.
55
+
56
+ ## Tools
57
+
58
+ | Tool | Asks first |
59
+ |---|---|
60
+ | `read_file`, `grep`, `list_files` | No |
61
+ | `write_file`, `edit_file`, `bash` | Yes: answer `y`, `a` (always, for this session) or `n` |
62
+
63
+ `-p` mode denies tools that need permission unless you pass `--yolo` or `--allow edit_file,write_file,bash`.
64
+
65
+ ## Project instructions
66
+
67
+ 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.
68
+
69
+ ## Sessions
70
+
71
+ 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.
72
+
73
+ ## Development
74
+
75
+ ```bash
76
+ npm test # end-to-end tests against a mock model server
77
+ node test/mock-server.js 8765 # run the mock server locally
78
+ ARRAKIS_BASE_URL=http://localhost:8765/v1 node bin/arrakis.js
21
79
  ```
80
+
81
+ Arrakis is also importable as a library: `import { Agent, Session, TOOLS } from '@mumbrane/arrakis'`.
package/bin/arrakis.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { hello, version } from '../index.js';
2
+ import { main } from '../src/cli.js';
3
3
 
4
- const [arg] = process.argv.slice(2);
5
- if (arg === '--version' || arg === '-v') console.log(version);
6
- else console.log(hello(arg));
4
+ main(process.argv.slice(2)).catch((err) => {
5
+ console.error(`arrakis: ${err?.message ?? err}`);
6
+ process.exit(1);
7
+ });
package/index.js CHANGED
@@ -1,5 +1,8 @@
1
- export const version = '0.1.0';
2
-
3
- export function hello(name = 'world') {
4
- return `Hello, ${name}, from Arrakis.`;
5
- }
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,14 +1,39 @@
1
1
  {
2
2
  "name": "@mumbrane/arrakis",
3
- "version": "0.1.0",
4
- "description": "Arrakis",
3
+ "version": "0.3.0",
4
+ "description": "Arrakis: a coding agent for your terminal, built by Mumbrane",
5
5
  "type": "module",
6
6
  "main": "./index.js",
7
- "exports": { ".": "./index.js" },
8
- "bin": { "arrakis": "./bin/arrakis.js" },
9
- "files": ["index.js", "bin"],
10
- "engines": { "node": ">=18" },
11
- "repository": { "type": "git", "url": "git+https://github.com/mumbrane/arrakis.git" },
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
+ },
12
25
  "license": "MIT",
13
- "publishConfig": { "access": "public" }
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
+ ]
14
39
  }
package/src/agent.js ADDED
@@ -0,0 +1,137 @@
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 if (err.status === 401 || err.status === 403) this.ui.error(`${err.message}\nYour API key was rejected. Run /provider (or: arrakis setup) to update it.`);
54
+ else if (err.status === 404) this.ui.error(`${err.message}\nThe model may not exist for this provider. Pick another with /model.`);
55
+ else this.ui.error(err.message);
56
+ return false;
57
+ } finally {
58
+ this.ui.endText();
59
+ this.abort = null;
60
+ this.session.repair();
61
+ }
62
+ }
63
+
64
+ async callModel(signal) {
65
+ const messages = [{ role: 'system', content: buildSystemPrompt({ cwd: this.cwd, model: this.config.model }) }, ...this.session.messages];
66
+ let content = '';
67
+ const calls = [];
68
+ this.ui.startResponse();
69
+ try {
70
+ for await (const event of streamChat({ config: this.config, messages, tools: toolSchemas(), signal })) {
71
+ const delta = event.choices?.[0]?.delta;
72
+ if (!delta) continue;
73
+ const reasoning = delta.reasoning_content ?? delta.reasoning;
74
+ if (reasoning) this.ui.thinking(reasoning);
75
+ if (delta.content) {
76
+ content += delta.content;
77
+ this.ui.text(delta.content);
78
+ }
79
+ for (const tc of delta.tool_calls ?? []) {
80
+ const idx = tc.index ?? (tc.id ? calls.length : Math.max(0, calls.length - 1));
81
+ const c = (calls[idx] ??= { id: '', type: 'function', function: { name: '', arguments: '' } });
82
+ if (tc.id) c.id = tc.id;
83
+ if (tc.function?.name && !c.function.name) c.function.name = tc.function.name;
84
+ if (tc.function?.arguments) c.function.arguments += tc.function.arguments;
85
+ }
86
+ }
87
+ } finally {
88
+ this.ui.endText();
89
+ }
90
+ const toolCalls = calls.filter(Boolean).map((c, i) => ({ ...c, id: c.id || `call_${Date.now()}_${i}` }));
91
+ const msg = { role: 'assistant', content: content || (toolCalls.length ? null : '') };
92
+ if (toolCalls.length) msg.tool_calls = toolCalls;
93
+ this.session.add(msg);
94
+ return msg;
95
+ }
96
+
97
+ async maybeCompact(signal, force = false) {
98
+ const messages = this.session.messages;
99
+ if (!force && estimateTokens(messages) < this.config.contextWindow * COMPACT_AT) return false;
100
+ // Cut at a user message so tool calls stay paired with their results.
101
+ // A manual /compact keeps only the last exchange; automatic keeps a bit more.
102
+ const keep = force ? 2 : KEEP_RECENT;
103
+ let cut = -1;
104
+ for (let i = messages.length - 1; i > 0; i--) {
105
+ if (messages[i].role === 'user' && messages.length - i >= Math.min(keep, messages.length - 1)) {
106
+ cut = i;
107
+ break;
108
+ }
109
+ }
110
+ if (cut <= 0) {
111
+ for (let i = messages.length - 1; i > 0; i--) if (messages[i].role === 'user') { cut = i; break; }
112
+ }
113
+ if (cut <= 0) return false;
114
+ this.ui.info('Compacting conversation history…');
115
+ const transcript = messages.slice(0, cut).map(renderForSummary).join('\n\n');
116
+ const summary = await completeText({
117
+ config: this.config,
118
+ signal,
119
+ messages: [
120
+ { role: 'system', content: 'You summarize coding-agent conversations so the work can continue with less context.' },
121
+ {
122
+ role: 'user',
123
+ 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>`,
124
+ },
125
+ ],
126
+ });
127
+ this.session.compact(summary.trim() || '(no summary produced)', cut);
128
+ return true;
129
+ }
130
+ }
131
+
132
+ function renderForSummary(m) {
133
+ if (m.role === 'tool') return `[tool result]\n${truncate(String(m.content ?? ''), 2000)}`;
134
+ let s = `[${m.role}]\n${m.content ?? ''}`;
135
+ for (const c of m.tool_calls ?? []) s += `\n(called ${c.function.name} ${truncate(c.function.arguments, 1000)})`;
136
+ return s;
137
+ }
package/src/cli.js ADDED
@@ -0,0 +1,317 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { loadConfig, setConfigValue, readConfigFile, maskSecret, saveProvider, removeProviderKeys, CONFIG_KEYS, CONFIG_PATH } from './config.js';
3
+ import { resolveModel, listModels } from './client.js';
4
+ import { getProvider } from './providers.js';
5
+ import { createPrompts } from './prompts.js';
6
+ import { runSetup, pickModel } from './setup.js';
7
+ import { Session, listSessions } from './session.js';
8
+ import { Agent, estimateTokens } from './agent.js';
9
+ import { Permissions } from './permissions.js';
10
+ import { UI, colors } from './ui.js';
11
+ import { TOOLS } from './tools.js';
12
+ import { loadProjectInstructions } from './prompt.js';
13
+ import { VERSION } from './version.js';
14
+
15
+ const HELP = `arrakis ${VERSION} — a coding agent for your terminal
16
+
17
+ Usage
18
+ arrakis [prompt] Start an interactive session (first run walks you through setup)
19
+ arrakis -p "prompt" Run one task non-interactively and print the answer
20
+ arrakis -c Continue the most recent session in this directory
21
+ arrakis -r <id> Resume a session by id (or id prefix)
22
+ arrakis setup Choose a provider, enter an API key and pick a model
23
+ arrakis models List the models your provider offers
24
+ arrakis sessions List recent sessions
25
+ arrakis config Show configuration
26
+ arrakis config set <key> <v> Set a value (provider, baseUrl, apiKey, model, contextWindow, maxTokens)
27
+ arrakis logout Remove saved API keys
28
+
29
+ Options
30
+ -p, --print Non-interactive: print the response and exit (reads stdin if no prompt)
31
+ -m, --model <name> Model to use for this run
32
+ --base-url <url> API base URL for this run
33
+ -c, --continue Continue the latest session for this directory
34
+ -r, --resume <id> Resume a specific session
35
+ --yolo Allow every file write and command without asking
36
+ --allow <tools> Comma-separated tools to allow without asking (e.g. edit_file,write_file)
37
+ -v, --version Print version
38
+ -h, --help Show this help
39
+
40
+ Environment (overrides the config file)
41
+ ARRAKIS_PROVIDER, ARRAKIS_BASE_URL, ARRAKIS_API_KEY, ARRAKIS_MODEL, ARRAKIS_CONTEXT_WINDOW, ARRAKIS_HOME`;
42
+
43
+ const SLASH_HELP = `/help Show commands
44
+ /clear Start a new session
45
+ /compact Summarize history to free up context
46
+ /model [name] Pick a model from your provider (or set one by name)
47
+ /provider Switch provider or update your API key
48
+ /sessions List recent sessions
49
+ /status Session, model, context usage and permissions
50
+ /yolo Toggle allowing all tool calls without asking
51
+ /exit Quit (or Ctrl-D)
52
+
53
+ End a line with \\ to continue on the next line. Ctrl-C interrupts the model.`;
54
+
55
+ export async function main(argv) {
56
+ if (argv[0] === 'config') return configCommand(argv.slice(1));
57
+ if (argv[0] === 'sessions') return sessionsCommand();
58
+ if (argv[0] === 'setup' || argv[0] === 'login') return setupCommand();
59
+ if (argv[0] === 'models') return modelsCommand();
60
+ if (argv[0] === 'logout') {
61
+ removeProviderKeys();
62
+ return console.log(`Removed saved API keys from ${CONFIG_PATH}`);
63
+ }
64
+
65
+ const { values, positionals } = parseArgs({
66
+ args: argv,
67
+ allowPositionals: true,
68
+ options: {
69
+ print: { type: 'boolean', short: 'p' },
70
+ model: { type: 'string', short: 'm' },
71
+ 'base-url': { type: 'string' },
72
+ continue: { type: 'boolean', short: 'c' },
73
+ resume: { type: 'string', short: 'r' },
74
+ yolo: { type: 'boolean' },
75
+ allow: { type: 'string' },
76
+ version: { type: 'boolean', short: 'v' },
77
+ help: { type: 'boolean', short: 'h' },
78
+ },
79
+ });
80
+ if (values.version) return console.log(VERSION);
81
+ if (values.help) return console.log(HELP);
82
+
83
+ const print = !!values.print;
84
+ let prompt = positionals.join(' ').trim();
85
+ if (print && !prompt && !process.stdin.isTTY) prompt = (await readStdin()).trim();
86
+ if (print && !prompt) throw new Error('No prompt given. Usage: arrakis -p "your task"');
87
+
88
+ const cwd = process.cwd();
89
+ let config = loadConfig({ model: values.model, baseUrl: values['base-url'] });
90
+ const ui = new UI({ print });
91
+ const prompts = createPrompts(ui);
92
+ if (!config.configured) {
93
+ if (print) throw new Error('arrakis is not set up yet. Run `arrakis` once to choose a provider and enter an API key.');
94
+ ui.start();
95
+ const next = await runSetup({ ui, prompts, welcome: true });
96
+ if (!next) {
97
+ ui.close();
98
+ ui.write(ui.out, 'Setup cancelled. Run arrakis again when you are ready.\n');
99
+ return;
100
+ }
101
+ config = loadConfig({ model: values.model, baseUrl: values['base-url'] });
102
+ }
103
+ config.model = await resolveModel(config);
104
+
105
+ let session;
106
+ if (values.resume) session = Session.load(values.resume);
107
+ else if (values.continue) {
108
+ session = Session.latest(cwd);
109
+ if (!session) throw new Error(`No previous session in ${cwd}. Start one with: arrakis`);
110
+ } else session = Session.create({ cwd, model: config.model });
111
+
112
+ const permissions = new Permissions({
113
+ ui,
114
+ mode: values.yolo ? 'yolo' : print ? 'deny' : 'ask',
115
+ allow: values.allow ? values.allow.split(',').map((s) => s.trim()).filter(Boolean) : [],
116
+ });
117
+ const agent = new Agent({ config, session, ui, permissions, cwd });
118
+
119
+ if (print) {
120
+ process.on('SIGINT', () => {
121
+ agent.interrupt();
122
+ process.exit(130);
123
+ });
124
+ const ok = await agent.send(prompt);
125
+ process.exitCode = ok ? 0 : 1;
126
+ return;
127
+ }
128
+ await interactive({ agent, ui, prompts, config, cwd, firstPrompt: prompt });
129
+ }
130
+
131
+ async function interactive({ agent, ui, prompts, config, cwd, firstPrompt }) {
132
+ const c = ui.c;
133
+ ui.start();
134
+ let armedExit = false;
135
+ ui.onInterrupt(() => {
136
+ if (agent.busy) return agent.interrupt();
137
+ if (armedExit) {
138
+ ui.write(ui.out, '\n');
139
+ process.exit(0);
140
+ }
141
+ armedExit = true;
142
+ ui.write(ui.out, `\n${c.dim('(Press Ctrl-C again to exit)')}\n`);
143
+ ui.rl?.prompt();
144
+ });
145
+
146
+ const instr = loadProjectInstructions(cwd).filter((i) => i.text.trim());
147
+ ui.write(ui.out, `\n${c.accent(c.bold(' ◆ arrakis'))} ${c.dim(`v${VERSION}`)}\n`);
148
+ ui.write(ui.out, c.dim(` ${config.model} · ${config.providerName || config.baseUrl} · ${cwd}\n`));
149
+ if (instr.length) ui.write(ui.out, c.dim(` instructions: ${instr.map((i) => i.file).join(', ')}\n`));
150
+ if (agent.session.messages.length) ui.write(ui.out, c.dim(` resumed session ${agent.session.id} (${agent.session.messages.length} messages)\n`));
151
+ ui.write(ui.out, c.dim(' /help for commands · Ctrl-C to interrupt · Ctrl-D to quit\n\n'));
152
+
153
+ if (firstPrompt) await agent.send(firstPrompt);
154
+ while (true) {
155
+ const line = await ui.prompt();
156
+ if (line === null) break;
157
+ armedExit = false;
158
+ const text = line.trim();
159
+ if (!text) continue;
160
+ if (text.startsWith('/')) {
161
+ if ((await slashCommand(text, { agent, ui, prompts, config, cwd })) === 'exit') break;
162
+ continue;
163
+ }
164
+ await agent.send(text);
165
+ ui.write(ui.out, '\n');
166
+ }
167
+ ui.close();
168
+ ui.write(ui.out, c.dim(`Session saved. Resume with: arrakis -r ${agent.session.id}\n`));
169
+ }
170
+
171
+ async function slashCommand(text, { agent, ui, prompts, config, cwd }) {
172
+ const [cmd, ...rest] = text.slice(1).split(/\s+/);
173
+ const arg = rest.join(' ');
174
+ const c = ui.c;
175
+ switch (cmd) {
176
+ case 'help':
177
+ ui.write(ui.out, SLASH_HELP + '\n');
178
+ break;
179
+ case 'exit':
180
+ case 'quit':
181
+ return 'exit';
182
+ case 'clear':
183
+ agent.session = Session.create({ cwd, model: config.model });
184
+ ui.info(`Started new session ${agent.session.id}.`);
185
+ break;
186
+ case 'compact': {
187
+ const ac = new AbortController();
188
+ agent.abort = ac;
189
+ try {
190
+ const done = await agent.maybeCompact(ac.signal, true);
191
+ ui.info(done ? `Compacted. ~${estimateTokens(agent.session.messages)} tokens of history.` : 'Nothing to compact yet.');
192
+ } catch (err) {
193
+ ui.error(err.name === 'AbortError' ? 'Interrupted.' : err.message);
194
+ } finally {
195
+ agent.abort = null;
196
+ }
197
+ break;
198
+ }
199
+ case 'model': {
200
+ let chosen = arg ? { id: arg } : null;
201
+ if (!arg) {
202
+ let models = [];
203
+ try {
204
+ models = await listModels(config);
205
+ } catch (err) {
206
+ ui.error(`Couldn't list models: ${err.message}`);
207
+ }
208
+ chosen = await pickModel({ ui, prompts, provider: getProvider(config.provider), models, current: config.model });
209
+ }
210
+ if (!chosen) break;
211
+ config.model = chosen.id;
212
+ if (chosen.contextWindow) config.contextWindow = chosen.contextWindow;
213
+ if (config.provider) saveProvider(config.provider, { model: chosen.id, contextWindow: chosen.contextWindow || undefined });
214
+ ui.info(`Now using ${chosen.id}.`);
215
+ break;
216
+ }
217
+ case 'provider':
218
+ case 'setup':
219
+ case 'login': {
220
+ if (agent.session.messages.length) ui.info('Your conversation carries over to the new provider.');
221
+ const next = await runSetup({ ui, prompts });
222
+ if (next) Object.assign(config, next);
223
+ break;
224
+ }
225
+ case 'sessions':
226
+ printSessions(ui.out, 10);
227
+ break;
228
+ case 'status': {
229
+ const used = estimateTokens(agent.session.messages);
230
+ ui.write(ui.out, [
231
+ `session ${agent.session.id}`,
232
+ `log ${agent.session.file}`,
233
+ `provider ${config.providerName || 'custom'} (${config.baseUrl})`,
234
+ `model ${config.model}`,
235
+ `context ~${used.toLocaleString()} / ${config.contextWindow.toLocaleString()} tokens (${Math.round((used / config.contextWindow) * 100)}%)`,
236
+ `permissions ${agent.permissions.mode}${agent.permissions.allowed.size ? ` (always allowed: ${[...agent.permissions.allowed].join(', ')})` : ''}`,
237
+ `tools ${TOOLS.map((t) => t.name).join(', ')}`,
238
+ ].join('\n') + '\n');
239
+ break;
240
+ }
241
+ case 'yolo':
242
+ agent.permissions.mode = agent.permissions.mode === 'yolo' ? 'ask' : 'yolo';
243
+ ui.info(agent.permissions.mode === 'yolo' ? 'YOLO on: tool calls run without asking.' : 'YOLO off: writes and commands ask first.');
244
+ break;
245
+ default:
246
+ ui.write(ui.out, c.red(`Unknown command /${cmd}. Try /help.\n`));
247
+ }
248
+ }
249
+
250
+ function configCommand(args) {
251
+ const [sub, key, ...rest] = args;
252
+ if (sub === 'set') {
253
+ if (!key) throw new Error('Usage: arrakis config set <key> <value>');
254
+ setConfigValue(key, rest.join(' '));
255
+ console.log(`Saved ${key} to ${CONFIG_PATH}`);
256
+ return;
257
+ }
258
+ if (sub === 'unset') {
259
+ setConfigValue(key, undefined);
260
+ console.log(`Removed ${key} from ${CONFIG_PATH}`);
261
+ return;
262
+ }
263
+ if (sub && sub !== 'show') throw new Error('Usage: arrakis config [show | set <key> <value> | unset <key>]');
264
+ const config = loadConfig();
265
+ const file = readConfigFile();
266
+ console.log(`Config file: ${CONFIG_PATH}\n`);
267
+ if (!config.configured) console.log('Not set up yet. Run: arrakis setup\n');
268
+ const providerFile = (config.provider && file.providers[config.provider]) || {};
269
+ for (const [k, spec] of Object.entries(CONFIG_KEYS)) {
270
+ const inFile = k === 'provider' ? file.provider !== undefined : spec.global ? file[k] !== undefined : providerFile[k] !== undefined;
271
+ const source = process.env[spec.env] ? `env ${spec.env}` : inFile ? 'config file' : 'default';
272
+ let value = spec.secret ? maskSecret(config[k]) : config[k] || '(not set)';
273
+ if (k === 'provider' && config.providerName) value = `${config.provider} (${config.providerName})`;
274
+ console.log(`${k.padEnd(14)} ${String(value).padEnd(40)} ${source}`);
275
+ }
276
+ const others = Object.keys(file.providers).filter((id) => id !== config.provider);
277
+ if (others.length) console.log(`\nOther saved providers: ${others.join(', ')}`);
278
+ }
279
+
280
+ async function setupCommand() {
281
+ const ui = new UI();
282
+ ui.start();
283
+ try {
284
+ await runSetup({ ui, prompts: createPrompts(ui), welcome: !loadConfig().configured });
285
+ } finally {
286
+ ui.close();
287
+ }
288
+ }
289
+
290
+ async function modelsCommand() {
291
+ const config = loadConfig();
292
+ if (!config.configured) throw new Error('Not set up yet. Run: arrakis setup');
293
+ const models = await listModels(config);
294
+ if (!models.length) return console.log(`${config.providerName || config.baseUrl} listed no models.`);
295
+ for (const m of models) console.log(`${m.id === config.model ? '*' : ' '} ${m.id}${m.contextWindow ? ` (${m.contextWindow.toLocaleString()} tokens)` : ''}`);
296
+ }
297
+
298
+ function sessionsCommand() {
299
+ printSessions(process.stdout, 20);
300
+ }
301
+
302
+ function printSessions(stream, limit) {
303
+ const c = colors(stream);
304
+ const sessions = listSessions().slice(0, limit);
305
+ if (!sessions.length) return stream.write('No sessions yet.\n');
306
+ for (const s of sessions) {
307
+ const when = new Date(s.updated).toLocaleString();
308
+ 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`);
309
+ }
310
+ stream.write(c.dim('\nResume with: arrakis -r <id>\n'));
311
+ }
312
+
313
+ async function readStdin() {
314
+ let data = '';
315
+ for await (const chunk of process.stdin) data += chunk;
316
+ return data;
317
+ }