@mumbrane/arrakis 0.3.0 → 0.4.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,6 +1,11 @@
1
1
  # arrakis
2
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.
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. It works with Claude, GPT, Gemini, Grok, DeepSeek, Mistral, local models and more.
4
+
5
+ - **Sub-agents:** hands big jobs to parallel agents with their own fresh context
6
+ - **Plan mode:** investigates and proposes a plan before touching anything
7
+ - **Task lists:** tracks multi-step work as it goes
8
+ - **Crash-safe sessions:** every step is logged; pick up exactly where you left off
4
9
 
5
10
  ## Install
6
11
 
@@ -42,7 +47,10 @@ In a session:
42
47
 
43
48
  | Command | What it does |
44
49
  |---|---|
45
- | `/help` | List commands |
50
+ | `/help` | List commands (including your own) |
51
+ | `/plan` | Plan mode: investigate and propose, change nothing; `/plan` again to approve |
52
+ | `/init` | Write `ARRAKIS.md` project notes for this folder |
53
+ | `/todos` | Show the current task list |
46
54
  | `/status` | Session, model, context usage, permissions |
47
55
  | `/compact` | Summarize history to free up context |
48
56
  | `/model [name]` | Pick a model from your provider |
@@ -51,14 +59,21 @@ In a session:
51
59
  | `/yolo` | Toggle running tool calls without asking |
52
60
  | `/exit` | Quit (or Ctrl-D) |
53
61
 
54
- Ctrl-C interrupts the model mid-response. End a line with `\` to keep typing on the next line.
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.
63
+
64
+ ### Custom commands
65
+
66
+ Put a Markdown file in `.arrakis/commands/` (per project) or `~/.arrakis/commands/` (everywhere) and it becomes a slash command. `.arrakis/commands/review.md` becomes `/review`; `$ARGUMENTS` in the file is replaced with whatever you type after the command.
55
67
 
56
68
  ## Tools
57
69
 
58
70
  | Tool | Asks first |
59
71
  |---|---|
60
72
  | `read_file`, `grep`, `list_files` | No |
61
- | `write_file`, `edit_file`, `bash` | Yes: answer `y`, `a` (always, for this session) or `n` |
73
+ | `todo_write` (task list), `task` (sub-agents) | No |
74
+ | `write_file`, `edit_file`, `bash`, `web_fetch` | Yes: answer `y`, `a` (always, for this session) or `n` |
75
+
76
+ Sub-agents of type `explore` (the default) can only read and search. `general` sub-agents can also edit and run commands, and they ask permission the same way.
62
77
 
63
78
  `-p` mode denies tools that need permission unless you pass `--yolo` or `--allow edit_file,write_file,bash`.
64
79
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mumbrane/arrakis",
3
- "version": "0.3.0",
3
+ "version": "0.4.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
@@ -1,27 +1,45 @@
1
1
  import { streamChat, completeText } from './client.js';
2
- import { toolSchemas, executeToolCall, truncate } from './tools.js';
2
+ import { toolSchemas, executeToolCall, truncate, READ_ONLY_TOOLS, PARALLEL_SAFE } from './tools.js';
3
3
  import { buildSystemPrompt } from './prompt.js';
4
+ import { Session } from './session.js';
4
5
 
5
- const MAX_STEPS = 200;
6
+ const MAX_STEPS = 400;
7
+ const MAX_SUB_STEPS = 150;
6
8
  const COMPACT_AT = 0.8;
7
9
  const KEEP_RECENT = 6;
8
10
 
9
11
  export const estimateTokens = (messages) => Math.ceil(JSON.stringify(messages).length / 4);
10
12
 
11
13
  export class Agent {
12
- constructor({ config, session, ui, permissions, cwd }) {
14
+ // 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 }) {
13
16
  this.config = config;
14
17
  this.session = session;
15
18
  this.ui = ui;
16
19
  this.permissions = permissions;
17
20
  this.cwd = cwd;
21
+ this.depth = depth;
22
+ this.label = label;
23
+ this.toolFilter = toolFilter;
18
24
  this.abort = null;
25
+ this.todos = [];
26
+ this.toolCount = 0;
27
+ this.lastError = null;
19
28
  }
20
29
 
21
30
  get busy() {
22
31
  return this.abort !== null;
23
32
  }
24
33
 
34
+ get silent() {
35
+ return this.depth > 0;
36
+ }
37
+
38
+ allowsTool(name) {
39
+ if (this.depth > 0 && (name === 'task' || name === 'todo_write')) return false;
40
+ return this.toolFilter ? this.toolFilter(name) : true;
41
+ }
42
+
25
43
  interrupt() {
26
44
  if (!this.abort) return;
27
45
  this.abort.abort();
@@ -29,52 +47,119 @@ export class Agent {
29
47
  }
30
48
 
31
49
  // Run one user turn to completion. Returns true on success.
32
- async send(text) {
50
+ async send(text, { parentSignal } = {}) {
33
51
  this.session.add({ role: 'user', content: text });
34
52
  this.abort = new AbortController();
35
53
  const signal = this.abort.signal;
54
+ const onParentAbort = () => this.abort?.abort();
55
+ parentSignal?.addEventListener('abort', onParentAbort, { once: true });
56
+ if (!this.silent) this.ui.setBusy(true);
36
57
  try {
37
- for (let step = 0; step < MAX_STEPS; step++) {
58
+ const limit = this.depth > 0 ? MAX_SUB_STEPS : MAX_STEPS;
59
+ for (let step = 0; step < limit; step++) {
38
60
  await this.maybeCompact(signal);
39
61
  const msg = await this.callModel(signal);
40
62
  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
- }
63
+ await this.runTools(msg.tool_calls, signal);
47
64
  if (signal.aborted) throw new DOMException('Interrupted', 'AbortError');
48
65
  }
49
- this.ui.error(`Stopped after ${MAX_STEPS} steps.`);
66
+ this.lastError = `Stopped after ${limit} steps.`;
67
+ if (!this.silent) this.ui.error(this.lastError);
50
68
  return false;
51
69
  } 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.`);
70
+ this.lastError = err.name === 'AbortError' ? 'Interrupted.' : err.message;
71
+ if (this.silent) return false;
72
+ if (err.name === 'AbortError') this.ui.info('Interrupted. Tell arrakis what to do differently, or keep going.');
73
+ else if (err.status === 401 || err.status === 403) this.ui.error(`${err.message}\nYour API key was rejected. Run /provider to update it.`);
54
74
  else if (err.status === 404) this.ui.error(`${err.message}\nThe model may not exist for this provider. Pick another with /model.`);
55
75
  else this.ui.error(err.message);
56
76
  return false;
57
77
  } finally {
58
- this.ui.endText();
78
+ parentSignal?.removeEventListener('abort', onParentAbort);
79
+ if (!this.silent) {
80
+ this.ui.stopSpinner();
81
+ this.ui.endText();
82
+ this.ui.setBusy(false);
83
+ }
59
84
  this.abort = null;
60
85
  this.session.repair();
61
86
  }
62
87
  }
63
88
 
89
+ async runTools(calls, signal) {
90
+ const ctx = {
91
+ cwd: this.cwd,
92
+ signal,
93
+ ui: this.ui,
94
+ permissions: this.permissions,
95
+ agent: this,
96
+ depth: this.depth,
97
+ label: this.label,
98
+ allowed: (name) => this.allowsTool(name),
99
+ };
100
+ this.toolCount += calls.length;
101
+ const parallel = calls.length > 1 && calls.every((c) => PARALLEL_SAFE.has(c.function?.name));
102
+ let results;
103
+ if (parallel) {
104
+ results = await Promise.all(calls.map((call) => executeToolCall(call, ctx)));
105
+ } else {
106
+ results = [];
107
+ for (const call of calls) {
108
+ results.push(signal.aborted ? 'Interrupted by the user before this tool ran.' : await executeToolCall(call, ctx));
109
+ }
110
+ }
111
+ if (!this.silent) this.ui.stopSpinner();
112
+ calls.forEach((call, i) => this.session.add({ role: 'tool', tool_call_id: call.id, content: results[i] }));
113
+ }
114
+
115
+ async runSubagent({ description = 'sub-task', prompt, agent_type = 'explore' }, signal) {
116
+ if (!prompt) throw new Error('prompt is required');
117
+ const readOnly = agent_type !== 'general';
118
+ const sub = new Agent({
119
+ config: this.config,
120
+ session: Session.memory(),
121
+ ui: this.ui,
122
+ permissions: this.permissions,
123
+ cwd: this.cwd,
124
+ depth: this.depth + 1,
125
+ label: description,
126
+ toolFilter: readOnly ? (name) => READ_ONLY_TOOLS.has(name) : null,
127
+ });
128
+ sub.subagentType = readOnly ? 'explore' : 'general';
129
+ const started = Date.now();
130
+ const ok = await sub.send(prompt, { parentSignal: signal });
131
+ const secs = Math.round((Date.now() - started) / 1000);
132
+ const report = [...sub.session.messages].reverse().find((m) => m.role === 'assistant' && m.content)?.content ?? '';
133
+ const stats = `${sub.toolCount} tool use${sub.toolCount === 1 ? '' : 's'} · ${secs}s`;
134
+ if (!ok) {
135
+ return { content: `Sub-agent "${description}" did not finish: ${sub.lastError}\n\nPartial report:\n${report || '(none)'}`, display: `${description}: stopped, ${sub.lastError} (${stats})` };
136
+ }
137
+ return { content: report || '(The sub-agent returned no report.)', display: `${description}: done (${stats})` };
138
+ }
139
+
64
140
  async callModel(signal) {
65
- const messages = [{ role: 'system', content: buildSystemPrompt({ cwd: this.cwd, model: this.config.model }) }, ...this.session.messages];
141
+ const system = buildSystemPrompt({
142
+ cwd: this.cwd,
143
+ model: this.config.model,
144
+ planMode: this.permissions.planMode,
145
+ subagent: this.depth > 0 ? { type: this.subagentType } : null,
146
+ });
147
+ const messages = [{ role: 'system', content: system }, ...this.session.messages];
66
148
  let content = '';
67
149
  const calls = [];
68
- this.ui.startResponse();
150
+ if (!this.silent) {
151
+ this.ui.startResponse();
152
+ this.ui.startSpinner();
153
+ }
69
154
  try {
70
- for await (const event of streamChat({ config: this.config, messages, tools: toolSchemas(), signal })) {
155
+ for await (const event of streamChat({ config: this.config, messages, tools: toolSchemas((n) => this.allowsTool(n)), signal })) {
71
156
  const delta = event.choices?.[0]?.delta;
72
157
  if (!delta) continue;
73
158
  const reasoning = delta.reasoning_content ?? delta.reasoning;
74
- if (reasoning) this.ui.thinking(reasoning);
159
+ if (reasoning && !this.silent) this.ui.thinking(reasoning);
75
160
  if (delta.content) {
76
161
  content += delta.content;
77
- this.ui.text(delta.content);
162
+ if (!this.silent) this.ui.text(delta.content);
78
163
  }
79
164
  for (const tc of delta.tool_calls ?? []) {
80
165
  const idx = tc.index ?? (tc.id ? calls.length : Math.max(0, calls.length - 1));
@@ -85,7 +170,7 @@ export class Agent {
85
170
  }
86
171
  }
87
172
  } finally {
88
- this.ui.endText();
173
+ if (!this.silent) this.ui.endText();
89
174
  }
90
175
  const toolCalls = calls.filter(Boolean).map((c, i) => ({ ...c, id: c.id || `call_${Date.now()}_${i}` }));
91
176
  const msg = { role: 'assistant', content: content || (toolCalls.length ? null : '') };
@@ -98,7 +183,6 @@ export class Agent {
98
183
  const messages = this.session.messages;
99
184
  if (!force && estimateTokens(messages) < this.config.contextWindow * COMPACT_AT) return false;
100
185
  // 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
186
  const keep = force ? 2 : KEEP_RECENT;
103
187
  let cut = -1;
104
188
  for (let i = messages.length - 1; i > 0; i--) {
@@ -110,8 +194,8 @@ export class Agent {
110
194
  if (cut <= 0) {
111
195
  for (let i = messages.length - 1; i > 0; i--) if (messages[i].role === 'user') { cut = i; break; }
112
196
  }
113
- if (cut <= 0) return false;
114
- this.ui.info('Compacting conversation history…');
197
+ if (cut <= 0) return this.trimToolResults();
198
+ if (!this.silent) this.ui.info('Compacting conversation history to free up context…');
115
199
  const transcript = messages.slice(0, cut).map(renderForSummary).join('\n\n');
116
200
  const summary = await completeText({
117
201
  config: this.config,
@@ -120,13 +204,33 @@ export class Agent {
120
204
  { role: 'system', content: 'You summarize coding-agent conversations so the work can continue with less context.' },
121
205
  {
122
206
  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>`,
207
+ 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, the current task list, and what is left to do. Be specific and concise.\n\n<conversation>\n${truncate(transcript, 400000)}\n</conversation>`,
124
208
  },
125
209
  ],
126
210
  });
127
211
  this.session.compact(summary.trim() || '(no summary produced)', cut);
212
+ if (estimateTokens(this.session.messages) >= this.config.contextWindow * COMPACT_AT) this.trimToolResults();
128
213
  return true;
129
214
  }
215
+
216
+ // One long turn with no user message to cut at: shorten old tool results.
217
+ trimToolResults() {
218
+ const messages = this.session.messages;
219
+ const recent = Math.max(0, messages.length - 8);
220
+ let changed = false;
221
+ const next = messages.map((m, i) => {
222
+ if (i < recent && m.role === 'tool' && typeof m.content === 'string' && m.content.length > 600) {
223
+ changed = true;
224
+ return { ...m, content: `${m.content.slice(0, 500)}\n… [older tool output trimmed to save context; re-run the tool if you need it]` };
225
+ }
226
+ return m;
227
+ });
228
+ if (changed) {
229
+ this.session.replace(next);
230
+ if (!this.silent) this.ui.info('Trimmed old tool output to free up context.');
231
+ }
232
+ return changed;
233
+ }
130
234
  }
131
235
 
132
236
  function renderForSummary(m) {
package/src/cli.js CHANGED
@@ -11,6 +11,7 @@ import { UI, colors } from './ui.js';
11
11
  import { TOOLS } from './tools.js';
12
12
  import { loadProjectInstructions } from './prompt.js';
13
13
  import { VERSION } from './version.js';
14
+ import { expandMentions, loadCustomCommands, renderCommand, INIT_PROMPT } from './input.js';
14
15
 
15
16
  const HELP = `arrakis ${VERSION} — a coding agent for your terminal
16
17
 
@@ -41,6 +42,9 @@ Environment (overrides the config file)
41
42
  ARRAKIS_PROVIDER, ARRAKIS_BASE_URL, ARRAKIS_API_KEY, ARRAKIS_MODEL, ARRAKIS_CONTEXT_WINDOW, ARRAKIS_HOME`;
42
43
 
43
44
  const SLASH_HELP = `/help Show commands
45
+ /plan Toggle plan mode: investigate and propose a plan, change nothing
46
+ /init Write ARRAKIS.md project notes for this folder
47
+ /todos Show the current task list
44
48
  /clear Start a new session
45
49
  /compact Summarize history to free up context
46
50
  /model [name] Pick a model from your provider (or set one by name)
@@ -50,7 +54,8 @@ const SLASH_HELP = `/help Show commands
50
54
  /yolo Toggle allowing all tool calls without asking
51
55
  /exit Quit (or Ctrl-D)
52
56
 
53
- End a line with \\ to continue on the next line. Ctrl-C interrupts the model.`;
57
+ Type @path to attach a file or folder. End a line with \\ to continue on the next line.
58
+ Esc or Ctrl-C interrupts the model. Add your own commands as .arrakis/commands/<name>.md.`;
54
59
 
55
60
  export async function main(argv) {
56
61
  if (argv[0] === 'config') return configCommand(argv.slice(1));
@@ -121,7 +126,7 @@ export async function main(argv) {
121
126
  agent.interrupt();
122
127
  process.exit(130);
123
128
  });
124
- const ok = await agent.send(prompt);
129
+ const ok = await agent.send(expandMentions(prompt, cwd).text);
125
130
  process.exitCode = ok ? 0 : 1;
126
131
  return;
127
132
  }
@@ -139,33 +144,53 @@ async function interactive({ agent, ui, prompts, config, cwd, firstPrompt }) {
139
144
  process.exit(0);
140
145
  }
141
146
  armedExit = true;
142
- ui.write(ui.out, `\n${c.dim('(Press Ctrl-C again to exit)')}\n`);
147
+ ui.write(ui.out, `\n${c.gray('(Press Ctrl-C again to exit)')}\n`);
143
148
  ui.rl?.prompt();
144
149
  });
150
+ ui.onEscape = () => {
151
+ if (agent.busy) agent.interrupt();
152
+ };
153
+ ui.statusLine = () => {
154
+ const used = Math.round((estimateTokens(agent.session.messages) / config.contextWindow) * 100);
155
+ const parts = [config.model, `${used}% context`];
156
+ if (agent.permissions.planMode) parts.push('plan mode');
157
+ if (agent.permissions.mode === 'yolo') parts.push('yolo');
158
+ parts.push('/help');
159
+ return parts.join(' · ');
160
+ };
145
161
 
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'));
162
+ ui.banner({
163
+ version: VERSION,
164
+ model: config.model,
165
+ provider: config.providerName || config.baseUrl,
166
+ cwd,
167
+ instructions: loadProjectInstructions(cwd).filter((i) => i.text.trim()).map((i) => i.file),
168
+ resumed: agent.session.messages.length ? `resumed ${agent.session.id} (${agent.session.messages.length} messages)` : '',
169
+ });
170
+
171
+ const send = async (text) => {
172
+ const { text: full, attached } = expandMentions(text, cwd);
173
+ if (attached.length) ui.info(` Attached ${attached.join(', ')}`);
174
+ await agent.send(full);
175
+ };
152
176
 
153
- if (firstPrompt) await agent.send(firstPrompt);
177
+ if (firstPrompt) await send(firstPrompt);
154
178
  while (true) {
155
179
  const line = await ui.prompt();
156
180
  if (line === null) break;
157
181
  armedExit = false;
158
182
  const text = line.trim();
159
183
  if (!text) continue;
160
- if (text.startsWith('/')) {
161
- if ((await slashCommand(text, { agent, ui, prompts, config, cwd })) === 'exit') break;
184
+ if (text.startsWith('/') && !text.startsWith('//')) {
185
+ const result = await slashCommand(text, { agent, ui, prompts, config, cwd });
186
+ if (result === 'exit') break;
187
+ if (result?.send) await send(result.send);
162
188
  continue;
163
189
  }
164
- await agent.send(text);
165
- ui.write(ui.out, '\n');
190
+ await send(text);
166
191
  }
167
192
  ui.close();
168
- ui.write(ui.out, c.dim(`Session saved. Resume with: arrakis -r ${agent.session.id}\n`));
193
+ ui.write(ui.out, c.gray(`\nSession saved. Resume with: arrakis -r ${agent.session.id}\n`));
169
194
  }
170
195
 
171
196
  async function slashCommand(text, { agent, ui, prompts, config, cwd }) {
@@ -173,8 +198,28 @@ async function slashCommand(text, { agent, ui, prompts, config, cwd }) {
173
198
  const arg = rest.join(' ');
174
199
  const c = ui.c;
175
200
  switch (cmd) {
176
- case 'help':
201
+ case 'help': {
177
202
  ui.write(ui.out, SLASH_HELP + '\n');
203
+ const custom = loadCustomCommands(cwd);
204
+ if (custom.size) {
205
+ ui.write(ui.out, `\n${c.bold('Your commands')}\n`);
206
+ for (const cmd of custom.values()) ui.write(ui.out, `/${cmd.name.padEnd(17)} ${c.gray(cmd.description)}\n`);
207
+ }
208
+ break;
209
+ }
210
+ case 'plan':
211
+ agent.permissions.planMode = !agent.permissions.planMode;
212
+ if (agent.permissions.planMode) ui.info('Plan mode on: arrakis will investigate and propose a plan without changing anything. /plan again to approve and let it work.');
213
+ else {
214
+ ui.info('Plan mode off: arrakis can make changes now.');
215
+ if (agent.session.messages.length) return { send: 'Plan mode is off and the plan is approved. Go ahead and carry it out.' };
216
+ }
217
+ break;
218
+ case 'init':
219
+ return { send: INIT_PROMPT };
220
+ case 'todos':
221
+ if (agent.todos.length) ui.todos(agent.todos);
222
+ else ui.info('No task list yet. arrakis makes one for multi-step work.');
178
223
  break;
179
224
  case 'exit':
180
225
  case 'quit':
@@ -233,6 +278,8 @@ async function slashCommand(text, { agent, ui, prompts, config, cwd }) {
233
278
  `provider ${config.providerName || 'custom'} (${config.baseUrl})`,
234
279
  `model ${config.model}`,
235
280
  `context ~${used.toLocaleString()} / ${config.contextWindow.toLocaleString()} tokens (${Math.round((used / config.contextWindow) * 100)}%)`,
281
+ `plan mode ${agent.permissions.planMode ? 'on' : 'off'}`,
282
+ `todos ${agent.todos.length ? `${agent.todos.filter((t) => t.status === 'completed').length}/${agent.todos.length} done` : 'none'}`,
236
283
  `permissions ${agent.permissions.mode}${agent.permissions.allowed.size ? ` (always allowed: ${[...agent.permissions.allowed].join(', ')})` : ''}`,
237
284
  `tools ${TOOLS.map((t) => t.name).join(', ')}`,
238
285
  ].join('\n') + '\n');
@@ -242,8 +289,11 @@ async function slashCommand(text, { agent, ui, prompts, config, cwd }) {
242
289
  agent.permissions.mode = agent.permissions.mode === 'yolo' ? 'ask' : 'yolo';
243
290
  ui.info(agent.permissions.mode === 'yolo' ? 'YOLO on: tool calls run without asking.' : 'YOLO off: writes and commands ask first.');
244
291
  break;
245
- default:
292
+ default: {
293
+ const custom = loadCustomCommands(cwd).get(cmd.toLowerCase());
294
+ if (custom) return { send: renderCommand(custom, arg) };
246
295
  ui.write(ui.out, c.red(`Unknown command /${cmd}. Try /help.\n`));
296
+ }
247
297
  }
248
298
  }
249
299
 
package/src/input.js ADDED
@@ -0,0 +1,75 @@
1
+ // User input helpers: @file mentions and custom slash commands.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { HOME_DIR } from './config.js';
5
+
6
+ const MAX_ATTACH = 100_000;
7
+
8
+ // "@src/app.js" in a message attaches that file's contents (or a directory listing).
9
+ export function expandMentions(text, cwd) {
10
+ const attached = [];
11
+ const blocks = [];
12
+ const seen = new Set();
13
+ for (const m of text.matchAll(/(^|\s)@((?:[^\s"'`]|\\ )+)/g)) {
14
+ const ref = m[2].replace(/\\ /g, ' ').replace(/[.,;:!?)]+$/, '');
15
+ if (seen.has(ref)) continue;
16
+ seen.add(ref);
17
+ const full = path.resolve(cwd, ref.startsWith('~/') ? path.join(process.env.HOME || '', ref.slice(2)) : ref);
18
+ let stat;
19
+ try {
20
+ stat = fs.statSync(full);
21
+ } catch {
22
+ continue;
23
+ }
24
+ if (stat.isDirectory()) {
25
+ const entries = fs.readdirSync(full, { withFileTypes: true }).map((e) => (e.isDirectory() ? `${e.name}/` : e.name)).sort();
26
+ blocks.push(`<directory path="${ref}">\n${entries.slice(0, 500).join('\n')}\n</directory>`);
27
+ attached.push(`${ref}/`);
28
+ } else if (stat.isFile()) {
29
+ const buf = fs.readFileSync(full);
30
+ if (buf.subarray(0, 8000).includes(0)) continue;
31
+ let body = buf.toString('utf8');
32
+ if (body.length > MAX_ATTACH) body = body.slice(0, MAX_ATTACH) + `\n… (truncated; file is ${body.length} characters, use read_file for the rest)`;
33
+ blocks.push(`<file path="${ref}">\n${body}\n</file>`);
34
+ attached.push(ref);
35
+ }
36
+ }
37
+ if (!blocks.length) return { text, attached };
38
+ return { text: `${text}\n\n${blocks.join('\n\n')}`, attached };
39
+ }
40
+
41
+ // Markdown files in .arrakis/commands (project) and ~/.arrakis/commands (global)
42
+ // become slash commands. $ARGUMENTS in the file is replaced with what follows.
43
+ export function loadCustomCommands(cwd) {
44
+ const dirs = [path.join(HOME_DIR, 'commands'), path.join(cwd, '.arrakis', 'commands')];
45
+ const commands = new Map();
46
+ for (const dir of dirs) {
47
+ let files = [];
48
+ try {
49
+ files = fs.readdirSync(dir).filter((f) => f.endsWith('.md'));
50
+ } catch {
51
+ continue;
52
+ }
53
+ for (const f of files) {
54
+ const body = fs.readFileSync(path.join(dir, f), 'utf8');
55
+ const name = f.slice(0, -3).toLowerCase().replace(/[^a-z0-9_-]/g, '-');
56
+ const firstLine = body.split('\n').find((l) => l.trim())?.replace(/^#+\s*/, '').trim() ?? '';
57
+ commands.set(name, { name, file: path.join(dir, f), body, description: firstLine.slice(0, 60) });
58
+ }
59
+ }
60
+ return commands;
61
+ }
62
+
63
+ export function renderCommand(cmd, args) {
64
+ return cmd.body.includes('$ARGUMENTS') ? cmd.body.replaceAll('$ARGUMENTS', args) : args ? `${cmd.body}\n\n${args}` : cmd.body;
65
+ }
66
+
67
+ export const INIT_PROMPT = `Look through this project and write an ARRAKIS.md file at the repository root that will help a coding agent work here in future sessions. Use sub-agents (task tool, explore) to survey large codebases in parallel.
68
+
69
+ Include, briefly:
70
+ - What the project is and how it's organized (key directories and entry points)
71
+ - How to install, build, run, test and lint (exact commands, from package files, Makefiles, CI config, READMEs)
72
+ - Code style and conventions you can see (language versions, formatting, naming, patterns to follow)
73
+ - Anything non-obvious: gotchas, generated files not to edit, environment setup
74
+
75
+ Keep it concise and specific to this repository; don't pad it with generic advice. If ARRAKIS.md or AGENTS.md already exists, improve it rather than replacing useful content.`;
@@ -0,0 +1,134 @@
1
+ // Streaming Markdown renderer for the terminal. Text arrives in chunks; each
2
+ // complete line is rendered as soon as its newline arrives. Tables are held
3
+ // until they end so their columns can be aligned.
4
+
5
+ const ANSI = /\x1b\[[0-9;]*m/g;
6
+ export const visibleLength = (s) => s.replace(ANSI, '').length;
7
+
8
+ const KEYWORDS = new Set(
9
+ ('abstract and as async await break case catch class const continue def default defer del delete do elif else enum export extends ' +
10
+ 'false final finally fn for from func function go if impl import in interface is lambda let loop match mod module mut new nil none ' +
11
+ 'not null or package pass private protected pub public raise return self static struct super switch this throw throws true try type ' +
12
+ 'typeof undefined use var void where while with yield None True False').split(' '),
13
+ );
14
+
15
+ export function highlight(line, c) {
16
+ const token = /(\/\/.*$|#(?![!{\[]).*$|--\s.*$)|("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`)|(\b\d+(?:\.\d+)?\b)|([A-Za-z_][A-Za-z0-9_]*)/g;
17
+ return line.replace(token, (m, comment, str, num, word) => {
18
+ if (comment) return c.gray(comment);
19
+ if (str) return c.green(str);
20
+ if (num) return c.yellow(num);
21
+ if (word && KEYWORDS.has(word)) return c.magenta(word);
22
+ return m;
23
+ });
24
+ }
25
+
26
+ export function renderInline(s, c) {
27
+ // Split out `code` spans first so nothing inside them is touched.
28
+ return s
29
+ .split(/(`[^`]+`)/)
30
+ .map((part) => {
31
+ if (/^`[^`]+`$/.test(part)) return c.cyan(part.slice(1, -1));
32
+ return part
33
+ .replace(/\*\*([^*]+)\*\*|__([^_]+)__/g, (_, a, b) => c.bold(a ?? b))
34
+ .replace(/(^|[\s(])\*([^*\s][^*]*)\*(?=$|[\s).,:;!?])/g, (_, pre, a) => pre + c.italic(a))
35
+ .replace(/(^|[\s(])_([^_\s][^_]*)_(?=$|[\s).,:;!?])/g, (_, pre, a) => pre + c.italic(a))
36
+ .replace(/~~([^~]+)~~/g, (_, a) => c.dim(a))
37
+ .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, text, url) => (text === url ? c.underline(url) : `${c.underline(text)} ${c.gray(`(${url})`)}`));
38
+ })
39
+ .join('');
40
+ }
41
+
42
+ export class MarkdownStream {
43
+ constructor(c, { width = 100 } = {}) {
44
+ this.c = c;
45
+ this.width = width;
46
+ this.buf = '';
47
+ this.inCode = false;
48
+ this.fence = '';
49
+ this.table = [];
50
+ }
51
+
52
+ push(chunk) {
53
+ this.buf += chunk;
54
+ let out = '';
55
+ let nl;
56
+ while ((nl = this.buf.indexOf('\n')) >= 0) {
57
+ out += this.line(this.buf.slice(0, nl));
58
+ this.buf = this.buf.slice(nl + 1);
59
+ }
60
+ return out;
61
+ }
62
+
63
+ flush() {
64
+ let out = '';
65
+ if (this.buf) {
66
+ out += this.line(this.buf);
67
+ this.buf = '';
68
+ }
69
+ out += this.flushTable();
70
+ if (this.inCode) {
71
+ out += this.c.gray(' ╰─') + '\n';
72
+ this.inCode = false;
73
+ }
74
+ return out;
75
+ }
76
+
77
+ line(raw) {
78
+ const c = this.c;
79
+ const fence = raw.match(/^\s*(```+|~~~+)\s*([\w+#.-]*)/);
80
+ if (fence && (!this.inCode || raw.trim().startsWith(this.fence))) {
81
+ const out = this.flushTable();
82
+ if (!this.inCode) {
83
+ this.inCode = true;
84
+ this.fence = fence[1];
85
+ return out + c.gray(` ╭─ ${fence[2] || 'code'}`) + '\n';
86
+ }
87
+ this.inCode = false;
88
+ return out + c.gray(' ╰─') + '\n';
89
+ }
90
+ if (this.inCode) return `${c.gray(' │ ')}${highlight(raw, c)}\n`;
91
+
92
+ if (/^\s*\|.*\|\s*$/.test(raw)) {
93
+ this.table.push(raw);
94
+ return '';
95
+ }
96
+ let out = this.flushTable();
97
+
98
+ let m;
99
+ if ((m = raw.match(/^(#{1,6})\s+(.*)$/))) {
100
+ const text = renderInline(m[2].replace(/\s+#+\s*$/, ''), c);
101
+ return out + (m[1].length === 1 ? c.bold(c.underline(c.accent(text))) : m[1].length === 2 ? c.bold(c.accent(text)) : c.bold(text)) + '\n';
102
+ }
103
+ if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(raw)) return out + c.gray('─'.repeat(Math.min(this.width, 60))) + '\n';
104
+ if ((m = raw.match(/^\s*>\s?(.*)$/))) return out + `${c.gray('│ ')}${c.italic(renderInline(m[1], c))}\n`;
105
+ if ((m = raw.match(/^(\s*)[-*+]\s+\[( |x|X)\]\s+(.*)$/))) {
106
+ const done = m[2].toLowerCase() === 'x';
107
+ return out + `${m[1]}${done ? c.green('☑') : c.gray('☐')} ${done ? c.dim(renderInline(m[3], c)) : renderInline(m[3], c)}\n`;
108
+ }
109
+ if ((m = raw.match(/^(\s*)[-*+]\s+(.*)$/))) return out + `${m[1]}${c.accent('•')} ${renderInline(m[2], c)}\n`;
110
+ if ((m = raw.match(/^(\s*)(\d+)[.)]\s+(.*)$/))) return out + `${m[1]}${c.accent(m[2] + '.')} ${renderInline(m[3], c)}\n`;
111
+ return out + renderInline(raw, c) + '\n';
112
+ }
113
+
114
+ flushTable() {
115
+ if (!this.table.length) return '';
116
+ const c = this.c;
117
+ const rows = this.table
118
+ .map((l) => l.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((cell) => renderInline(cell.trim(), c)))
119
+ .filter((cells) => !cells.every((cell) => /^:?-{2,}:?$/.test(cell.replace(ANSI, ''))));
120
+ this.table = [];
121
+ if (!rows.length) return '';
122
+ const cols = Math.max(...rows.map((r) => r.length));
123
+ const widths = Array.from({ length: cols }, (_, i) => Math.max(3, ...rows.map((r) => visibleLength(r[i] ?? ''))));
124
+ const pad = (s, w) => s + ' '.repeat(Math.max(0, w - visibleLength(s)));
125
+ const rule = (l, mid, r) => c.gray(l + widths.map((w) => '─'.repeat(w + 2)).join(mid) + r);
126
+ const lines = [rule('┌', '┬', '┐')];
127
+ rows.forEach((r, i) => {
128
+ lines.push(c.gray('│') + widths.map((w, j) => ` ${i === 0 ? c.bold(pad(r[j] ?? '', w)) : pad(r[j] ?? '', w)} `).join(c.gray('│')) + c.gray('│'));
129
+ if (i === 0 && rows.length > 1) lines.push(rule('├', '┼', '┤'));
130
+ });
131
+ lines.push(rule('└', '┴', '┘'));
132
+ return lines.join('\n') + '\n';
133
+ }
134
+ }