@mumbrane/arrakis 0.4.0 → 0.6.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
@@ -5,6 +5,11 @@ A coding agent for your terminal, built by Mumbrane. It reads your code, edits f
5
5
  - **Sub-agents:** hands big jobs to parallel agents with their own fresh context
6
6
  - **Plan mode:** investigates and proposes a plan before touching anything
7
7
  - **Task lists:** tracks multi-step work as it goes
8
+ - **Undo:** every file change is checkpointed; `/undo` puts things back
9
+ - **MCP:** plug in GitHub, databases, Slack and any other MCP server
10
+ - **Images:** attach screenshots and mockups
11
+ - **Background jobs:** hand off a task and close the terminal
12
+ - **Hooks:** run your own scripts before or after the agent's actions
8
13
  - **Crash-safe sessions:** every step is logged; pick up exactly where you left off
9
14
 
10
15
  ## Install
@@ -51,6 +56,10 @@ In a session:
51
56
  | `/plan` | Plan mode: investigate and propose, change nothing; `/plan` again to approve |
52
57
  | `/init` | Write `ARRAKIS.md` project notes for this folder |
53
58
  | `/todos` | Show the current task list |
59
+ | `/undo [n]` | Revert arrakis's file changes from the last turn (or pick a turn) |
60
+ | `/paste` | Attach the image on your clipboard (macOS) |
61
+ | `/mcp` | Show connected MCP servers and their tools |
62
+ | `/bg <task>` / `/jobs` | Start a background job / check on jobs |
54
63
  | `/status` | Session, model, context usage, permissions |
55
64
  | `/compact` | Summarize history to free up context |
56
65
  | `/model [name]` | Pick a model from your provider |
@@ -59,7 +68,7 @@ In a session:
59
68
  | `/yolo` | Toggle running tool calls without asking |
60
69
  | `/exit` | Quit (or Ctrl-D) |
61
70
 
62
- Type `@path/to/file` to attach a file (or folder listing) to your message. Esc or Ctrl-C interrupts the model mid-response. End a line with `\` to keep typing on the next line.
71
+ Type `@path/to/file` to attach a file (or folder listing) to your message; images (`@screenshot.png`, or drag one into the terminal) are sent to the model too. Tab completes commands and `@` paths, and ↑ recalls earlier messages, even from past sessions. Esc or Ctrl-C interrupts the model mid-response. End a line with `\` to keep typing on the next line.
63
72
 
64
73
  ### Custom commands
65
74
 
@@ -77,6 +86,50 @@ Sub-agents of type `explore` (the default) can only read and search. `general` s
77
86
 
78
87
  `-p` mode denies tools that need permission unless you pass `--yolo` or `--allow edit_file,write_file,bash`.
79
88
 
89
+ ## Undo
90
+
91
+ Before arrakis writes or edits a file, it saves the original. `/undo` reverts the last turn's changes; with several turns it lets you pick how far back to go. Checkpoints are stored with the session, so undo still works after `arrakis -c`. Changes made by shell commands (`bash`) aren't tracked, so use git for those.
92
+
93
+ ## MCP servers
94
+
95
+ Connect any [Model Context Protocol](https://modelcontextprotocol.io) server, local or remote:
96
+
97
+ ```bash
98
+ arrakis mcp add github -- npx -y @modelcontextprotocol/server-github
99
+ arrakis mcp add docs --url https://example.com/mcp
100
+ arrakis mcp # check they connect and list their tools
101
+ ```
102
+
103
+ Servers live in `~/.arrakis/mcp.json` using the standard `mcpServers` format, so configs from other tools work as-is. Add API keys under `"env"` (local servers) or `"headers"` (remote ones); `${VAR}` reads from your environment. A project can ship servers in `.mcp.json` or `.arrakis/mcp.json`; arrakis asks before trusting a folder's servers the first time. MCP tools ask permission before running unless the server marks them read-only.
104
+
105
+ ## Background jobs
106
+
107
+ ```bash
108
+ arrakis bg "audit the dependencies for known vulnerabilities and write a report to AUDIT.md" --allow write_file
109
+ arrakis jobs # list jobs
110
+ arrakis jobs log job-3fa2c1 -f # follow one
111
+ arrakis jobs stop job-3fa2c1
112
+ ```
113
+
114
+ Jobs keep running after you close the terminal. With no flags they can read and search but not change anything; `--allow` lets specific tools through and `--yolo` allows everything. Each job has a session, so `arrakis -r <session>` continues the conversation afterwards. Inside a session, `/bg <task>` starts one with the same permissions you've granted so far.
115
+
116
+ ## Hooks
117
+
118
+ Run your own commands at points in the agent's work, in `~/.arrakis/config.json` (or `.arrakis/settings.json` in a project, which asks before first use):
119
+
120
+ ```json
121
+ {
122
+ "hooks": {
123
+ "PreToolUse": [{ "matcher": "bash", "command": "./scripts/check-command.sh" }],
124
+ "PostToolUse": [{ "matcher": "edit_file|write_file", "command": "npx prettier --write \"$ARRAKIS_FILE\"" }],
125
+ "UserPromptSubmit": [{ "command": "git status --short" }],
126
+ "Stop": [{ "command": "say done" }]
127
+ }
128
+ }
129
+ ```
130
+
131
+ Each hook gets the event as JSON on stdin and `ARRAKIS_EVENT`, `ARRAKIS_TOOL` and `ARRAKIS_FILE` in its environment. A `PreToolUse` hook that exits with code 2 blocks the tool, and its stderr is shown to the model as the reason. `UserPromptSubmit` output is added to your message as context.
132
+
80
133
  ## Project instructions
81
134
 
82
135
  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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mumbrane/arrakis",
3
- "version": "0.4.0",
3
+ "version": "0.6.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
@@ -8,11 +8,23 @@ const MAX_SUB_STEPS = 150;
8
8
  const COMPACT_AT = 0.8;
9
9
  const KEEP_RECENT = 6;
10
10
 
11
- export const estimateTokens = (messages) => Math.ceil(JSON.stringify(messages).length / 4);
11
+ // Rough token count: ~4 characters per token, ~1600 tokens per image.
12
+ export function estimateTokens(messages) {
13
+ let chars = 0;
14
+ for (const m of messages) {
15
+ if (Array.isArray(m.content)) for (const p of m.content) chars += p.type === 'image_url' ? 6400 : String(p.text ?? '').length;
16
+ else chars += String(m.content ?? '').length;
17
+ if (m.tool_calls) chars += JSON.stringify(m.tool_calls).length;
18
+ chars += 16;
19
+ }
20
+ return Math.ceil(chars / 4);
21
+ }
22
+
23
+ const textOf = (content) => (Array.isArray(content) ? content.map((p) => (p.type === 'text' ? p.text : '[image]')).join('\n') : String(content ?? ''));
12
24
 
13
25
  export class Agent {
14
26
  // depth 0 is the agent the user talks to; sub-agents have depth >= 1.
15
- constructor({ config, session, ui, permissions, cwd, depth = 0, label = '', toolFilter = null }) {
27
+ constructor({ config, session, ui, permissions, cwd, depth = 0, label = '', toolFilter = null, checkpoints = null, hooks = null }) {
16
28
  this.config = config;
17
29
  this.session = session;
18
30
  this.ui = ui;
@@ -21,6 +33,9 @@ export class Agent {
21
33
  this.depth = depth;
22
34
  this.label = label;
23
35
  this.toolFilter = toolFilter;
36
+ this.checkpoints = checkpoints;
37
+ this.hooks = hooks;
38
+ this.notes = []; // things to tell the model with the next message (e.g. an undo)
24
39
  this.abort = null;
25
40
  this.todos = [];
26
41
  this.toolCount = 0;
@@ -47,8 +62,23 @@ export class Agent {
47
62
  }
48
63
 
49
64
  // Run one user turn to completion. Returns true on success.
50
- async send(text, { parentSignal } = {}) {
51
- this.session.add({ role: 'user', content: text });
65
+ async send(input, { parentSignal } = {}) {
66
+ let content = input;
67
+ if (this.depth === 0 && this.hooks) {
68
+ const text = typeof input === 'string' ? input : input.find((p) => p.type === 'text')?.text ?? '';
69
+ const hook = await this.hooks.run('UserPromptSubmit', { prompt: text, sessionId: this.session.id });
70
+ if (hook.blocked) {
71
+ this.ui.error(`Message blocked by a hook: ${hook.reason}`);
72
+ return false;
73
+ }
74
+ if (hook.output) this.notes.push(`<hook-context>\n${hook.output}\n</hook-context>`);
75
+ }
76
+ if (this.notes.length) {
77
+ const note = this.notes.splice(0).join('\n');
78
+ content = typeof input === 'string' ? `${input}\n\n${note}` : [...input, { type: 'text', text: note }];
79
+ }
80
+ this.session.add({ role: 'user', content });
81
+ if (this.depth === 0) this.checkpoints?.beginTurn(typeof input === 'string' ? input : input.find((p) => p.type === 'text')?.text ?? '(message)');
52
82
  this.abort = new AbortController();
53
83
  const signal = this.abort.signal;
54
84
  const onParentAbort = () => this.abort?.abort();
@@ -59,7 +89,10 @@ export class Agent {
59
89
  for (let step = 0; step < limit; step++) {
60
90
  await this.maybeCompact(signal);
61
91
  const msg = await this.callModel(signal);
62
- if (!msg.tool_calls?.length) return true;
92
+ if (!msg.tool_calls?.length) {
93
+ if (this.depth === 0 && this.hooks) await this.hooks.run('Stop', { sessionId: this.session.id });
94
+ return true;
95
+ }
63
96
  await this.runTools(msg.tool_calls, signal);
64
97
  if (signal.aborted) throw new DOMException('Interrupted', 'AbortError');
65
98
  }
@@ -76,6 +109,7 @@ export class Agent {
76
109
  return false;
77
110
  } finally {
78
111
  parentSignal?.removeEventListener('abort', onParentAbort);
112
+ if (this.depth === 0) this.checkpoints?.endTurn();
79
113
  if (!this.silent) {
80
114
  this.ui.stopSpinner();
81
115
  this.ui.endText();
@@ -96,6 +130,9 @@ export class Agent {
96
130
  depth: this.depth,
97
131
  label: this.label,
98
132
  allowed: (name) => this.allowsTool(name),
133
+ checkpoints: this.checkpoints,
134
+ hooks: this.hooks,
135
+ sessionId: this.session.id,
99
136
  };
100
137
  this.toolCount += calls.length;
101
138
  const parallel = calls.length > 1 && calls.every((c) => PARALLEL_SAFE.has(c.function?.name));
@@ -124,6 +161,8 @@ export class Agent {
124
161
  depth: this.depth + 1,
125
162
  label: description,
126
163
  toolFilter: readOnly ? (name) => READ_ONLY_TOOLS.has(name) : null,
164
+ checkpoints: this.checkpoints,
165
+ hooks: this.hooks,
127
166
  });
128
167
  sub.subagentType = readOnly ? 'explore' : 'general';
129
168
  const started = Date.now();
@@ -166,7 +205,10 @@ export class Agent {
166
205
  const c = (calls[idx] ??= { id: '', type: 'function', function: { name: '', arguments: '' } });
167
206
  if (tc.id) c.id = tc.id;
168
207
  if (tc.function?.name && !c.function.name) c.function.name = tc.function.name;
169
- if (tc.function?.arguments) c.function.arguments += tc.function.arguments;
208
+ if (tc.function?.arguments) {
209
+ c.function.arguments += tc.function.arguments;
210
+ if (!this.silent) this.ui.addTokens?.(tc.function.arguments.length / 4);
211
+ }
170
212
  }
171
213
  }
172
214
  } finally {
@@ -235,7 +277,7 @@ export class Agent {
235
277
 
236
278
  function renderForSummary(m) {
237
279
  if (m.role === 'tool') return `[tool result]\n${truncate(String(m.content ?? ''), 2000)}`;
238
- let s = `[${m.role}]\n${m.content ?? ''}`;
280
+ let s = `[${m.role}]\n${textOf(m.content)}`;
239
281
  for (const c of m.tool_calls ?? []) s += `\n(called ${c.function.name} ${truncate(c.function.arguments, 1000)})`;
240
282
  return s;
241
283
  }
@@ -0,0 +1,83 @@
1
+ // File checkpoints: before arrakis writes or edits a file, the original is
2
+ // saved. /undo puts files back the way they were before a turn. Stored next to
3
+ // the session log (<session>.checkpoints/), so undo works after a restart.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+
7
+ export class Checkpoints {
8
+ constructor(sessionFile) {
9
+ this.dir = sessionFile ? sessionFile.replace(/\.jsonl$/, '.checkpoints') : null;
10
+ this.turns = [];
11
+ this.current = null;
12
+ this.blobs = 0;
13
+ if (this.dir) {
14
+ try {
15
+ const index = JSON.parse(fs.readFileSync(path.join(this.dir, 'index.json'), 'utf8'));
16
+ this.turns = index.turns ?? [];
17
+ this.blobs = index.blobs ?? 0;
18
+ } catch {}
19
+ }
20
+ }
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: {} };
24
+ }
25
+
26
+ // Save a file's current state the first time a turn touches it.
27
+ record(file) {
28
+ if (!this.current) this.beginTurn('(changes)');
29
+ const abs = path.resolve(file);
30
+ if (abs in this.current.files) return;
31
+ let blob = null;
32
+ if (fs.existsSync(abs) && fs.statSync(abs).isFile()) {
33
+ blob = `${++this.blobs}.bin`;
34
+ if (this.dir) {
35
+ fs.mkdirSync(this.dir, { recursive: true });
36
+ fs.copyFileSync(abs, path.join(this.dir, blob));
37
+ } else {
38
+ (this.memory ??= new Map()).set(blob, fs.readFileSync(abs));
39
+ }
40
+ }
41
+ this.current.files[abs] = blob; // null means the file didn't exist
42
+ if (!this.turns.includes(this.current)) this.turns.push(this.current);
43
+ this.save();
44
+ }
45
+
46
+ endTurn() {
47
+ this.current = null;
48
+ }
49
+
50
+ list() {
51
+ return this.turns.map((t) => ({ id: t.id, label: t.label, time: t.time, files: Object.keys(t.files) }));
52
+ }
53
+
54
+ // Undo the most recent turn with changes (or every turn back to `toId`).
55
+ undo(toId) {
56
+ const target = toId ?? this.turns.at(-1)?.id;
57
+ if (target === undefined) return [];
58
+ const restored = new Map();
59
+ while (this.turns.length && this.turns.at(-1).id >= target) {
60
+ const turn = this.turns.pop();
61
+ for (const [file, blob] of Object.entries(turn.files)) {
62
+ if (blob === null) {
63
+ fs.rmSync(file, { force: true });
64
+ restored.set(file, 'removed');
65
+ } else {
66
+ fs.mkdirSync(path.dirname(file), { recursive: true });
67
+ const data = this.dir ? fs.readFileSync(path.join(this.dir, blob)) : this.memory.get(blob);
68
+ fs.writeFileSync(file, data);
69
+ restored.set(file, 'restored');
70
+ }
71
+ }
72
+ }
73
+ this.current = null;
74
+ this.save();
75
+ return [...restored].map(([file, action]) => ({ file, action }));
76
+ }
77
+
78
+ save() {
79
+ if (!this.dir) return;
80
+ fs.mkdirSync(this.dir, { recursive: true });
81
+ fs.writeFileSync(path.join(this.dir, 'index.json'), JSON.stringify({ turns: this.turns, blobs: this.blobs }));
82
+ }
83
+ }