@mumbrane/arrakis 0.10.0 → 0.12.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
@@ -47,6 +47,8 @@ For CI or scripts, skip setup with environment variables: `ARRAKIS_PROVIDER` (e.
47
47
  arrakis # interactive session in the current directory
48
48
  arrakis "fix the failing test" # interactive, starting with a task
49
49
  arrakis -p "explain src/app.ts" # one-shot: prints the answer and exits
50
+ arrakis -p --json "…" # one-shot with a JSON result (for scripts and CI)
51
+ arrakis -p --max-cost 0.50 "…" # stop if the estimated cost passes $0.50
50
52
  arrakis -c # continue the last session in this directory
51
53
  arrakis -r <id> # resume a specific session
52
54
  arrakis sessions # list recent sessions
@@ -65,6 +67,12 @@ In a session:
65
67
  | `/resume` (or `/sessions`) | Pick an earlier session; its conversation is shown and you carry on in it |
66
68
  | `/permissions` | See and revoke what is always allowed |
67
69
  | `/export [file]` | Save the conversation as Markdown |
70
+ | `/memory` | Show or edit what arrakis remembers; start any message with `#` to add to it |
71
+ | `/diff` / `/commit` | Show uncommitted changes / have arrakis write the message and commit |
72
+ | `/rewind` (or Esc Esc) | Go back to before an earlier message: files are restored and your message comes back to edit |
73
+ | `/theme` | Color theme: auto, spice, spice-light, mono |
74
+ | `/budget [$]` | Stop when this session's estimated cost reaches a limit |
75
+ | `/rename [name]` | Name this session (shows in `/resume`) |
68
76
  | `/undo [n]` | Revert arrakis's file changes from the last turn (or pick a turn) |
69
77
  | `/paste` | Attach the image on your clipboard (macOS) |
70
78
  | `/mcp` | Show connected MCP servers and their tools |
@@ -105,6 +113,24 @@ With the Anthropic provider, arrakis talks to the Claude API directly (through A
105
113
  - **Fallbacks:** on models that support it, if Claude declines a request, the API can retry it on another Claude model.
106
114
  - Sessions stay append-only: the system prompt is fixed for the session and Claude's responses are replayed exactly, which keeps the cache warm and Claude's earlier reasoning valid.
107
115
 
116
+ ## Memory and permissions
117
+
118
+ Start a message with `#` to give arrakis a standing instruction, like `# use pnpm, not npm`. You choose whether it's for this project (`ARRAKIS.md`) or every project (`~/.arrakis/ARRAKIS.md`); `/memory` shows and edits both.
119
+
120
+ When arrakis wants to run a command, you can allow just that command for this project (for example `npm test`, which also covers `npm test -- --watch`). It's remembered in your own config, never in the repository, and a rule never covers chained or redirected commands (`;`, `&&`, `|`, `>`, `$( )`). `/permissions` lists and revokes them.
121
+
122
+ ## Cost and speed
123
+
124
+ Set a faster, cheaper model for sub-agents, which do most of the reading in research and exploration:
125
+
126
+ ```bash
127
+ arrakis config set subagentModel claude-haiku-5-5
128
+ ```
129
+
130
+ `arrakis doctor` checks Node, your provider and key, the model, the browser, MCP servers and skills.
131
+
132
+ Shortcuts: Esc Esc rewinds (or clears what you typed), Ctrl+R searches your earlier messages, Ctrl+O shows a tool's full output, Ctrl+V attaches the image on the clipboard (macOS), and a bell (plus a notification after a minute) tells you when a long task finishes.
133
+
108
134
  ## Skills
109
135
 
110
136
  A skill is a folder with a `SKILL.md`: a name, a one-line description of when to use it, and the steps to follow. Scripts and templates can sit next to it. arrakis only puts the descriptions in context and loads a skill's instructions when a task matches, so you can keep many of them.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mumbrane/arrakis",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "description": "Arrakis: a coding agent for your terminal, built by Mumbrane",
5
5
  "type": "module",
6
6
  "main": "./index.js",
package/src/agent.js CHANGED
@@ -86,7 +86,7 @@ export class Agent {
86
86
  content = typeof input === 'string' ? `${input}\n\n${note}` : [...input, { type: 'text', text: note }];
87
87
  }
88
88
  this.session.add({ role: 'user', content });
89
- if (this.depth === 0) this.checkpoints?.beginTurn(typeof input === 'string' ? input : input.find((p) => p.type === 'text')?.text ?? '(message)');
89
+ if (this.depth === 0) this.checkpoints?.beginTurn(typeof input === 'string' ? input : input.find((p) => p.type === 'text')?.text ?? '(message)', this.session.messages.length - 1);
90
90
  this.abort = new AbortController();
91
91
  const signal = this.abort.signal;
92
92
  const onParentAbort = () => this.abort?.abort();
@@ -97,6 +97,11 @@ export class Agent {
97
97
  for (let step = 0; step < limit; step++) {
98
98
  await this.maybeCompact(signal);
99
99
  const msg = await this.callModel(signal);
100
+ if (this.depth === 0 && this.budget && this.usage.cost >= this.budget) {
101
+ this.lastError = 'Budget reached.';
102
+ this.ui.error(`Budget reached: about $${this.usage.cost.toFixed(2)} of your $${this.budget.toFixed(2)} limit. Raise it with /budget <dollars>, or /budget off.`);
103
+ return false;
104
+ }
100
105
  if (!msg.tool_calls?.length) {
101
106
  if (this.depth === 0 && this.hooks) await this.hooks.run('Stop', { sessionId: this.session.id });
102
107
  if (this.depth === 0) this.warnContext();
@@ -166,7 +171,7 @@ export class Agent {
166
171
  if (!prompt) throw new Error('prompt is required');
167
172
  const readOnly = agent_type !== 'general';
168
173
  const sub = new Agent({
169
- config: this.config,
174
+ config: this.config.subagentModel ? { ...this.config, model: this.config.subagentModel } : this.config,
170
175
  session: Session.memory(),
171
176
  ui: this.ui,
172
177
  permissions: this.permissions,
@@ -19,8 +19,15 @@ export class Checkpoints {
19
19
  }
20
20
  }
21
21
 
22
- beginTurn(label) {
23
- this.current = { id: (this.turns.at(-1)?.id ?? 0) + 1, label: String(label).replace(/\s+/g, ' ').slice(0, 80), time: Date.now(), files: {} };
22
+ // `at` is the index of the user message that started this turn.
23
+ beginTurn(label, at) {
24
+ this.current = { id: (this.turns.at(-1)?.id ?? 0) + 1, label: String(label).replace(/\s+/g, ' ').slice(0, 80), time: Date.now(), at, files: {} };
25
+ }
26
+
27
+ // Undo every turn that started at or after message `index`.
28
+ restoreFrom(index) {
29
+ const first = this.turns.find((t) => typeof t.at === 'number' && t.at >= index);
30
+ return first ? this.undo(first.id) : [];
24
31
  }
25
32
 
26
33
  // Save a file's current state the first time a turn touches it.
package/src/cli.js CHANGED
@@ -27,7 +27,9 @@ import { installBrowser, browserStatus, closeBrowser, findBrowser } from './brow
27
27
  import { setExtraTools, findTool } from './tools.js';
28
28
  import { formatCost, formatTokens, priceFor } from './pricing.js';
29
29
  import { isNativeAnthropic, modelTraits } from './anthropic.js';
30
- import { isTrustedProject, trustProject, HOME_DIR } from './config.js';
30
+ import { setTheme, resolveTheme, PALETTES, THEME } from './theme.js';
31
+ import { isTrustedProject, trustProject, HOME_DIR, projectRules, saveProjectRule, removeProjectRule } from './config.js';
32
+ import { spawnSync } from 'node:child_process';
31
33
 
32
34
  const HELP = `arrakis ${VERSION} — a coding agent for your terminal
33
35
 
@@ -43,6 +45,7 @@ Usage
43
45
  arrakis mcp Show MCP servers and their tools
44
46
  arrakis mcp add <name> -- <command...> Add a local MCP server (or: --url <url>)
45
47
  arrakis mcp remove <name> Remove an MCP server
48
+ arrakis doctor Check your setup: provider, key, browser, MCP, skills
46
49
  arrakis sessions List recent sessions
47
50
  arrakis config Show configuration
48
51
  arrakis config set <key> <v> Set a value (provider, baseUrl, apiKey, model, contextWindow, maxTokens)
@@ -71,6 +74,13 @@ const SLASH_HELP = `/help Show commands
71
74
  /effort [level] How hard Claude thinks: low, medium, high, xhigh, max
72
75
  /resume Pick an earlier session and continue it (also /sessions)
73
76
  /permissions See and revoke what's always allowed
77
+ /memory Show or edit what arrakis remembers (start a message with # to add)
78
+ /rewind Go back to an earlier message: files and conversation (also esc esc)
79
+ /theme Pick a color theme: auto, spice, spice-light, mono
80
+ /budget [$] Stop when this session's estimated cost reaches a limit
81
+ /rename [name] Name this session
82
+ /diff Show uncommitted changes
83
+ /commit [note] Write a commit message and commit (asks first)
74
84
  /research [q] Deep research: parallel web research, then a cited report
75
85
  /skills Browse, run and create skills
76
86
  /browser Browser status; /browser close to close it
@@ -99,6 +109,7 @@ export async function main(argv) {
99
109
  if (argv[0] === 'jobs') return jobsCommand(argv.slice(1));
100
110
  if (argv[0] === 'mcp') return mcpCommand(argv.slice(1));
101
111
  if (argv[0] === 'skills') return skillsCommand();
112
+ if (argv[0] === 'doctor') return doctorCommand();
102
113
  if (argv[0] === 'browser') return browserCommand(argv.slice(1));
103
114
  if (argv[0] === 'logout') {
104
115
  removeProviderKeys();
@@ -116,6 +127,8 @@ export async function main(argv) {
116
127
  resume: { type: 'string', short: 'r' },
117
128
  yolo: { type: 'boolean' },
118
129
  allow: { type: 'string' },
130
+ json: { type: 'boolean' },
131
+ 'max-cost': { type: 'string' },
119
132
  version: { type: 'boolean', short: 'v' },
120
133
  help: { type: 'boolean', short: 'h' },
121
134
  },
@@ -130,7 +143,8 @@ export async function main(argv) {
130
143
 
131
144
  const cwd = process.cwd();
132
145
  let config = loadConfig({ model: values.model, baseUrl: values['base-url'] });
133
- const ui = !print && process.stdin.isTTY && process.stdout.isTTY && process.env.ARRAKIS_SIMPLE_UI !== '1' ? new FancyUI() : new UI({ print });
146
+ setTheme(process.env.ARRAKIS_THEME || readConfigFile().theme || 'auto');
147
+ const ui = !print && process.stdin.isTTY && process.stdout.isTTY && process.env.ARRAKIS_SIMPLE_UI !== '1' ? new FancyUI() : new UI({ print, quiet: Boolean(values.json) });
134
148
  const prompts = createPrompts(ui);
135
149
  if (!config.configured) {
136
150
  if (print) throw new Error('arrakis is not set up yet. Run `arrakis` once to choose a provider and enter an API key.');
@@ -157,6 +171,9 @@ export async function main(argv) {
157
171
  ui,
158
172
  mode: values.yolo ? 'yolo' : print ? 'deny' : 'ask',
159
173
  allow: values.allow ? values.allow.split(',').map((s) => s.trim()).filter(Boolean) : [],
174
+ commandRules: projectRules(cwd),
175
+ saveRule: (rule) => saveProjectRule(cwd, rule),
176
+ removeRule: (rule) => removeProjectRule(cwd, rule),
160
177
  });
161
178
 
162
179
  // Project MCP servers and hooks run commands, so ask before trusting a folder.
@@ -167,6 +184,7 @@ export async function main(argv) {
167
184
  if (skills.length) setExtraTools([...mcpTools(mcpServers), skillTool(() => skills)]);
168
185
  const hookSet = new Hooks(loadHooks(cwd, { includeProject: trusted }), { cwd, ui });
169
186
  const agent = new Agent({ config, session, ui, permissions, cwd, checkpoints: new Checkpoints(session.file), hooks: hookSet.count ? hookSet : null });
187
+ if (values['max-cost']) agent.budget = Number(values['max-cost']) || 0;
170
188
 
171
189
  if (print) {
172
190
  process.on('SIGINT', () => {
@@ -178,6 +196,19 @@ export async function main(argv) {
178
196
  const ok = await agent.send(content);
179
197
  mcpServers.forEach((s) => s.close());
180
198
  closeBrowser();
199
+ if (values.json) {
200
+ const last = [...agent.session.messages].reverse().find((m) => m.role === 'assistant' && m.content);
201
+ const u = agent.usage;
202
+ process.stdout.write(JSON.stringify({
203
+ ok,
204
+ result: last ? plainText(last.content) : '',
205
+ error: ok ? null : agent.lastError,
206
+ session_id: agent.session.id,
207
+ model: config.model,
208
+ usage: { input_tokens: u.input, output_tokens: u.output, cache_read_tokens: u.cacheRead, cache_write_tokens: u.cacheWrite, requests: u.requests },
209
+ cost_usd: u.priced && priceFor(config.model) ? Number(u.cost.toFixed(6)) : null,
210
+ }) + '\n');
211
+ }
181
212
  if (process.env.ARRAKIS_JOB_ID) updateJob(process.env.ARRAKIS_JOB_ID, { status: ok ? 'done' : 'failed', finished: Date.now() });
182
213
  process.exitCode = ok ? 0 : 1;
183
214
  return;
@@ -272,6 +303,30 @@ function completer(line, cwd, commands) {
272
303
  // Commands that take an argument, and the question to ask for it.
273
304
  const NEEDS_INPUT = { '/bg': 'What should the background job do?', '/export': 'File name (Enter for the default):', '/research': 'What should arrakis research?' };
274
305
 
306
+ const COMMIT_PROMPT = `Commit the current changes.
307
+ 1. Look at what changed: git status, git diff (staged and unstaged) and git log -5 --oneline to match this repository's message style.
308
+ 2. Stage the files that belong in this change (don't add secrets, build output or unrelated files; say if you skip something).
309
+ 3. Write a concise commit message: a short summary line, a blank line, then what changed and why if it's not obvious.
310
+ 4. Commit. Don't push, amend or change history.
311
+ Then tell me the commit hash and summary.`;
312
+
313
+ // "# …" in the composer: save a standing instruction to ARRAKIS.md.
314
+ async function remember(text, { ui, prompts, agent, cwd }) {
315
+ const where = await prompts.select({
316
+ title: 'Remember',
317
+ items: [
318
+ { label: 'In this project', value: path.join(cwd, 'ARRAKIS.md'), hint: 'ARRAKIS.md' },
319
+ { label: 'In every project', value: path.join(HOME_DIR, 'ARRAKIS.md'), hint: '~/.arrakis/ARRAKIS.md' },
320
+ ],
321
+ });
322
+ if (!where) return;
323
+ const existing = fs.existsSync(where) ? fs.readFileSync(where, 'utf8') : '# Notes for arrakis\n\n';
324
+ fs.mkdirSync(path.dirname(where), { recursive: true });
325
+ fs.writeFileSync(where, `${existing.replace(/\s*$/, '\n')}- ${text}\n`);
326
+ agent.notes.push(`[From now on, remember: ${text}]`);
327
+ ui.success(`Remembered in ${tildePath(where)}.`);
328
+ }
329
+
275
330
  function researchPrompt(question) {
276
331
  const slug = question.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 50) || 'research';
277
332
  return `Do deep research on this question and write a report:
@@ -301,6 +356,48 @@ function ago(ms) {
301
356
  const tildePath = (p) => (p.startsWith(os.homedir()) ? '~' + p.slice(os.homedir().length) : p);
302
357
  const plainText = (content) => (Array.isArray(content) ? content.filter((x) => x.type === 'text').map((x) => x.text).join('\n') : String(content ?? ''));
303
358
 
359
+ // Go back to before one of your messages: restore files arrakis changed since,
360
+ // and continue from there in a new session (the original stays saved).
361
+ async function rewindTo({ agent, ui, prompts, state, cwd }) {
362
+ const msgs = agent.session.messages;
363
+ const points = [];
364
+ msgs.forEach((m, i) => {
365
+ if (m.role !== 'user') return;
366
+ const text = plainText(m.content).replace(/\n\n<(file|directory) path=[\s\S]*$/, '').replace(/\n\n\[[^\]]*\]\s*$/g, '').trim();
367
+ if (!text || text.startsWith('[Summary of the earlier conversation')) return;
368
+ points.push({ i, text });
369
+ });
370
+ if (!points.length) {
371
+ ui.info('Nothing to rewind to yet.');
372
+ return;
373
+ }
374
+ const changedAfter = (i) => (agent.checkpoints?.turns ?? []).filter((t) => typeof t.at === 'number' && t.at >= i).reduce((n, t) => n + Object.keys(t.files).length, 0);
375
+ const pick = await prompts.select({
376
+ title: 'Rewind to before',
377
+ items: [...points].reverse().slice(0, 30).map((p) => {
378
+ const files = changedAfter(p.i);
379
+ return { label: p.text.replace(/\s+/g, ' ').slice(0, 60), value: p.i, hint: files ? `restores ${files} file${files === 1 ? '' : 's'}` : 'no file changes after this' };
380
+ }),
381
+ });
382
+ if (pick === null || pick === undefined) return;
383
+ const point = points.find((p) => p.i === pick);
384
+ const restored = agent.checkpoints?.restoreFrom(pick) ?? [];
385
+ const previous = agent.session.id;
386
+ const fresh = Session.create({ cwd, model: agent.config.model });
387
+ for (const m of msgs.slice(0, pick)) fresh.add(m);
388
+ agent.session = fresh;
389
+ agent.checkpoints = new Checkpoints(fresh.file);
390
+ agent.todos = [];
391
+ agent.notes = [];
392
+ ui.clearScreen?.();
393
+ state.showBanner?.();
394
+ replayConversation(ui, fresh);
395
+ for (const r of restored) ui.write(ui.log, ` ${ui.c.green('↺')} ${r.action} ${path.relative(cwd, r.file) || r.file}\n`);
396
+ ui.success(`Rewound to before "${point.text.replace(/\s+/g, ' ').slice(0, 50)}"${restored.length ? `; restored ${restored.length} file${restored.length === 1 ? '' : 's'}` : ''}. The full conversation is still saved (${previous}).`);
397
+ if (ui.setDraft) ui.setDraft(point.text);
398
+ else ui.info(` Your message was: ${point.text}`);
399
+ }
400
+
304
401
  // Switch to a saved session and show its conversation so you can pick up where it left off.
305
402
  function openSession({ agent, ui, state, id, cwd }) {
306
403
  agent.session = Session.load(id);
@@ -357,7 +454,7 @@ function replayConversation(ui, session, limit = 80) {
357
454
  }
358
455
  }
359
456
 
360
- const BUILTIN_COMMANDS = ['/help', '/resume', '/research', '/skills', '/model', '/provider', '/plan', '/init', '/todos', '/browser', '/undo', '/cost', '/effort', '/permissions', '/export', '/paste', '/mcp', '/bg', '/jobs', '/clear', '/compact', '/status', '/yolo', '/exit'];
457
+ const BUILTIN_COMMANDS = ['/help', '/resume', '/rewind', '/research', '/skills', '/memory', '/diff', '/commit', '/theme', '/budget', '/rename', '/model', '/provider', '/plan', '/init', '/todos', '/browser', '/undo', '/cost', '/effort', '/permissions', '/export', '/paste', '/mcp', '/bg', '/jobs', '/clear', '/compact', '/status', '/yolo', '/exit'];
361
458
 
362
459
  async function interactive({ agent, ui, prompts, config, cwd, firstPrompt, mcpServers = [], hooks = 0, skills = [] }) {
363
460
  const c = ui.c;
@@ -411,7 +508,8 @@ async function interactive({ agent, ui, prompts, config, cwd, firstPrompt, mcpSe
411
508
  ui.statusLine = () => {
412
509
  const used = Math.round((estimateTokens(agent.session.messages) / config.contextWindow) * 100);
413
510
  const branch = gitBranch(cwd);
414
- const cost = agent.usage.requests && agent.usage.priced && priceFor(config.model) ? formatCost(agent.usage.cost) : '';
511
+ let cost = agent.usage.requests && agent.usage.priced && priceFor(config.model) ? formatCost(agent.usage.cost) : '';
512
+ if (agent.budget) cost = `${cost || '$0.00'}/$${agent.budget.toFixed(2)}`;
415
513
  if (ui instanceof FancyUI) return [config.model, branch ? `⎇ ${branch}` : '', `${used}% ctx`, cost].filter(Boolean).join(' · ');
416
514
  const parts = [config.model, `${used}% context`];
417
515
  if (branch) parts.push(`⎇ ${branch}`);
@@ -441,7 +539,21 @@ async function interactive({ agent, ui, prompts, config, cwd, firstPrompt, mcpSe
441
539
  const { content, attached, errors } = buildMessage(text, cwd, state.pastedImages.splice(0));
442
540
  for (const e of errors) ui.error(e);
443
541
  if (attached.length) ui.info(` Attached ${attached.join(', ')}`);
542
+ const started = Date.now();
444
543
  await agent.send(content);
544
+ const secs = (Date.now() - started) / 1000;
545
+ if (secs >= 20) ui.notify?.(`Finished: ${text.replace(/\s+/g, ' ').slice(0, 80)}`, secs);
546
+ };
547
+ ui.onRewind = () => {
548
+ rewindTo({ agent, ui, prompts, state, cwd }).catch((err) => ui.error(err.message));
549
+ };
550
+ ui.onPasteImage = () => {
551
+ const { file, error } = pasteClipboardImage();
552
+ if (error) ui.info(` ${error}`);
553
+ else {
554
+ state.pastedImages.push(file);
555
+ ui.info(` 🖼 Image from the clipboard will be attached to your next message.`);
556
+ }
445
557
  };
446
558
 
447
559
  // Mention background jobs that finished since the last prompt.
@@ -463,6 +575,11 @@ async function interactive({ agent, ui, prompts, config, cwd, firstPrompt, mcpSe
463
575
  armedExit = false;
464
576
  const text = line.trim();
465
577
  if (!text) continue;
578
+ // "# always use pnpm" saves a standing instruction (memory).
579
+ if (/^#\s+\S/.test(text) && !text.startsWith('##')) {
580
+ await remember(text.replace(/^#\s+/, ''), { ui, prompts, agent, cwd });
581
+ continue;
582
+ }
466
583
  // "/name args" is a command; "/Users/me/shot.png what's this?" is a dragged-in path.
467
584
  if (/^\/[\w-]+(\s|$)/.test(text) && !/^\/[\w-]+\//.test(text)) {
468
585
  const result = await slashCommand(text, { agent, ui, prompts, config, cwd, state });
@@ -699,7 +816,7 @@ async function slashCommand(text, { agent, ui, prompts, config, cwd, state }) {
699
816
  }
700
817
  case 'permissions': {
701
818
  const p = agent.permissions;
702
- const allowed = [...p.allowed];
819
+ const allowed = [...p.allowed, ...[...p.commandRules].map((r) => `cmd:${r}`)];
703
820
  const mode = p.mode === 'yolo' ? 'everything is allowed (yolo)' : p.planMode ? 'plan mode (read-only)' : p.acceptEdits ? 'edits are accepted automatically' : 'asks before edits and commands';
704
821
  ui.info(` Mode: ${mode}`);
705
822
  if (!allowed.length) {
@@ -708,9 +825,15 @@ async function slashCommand(text, { agent, ui, prompts, config, cwd, state }) {
708
825
  }
709
826
  const pickTool = await prompts.select({
710
827
  title: 'Always allowed this session (pick one to revoke)',
711
- items: [...allowed.map((t) => ({ label: TOOL_NAMES[t] ?? t, value: t, hint: 'runs without asking' })), { label: 'Done', value: null }],
828
+ items: [
829
+ ...allowed.map((t) => (t.startsWith('cmd:') ? { label: `\`${t.slice(4)}\``, value: t, hint: 'this project, remembered' } : { label: TOOL_NAMES[t] ?? t, value: t, hint: 'this session' })),
830
+ { label: 'Done', value: null },
831
+ ],
712
832
  });
713
- if (pickTool) {
833
+ if (pickTool?.startsWith('cmd:')) {
834
+ p.revokeRule(pickTool.slice(4));
835
+ ui.success(`\`${pickTool.slice(4)}\` will ask again.`);
836
+ } else if (pickTool) {
714
837
  p.allowed.delete(pickTool);
715
838
  ui.success(`${TOOL_NAMES[pickTool] ?? pickTool} will ask again.`);
716
839
  }
@@ -779,6 +902,96 @@ async function slashCommand(text, { agent, ui, prompts, config, cwd, state }) {
779
902
  ui.info(` Browser: ${st.exe}\n ${st.running ? `Open${st.headless ? ' (headless)' : ''}. /browser close to close it.` : 'Not open; arrakis opens it when a task needs it.'}\n Set ARRAKIS_BROWSER_HEADFUL=1 to watch it work in a visible window.`);
780
903
  break;
781
904
  }
905
+ case 'rewind':
906
+ await rewindTo({ agent, ui, prompts, state, cwd });
907
+ break;
908
+ case 'theme': {
909
+ const names = ['auto', ...Object.keys(PALETTES)];
910
+ const hints = { auto: `follows your terminal (now: ${resolveTheme('auto')})`, spice: 'gold on dark', 'spice-light': 'for light terminal backgrounds', mono: 'no color, just contrast' };
911
+ const pick = arg || (await prompts.select({ title: 'Theme', items: names.map((n) => ({ label: n, value: n, hint: `${hints[n] ?? ''}${n === THEME ? ' · current' : ''}` })) }));
912
+ if (!pick) break;
913
+ if (!names.includes(pick)) {
914
+ ui.error(`Themes: ${names.join(', ')}`);
915
+ break;
916
+ }
917
+ setTheme(pick);
918
+ setConfigValue('theme', pick === 'auto' ? '' : pick);
919
+ ui.retheme();
920
+ ui.clearScreen?.();
921
+ state.showBanner?.();
922
+ replayConversation(ui, agent.session);
923
+ ui.success(`Theme: ${pick}.`);
924
+ break;
925
+ }
926
+ case 'budget': {
927
+ if (!arg) {
928
+ ui.info(agent.budget ? ` Budget: $${agent.budget.toFixed(2)} for this session (spent about ${formatCost(agent.usage.cost)}). /budget off to remove it.` : ' No budget set. /budget 5 stops a turn once this session has cost about $5.');
929
+ break;
930
+ }
931
+ if (/^(off|none|0)$/i.test(arg)) {
932
+ agent.budget = 0;
933
+ ui.success('Budget removed.');
934
+ break;
935
+ }
936
+ const dollars = Number(arg.replace(/^\$/, ''));
937
+ if (!(dollars > 0)) {
938
+ ui.error('Give an amount in dollars, like /budget 5');
939
+ break;
940
+ }
941
+ if (!priceFor(config.model)) ui.info(` Note: arrakis doesn't know prices for ${config.model}, so it can't track spend against a budget.`);
942
+ agent.budget = dollars;
943
+ ui.success(`Budget: $${dollars.toFixed(2)} for this session.`);
944
+ break;
945
+ }
946
+ case 'rename': {
947
+ const title = arg || (await prompts.input('Name this session: '));
948
+ if (!title) break;
949
+ agent.session.append({ type: 'title', title: title.slice(0, 70) });
950
+ ui.success(`Session named "${title.slice(0, 70)}".`);
951
+ break;
952
+ }
953
+ case 'memory': {
954
+ const files = [
955
+ { label: 'This project', value: path.join(cwd, 'ARRAKIS.md'), hint: 'ARRAKIS.md in this folder' },
956
+ { label: 'All projects', value: path.join(HOME_DIR, 'ARRAKIS.md'), hint: '~/.arrakis/ARRAKIS.md' },
957
+ ];
958
+ if (fs.existsSync(path.join(cwd, 'AGENTS.md'))) files.push({ label: 'AGENTS.md', value: path.join(cwd, 'AGENTS.md'), hint: 'shared agent notes' });
959
+ const file = await prompts.select({ title: 'Memory', items: files.map((f) => ({ ...f, hint: `${f.hint}${fs.existsSync(f.value) ? '' : ' · empty'}` })) });
960
+ if (!file) break;
961
+ const act = await prompts.select({ title: tildePath(file), items: [{ label: 'Show it', value: 'show' }, { label: 'Edit it in your editor', value: 'edit', hint: process.env.VISUAL || process.env.EDITOR || 'nano' }, { label: 'Back', value: null }] });
962
+ if (act === 'show') ui.write(ui.out, fs.existsSync(file) ? `${fs.readFileSync(file, 'utf8').trimEnd()}\n` : c.mist('(empty) · add to it by starting a message with #\n'));
963
+ else if (act === 'edit') {
964
+ if (!fs.existsSync(file)) fs.writeFileSync(file, '# Notes for arrakis\n\n');
965
+ const editor = process.env.VISUAL || process.env.EDITOR || 'nano';
966
+ ui.suspend?.();
967
+ spawnSync(editor, [file], { stdio: 'inherit', shell: true });
968
+ ui.resume?.();
969
+ agent.notes.push(`[The user edited ${tildePath(file)}. Re-read it if it matters for what you are doing.]`);
970
+ ui.success('Saved. arrakis will pick up the changes.');
971
+ }
972
+ break;
973
+ }
974
+ case 'diff': {
975
+ const status = spawnSync('git', ['status', '--short'], { cwd, encoding: 'utf8' });
976
+ if (status.status !== 0) {
977
+ ui.info('Not a git repository.');
978
+ break;
979
+ }
980
+ if (!status.stdout.trim()) {
981
+ ui.info('No changes.');
982
+ break;
983
+ }
984
+ const stat = spawnSync('git', ['diff', '--stat', 'HEAD'], { cwd, encoding: 'utf8' }).stdout.trim();
985
+ const diff = spawnSync('git', ['diff', 'HEAD'], { cwd, encoding: 'utf8', maxBuffer: 20e6 }).stdout.split('\n');
986
+ const untracked = status.stdout.split('\n').filter((l) => l.startsWith('??')).map((l) => l.slice(3));
987
+ const colored = diff.slice(0, 300).map((l) => (l.startsWith('+++') || l.startsWith('---') ? c.bold(c.lilac(l)) : l.startsWith('+') ? c.mint(l) : l.startsWith('-') ? c.rose(l) : l.startsWith('@@') ? c.violet(l) : c.mist(l)));
988
+ ui.write(ui.out, `${stat ? c.lilac(stat) + '\n\n' : ''}${colored.join('\n')}\n`);
989
+ if (diff.length > 300) ui.info(` … ${diff.length - 300} more lines (git diff for all of it)`);
990
+ if (untracked.length) ui.info(` New files not yet in git: ${untracked.join(', ')}`);
991
+ break;
992
+ }
993
+ case 'commit':
994
+ return { send: COMMIT_PROMPT + (arg ? `\n\nThe user added: ${arg}` : '') };
782
995
  case 'todos':
783
996
  if (agent.todos.length) ui.todos(agent.todos);
784
997
  else ui.info('No task list yet. arrakis makes one for multi-step work.');
@@ -843,7 +1056,7 @@ async function slashCommand(text, { agent, ui, prompts, config, cwd, state }) {
843
1056
  `session ${agent.session.id}`,
844
1057
  `log ${agent.session.file}`,
845
1058
  `provider ${config.providerName || 'custom'} (${config.baseUrl})`,
846
- `model ${config.model}`,
1059
+ `model ${config.model}${config.subagentModel ? ` (sub-agents: ${config.subagentModel})` : ''}`,
847
1060
  `context ~${used.toLocaleString()} / ${config.contextWindow.toLocaleString()} tokens (${Math.round((used / config.contextWindow) * 100)}%)`,
848
1061
  `plan mode ${agent.permissions.planMode ? 'on' : 'off'}`,
849
1062
  `todos ${agent.todos.length ? `${agent.todos.filter((t) => t.status === 'completed').length}/${agent.todos.length} done` : 'none'}`,
@@ -1032,6 +1245,60 @@ async function mcpCommand(args) {
1032
1245
  list.forEach((s) => s.close());
1033
1246
  }
1034
1247
 
1248
+ async function doctorCommand() {
1249
+ const c = colors(process.stdout);
1250
+ const ok = (label, detail = '') => console.log(`${c.mint('✓')} ${label}${detail ? ` ${c.mist(detail)}` : ''}`);
1251
+ const bad = (label, detail = '') => console.log(`${c.rose('✕')} ${label}${detail ? ` ${c.mist(detail)}` : ''}`);
1252
+ const warn = (label, detail = '') => console.log(`${c.amber('!')} ${label}${detail ? ` ${c.mist(detail)}` : ''}`);
1253
+ console.log(c.bold(`arrakis ${VERSION} · doctor\n`));
1254
+ const major = Number(process.versions.node.split('.')[0]);
1255
+ if (major >= 22) ok('Node.js', process.versions.node);
1256
+ else if (major >= 18) warn('Node.js', `${process.versions.node}; the browser tool needs Node 22+`);
1257
+ else bad('Node.js', `${process.versions.node}; arrakis needs Node 18.17+`);
1258
+ let config;
1259
+ try {
1260
+ config = loadConfig();
1261
+ } catch (err) {
1262
+ bad('Config', err.message);
1263
+ }
1264
+ if (config && !config.configured) bad('Provider', 'not set up · run: arrakis setup');
1265
+ else if (config) {
1266
+ ok('Provider', `${config.providerName || config.baseUrl}`);
1267
+ try {
1268
+ const models = await listModels(config);
1269
+ ok('API key', `works · ${models.length} models`);
1270
+ const model = config.model || models[0]?.id;
1271
+ if (model && models.length && !models.some((m) => m.id === model)) warn('Model', `${model} is not in the provider's list · pick one with /model`);
1272
+ else ok('Model', model);
1273
+ } catch (err) {
1274
+ bad('API key', err.status === 401 || err.status === 403 ? 'rejected · run: arrakis setup' : err.message);
1275
+ }
1276
+ }
1277
+ const exe = findBrowser();
1278
+ if (exe) ok('Browser', exe);
1279
+ else warn('Browser', 'none found · run: arrakis browser install');
1280
+ const cwd = process.cwd();
1281
+ const { servers } = loadMcpConfig(cwd, { includeProject: isTrustedProject(cwd) });
1282
+ const names = Object.keys(servers);
1283
+ if (names.length) {
1284
+ const list = await connectAll(cwd, { includeProject: isTrustedProject(cwd) });
1285
+ for (const s of list) (s.status === 'connected' ? ok : bad)(`MCP ${s.name}`, s.status === 'connected' ? `${s.tools.length} tools` : s.error);
1286
+ list.forEach((s) => s.close());
1287
+ } else ok('MCP', 'none configured');
1288
+ const skills = loadSkills(cwd, { includeProject: isTrustedProject(cwd) });
1289
+ ok('Skills', skills.length ? skills.map((s) => s.name).join(', ') : 'none');
1290
+ try {
1291
+ fs.mkdirSync(path.join(HOME_DIR, 'sessions'), { recursive: true });
1292
+ fs.accessSync(path.join(HOME_DIR, 'sessions'), fs.constants.W_OK);
1293
+ ok('Sessions folder', tildePath(path.join(HOME_DIR, 'sessions')));
1294
+ } catch {
1295
+ bad('Sessions folder', 'not writable');
1296
+ }
1297
+ const latest = await checkForUpdate().catch(() => null);
1298
+ if (latest) warn('Update', `${latest} is available · npm install -g @mumbrane/arrakis`);
1299
+ else ok('Up to date');
1300
+ }
1301
+
1035
1302
  function skillsCommand() {
1036
1303
  const cwd = process.cwd();
1037
1304
  const skills = loadSkills(cwd, { includeProject: isTrustedProject(cwd) });
package/src/config.js CHANGED
@@ -22,6 +22,8 @@ export const CONFIG_KEYS = {
22
22
  model: { env: 'ARRAKIS_MODEL', help: 'Model name' },
23
23
  contextWindow: { env: 'ARRAKIS_CONTEXT_WINDOW', help: 'Context window in tokens; history is compacted near 80%', number: true },
24
24
  effort: { env: 'ARRAKIS_EFFORT', help: 'Claude effort: low, medium, high, xhigh, max (Anthropic only)' },
25
+ subagentModel: { env: 'ARRAKIS_SUBAGENT_MODEL', help: 'Model for sub-agents (e.g. a faster, cheaper one); default: same as the main model', global: true },
26
+ theme: { env: 'ARRAKIS_THEME', help: 'Color theme: auto, spice, spice-light, mono', global: true },
25
27
  maxTokens: { env: 'ARRAKIS_MAX_TOKENS', help: 'Max output tokens per response (0 = provider default)', number: true, global: true },
26
28
  };
27
29
 
@@ -72,7 +74,9 @@ export function loadConfig(overrides = {}) {
72
74
  effort: saved.effort || '',
73
75
  contextWindow: Number(saved.contextWindow) || provider?.contextWindow || DEFAULT_CONTEXT,
74
76
  maxTokens: Number(file.maxTokens) || provider?.maxTokens || 0,
77
+ subagentModel: file.subagentModel || '',
75
78
  };
79
+ if (env.ARRAKIS_SUBAGENT_MODEL) config.subagentModel = env.ARRAKIS_SUBAGENT_MODEL;
76
80
  if (env.ARRAKIS_BASE_URL) config.baseUrl = env.ARRAKIS_BASE_URL;
77
81
  if (env.ARRAKIS_API_KEY) config.apiKey = env.ARRAKIS_API_KEY;
78
82
  if (env.ARRAKIS_MODEL) config.model = env.ARRAKIS_MODEL;
@@ -145,3 +149,24 @@ export function trustProject(dir) {
145
149
  file.trustedProjects = [...new Set([...(file.trustedProjects ?? []), path.resolve(dir)])];
146
150
  writeConfigFile(file);
147
151
  }
152
+
153
+ // Shell commands the user said to always allow, per project folder.
154
+ export function projectRules(dir) {
155
+ return readConfigFile().projectPermissions?.[path.resolve(dir)] ?? [];
156
+ }
157
+
158
+ export function saveProjectRule(dir, rule) {
159
+ const file = readConfigFile();
160
+ const key = path.resolve(dir);
161
+ file.projectPermissions ??= {};
162
+ file.projectPermissions[key] = [...new Set([...(file.projectPermissions[key] ?? []), rule])];
163
+ writeConfigFile(file);
164
+ }
165
+
166
+ export function removeProjectRule(dir, rule) {
167
+ const file = readConfigFile();
168
+ const key = path.resolve(dir);
169
+ if (!file.projectPermissions?.[key]) return;
170
+ file.projectPermissions[key] = file.projectPermissions[key].filter((r) => r !== rule);
171
+ writeConfigFile(file);
172
+ }
@@ -2,25 +2,67 @@
2
2
  // 'deny' refuses anything that needs permission (non-interactive default).
3
3
  // planMode (separate flag) blocks every tool that changes files or runs commands.
4
4
  // Prompts are serialized, so parallel sub-agents ask one question at a time.
5
+ //
6
+ // Command rules let one shell command run without asking ("npm test" also
7
+ // covers "npm test -- --watch"). They are remembered per project in your own
8
+ // config (~/.arrakis/config.json), never in the repository, so a cloned
9
+ // project can't grant itself permissions.
10
+
11
+ // Shell syntax that chains or redirects commands. A rule never covers these.
12
+ const COMPOUND = /[;&|><`$(){}\n\\]/;
13
+
14
+ // The part of a command a rule is about: "npm test", "git status", "ls".
15
+ export function commandPrefix(command) {
16
+ const c = String(command ?? '').trim();
17
+ if (!c || COMPOUND.test(c)) return null;
18
+ const words = c.split(/\s+/);
19
+ if (words.length > 1 && !words[1].startsWith('-') && /^[\w.:/@=-]+$/.test(words[1])) return `${words[0]} ${words[1]}`;
20
+ return words[0];
21
+ }
22
+
23
+ export function ruleCovers(rule, command) {
24
+ const c = String(command ?? '').trim();
25
+ if (COMPOUND.test(c)) return false;
26
+ return c === rule || c.startsWith(rule + ' ');
27
+ }
28
+
5
29
  export class Permissions {
6
- constructor({ ui, mode = 'ask', allow = [] }) {
30
+ constructor({ ui, mode = 'ask', allow = [], commandRules = [], saveRule = null, removeRule = null }) {
7
31
  this.ui = ui;
8
32
  this.mode = mode;
9
33
  this.planMode = false;
10
34
  this.acceptEdits = false; // shift+tab mode: file edits run without asking
11
35
  this.onDeny = null;
12
36
  this.allowed = new Set(allow);
37
+ this.commandRules = new Set(commandRules);
38
+ this.saveRule = saveRule;
39
+ this.removeRule = removeRule;
13
40
  this.lock = Promise.resolve();
14
41
  }
15
42
 
16
- check(toolName, preview) {
43
+ allowsCommand(command) {
44
+ return [...this.commandRules].some((r) => ruleCovers(r, command));
45
+ }
46
+
47
+ revokeRule(rule) {
48
+ this.commandRules.delete(rule);
49
+ this.removeRule?.(rule);
50
+ }
51
+
52
+ check(toolName, preview, args = {}) {
17
53
  const decide = async () => {
18
54
  if (this.mode === 'yolo' || this.allowed.has(toolName)) return true;
19
- if (this.acceptEdits && (toolName === 'edit_file' || toolName === 'write_file')) return true;
55
+ if (this.acceptEdits && (toolName === 'edit_file' || toolName === 'write_file' || toolName === 'multi_edit')) return true;
56
+ if (toolName === 'bash' && this.allowsCommand(args.command)) return true;
20
57
  if (this.mode === 'deny') return false;
21
58
  if (preview) preview.shown = true;
22
- const answer = await this.ui.confirm(preview, toolName);
59
+ const prefix = toolName === 'bash' ? commandPrefix(args.command) : null;
60
+ const answer = await this.ui.confirm(preview, toolName, { prefix });
23
61
  if (answer === 'always') this.allowed.add(toolName);
62
+ if (answer === 'prefix' && prefix) {
63
+ this.commandRules.add(prefix);
64
+ this.saveRule?.(prefix);
65
+ }
24
66
  if (answer === 'no') this.onDeny?.();
25
67
  return answer !== 'no';
26
68
  };
package/src/session.js CHANGED
@@ -55,6 +55,7 @@ export class Session {
55
55
  else if (e.type === 'compact') messages = e.messages;
56
56
  else if (e.type === 'clear') messages = [];
57
57
  else if (e.type === 'todos') todos = e.todos;
58
+ else if (e.type === 'title') meta.title = e.title;
58
59
  }
59
60
  const session = new Session({ id: meta.id, file, meta, messages });
60
61
  session.todos = todos;
@@ -152,6 +153,7 @@ export function listSessions() {
152
153
  const events = readEvents(file);
153
154
  const meta = events.find((e) => e.type === 'meta') ?? {};
154
155
  const firstUser = events.find((e) => e.type === 'message' && e.message.role === 'user');
156
+ const named = events.filter((e) => e.type === 'title').at(-1)?.title;
155
157
  const count = events.filter((e) => e.type === 'message').length;
156
158
  out.push({
157
159
  id: meta.id ?? f.replace(/\.jsonl$/, ''),
@@ -159,7 +161,7 @@ export function listSessions() {
159
161
  model: meta.model,
160
162
  updated: fs.statSync(file).mtimeMs,
161
163
  messages: count,
162
- title: cleanTitle(typeof firstUser?.message.content === 'string' ? firstUser.message.content : Array.isArray(firstUser?.message.content) ? firstUser.message.content.find((p) => p.type === 'text')?.text ?? '' : ''),
164
+ title: named || cleanTitle(typeof firstUser?.message.content === 'string' ? firstUser.message.content : Array.isArray(firstUser?.message.content) ? firstUser.message.content.find((p) => p.type === 'text')?.text ?? '' : ''),
163
165
  });
164
166
  }
165
167
  return out.sort((a, b) => b.updated - a.updated);
package/src/theme.js CHANGED
@@ -28,6 +28,36 @@ export const PALETTE = {
28
28
  delBg: [64, 28, 26],
29
29
  };
30
30
 
31
+ // Other palettes, same roles. `spice-light` is for light terminal backgrounds;
32
+ // `mono` drops the hues except for errors.
33
+ export const PALETTES = {
34
+ spice: { ...PALETTE },
35
+ 'spice-light': {
36
+ violet: [166, 98, 6], iris: [160, 66, 12], orchid: [190, 76, 16], lilac: [52, 38, 20], mist: [118, 102, 82], dusk: [196, 182, 156],
37
+ mint: [36, 128, 66], amber: [160, 112, 0], rose: [186, 44, 58], sky: [18, 106, 138], ink: [255, 250, 240],
38
+ panel: [244, 236, 220], raise: [236, 222, 194], addBg: [214, 240, 220], delBg: [250, 222, 222],
39
+ },
40
+ mono: {
41
+ violet: [225, 225, 225], iris: [160, 160, 160], orchid: [245, 245, 245], lilac: [215, 215, 215], mist: [140, 140, 140], dusk: [80, 80, 80],
42
+ mint: [200, 200, 200], amber: [210, 210, 210], rose: [235, 110, 110], sky: [190, 190, 190], ink: [20, 20, 20],
43
+ panel: [38, 38, 38], raise: [52, 52, 52], addBg: [40, 56, 44], delBg: [60, 40, 40],
44
+ },
45
+ };
46
+
47
+ // 'auto' picks the light palette when the terminal says its background is light.
48
+ export function resolveTheme(name) {
49
+ if (name && name !== 'auto' && PALETTES[name]) return name;
50
+ const bg = Number((process.env.COLORFGBG ?? '').split(';').pop());
51
+ return bg === 7 || bg === 15 ? 'spice-light' : 'spice';
52
+ }
53
+
54
+ export let THEME = 'spice';
55
+ export function setTheme(name) {
56
+ THEME = resolveTheme(name);
57
+ Object.assign(PALETTE, PALETTES[THEME]);
58
+ return THEME;
59
+ }
60
+
31
61
  const env = process.env;
32
62
  export const TRUECOLOR =
33
63
  /truecolor|24bit/i.test(env.COLORTERM ?? '') ||
package/src/tools.js CHANGED
@@ -254,6 +254,59 @@ export const TOOLS = [
254
254
  };
255
255
  },
256
256
  },
257
+ {
258
+ name: 'multi_edit',
259
+ writes: true,
260
+ description: 'Make several edits to one file in one step. Edits apply in order, each to the result of the previous one, and all must succeed or none are written. Each old_string must match exactly and be unique unless replace_all is set. Prefer this over repeated edit_file calls on the same file.',
261
+ parameters: {
262
+ type: 'object',
263
+ properties: {
264
+ path: { type: 'string', description: 'File path' },
265
+ edits: {
266
+ type: 'array',
267
+ items: {
268
+ type: 'object',
269
+ properties: { old_string: { type: 'string' }, new_string: { type: 'string' }, replace_all: { type: 'boolean' } },
270
+ required: ['old_string', 'new_string'],
271
+ },
272
+ },
273
+ },
274
+ required: ['path', 'edits'],
275
+ },
276
+ needsPermission: true,
277
+ summary: (a) => `${a.path} (${Array.isArray(a.edits) ? a.edits.length : 0} edits)`,
278
+ plan(a, ctx) {
279
+ const p = resolvePath(ctx, a.path);
280
+ if (!fs.existsSync(p)) throw new Error(`${a.path} does not exist. Use write_file to create it.`);
281
+ if (!Array.isArray(a.edits) || !a.edits.length) throw new Error('edits must be a non-empty array.');
282
+ let text = fs.readFileSync(p, 'utf8');
283
+ const lines = [];
284
+ a.edits.forEach((e, i) => {
285
+ if (!e.old_string) throw new Error(`Edit ${i + 1}: old_string must not be empty.`);
286
+ const count = text.split(e.old_string).length - 1;
287
+ if (!count) throw new Error(`Edit ${i + 1}: old_string was not found (after the edits before it). Nothing was changed.`);
288
+ if (count > 1 && !e.replace_all) throw new Error(`Edit ${i + 1}: old_string matches ${count} places; add context or set replace_all. Nothing was changed.`);
289
+ const start = text.slice(0, text.indexOf(e.old_string)).split('\n').length;
290
+ e.old_string.split('\n').slice(0, 6).forEach((t, j) => lines.push({ sign: '-', text: t, n: start + j }));
291
+ e.new_string.split('\n').slice(0, 6).forEach((t, j) => lines.push({ sign: '+', text: t, n: start + j }));
292
+ text = e.replace_all ? text.split(e.old_string).join(e.new_string) : text.replace(e.old_string, () => e.new_string);
293
+ });
294
+ return { p, text, lines };
295
+ },
296
+ validate(a, ctx) {
297
+ this.plan(a, ctx);
298
+ },
299
+ preview(a, ctx) {
300
+ const { lines } = this.plan(a, ctx);
301
+ return { title: `Edit ${rel(ctx, resolvePath(ctx, a.path))} (${a.edits.length} changes)`, lines };
302
+ },
303
+ run(a, ctx) {
304
+ const { p, text, lines } = this.plan(a, ctx);
305
+ ctx.checkpoints?.record(p);
306
+ fs.writeFileSync(p, text);
307
+ return { content: `Applied ${a.edits.length} edits to ${rel(ctx, p)}.`, display: `Updated ${rel(ctx, p)} · ${a.edits.length} edits`, lines };
308
+ },
309
+ },
257
310
  {
258
311
  name: 'bash',
259
312
  writes: true,
@@ -617,7 +670,7 @@ export async function executeToolCall(call, ctx) {
617
670
  if (tool.needsPermission || tool.needsPermissionFor?.(args)) {
618
671
  preview = safe(() => tool.preview?.(args, ctx));
619
672
  if (preview && sub) preview.title = `[${ctx.label}] ${preview.title}`;
620
- const allowed = await ctx.permissions.check(tool.name, preview);
673
+ const allowed = await ctx.permissions.check(tool.name, preview, args);
621
674
  if (!allowed) {
622
675
  ctx.ui.toolResult('Denied', true);
623
676
  return 'Permission denied: the user declined this tool call. Do not retry it; ask the user how to proceed.';
package/src/tui.js CHANGED
@@ -8,7 +8,7 @@
8
8
  import readline from 'node:readline';
9
9
  import fs from 'node:fs';
10
10
  import path from 'node:path';
11
- import { spawnSync } from 'node:child_process';
11
+ import { spawn, spawnSync } from 'node:child_process';
12
12
  import { UI, truncate } from './ui.js';
13
13
  import { MarkdownStream, visibleLength } from './markdown.js';
14
14
  import { GLYPH, LOGO, PALETTE } from './theme.js';
@@ -120,6 +120,16 @@ export class FancyUI extends UI {
120
120
  this.render();
121
121
  }
122
122
 
123
+ // A bell, and on macOS a notification, when a long turn finishes.
124
+ notify(message, secs) {
125
+ if (process.env.ARRAKIS_NO_NOTIFY) return;
126
+ this.out.write('\x07');
127
+ if (process.platform === 'darwin' && secs >= 60) {
128
+ const text = message.replace(/["\\]/g, '').slice(0, 120);
129
+ spawn('osascript', ['-e', `display notification "${text}" with title "arrakis"`], { stdio: 'ignore', detached: true }).unref();
130
+ }
131
+ }
132
+
123
133
  addTokens(n) {
124
134
  this.tokens += n;
125
135
  }
@@ -213,8 +223,60 @@ export class FancyUI extends UI {
213
223
  this.cursor += s.length;
214
224
  }
215
225
 
226
+ // Ctrl+R: search earlier messages. Type to narrow, Ctrl+R for older matches,
227
+ // Enter to keep the match, Esc to go back to what you had.
228
+ searchKey(str, key) {
229
+ const h = this.hsearch;
230
+ const find = () => {
231
+ let skip = h.skip;
232
+ for (let i = this.historyList.length - 1; i >= 0; i--) {
233
+ if (!this.historyList[i].toLowerCase().includes(h.query.toLowerCase())) continue;
234
+ if (skip-- > 0) continue;
235
+ return this.historyList[i];
236
+ }
237
+ return null;
238
+ };
239
+ if (key.ctrl && key.name === 'r') h.skip++;
240
+ else if (key.name === 'escape' || (key.ctrl && (key.name === 'g' || key.name === 'c'))) {
241
+ this.buffer = h.saved;
242
+ this.cursor = this.buffer.length;
243
+ this.hsearch = null;
244
+ return this.render();
245
+ } else if (key.name === 'backspace') {
246
+ h.query = h.query.slice(0, -1);
247
+ h.skip = 0;
248
+ } else if (str && !key.ctrl && !key.meta && str.length === 1 && str >= ' ') {
249
+ h.query += str;
250
+ h.skip = 0;
251
+ } else {
252
+ this.hsearch = null;
253
+ if (key.name === 'return' || key.name === 'enter') return this.render();
254
+ return this.handleKey(str, key);
255
+ }
256
+ const match = find();
257
+ if (match === null && h.skip > 0) h.skip--;
258
+ const found = match ?? find();
259
+ if (found !== null) {
260
+ this.buffer = found;
261
+ this.cursor = found.length;
262
+ }
263
+ h.failed = found === null;
264
+ this.render();
265
+ }
266
+
267
+ setDraft(text) {
268
+ this.buffer = text;
269
+ this.cursor = text.length;
270
+ this.render();
271
+ }
272
+
216
273
  handleKey(str, key) {
217
274
  if (this.menu) return this.menuKey(str, key);
275
+ if (this.hsearch) return this.searchKey(str, key);
276
+ if (key.ctrl && key.name === 'r' && !this.busy) {
277
+ this.hsearch = { query: '', skip: 0, saved: this.buffer };
278
+ return this.render();
279
+ }
218
280
  if (key.name === 'paste-start') return (this.pasting = true);
219
281
  if (key.name === 'paste-end') {
220
282
  this.pasting = false;
@@ -269,16 +331,20 @@ export class FancyUI extends UI {
269
331
  this.showHelp = false;
270
332
  return this.render();
271
333
  }
272
- if (this.buffer) {
273
- if (this.escArmed) {
334
+ // Esc Esc: clear what you typed; on an empty composer, rewind. (Two quick
335
+ // presses arrive as one event with the sequence "\x1b\x1b".)
336
+ if (this.escArmed || key.sequence === '\x1b\x1b') {
337
+ this.escArmed = false;
338
+ if (this.buffer) {
274
339
  this.buffer = '';
275
340
  this.cursor = 0;
276
- this.escArmed = false;
277
341
  return this.afterEdit();
278
342
  }
279
- this.escArmed = true;
280
- setTimeout(() => (this.escArmed = false), 800).unref?.();
343
+ if (this.pending && !this.pending.label) this.onRewind?.();
344
+ return;
281
345
  }
346
+ this.escArmed = true;
347
+ setTimeout(() => (this.escArmed = false), 800).unref?.();
282
348
  return;
283
349
  }
284
350
  if (name === 'tab' && key.shift) {
@@ -336,6 +402,17 @@ export class FancyUI extends UI {
336
402
  else if (key.ctrl && name === 'k') {
337
403
  const nl = this.buffer.indexOf('\n', this.cursor);
338
404
  this.buffer = this.buffer.slice(0, this.cursor) + (nl < 0 ? '' : this.buffer.slice(nl));
405
+ } else if (key.ctrl && name === 'o') {
406
+ // Show the last tool's full output.
407
+ if (this.lastOutput) {
408
+ const lines = this.lastOutput.split('\n');
409
+ const shown = lines.slice(0, 400).map((l) => ` ${this.c.mist(l)}`).join('\n');
410
+ this.printAbove(`${shown}${lines.length > 400 ? `\n ${this.c.faint(`… ${lines.length - 400} more lines`)}` : ''}\n`);
411
+ }
412
+ return this.render();
413
+ } else if (key.ctrl && name === 'v') {
414
+ this.onPasteImage?.();
415
+ return this.render();
339
416
  } else if (key.ctrl && name === 'l') {
340
417
  this.clearScreen();
341
418
  return this.render();
@@ -484,16 +561,17 @@ export class FancyUI extends UI {
484
561
 
485
562
  // ---- permission menu ---------------------------------------------------
486
563
 
487
- confirm(preview, toolName) {
564
+ confirm(preview, toolName, { prefix } = {}) {
488
565
  return new Promise((resolve) => {
489
566
  this.stopSpinnerTimer();
490
- const what = { edit_file: 'edits', write_file: 'file writes', bash: 'commands', web_fetch: 'web fetches' }[toolName] ?? `"${toolName}"`;
567
+ const what = { edit_file: 'edits', write_file: 'file writes', bash: 'commands', web_fetch: 'web fetches', browser: 'browser actions' }[toolName] ?? `"${toolName}"`;
491
568
  this.menu = {
492
569
  preview,
493
570
  toolName,
494
571
  options: [
495
572
  { label: 'Yes', value: 'yes' },
496
- { label: `Always allow ${what}`, value: 'always' },
573
+ ...(prefix ? [{ label: `Always \`${prefix}\` here`, value: 'prefix' }] : []),
574
+ { label: prefix ? 'All commands this session' : `Always allow ${what}`, value: 'always' },
497
575
  { label: 'No, I\'ll explain', value: 'no' },
498
576
  ],
499
577
  selected: 0,
@@ -523,6 +601,7 @@ export class FancyUI extends UI {
523
601
  const choice = m.options[index];
524
602
  if (choice.value === 'no') this.printAbove(` ${this.c.faint(GLYPH.result)} ${this.c.rose('declined')} ${this.c.mist('· tell arrakis what to do instead')}\n`);
525
603
  else if (choice.value === 'always') this.printAbove(` ${this.c.faint(GLYPH.result)} ${this.c.mint('allowed for the rest of this session')}\n`);
604
+ else if (choice.value === 'prefix') this.printAbove(` ${this.c.faint(GLYPH.result)} ${this.c.mint(`${choice.label.replace(/^Always /, '').replace(/ here$/, '')} will run without asking in this project`)} ${this.c.mist('· /permissions to change')}\n`);
526
605
  this.resumeSpinnerTimer();
527
606
  this.render();
528
607
  m.resolve(choice.value);
@@ -841,11 +920,14 @@ export class FancyUI extends UI {
841
920
  const help = [
842
921
  [k('/', 'commands'), k('@', 'attach files'), k('\\⏎', 'new line')],
843
922
  [k('⇧⇥', 'cycle modes'), k('esc', 'interrupt'), k('↑↓', 'history')],
844
- [k('tab', 'complete'), k('esc esc', 'clear input'), k('ctrl+c', 'clear / exit')],
923
+ [k('tab', 'complete'), k('esc esc', 'clear input / rewind'), k('ctrl+c', 'clear / exit')],
924
+ [k('ctrl+r', 'search history'), k('ctrl+o', 'full tool output'), k('ctrl+v', 'paste image')],
845
925
  ];
846
926
  for (const row of help) lines.push(' ' + row.map((x) => x + ' '.repeat(Math.max(2, 24 - visibleLength(x)))).join(''));
847
927
  } else {
848
- const left = this.exitArmed ? c.amber('press ctrl+c again to exit') : this.modeLabel() || c.faint('? shortcuts');
928
+ const left = this.hsearch
929
+ ? `${c.violet('search history:')} ${c.lilac(this.hsearch.query)}${c.faint('▏')} ${this.hsearch.failed ? c.rose('no match') : c.faint('ctrl+r older · enter keep · esc cancel')}`
930
+ : this.exitArmed ? c.amber('press ctrl+c again to exit') : this.escArmed && !this.buffer && this.pending ? c.amber('esc again to rewind the conversation') : this.modeLabel() || c.faint('? shortcuts');
849
931
  const right = c.mist(this.statusLine());
850
932
  const gap = Math.max(2, cols - 3 - visibleLength(left) - visibleLength(right));
851
933
  lines.push(truncate(` ${left}${' '.repeat(gap)}${right}`, cols - 1));
package/src/ui.js CHANGED
@@ -14,7 +14,7 @@ const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇',
14
14
  const VERBS = ['Thinking', 'Reading the sands', 'Harvesting spice', 'Folding space', 'Charting the dunes', 'Working', 'Considering'];
15
15
 
16
16
  export const TOOL_LABELS = {
17
- read_file: 'Read', write_file: 'Write', edit_file: 'Edit', bash: 'Bash', grep: 'Search',
17
+ read_file: 'Read', write_file: 'Write', edit_file: 'Edit', multi_edit: 'Edit', bash: 'Bash', grep: 'Search',
18
18
  list_files: 'List', task: 'Agent', todo_write: 'Todos', web_fetch: 'Fetch',
19
19
  };
20
20
 
@@ -24,8 +24,9 @@ const tildify = (p) => (p.startsWith(os.homedir()) ? '~' + p.slice(os.homedir().
24
24
  // else (tool activity, notices, spinner) to stderr, so output can be piped.
25
25
  // "Fancy" mode (a real terminal) adds the spinner, input chrome and Markdown.
26
26
  export class UI {
27
- constructor({ print = false } = {}) {
27
+ constructor({ print = false, quiet = false } = {}) {
28
28
  this.print = print;
29
+ this.quiet = quiet; // --json: no streamed reply text
29
30
  this.out = process.stdout;
30
31
  this.log = print ? process.stderr : process.stdout;
31
32
  this.c = colors(this.out);
@@ -45,6 +46,12 @@ export class UI {
45
46
  this.onEscape = null;
46
47
  }
47
48
 
49
+ // Rebuild colors after a theme change.
50
+ retheme() {
51
+ this.c = colors(this.out);
52
+ this.lc = colors(this.log);
53
+ }
54
+
48
55
  get width() {
49
56
  return Math.max(40, (this.out.columns || 100) - 1);
50
57
  }
@@ -282,6 +289,7 @@ export class UI {
282
289
  }
283
290
 
284
291
  text(s) {
292
+ if (this.quiet) return;
285
293
  this.stopSpinner();
286
294
  if (this.mode === 'thinking') this.write(this.log, '\n\n');
287
295
  else if (this.mode !== 'text') {
@@ -319,10 +327,11 @@ export class UI {
319
327
  toolResult(result, isError = false, { lines: extra } = {}) {
320
328
  const t = this.lc;
321
329
  const all = String(result).split('\n');
330
+ this.lastOutput = String(result);
322
331
  const shown = all.slice(0, 4).map((l) => truncate(l, this.width - 6));
323
332
  const color = isError ? t.rose : t.mist;
324
333
  let body = shown.map((l, i) => ` ${i === 0 ? t.faint(GLYPH.result) : ' '} ${color(l)}`).join('\n');
325
- if (all.length > 4) body += `\n ${t.faint(`+${all.length - 4} more lines`)}`;
334
+ if (all.length > 4) body += `\n ${t.faint(`+${all.length - 4} more lines${this.fancy ? ' · ctrl+o to show all' : ''}`)}`;
326
335
  this.write(this.log, body + '\n');
327
336
  if (extra?.length) this.diff(extra);
328
337
  }
@@ -356,15 +365,17 @@ export class UI {
356
365
  }
357
366
  }
358
367
 
359
- async confirm(preview) {
368
+ async confirm(preview, toolName, { prefix } = {}) {
360
369
  this.stopSpinner();
361
370
  const t = this.lc;
362
371
  if (preview) {
363
372
  this.write(this.log, ` ${t.orchid(GLYPH.user)} ${t.bold(t.lilac(preview.title))}\n`);
364
373
  if (preview.lines?.length) this.diff(preview.lines);
365
374
  }
366
- const answer = await this.readLine(` ${t.orchid(GLYPH.user)} ${t.bold('Allow?')} ${t.mist('[y]es [a]lways this session [n]o')} `);
375
+ const choices = prefix ? `[y]es [p] always allow "${prefix}" here [a]lways this session [n]o` : '[y]es [a]lways this session [n]o';
376
+ const answer = await this.readLine(` ${t.orchid(GLYPH.user)} ${t.bold('Allow?')} ${t.mist(choices)} `);
367
377
  const a = (answer ?? 'n').trim().toLowerCase();
378
+ if (prefix && a === 'p') return 'prefix';
368
379
  if (a === 'a' || a === 'always') return 'always';
369
380
  if (a === 'y' || a === 'yes' || a === '') return 'yes';
370
381
  return 'no';