@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 +19 -4
- package/package.json +1 -1
- package/src/agent.js +129 -25
- package/src/cli.js +67 -17
- package/src/input.js +75 -0
- package/src/markdown.js +134 -0
- package/src/permissions.js +16 -6
- package/src/prompt.js +17 -1
- package/src/session.js +11 -0
- package/src/tools.js +173 -12
- package/src/ui.js +241 -30
package/src/permissions.js
CHANGED
|
@@ -1,17 +1,27 @@
|
|
|
1
1
|
// Modes: 'ask' prompts for each write/command; 'yolo' allows everything;
|
|
2
2
|
// 'deny' refuses anything that needs permission (non-interactive default).
|
|
3
|
+
// planMode (separate flag) blocks every tool that changes files or runs commands.
|
|
4
|
+
// Prompts are serialized, so parallel sub-agents ask one question at a time.
|
|
3
5
|
export class Permissions {
|
|
4
6
|
constructor({ ui, mode = 'ask', allow = [] }) {
|
|
5
7
|
this.ui = ui;
|
|
6
8
|
this.mode = mode;
|
|
9
|
+
this.planMode = false;
|
|
7
10
|
this.allowed = new Set(allow);
|
|
11
|
+
this.lock = Promise.resolve();
|
|
8
12
|
}
|
|
9
13
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
check(toolName, preview) {
|
|
15
|
+
const decide = async () => {
|
|
16
|
+
if (this.mode === 'yolo' || this.allowed.has(toolName)) return true;
|
|
17
|
+
if (this.mode === 'deny') return false;
|
|
18
|
+
if (preview) preview.shown = true;
|
|
19
|
+
const answer = await this.ui.confirm(preview);
|
|
20
|
+
if (answer === 'always') this.allowed.add(toolName);
|
|
21
|
+
return answer !== 'no';
|
|
22
|
+
};
|
|
23
|
+
const result = this.lock.then(decide, decide);
|
|
24
|
+
this.lock = result.catch(() => {});
|
|
25
|
+
return result;
|
|
16
26
|
}
|
|
17
27
|
}
|
package/src/prompt.js
CHANGED
|
@@ -46,7 +46,7 @@ export function loadProjectInstructions(cwd) {
|
|
|
46
46
|
});
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
-
export function buildSystemPrompt({ cwd, model }) {
|
|
49
|
+
export function buildSystemPrompt({ cwd, model, planMode = false, subagent = null }) {
|
|
50
50
|
const git = findUp(cwd, '.git');
|
|
51
51
|
const instructions = loadProjectInstructions(cwd).filter((i) => i.text.trim());
|
|
52
52
|
let prompt = `You are Arrakis, a coding agent built by Mumbrane that runs in the user's terminal. You help with software engineering: reading and changing code, running commands, debugging, and explaining.
|
|
@@ -68,11 +68,27 @@ export function buildSystemPrompt({ cwd, model }) {
|
|
|
68
68
|
- If the user denies a tool call, don't retry it; ask how they want to proceed.
|
|
69
69
|
- Never print or exfiltrate secrets such as API keys or tokens.
|
|
70
70
|
|
|
71
|
+
# Bigger tasks
|
|
72
|
+
- For work with several steps, keep a task list with todo_write: one item in_progress at a time, marked completed as soon as it's done. It shows the user where you are.
|
|
73
|
+
- Use the task tool to hand self-contained jobs to sub-agents with fresh context: searching a big codebase, researching a question, or independent pieces of work. Call it several times in one response to run sub-agents in parallel. Give each one complete instructions, since they can't see this conversation. Prefer agent_type "explore" unless the job needs edits.
|
|
74
|
+
- Use read-only tools (read_file, grep, list_files) in parallel when you need several files; they run at the same time.
|
|
75
|
+
- Use web_fetch for documentation or pages the task needs.
|
|
76
|
+
- For large changes, make them in steps and verify as you go rather than all at once.
|
|
77
|
+
|
|
71
78
|
# Style
|
|
72
79
|
- Be concise and direct. Lead with the answer or result; skip preamble.
|
|
73
80
|
- Reference code as path:line.
|
|
74
81
|
- When done, say briefly what changed and anything left unverified.`;
|
|
75
82
|
|
|
83
|
+
if (planMode) {
|
|
84
|
+
prompt += `\n\n# Plan mode is ON
|
|
85
|
+
The user wants a plan before any changes. Investigate with read-only tools (read_file, grep, list_files, web_fetch, sub-agents of type explore). Do not edit files or run commands; those tools are blocked. When you understand the problem, present a concise, concrete plan: the files to change, what changes, and how you'll verify it. Then stop and wait. The user approves by turning plan mode off with /plan.`;
|
|
86
|
+
}
|
|
87
|
+
if (subagent) {
|
|
88
|
+
prompt += `\n\n# You are a sub-agent
|
|
89
|
+
The main agent started you to do one job. You can't see its conversation and you can't ask the user anything, so work autonomously with what's in your instructions.
|
|
90
|
+
${subagent.type === 'explore' ? "You are read-only: search and read, don't try to change anything.\n" : ''}When you're done, reply with a concise report: what you found or did, with file paths and line numbers, and anything uncertain. That report is all the main agent sees, so include the details it needs.`;
|
|
91
|
+
}
|
|
76
92
|
if (instructions.length) {
|
|
77
93
|
prompt += `\n\n# Project instructions\nThese come from instruction files the user wrote. Follow them.\n`;
|
|
78
94
|
for (const { file, text } of instructions) prompt += `\n## ${file}\n${text.trim()}\n`;
|
package/src/session.js
CHANGED
|
@@ -59,12 +59,18 @@ export class Session {
|
|
|
59
59
|
return session;
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
+
// A session that lives only in memory (used by sub-agents).
|
|
63
|
+
static memory() {
|
|
64
|
+
return new Session({ id: 'memory', file: null, meta: {} });
|
|
65
|
+
}
|
|
66
|
+
|
|
62
67
|
static latest(cwd) {
|
|
63
68
|
const s = listSessions().find((x) => x.cwd === cwd);
|
|
64
69
|
return s ? Session.load(s.id) : null;
|
|
65
70
|
}
|
|
66
71
|
|
|
67
72
|
append(event) {
|
|
73
|
+
if (!this.file) return;
|
|
68
74
|
const line = JSON.stringify({ ...event, t: event.t ?? Date.now() }) + '\n';
|
|
69
75
|
const fd = fs.openSync(this.file, 'a', 0o600);
|
|
70
76
|
try {
|
|
@@ -89,6 +95,11 @@ export class Session {
|
|
|
89
95
|
this.append({ type: 'compact', messages: this.messages });
|
|
90
96
|
}
|
|
91
97
|
|
|
98
|
+
replace(messages) {
|
|
99
|
+
this.messages = messages;
|
|
100
|
+
this.append({ type: 'compact', messages });
|
|
101
|
+
}
|
|
102
|
+
|
|
92
103
|
// Every assistant tool call needs a matching tool result, or the API rejects
|
|
93
104
|
// the history. After an interrupt or crash, fill in the missing ones.
|
|
94
105
|
repair() {
|
package/src/tools.js
CHANGED
|
@@ -157,6 +157,7 @@ export const TOOLS = [
|
|
|
157
157
|
},
|
|
158
158
|
{
|
|
159
159
|
name: 'write_file',
|
|
160
|
+
writes: true,
|
|
160
161
|
description: 'Create a new file or completely overwrite an existing one. Prefer edit_file for changes to existing files.',
|
|
161
162
|
parameters: {
|
|
162
163
|
type: 'object',
|
|
@@ -182,11 +183,16 @@ export const TOOLS = [
|
|
|
182
183
|
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
183
184
|
const content = String(a.content ?? '');
|
|
184
185
|
fs.writeFileSync(p, content);
|
|
185
|
-
|
|
186
|
+
const all = content.split('\n');
|
|
187
|
+
const msg = `Wrote ${all.length} lines to ${rel(ctx, p)}`;
|
|
188
|
+
const lines = all.slice(0, 8).map((text, i) => ({ sign: '+', text, n: i + 1 }));
|
|
189
|
+
if (all.length > 8) lines.push({ sign: ' ', text: `… ${all.length - 8} more lines` });
|
|
190
|
+
return { content: msg, display: msg, lines };
|
|
186
191
|
},
|
|
187
192
|
},
|
|
188
193
|
{
|
|
189
194
|
name: 'edit_file',
|
|
195
|
+
writes: true,
|
|
190
196
|
description: 'Replace exact text in a file. old_string must match the file exactly (including whitespace) and be unique unless replace_all is true. Read the file first.',
|
|
191
197
|
parameters: {
|
|
192
198
|
type: 'object',
|
|
@@ -218,11 +224,23 @@ export const TOOLS = [
|
|
|
218
224
|
const { p, text, count } = this.validate(a, ctx);
|
|
219
225
|
const updated = a.replace_all ? text.split(a.old_string).join(a.new_string) : text.replace(a.old_string, () => a.new_string);
|
|
220
226
|
fs.writeFileSync(p, updated);
|
|
221
|
-
|
|
227
|
+
const startLine = text.slice(0, text.indexOf(a.old_string)).split('\n').length;
|
|
228
|
+
const oldLines = a.old_string.split('\n');
|
|
229
|
+
const newLines = a.new_string.split('\n');
|
|
230
|
+
const lines = [
|
|
231
|
+
...oldLines.slice(0, 12).map((t, i) => ({ sign: '-', text: t, n: startLine + i })),
|
|
232
|
+
...newLines.slice(0, 12).map((t, i) => ({ sign: '+', text: t, n: startLine + i })),
|
|
233
|
+
];
|
|
234
|
+
return {
|
|
235
|
+
content: `Edited ${rel(ctx, p)} (${a.replace_all ? count : 1} replacement${count > 1 && a.replace_all ? 's' : ''})`,
|
|
236
|
+
display: `Updated ${rel(ctx, p)} with ${newLines.length} addition${newLines.length === 1 ? '' : 's'} and ${oldLines.length} removal${oldLines.length === 1 ? '' : 's'}${a.replace_all && count > 1 ? ` (${count} places)` : ''}`,
|
|
237
|
+
lines,
|
|
238
|
+
};
|
|
222
239
|
},
|
|
223
240
|
},
|
|
224
241
|
{
|
|
225
242
|
name: 'bash',
|
|
243
|
+
writes: true,
|
|
226
244
|
description: 'Run a shell command in the working directory and return its combined stdout/stderr. Each call starts fresh in the working directory. No stdin: avoid interactive commands.',
|
|
227
245
|
parameters: {
|
|
228
246
|
type: 'object',
|
|
@@ -332,38 +350,181 @@ export const TOOLS = [
|
|
|
332
350
|
},
|
|
333
351
|
];
|
|
334
352
|
|
|
335
|
-
|
|
336
|
-
|
|
353
|
+
TOOLS.push(
|
|
354
|
+
{
|
|
355
|
+
name: 'web_fetch',
|
|
356
|
+
description: 'Fetch a URL and return its content as text (HTML is converted to readable text). Use it for documentation, issues, API references and other pages the task needs.',
|
|
357
|
+
parameters: {
|
|
358
|
+
type: 'object',
|
|
359
|
+
properties: {
|
|
360
|
+
url: { type: 'string', description: 'Full http(s) URL' },
|
|
361
|
+
max_chars: { type: 'integer', description: 'Max characters to return (default 30000)' },
|
|
362
|
+
},
|
|
363
|
+
required: ['url'],
|
|
364
|
+
},
|
|
365
|
+
needsPermission: true,
|
|
366
|
+
summary: (a) => a.url,
|
|
367
|
+
preview: (a) => ({ title: `Fetch ${a.url}`, lines: [] }),
|
|
368
|
+
async run(a, ctx) {
|
|
369
|
+
const url = new URL(a.url);
|
|
370
|
+
if (!/^https?:$/.test(url.protocol)) throw new Error('Only http and https URLs are supported.');
|
|
371
|
+
const res = await fetch(url, {
|
|
372
|
+
signal: anySignal([ctx.signal, AbortSignal.timeout(30000)]),
|
|
373
|
+
redirect: 'follow',
|
|
374
|
+
headers: { 'user-agent': 'arrakis-cli', accept: 'text/html,text/plain,application/json;q=0.9,*/*;q=0.5' },
|
|
375
|
+
});
|
|
376
|
+
const type = res.headers.get('content-type') || '';
|
|
377
|
+
if (/^(image|audio|video)\/|application\/(pdf|zip|octet-stream)/.test(type)) {
|
|
378
|
+
return { content: `URL: ${res.url}\nStatus: ${res.status}\nContent-Type: ${type}\n(binary content not shown)`, display: `${res.status} · ${type}` };
|
|
379
|
+
}
|
|
380
|
+
let text = (await res.text()).slice(0, 5_000_000);
|
|
381
|
+
if (/html/i.test(type) || /^\s*<(!doctype|html)/i.test(text)) text = htmlToText(text);
|
|
382
|
+
const body = truncate(text, a.max_chars || MAX_OUTPUT);
|
|
383
|
+
return { content: `URL: ${res.url}\nStatus: ${res.status}\n\n${body}`, display: `${res.status} · ${text.length.toLocaleString()} characters` };
|
|
384
|
+
},
|
|
385
|
+
},
|
|
386
|
+
{
|
|
387
|
+
name: 'todo_write',
|
|
388
|
+
description: 'Create or update your task list for work with several steps. Send the whole list every time. Keep exactly one item in_progress while you work, and mark each item completed as soon as it is done. Skip this for simple one-step requests.',
|
|
389
|
+
parameters: {
|
|
390
|
+
type: 'object',
|
|
391
|
+
properties: {
|
|
392
|
+
todos: {
|
|
393
|
+
type: 'array',
|
|
394
|
+
items: {
|
|
395
|
+
type: 'object',
|
|
396
|
+
properties: {
|
|
397
|
+
content: { type: 'string', description: 'What to do, in a few words' },
|
|
398
|
+
status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] },
|
|
399
|
+
},
|
|
400
|
+
required: ['content', 'status'],
|
|
401
|
+
},
|
|
402
|
+
},
|
|
403
|
+
},
|
|
404
|
+
required: ['todos'],
|
|
405
|
+
},
|
|
406
|
+
summary: (a) => {
|
|
407
|
+
const list = Array.isArray(a.todos) ? a.todos : [];
|
|
408
|
+
return `${list.filter((t) => t.status === 'completed').length}/${list.length} done`;
|
|
409
|
+
},
|
|
410
|
+
run(a, ctx) {
|
|
411
|
+
if (!Array.isArray(a.todos)) throw new Error('todos must be an array');
|
|
412
|
+
const todos = a.todos.map((t) => ({ content: String(t.content ?? ''), status: ['pending', 'in_progress', 'completed'].includes(t.status) ? t.status : 'pending' }));
|
|
413
|
+
if (ctx.agent) ctx.agent.todos = todos;
|
|
414
|
+
ctx.ui.todos(todos);
|
|
415
|
+
return { content: 'Todo list updated. Keep it current as you work.', display: null };
|
|
416
|
+
},
|
|
417
|
+
},
|
|
418
|
+
{
|
|
419
|
+
name: 'task',
|
|
420
|
+
description:
|
|
421
|
+
'Hand a self-contained job to a sub-agent that has its own fresh context window. Use it to explore or search large codebases, research a question, or do independent pieces of work in parallel: call it several times in one response and the sub-agents run at the same time. The sub-agent cannot see this conversation, so put everything it needs in prompt. It returns a report, which only you see; summarize it for the user. agent_type "explore" is read-only (search and read); "general" can also edit files and run commands.',
|
|
422
|
+
parameters: {
|
|
423
|
+
type: 'object',
|
|
424
|
+
properties: {
|
|
425
|
+
description: { type: 'string', description: 'A 3-6 word label for the job' },
|
|
426
|
+
prompt: { type: 'string', description: 'Full instructions: the goal, relevant paths, what to report back' },
|
|
427
|
+
agent_type: { type: 'string', enum: ['explore', 'general'], description: 'explore (default): read-only. general: can edit and run commands.' },
|
|
428
|
+
},
|
|
429
|
+
required: ['description', 'prompt'],
|
|
430
|
+
},
|
|
431
|
+
summary: (a) => `${a.agent_type === 'general' ? 'general' : 'explore'}: ${a.description}`,
|
|
432
|
+
async run(a, ctx) {
|
|
433
|
+
if (!ctx.agent?.runSubagent) throw new Error('Sub-agents are not available here.');
|
|
434
|
+
return ctx.agent.runSubagent(a, ctx.signal);
|
|
435
|
+
},
|
|
436
|
+
},
|
|
437
|
+
);
|
|
438
|
+
|
|
439
|
+
export const READ_ONLY_TOOLS = new Set(['read_file', 'grep', 'list_files', 'web_fetch']);
|
|
440
|
+
export const PARALLEL_SAFE = new Set(['read_file', 'grep', 'list_files', 'web_fetch', 'task']);
|
|
441
|
+
|
|
442
|
+
function anySignal(signals) {
|
|
443
|
+
const list = signals.filter(Boolean);
|
|
444
|
+
if (AbortSignal.any) return AbortSignal.any(list);
|
|
445
|
+
const ac = new AbortController();
|
|
446
|
+
for (const s of list) {
|
|
447
|
+
if (s.aborted) ac.abort(s.reason);
|
|
448
|
+
else s.addEventListener('abort', () => ac.abort(s.reason), { once: true });
|
|
449
|
+
}
|
|
450
|
+
return ac.signal;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
export function htmlToText(html) {
|
|
454
|
+
const title = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1]?.trim();
|
|
455
|
+
let t = html
|
|
456
|
+
.replace(/<(script|style|noscript|svg|template|iframe)[\s\S]*?<\/\1>/gi, '')
|
|
457
|
+
.replace(/<!--[\s\S]*?-->/g, '')
|
|
458
|
+
.replace(/<head[\s\S]*?<\/head>/i, '')
|
|
459
|
+
.replace(/<h([1-6])[^>]*>/gi, (_, n) => '\n\n' + '#'.repeat(Number(n)) + ' ')
|
|
460
|
+
.replace(/<li[^>]*>/gi, '\n- ')
|
|
461
|
+
.replace(/<(br|hr)\s*\/?>/gi, '\n')
|
|
462
|
+
.replace(/<\/(p|div|section|article|header|footer|h[1-6]|li|tr|table|ul|ol|pre|blockquote)>/gi, '\n')
|
|
463
|
+
.replace(/<(td|th)[^>]*>/gi, ' | ')
|
|
464
|
+
.replace(/<a [^>]*href="([^"#][^"]*)"[^>]*>([\s\S]*?)<\/a>/gi, (_, href, text) => `${text.replace(/<[^>]+>/g, '')} (${href})`)
|
|
465
|
+
.replace(/<[^>]+>/g, '')
|
|
466
|
+
.replace(/ /g, ' ')
|
|
467
|
+
.replace(/&/g, '&')
|
|
468
|
+
.replace(/</g, '<')
|
|
469
|
+
.replace(/>/g, '>')
|
|
470
|
+
.replace(/"/g, '"')
|
|
471
|
+
.replace(/'|'/g, "'")
|
|
472
|
+
.replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)))
|
|
473
|
+
.replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16)));
|
|
474
|
+
t = t
|
|
475
|
+
.split('\n')
|
|
476
|
+
.map((l) => l.replace(/[ \t]+/g, ' ').trim())
|
|
477
|
+
.join('\n')
|
|
478
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
479
|
+
.trim();
|
|
480
|
+
return title ? `# ${title}\n\n${t}` : t;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
export const toolSchemas = (filter = () => true) =>
|
|
484
|
+
TOOLS.filter((t) => filter(t.name)).map((t) => ({ type: 'function', function: { name: t.name, description: t.description, parameters: t.parameters } }));
|
|
337
485
|
|
|
338
486
|
export const findTool = (name) => TOOLS.find((t) => t.name === name);
|
|
339
487
|
|
|
340
488
|
// Run one tool call from the model. Always returns a string for the tool message.
|
|
489
|
+
// ctx: { cwd, signal, ui, permissions, agent, depth, label, allowed }
|
|
341
490
|
export async function executeToolCall(call, ctx) {
|
|
342
491
|
const tool = findTool(call.function?.name);
|
|
343
|
-
if (!tool
|
|
492
|
+
if (!tool || (ctx.allowed && !ctx.allowed(tool.name))) {
|
|
493
|
+
return `Error: unknown tool "${call.function?.name}".`;
|
|
494
|
+
}
|
|
344
495
|
let args;
|
|
345
496
|
try {
|
|
346
497
|
args = call.function.arguments ? JSON.parse(call.function.arguments) : {};
|
|
347
498
|
} catch {
|
|
348
499
|
return `Error: tool arguments were not valid JSON: ${String(call.function.arguments).slice(0, 200)}`;
|
|
349
500
|
}
|
|
350
|
-
|
|
501
|
+
const sub = (ctx.depth ?? 0) > 0;
|
|
502
|
+
ctx.ui.toolStart(tool.name, safe(() => tool.summary?.(args)) ?? '', { prefix: sub ? `${ctx.label}` : '' });
|
|
351
503
|
try {
|
|
352
504
|
if (tool.validate) tool.validate(args, ctx);
|
|
505
|
+
if (tool.writes && ctx.permissions.planMode) {
|
|
506
|
+
if (!sub) ctx.ui.toolResult('Blocked: plan mode is on', true);
|
|
507
|
+
return 'Blocked: plan mode is on, so files cannot be changed and commands cannot run. Finish investigating with the read-only tools, then present your plan. The user turns plan mode off with /plan when they approve.';
|
|
508
|
+
}
|
|
509
|
+
let preview = null;
|
|
353
510
|
if (tool.needsPermission) {
|
|
354
|
-
|
|
511
|
+
preview = safe(() => tool.preview?.(args, ctx));
|
|
512
|
+
if (preview && sub) preview.title = `[${ctx.label}] ${preview.title}`;
|
|
355
513
|
const allowed = await ctx.permissions.check(tool.name, preview);
|
|
356
514
|
if (!allowed) {
|
|
357
515
|
ctx.ui.toolResult('Denied', true);
|
|
358
516
|
return 'Permission denied: the user declined this tool call. Do not retry it; ask the user how to proceed.';
|
|
359
517
|
}
|
|
360
518
|
}
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
519
|
+
if (!sub) ctx.ui.startSpinner(tool.name === 'task' ? 'Agents working' : 'Running');
|
|
520
|
+
const raw = await tool.run(args, ctx);
|
|
521
|
+
const { content, display, lines } = raw && typeof raw === 'object' ? raw : { content: String(raw) };
|
|
522
|
+
// Skip the diff when the user just saw it in the approval prompt.
|
|
523
|
+
if (!sub && display !== null) ctx.ui.toolResult(display ?? content, false, { lines: preview?.shown ? null : lines });
|
|
524
|
+
return truncate(String(content));
|
|
364
525
|
} catch (err) {
|
|
365
|
-
const msg = `Error: ${err.message}`;
|
|
366
|
-
ctx.ui.toolResult(msg, true);
|
|
526
|
+
const msg = `Error: ${err.name === 'AbortError' || err.name === 'TimeoutError' ? (ctx.signal?.aborted ? 'interrupted by the user' : 'timed out') : err.message}`;
|
|
527
|
+
if (!sub) ctx.ui.toolResult(msg, true);
|
|
367
528
|
return msg;
|
|
368
529
|
}
|
|
369
530
|
}
|