@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 +54 -1
- package/package.json +1 -1
- package/src/agent.js +49 -7
- package/src/checkpoints.js +83 -0
- package/src/cli.js +346 -11
- package/src/config.js +11 -0
- package/src/hooks.js +114 -0
- package/src/input.js +71 -1
- package/src/jobs.js +97 -0
- package/src/mcp.js +343 -0
- package/src/permissions.js +5 -1
- package/src/session.js +1 -1
- package/src/tools.js +29 -5
- package/src/tui.js +812 -0
- package/src/ui.js +33 -7
- package/src/update.js +33 -0
package/src/cli.js
CHANGED
|
@@ -8,10 +8,21 @@ import { Session, listSessions } from './session.js';
|
|
|
8
8
|
import { Agent, estimateTokens } from './agent.js';
|
|
9
9
|
import { Permissions } from './permissions.js';
|
|
10
10
|
import { UI, colors } from './ui.js';
|
|
11
|
+
import { FancyUI } from './tui.js';
|
|
11
12
|
import { TOOLS } from './tools.js';
|
|
12
13
|
import { loadProjectInstructions } from './prompt.js';
|
|
13
14
|
import { VERSION } from './version.js';
|
|
14
|
-
import { expandMentions, loadCustomCommands, renderCommand, INIT_PROMPT } from './input.js';
|
|
15
|
+
import { expandMentions, buildMessage, pasteClipboardImage, loadCustomCommands, renderCommand, INIT_PROMPT } from './input.js';
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import os from 'node:os';
|
|
19
|
+
import { Checkpoints } from './checkpoints.js';
|
|
20
|
+
import { connectAll, mcpTools, loadMcpConfig, mcpConfigFiles } from './mcp.js';
|
|
21
|
+
import { Hooks, loadHooks, projectHasHooks, projectSettingsFile } from './hooks.js';
|
|
22
|
+
import { startJob, listJobs, findJob, stopJob, readLog, updateJob, jobLog } from './jobs.js';
|
|
23
|
+
import { checkForUpdate } from './update.js';
|
|
24
|
+
import { setExtraTools } from './tools.js';
|
|
25
|
+
import { isTrustedProject, trustProject, HOME_DIR } from './config.js';
|
|
15
26
|
|
|
16
27
|
const HELP = `arrakis ${VERSION} — a coding agent for your terminal
|
|
17
28
|
|
|
@@ -22,6 +33,11 @@ Usage
|
|
|
22
33
|
arrakis -r <id> Resume a session by id (or id prefix)
|
|
23
34
|
arrakis setup Choose a provider, enter an API key and pick a model
|
|
24
35
|
arrakis models List the models your provider offers
|
|
36
|
+
arrakis bg "task" Run a task in the background (add --yolo or --allow to let it edit)
|
|
37
|
+
arrakis jobs [log|stop <id>] List background jobs, read a job's log, or stop one
|
|
38
|
+
arrakis mcp Show MCP servers and their tools
|
|
39
|
+
arrakis mcp add <name> -- <command...> Add a local MCP server (or: --url <url>)
|
|
40
|
+
arrakis mcp remove <name> Remove an MCP server
|
|
25
41
|
arrakis sessions List recent sessions
|
|
26
42
|
arrakis config Show configuration
|
|
27
43
|
arrakis config set <key> <v> Set a value (provider, baseUrl, apiKey, model, contextWindow, maxTokens)
|
|
@@ -45,6 +61,10 @@ const SLASH_HELP = `/help Show commands
|
|
|
45
61
|
/plan Toggle plan mode: investigate and propose a plan, change nothing
|
|
46
62
|
/init Write ARRAKIS.md project notes for this folder
|
|
47
63
|
/todos Show the current task list
|
|
64
|
+
/undo [n] Revert arrakis's file changes from the last turn (or back to turn n)
|
|
65
|
+
/paste Attach the image on your clipboard to your next message
|
|
66
|
+
/mcp Show connected MCP servers and tools
|
|
67
|
+
/bg <task> Start a background job; /jobs to check on it
|
|
48
68
|
/clear Start a new session
|
|
49
69
|
/compact Summarize history to free up context
|
|
50
70
|
/model [name] Pick a model from your provider (or set one by name)
|
|
@@ -62,6 +82,9 @@ export async function main(argv) {
|
|
|
62
82
|
if (argv[0] === 'sessions') return sessionsCommand();
|
|
63
83
|
if (argv[0] === 'setup' || argv[0] === 'login') return setupCommand();
|
|
64
84
|
if (argv[0] === 'models') return modelsCommand();
|
|
85
|
+
if (argv[0] === 'bg') return bgCommand(argv.slice(1));
|
|
86
|
+
if (argv[0] === 'jobs') return jobsCommand(argv.slice(1));
|
|
87
|
+
if (argv[0] === 'mcp') return mcpCommand(argv.slice(1));
|
|
65
88
|
if (argv[0] === 'logout') {
|
|
66
89
|
removeProviderKeys();
|
|
67
90
|
return console.log(`Removed saved API keys from ${CONFIG_PATH}`);
|
|
@@ -92,7 +115,7 @@ export async function main(argv) {
|
|
|
92
115
|
|
|
93
116
|
const cwd = process.cwd();
|
|
94
117
|
let config = loadConfig({ model: values.model, baseUrl: values['base-url'] });
|
|
95
|
-
const ui = new UI({ print });
|
|
118
|
+
const ui = !print && process.stdin.isTTY && process.stdout.isTTY && process.env.ARRAKIS_SIMPLE_UI !== '1' ? new FancyUI() : new UI({ print });
|
|
96
119
|
const prompts = createPrompts(ui);
|
|
97
120
|
if (!config.configured) {
|
|
98
121
|
if (print) throw new Error('arrakis is not set up yet. Run `arrakis` once to choose a provider and enter an API key.');
|
|
@@ -113,29 +136,150 @@ export async function main(argv) {
|
|
|
113
136
|
session = Session.latest(cwd);
|
|
114
137
|
if (!session) throw new Error(`No previous session in ${cwd}. Start one with: arrakis`);
|
|
115
138
|
} else session = Session.create({ cwd, model: config.model });
|
|
139
|
+
if (process.env.ARRAKIS_JOB_ID) updateJob(process.env.ARRAKIS_JOB_ID, { sessionId: session.id });
|
|
116
140
|
|
|
117
141
|
const permissions = new Permissions({
|
|
118
142
|
ui,
|
|
119
143
|
mode: values.yolo ? 'yolo' : print ? 'deny' : 'ask',
|
|
120
144
|
allow: values.allow ? values.allow.split(',').map((s) => s.trim()).filter(Boolean) : [],
|
|
121
145
|
});
|
|
122
|
-
|
|
146
|
+
|
|
147
|
+
// Project MCP servers and hooks run commands, so ask before trusting a folder.
|
|
148
|
+
const trusted = await checkProjectTrust({ cwd, ui, prompts, print });
|
|
149
|
+
const mcpServers = await connectMcp({ cwd, ui, includeProject: trusted });
|
|
150
|
+
const hookSet = new Hooks(loadHooks(cwd, { includeProject: trusted }), { cwd, ui });
|
|
151
|
+
const agent = new Agent({ config, session, ui, permissions, cwd, checkpoints: new Checkpoints(session.file), hooks: hookSet.count ? hookSet : null });
|
|
123
152
|
|
|
124
153
|
if (print) {
|
|
125
154
|
process.on('SIGINT', () => {
|
|
126
155
|
agent.interrupt();
|
|
127
156
|
process.exit(130);
|
|
128
157
|
});
|
|
129
|
-
const
|
|
158
|
+
const { content, errors } = buildMessage(prompt, cwd);
|
|
159
|
+
for (const e of errors) ui.error(e);
|
|
160
|
+
const ok = await agent.send(content);
|
|
161
|
+
mcpServers.forEach((s) => s.close());
|
|
162
|
+
if (process.env.ARRAKIS_JOB_ID) updateJob(process.env.ARRAKIS_JOB_ID, { status: ok ? 'done' : 'failed', finished: Date.now() });
|
|
130
163
|
process.exitCode = ok ? 0 : 1;
|
|
131
164
|
return;
|
|
132
165
|
}
|
|
133
|
-
await interactive({ agent, ui, prompts, config, cwd, firstPrompt: prompt });
|
|
166
|
+
await interactive({ agent, ui, prompts, config, cwd, firstPrompt: prompt, mcpServers, hooks: hookSet.count });
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async function checkProjectTrust({ cwd, ui, prompts, print }) {
|
|
170
|
+
const { projectFiles } = loadMcpConfig(cwd, { includeProject: true });
|
|
171
|
+
const hasHooks = projectHasHooks(cwd);
|
|
172
|
+
if (!projectFiles.length && !hasHooks) return true;
|
|
173
|
+
if (isTrustedProject(cwd)) return true;
|
|
174
|
+
if (cwd === os.homedir()) return false;
|
|
175
|
+
const what = [...projectFiles.map((f) => path.relative(cwd, f)), ...(hasHooks ? [path.relative(cwd, projectSettingsFile(cwd)) + ' (hooks)'] : [])];
|
|
176
|
+
if (print) {
|
|
177
|
+
ui.info(`Skipping project MCP servers/hooks in ${what.join(', ')} (not trusted yet; run arrakis here once to allow them).`);
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
ui.start();
|
|
181
|
+
const { servers } = loadMcpConfig(cwd, { includeProject: true });
|
|
182
|
+
const c = ui.c;
|
|
183
|
+
ui.write(ui.out, `\n${c.yellow('!')} ${c.bold('This folder configures tools that run commands on your computer:')}\n`);
|
|
184
|
+
for (const [name, cfg] of Object.entries(servers)) {
|
|
185
|
+
if (!projectFiles.includes(cfg.source)) continue;
|
|
186
|
+
ui.write(ui.out, ` ${c.bold(name)} ${c.gray(cfg.url ?? [cfg.command, ...(cfg.args ?? [])].join(' '))}\n`);
|
|
187
|
+
}
|
|
188
|
+
if (hasHooks) ui.write(ui.out, ` ${c.bold('hooks')} ${c.gray(path.relative(cwd, projectSettingsFile(cwd)))}\n`);
|
|
189
|
+
const answer = await prompts.select({
|
|
190
|
+
title: 'Allow them?',
|
|
191
|
+
items: [
|
|
192
|
+
{ label: 'Yes, trust this folder', value: 'yes' },
|
|
193
|
+
{ label: 'No, not this time', value: 'no' },
|
|
194
|
+
],
|
|
195
|
+
initial: 1,
|
|
196
|
+
});
|
|
197
|
+
if (answer === 'yes') {
|
|
198
|
+
trustProject(cwd);
|
|
199
|
+
return true;
|
|
200
|
+
}
|
|
201
|
+
return false;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function connectMcp({ cwd, ui, includeProject }) {
|
|
205
|
+
const { servers } = loadMcpConfig(cwd, { includeProject });
|
|
206
|
+
if (!Object.keys(servers).length) return [];
|
|
207
|
+
ui.startSpinner('Connecting MCP servers');
|
|
208
|
+
const list = await connectAll(cwd, { includeProject });
|
|
209
|
+
ui.stopSpinner();
|
|
210
|
+
setExtraTools(mcpTools(list));
|
|
211
|
+
for (const s of list) if (s.status === 'failed') ui.error(`MCP server "${s.name}" failed to start: ${s.error}`);
|
|
212
|
+
return list;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function gitBranch(cwd) {
|
|
216
|
+
let dir = cwd;
|
|
217
|
+
while (true) {
|
|
218
|
+
try {
|
|
219
|
+
const head = fs.readFileSync(path.join(dir, '.git', 'HEAD'), 'utf8').trim();
|
|
220
|
+
return head.startsWith('ref: refs/heads/') ? head.slice(16) : head.slice(0, 7);
|
|
221
|
+
} catch {}
|
|
222
|
+
const parent = path.dirname(dir);
|
|
223
|
+
if (parent === dir) return null;
|
|
224
|
+
dir = parent;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function completer(line, cwd, commands) {
|
|
229
|
+
if (/^\/\S*$/.test(line)) {
|
|
230
|
+
const hits = commands.filter((c) => c.startsWith(line));
|
|
231
|
+
return [hits.length ? hits : commands, line];
|
|
232
|
+
}
|
|
233
|
+
const m = line.match(/@([^\s]*)$/);
|
|
234
|
+
if (m) {
|
|
235
|
+
const partial = m[1];
|
|
236
|
+
const dirPart = partial.includes('/') ? partial.slice(0, partial.lastIndexOf('/') + 1) : '';
|
|
237
|
+
const base = partial.slice(dirPart.length);
|
|
238
|
+
try {
|
|
239
|
+
const entries = fs.readdirSync(path.resolve(cwd, dirPart || '.'), { withFileTypes: true })
|
|
240
|
+
.filter((e) => e.name.startsWith(base) && (base.startsWith('.') || !e.name.startsWith('.')) && e.name !== 'node_modules')
|
|
241
|
+
.map((e) => `@${dirPart}${e.name}${e.isDirectory() ? '/' : ''}`)
|
|
242
|
+
.sort();
|
|
243
|
+
return [entries, `@${partial}`];
|
|
244
|
+
} catch {
|
|
245
|
+
return [[], `@${partial}`];
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return [[], line];
|
|
134
249
|
}
|
|
135
250
|
|
|
136
|
-
|
|
251
|
+
const BUILTIN_COMMANDS = ['/help', '/plan', '/init', '/todos', '/undo', '/paste', '/mcp', '/bg', '/jobs', '/clear', '/compact', '/model', '/provider', '/sessions', '/status', '/yolo', '/exit'];
|
|
252
|
+
|
|
253
|
+
async function interactive({ agent, ui, prompts, config, cwd, firstPrompt, mcpServers = [], hooks = 0 }) {
|
|
137
254
|
const c = ui.c;
|
|
255
|
+
ui.historyFile = path.join(HOME_DIR, 'history');
|
|
256
|
+
ui.completer = (line) => completer(line, cwd, [...BUILTIN_COMMANDS, ...[...loadCustomCommands(cwd).keys()].map((k) => `/${k}`)]);
|
|
257
|
+
// Recreate the line reader so it picks up completion and history.
|
|
258
|
+
if (ui instanceof FancyUI) {
|
|
259
|
+
ui.cwd = cwd;
|
|
260
|
+
const descriptions = Object.fromEntries(SLASH_HELP.split('\n').filter((l) => l.startsWith('/')).map((l) => [l.slice(1).split(/\s/)[0], l.replace(/^\/\S+(\s+\[[^\]]*\]|\s+<[^>]*>)?\s+/, '')]));
|
|
261
|
+
ui.commandList = () => [
|
|
262
|
+
...BUILTIN_COMMANDS.map((c) => ({ name: c.slice(1), description: descriptions[c.slice(1)] ?? '' })),
|
|
263
|
+
...[...loadCustomCommands(cwd).values()].map((c) => ({ name: c.name, description: c.description })),
|
|
264
|
+
];
|
|
265
|
+
const p = agent.permissions;
|
|
266
|
+
ui.onCycleMode = () => {
|
|
267
|
+
if (p.planMode) p.planMode = false;
|
|
268
|
+
else if (p.acceptEdits) {
|
|
269
|
+
p.acceptEdits = false;
|
|
270
|
+
p.planMode = true;
|
|
271
|
+
} else p.acceptEdits = true;
|
|
272
|
+
};
|
|
273
|
+
ui.modeLabel = () =>
|
|
274
|
+
p.planMode ? `${c.accent('⏸ plan mode on')} ${c.gray('(shift+tab to cycle)')}`
|
|
275
|
+
: p.acceptEdits ? `${c.accent('⏵⏵ accept edits on')} ${c.gray('(shift+tab to cycle)')}`
|
|
276
|
+
: p.mode === 'yolo' ? `${c.red('⏵⏵ yolo: everything runs without asking')}`
|
|
277
|
+
: '';
|
|
278
|
+
p.onDeny = () => agent.interrupt();
|
|
279
|
+
} else if (ui.fancy) ui.suspend();
|
|
138
280
|
ui.start();
|
|
281
|
+
const update = await checkForUpdate().catch(() => null);
|
|
282
|
+
const state = { pastedImages: [], jobsSeen: new Map(listJobs().map((j) => [j.id, j.status])), mcpServers };
|
|
139
283
|
let armedExit = false;
|
|
140
284
|
ui.onInterrupt(() => {
|
|
141
285
|
if (agent.busy) return agent.interrupt();
|
|
@@ -152,7 +296,10 @@ async function interactive({ agent, ui, prompts, config, cwd, firstPrompt }) {
|
|
|
152
296
|
};
|
|
153
297
|
ui.statusLine = () => {
|
|
154
298
|
const used = Math.round((estimateTokens(agent.session.messages) / config.contextWindow) * 100);
|
|
299
|
+
const branch = gitBranch(cwd);
|
|
300
|
+
if (ui instanceof FancyUI) return [config.model, branch ? `⎇ ${branch}` : '', `${used}% context`].filter(Boolean).join(' · ');
|
|
155
301
|
const parts = [config.model, `${used}% context`];
|
|
302
|
+
if (branch) parts.push(`⎇ ${branch}`);
|
|
156
303
|
if (agent.permissions.planMode) parts.push('plan mode');
|
|
157
304
|
if (agent.permissions.mode === 'yolo') parts.push('yolo');
|
|
158
305
|
parts.push('/help');
|
|
@@ -166,23 +313,40 @@ async function interactive({ agent, ui, prompts, config, cwd, firstPrompt }) {
|
|
|
166
313
|
cwd,
|
|
167
314
|
instructions: loadProjectInstructions(cwd).filter((i) => i.text.trim()).map((i) => i.file),
|
|
168
315
|
resumed: agent.session.messages.length ? `resumed ${agent.session.id} (${agent.session.messages.length} messages)` : '',
|
|
316
|
+
mcp: mcpServers,
|
|
317
|
+
hooks,
|
|
318
|
+
update,
|
|
169
319
|
});
|
|
170
320
|
|
|
171
321
|
const send = async (text) => {
|
|
172
|
-
const {
|
|
322
|
+
const { content, attached, errors } = buildMessage(text, cwd, state.pastedImages.splice(0));
|
|
323
|
+
for (const e of errors) ui.error(e);
|
|
173
324
|
if (attached.length) ui.info(` Attached ${attached.join(', ')}`);
|
|
174
|
-
await agent.send(
|
|
325
|
+
await agent.send(content);
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
// Mention background jobs that finished since the last prompt.
|
|
329
|
+
const reportJobs = () => {
|
|
330
|
+
for (const job of listJobs()) {
|
|
331
|
+
const before = state.jobsSeen.get(job.id);
|
|
332
|
+
if (before === 'running' && job.status !== 'running') {
|
|
333
|
+
ui.info(`${job.status === 'done' ? '✓' : '✗'} Background job ${job.id} ${job.status}: ${job.prompt.slice(0, 60)} (arrakis jobs log ${job.id})`);
|
|
334
|
+
}
|
|
335
|
+
state.jobsSeen.set(job.id, job.status);
|
|
336
|
+
}
|
|
175
337
|
};
|
|
176
338
|
|
|
177
339
|
if (firstPrompt) await send(firstPrompt);
|
|
178
340
|
while (true) {
|
|
341
|
+
reportJobs();
|
|
179
342
|
const line = await ui.prompt();
|
|
180
343
|
if (line === null) break;
|
|
181
344
|
armedExit = false;
|
|
182
345
|
const text = line.trim();
|
|
183
346
|
if (!text) continue;
|
|
184
|
-
|
|
185
|
-
|
|
347
|
+
// "/name args" is a command; "/Users/me/shot.png what's this?" is a dragged-in path.
|
|
348
|
+
if (/^\/[\w-]+(\s|$)/.test(text) && !/^\/[\w-]+\//.test(text)) {
|
|
349
|
+
const result = await slashCommand(text, { agent, ui, prompts, config, cwd, state });
|
|
186
350
|
if (result === 'exit') break;
|
|
187
351
|
if (result?.send) await send(result.send);
|
|
188
352
|
continue;
|
|
@@ -190,10 +354,11 @@ async function interactive({ agent, ui, prompts, config, cwd, firstPrompt }) {
|
|
|
190
354
|
await send(text);
|
|
191
355
|
}
|
|
192
356
|
ui.close();
|
|
357
|
+
state.mcpServers.forEach((s) => s.close());
|
|
193
358
|
ui.write(ui.out, c.gray(`\nSession saved. Resume with: arrakis -r ${agent.session.id}\n`));
|
|
194
359
|
}
|
|
195
360
|
|
|
196
|
-
async function slashCommand(text, { agent, ui, prompts, config, cwd }) {
|
|
361
|
+
async function slashCommand(text, { agent, ui, prompts, config, cwd, state }) {
|
|
197
362
|
const [cmd, ...rest] = text.slice(1).split(/\s+/);
|
|
198
363
|
const arg = rest.join(' ');
|
|
199
364
|
const c = ui.c;
|
|
@@ -217,6 +382,72 @@ async function slashCommand(text, { agent, ui, prompts, config, cwd }) {
|
|
|
217
382
|
break;
|
|
218
383
|
case 'init':
|
|
219
384
|
return { send: INIT_PROMPT };
|
|
385
|
+
case 'undo': {
|
|
386
|
+
const turns = agent.checkpoints?.list() ?? [];
|
|
387
|
+
if (!turns.length) {
|
|
388
|
+
ui.info('Nothing to undo: arrakis has not changed any files in this session. (Changes made by shell commands are not tracked.)');
|
|
389
|
+
break;
|
|
390
|
+
}
|
|
391
|
+
let target = turns.at(-1).id;
|
|
392
|
+
if (arg) {
|
|
393
|
+
target = Number(arg);
|
|
394
|
+
if (!turns.some((t) => t.id === target)) {
|
|
395
|
+
ui.error(`No turn ${arg}. Turns with changes: ${turns.map((t) => t.id).join(', ')}`);
|
|
396
|
+
break;
|
|
397
|
+
}
|
|
398
|
+
} else if (turns.length > 1) {
|
|
399
|
+
const pick = await prompts.select({
|
|
400
|
+
title: 'Undo back to before',
|
|
401
|
+
items: [...turns].reverse().map((t) => ({ label: `${t.label || '(turn)'}`, value: t.id, hint: `${t.files.length} file${t.files.length === 1 ? '' : 's'} · ${new Date(t.time).toLocaleTimeString()}` })),
|
|
402
|
+
});
|
|
403
|
+
if (pick === null) break;
|
|
404
|
+
target = pick;
|
|
405
|
+
}
|
|
406
|
+
const restored = agent.checkpoints.undo(target);
|
|
407
|
+
for (const r of restored) ui.write(ui.log, ` ${c.green('↺')} ${r.action} ${path.relative(cwd, r.file) || r.file}\n`);
|
|
408
|
+
agent.notes.push(`[The user undid your file changes${restored.length ? ` to: ${restored.map((r) => path.relative(cwd, r.file)).join(', ')}` : ''}. Those files are back to how they were before. Re-read them before editing again.]`);
|
|
409
|
+
ui.success(`Reverted ${restored.length} file${restored.length === 1 ? '' : 's'}.`);
|
|
410
|
+
break;
|
|
411
|
+
}
|
|
412
|
+
case 'paste': {
|
|
413
|
+
const { file, error } = pasteClipboardImage();
|
|
414
|
+
if (error) ui.error(error);
|
|
415
|
+
else {
|
|
416
|
+
state.pastedImages.push(file);
|
|
417
|
+
ui.success('Image from clipboard will be attached to your next message.');
|
|
418
|
+
}
|
|
419
|
+
break;
|
|
420
|
+
}
|
|
421
|
+
case 'mcp': {
|
|
422
|
+
const servers = state.mcpServers;
|
|
423
|
+
if (!servers.length) {
|
|
424
|
+
ui.info(`No MCP servers configured. Add one with: arrakis mcp add <name> -- <command>\nConfig files: ${[...mcpConfigFiles(cwd).user, ...mcpConfigFiles(cwd).project].join(', ')}`);
|
|
425
|
+
break;
|
|
426
|
+
}
|
|
427
|
+
for (const s of servers) {
|
|
428
|
+
ui.write(ui.out, `${s.status === 'connected' ? c.green('●') : c.red('●')} ${c.bold(s.name)} ${c.gray(s.status === 'connected' ? `${s.tools.length} tools` : s.error)}\n`);
|
|
429
|
+
if (s.status === 'connected') ui.write(ui.out, c.gray(` ${s.tools.map((t) => t.name).join(', ')}\n`));
|
|
430
|
+
}
|
|
431
|
+
break;
|
|
432
|
+
}
|
|
433
|
+
case 'bg': {
|
|
434
|
+
if (!arg) {
|
|
435
|
+
ui.info('Usage: /bg <task>. The job runs in the background; check it with /jobs.');
|
|
436
|
+
break;
|
|
437
|
+
}
|
|
438
|
+
const flags = agent.permissions.mode === 'yolo' ? ['--yolo'] : agent.permissions.allowed.size ? ['--allow', [...agent.permissions.allowed].join(',')] : [];
|
|
439
|
+
const job = startJob({ prompt: arg, cwd, flags });
|
|
440
|
+
state.jobsSeen.set(job.id, 'running');
|
|
441
|
+
ui.success(`Started background job ${job.id}.${flags.length ? '' : ' It can read and search but not change files (start arrakis with --yolo, or answer "always" to a tool, to let jobs edit).'}`);
|
|
442
|
+
break;
|
|
443
|
+
}
|
|
444
|
+
case 'jobs': {
|
|
445
|
+
const jobs = listJobs().slice(0, 10);
|
|
446
|
+
if (!jobs.length) ui.info('No background jobs. Start one with /bg <task>.');
|
|
447
|
+
for (const j of jobs) ui.write(ui.out, `${jobMark(j, c)} ${c.bold(j.id)} ${c.gray(j.status)} ${j.prompt.slice(0, 70)}\n`);
|
|
448
|
+
if (jobs.length) ui.info('Read a log with: arrakis jobs log <id>');
|
|
449
|
+
break;
|
|
450
|
+
}
|
|
220
451
|
case 'todos':
|
|
221
452
|
if (agent.todos.length) ui.todos(agent.todos);
|
|
222
453
|
else ui.info('No task list yet. arrakis makes one for multi-step work.');
|
|
@@ -226,6 +457,7 @@ async function slashCommand(text, { agent, ui, prompts, config, cwd }) {
|
|
|
226
457
|
return 'exit';
|
|
227
458
|
case 'clear':
|
|
228
459
|
agent.session = Session.create({ cwd, model: config.model });
|
|
460
|
+
agent.checkpoints = new Checkpoints(agent.session.file);
|
|
229
461
|
ui.info(`Started new session ${agent.session.id}.`);
|
|
230
462
|
break;
|
|
231
463
|
case 'compact': {
|
|
@@ -360,6 +592,109 @@ function printSessions(stream, limit) {
|
|
|
360
592
|
stream.write(c.dim('\nResume with: arrakis -r <id>\n'));
|
|
361
593
|
}
|
|
362
594
|
|
|
595
|
+
const jobMark = (j, c) => (j.status === 'running' ? c.accent('●') : j.status === 'done' ? c.green('✓') : c.red('✗'));
|
|
596
|
+
|
|
597
|
+
function bgCommand(args) {
|
|
598
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { yolo: { type: 'boolean' }, allow: { type: 'string' } } });
|
|
599
|
+
const prompt = positionals.join(' ').trim();
|
|
600
|
+
if (!prompt) throw new Error('Usage: arrakis bg [--yolo | --allow edit_file,bash] "task"');
|
|
601
|
+
const flags = values.yolo ? ['--yolo'] : values.allow ? ['--allow', values.allow] : [];
|
|
602
|
+
const job = startJob({ prompt, cwd: process.cwd(), flags });
|
|
603
|
+
console.log(`Started ${job.id} (pid ${job.pid}).`);
|
|
604
|
+
if (!flags.length) console.log('It can read and search but not change files. Add --yolo or --allow to let it edit.');
|
|
605
|
+
console.log(`Follow it with: arrakis jobs log ${job.id} -f`);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
async function jobsCommand(args) {
|
|
609
|
+
const c = colors(process.stdout);
|
|
610
|
+
const [sub, id, flag] = args;
|
|
611
|
+
if (sub === 'log') {
|
|
612
|
+
if (!id) throw new Error('Usage: arrakis jobs log <id> [-f]');
|
|
613
|
+
const job = findJob(id);
|
|
614
|
+
process.stdout.write(readLog(job.id));
|
|
615
|
+
if (flag === '-f' || flag === '--follow') {
|
|
616
|
+
let size = fs.statSync(jobLog(job.id)).size;
|
|
617
|
+
while (findJob(job.id).status === 'running') {
|
|
618
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
619
|
+
const now = fs.statSync(jobLog(job.id)).size;
|
|
620
|
+
if (now > size) {
|
|
621
|
+
const fd = fs.openSync(jobLog(job.id), 'r');
|
|
622
|
+
const buf = Buffer.alloc(now - size);
|
|
623
|
+
fs.readSync(fd, buf, 0, buf.length, size);
|
|
624
|
+
fs.closeSync(fd);
|
|
625
|
+
process.stdout.write(buf);
|
|
626
|
+
size = now;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
const final = findJob(job.id);
|
|
631
|
+
if (final.sessionId) console.log(c.gray(`\n[${final.status}] Continue the conversation with: arrakis -r ${final.sessionId}`));
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
if (sub === 'stop') {
|
|
635
|
+
if (!id) throw new Error('Usage: arrakis jobs stop <id>');
|
|
636
|
+
const job = stopJob(id);
|
|
637
|
+
return console.log(`Stopped ${job.id}.`);
|
|
638
|
+
}
|
|
639
|
+
const jobs = listJobs();
|
|
640
|
+
if (!jobs.length) return console.log('No background jobs. Start one with: arrakis bg "task"');
|
|
641
|
+
for (const j of jobs.slice(0, 20)) {
|
|
642
|
+
console.log(`${jobMark(j, c)} ${c.bold(j.id)} ${c.gray(`${j.status} · ${new Date(j.started).toLocaleString()}`)}\n ${j.prompt.slice(0, 90)}\n ${c.gray(j.cwd)}`);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
async function mcpCommand(args) {
|
|
647
|
+
const c = colors(process.stdout);
|
|
648
|
+
const file = path.join(HOME_DIR, 'mcp.json');
|
|
649
|
+
const read = () => {
|
|
650
|
+
try {
|
|
651
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
652
|
+
} catch {
|
|
653
|
+
return { mcpServers: {} };
|
|
654
|
+
}
|
|
655
|
+
};
|
|
656
|
+
const write = (json) => {
|
|
657
|
+
fs.mkdirSync(HOME_DIR, { recursive: true });
|
|
658
|
+
fs.writeFileSync(file, JSON.stringify(json, null, 2) + '\n', { mode: 0o600 });
|
|
659
|
+
};
|
|
660
|
+
const [sub, name, ...rest] = args;
|
|
661
|
+
if (sub === 'add') {
|
|
662
|
+
if (!name) throw new Error('Usage: arrakis mcp add <name> -- <command> [args...] or arrakis mcp add <name> --url <url>');
|
|
663
|
+
const json = read();
|
|
664
|
+
json.mcpServers ??= {};
|
|
665
|
+
const urlAt = rest.indexOf('--url');
|
|
666
|
+
if (urlAt >= 0) json.mcpServers[name] = { url: rest[urlAt + 1] };
|
|
667
|
+
else {
|
|
668
|
+
const cmd = rest[0] === '--' ? rest.slice(1) : rest;
|
|
669
|
+
if (!cmd.length) throw new Error('Give the command that starts the server after --, e.g. arrakis mcp add github -- npx -y @modelcontextprotocol/server-github');
|
|
670
|
+
json.mcpServers[name] = { command: cmd[0], args: cmd.slice(1) };
|
|
671
|
+
}
|
|
672
|
+
write(json);
|
|
673
|
+
return console.log(`Added MCP server "${name}" to ${file}. Add any keys it needs under "env" (or "headers" for a URL) in that file.`);
|
|
674
|
+
}
|
|
675
|
+
if (sub === 'remove') {
|
|
676
|
+
const json = read();
|
|
677
|
+
if (!json.mcpServers?.[name]) throw new Error(`No MCP server "${name}" in ${file}`);
|
|
678
|
+
delete json.mcpServers[name];
|
|
679
|
+
write(json);
|
|
680
|
+
return console.log(`Removed "${name}".`);
|
|
681
|
+
}
|
|
682
|
+
const cwd = process.cwd();
|
|
683
|
+
const trusted = isTrustedProject(cwd);
|
|
684
|
+
const { servers } = loadMcpConfig(cwd, { includeProject: trusted });
|
|
685
|
+
if (!Object.keys(servers).length) {
|
|
686
|
+
return console.log(`No MCP servers configured.\nAdd one: arrakis mcp add <name> -- <command>\nConfig files: ${[...mcpConfigFiles(cwd).user, ...mcpConfigFiles(cwd).project].join(', ')}`);
|
|
687
|
+
}
|
|
688
|
+
console.log(c.gray('Connecting…'));
|
|
689
|
+
const list = await connectAll(cwd, { includeProject: trusted });
|
|
690
|
+
for (const s of list) {
|
|
691
|
+
console.log(`${s.status === 'connected' ? c.green('●') : c.red('●')} ${c.bold(s.name)} ${c.gray(servers[s.name].source)}`);
|
|
692
|
+
if (s.status === 'connected') for (const t of s.tools) console.log(` ${t.name}${t.description ? c.gray(` · ${t.description.split('\n')[0].slice(0, 80)}`) : ''}`);
|
|
693
|
+
else console.log(c.red(` ${s.error}`));
|
|
694
|
+
}
|
|
695
|
+
list.forEach((s) => s.close());
|
|
696
|
+
}
|
|
697
|
+
|
|
363
698
|
async function readStdin() {
|
|
364
699
|
let data = '';
|
|
365
700
|
for await (const chunk of process.stdin) data += chunk;
|
package/src/config.js
CHANGED
|
@@ -131,3 +131,14 @@ export function maskSecret(value) {
|
|
|
131
131
|
if (!value) return '(not set)';
|
|
132
132
|
return value.length <= 10 ? '****' : `${value.slice(0, 6)}…${value.slice(-4)}`;
|
|
133
133
|
}
|
|
134
|
+
|
|
135
|
+
// Projects whose own MCP servers and hooks the user has allowed to run.
|
|
136
|
+
export function isTrustedProject(dir) {
|
|
137
|
+
return (readConfigFile().trustedProjects ?? []).includes(path.resolve(dir));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function trustProject(dir) {
|
|
141
|
+
const file = readConfigFile();
|
|
142
|
+
file.trustedProjects = [...new Set([...(file.trustedProjects ?? []), path.resolve(dir)])];
|
|
143
|
+
writeConfigFile(file);
|
|
144
|
+
}
|
package/src/hooks.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Hooks: your own shell commands that run at points in the agent's work.
|
|
2
|
+
//
|
|
3
|
+
// In ~/.arrakis/config.json (yours) or <project>/.arrakis/settings.json
|
|
4
|
+
// (asks before first use):
|
|
5
|
+
// {
|
|
6
|
+
// "hooks": {
|
|
7
|
+
// "PreToolUse": [{ "matcher": "bash", "command": "./scripts/check-command.sh" }],
|
|
8
|
+
// "PostToolUse": [{ "matcher": "edit_file|write_file", "command": "npx prettier --write \"$ARRAKIS_FILE\"" }],
|
|
9
|
+
// "UserPromptSubmit": [{ "command": "echo \"Current branch: $(git branch --show-current)\"" }],
|
|
10
|
+
// "Stop": [{ "command": "say done" }]
|
|
11
|
+
// }
|
|
12
|
+
// }
|
|
13
|
+
//
|
|
14
|
+
// Each command gets a JSON description of the event on stdin, plus
|
|
15
|
+
// ARRAKIS_EVENT, ARRAKIS_TOOL and ARRAKIS_FILE in its environment.
|
|
16
|
+
// - PreToolUse: exit code 2 blocks the tool; stderr is shown to the model as the reason.
|
|
17
|
+
// - UserPromptSubmit: stdout is added to the message as context; exit 2 blocks the message.
|
|
18
|
+
// - Other non-zero exits are reported as warnings.
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import { spawn } from 'node:child_process';
|
|
22
|
+
import { readConfigFile } from './config.js';
|
|
23
|
+
|
|
24
|
+
export const HOOK_EVENTS = ['PreToolUse', 'PostToolUse', 'UserPromptSubmit', 'Stop'];
|
|
25
|
+
|
|
26
|
+
export function projectSettingsFile(cwd) {
|
|
27
|
+
return path.join(cwd, '.arrakis', 'settings.json');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function loadHooks(cwd, { includeProject }) {
|
|
31
|
+
const hooks = Object.fromEntries(HOOK_EVENTS.map((e) => [e, []]));
|
|
32
|
+
const add = (source, defs) => {
|
|
33
|
+
for (const event of HOOK_EVENTS) for (const h of defs?.[event] ?? []) if (h?.command) hooks[event].push({ ...h, source });
|
|
34
|
+
};
|
|
35
|
+
add('user', readConfigFile().hooks);
|
|
36
|
+
if (includeProject) {
|
|
37
|
+
try {
|
|
38
|
+
add('project', JSON.parse(fs.readFileSync(projectSettingsFile(cwd), 'utf8')).hooks);
|
|
39
|
+
} catch {}
|
|
40
|
+
}
|
|
41
|
+
return hooks;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function projectHasHooks(cwd) {
|
|
45
|
+
try {
|
|
46
|
+
const hooks = JSON.parse(fs.readFileSync(projectSettingsFile(cwd), 'utf8')).hooks ?? {};
|
|
47
|
+
return HOOK_EVENTS.some((e) => hooks[e]?.length);
|
|
48
|
+
} catch {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function matches(matcher, tool) {
|
|
54
|
+
if (!matcher || matcher === '*') return true;
|
|
55
|
+
try {
|
|
56
|
+
return new RegExp(`^(?:${matcher})$`).test(tool);
|
|
57
|
+
} catch {
|
|
58
|
+
return matcher === tool;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function runHook(command, payload, cwd, env) {
|
|
63
|
+
return new Promise((resolve) => {
|
|
64
|
+
const child = spawn(command, { cwd, shell: true, env: { ...process.env, ...env }, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
65
|
+
let stdout = '';
|
|
66
|
+
let stderr = '';
|
|
67
|
+
child.stdout.on('data', (d) => (stdout += d));
|
|
68
|
+
child.stderr.on('data', (d) => (stderr += d));
|
|
69
|
+
const timer = setTimeout(() => child.kill('SIGKILL'), 60000);
|
|
70
|
+
child.on('error', (err) => {
|
|
71
|
+
clearTimeout(timer);
|
|
72
|
+
resolve({ code: -1, stdout, stderr: err.message });
|
|
73
|
+
});
|
|
74
|
+
child.on('close', (code) => {
|
|
75
|
+
clearTimeout(timer);
|
|
76
|
+
resolve({ code, stdout: stdout.trim(), stderr: stderr.trim() });
|
|
77
|
+
});
|
|
78
|
+
child.stdin.on('error', () => {});
|
|
79
|
+
child.stdin.end(JSON.stringify(payload));
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export class Hooks {
|
|
84
|
+
constructor(hooks, { cwd, ui }) {
|
|
85
|
+
this.hooks = hooks;
|
|
86
|
+
this.cwd = cwd;
|
|
87
|
+
this.ui = ui;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
get count() {
|
|
91
|
+
return HOOK_EVENTS.reduce((n, e) => n + this.hooks[e].length, 0);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Returns { blocked: bool, reason, output }.
|
|
95
|
+
async run(event, { tool, input, result, prompt, sessionId } = {}) {
|
|
96
|
+
const list = (this.hooks[event] ?? []).filter((h) => event.endsWith('ToolUse') ? matches(h.matcher, tool) : true);
|
|
97
|
+
const outputs = [];
|
|
98
|
+
for (const h of list) {
|
|
99
|
+
const file = input?.path ? path.resolve(this.cwd, input.path) : '';
|
|
100
|
+
const { code, stdout, stderr } = await runHook(
|
|
101
|
+
h.command,
|
|
102
|
+
{ event, tool, input, result, prompt, cwd: this.cwd, session_id: sessionId },
|
|
103
|
+
this.cwd,
|
|
104
|
+
{ ARRAKIS_EVENT: event, ARRAKIS_TOOL: tool ?? '', ARRAKIS_FILE: file },
|
|
105
|
+
);
|
|
106
|
+
if (code === 2 && (event === 'PreToolUse' || event === 'UserPromptSubmit')) {
|
|
107
|
+
return { blocked: true, reason: stderr || stdout || `Blocked by ${event} hook: ${h.command}` };
|
|
108
|
+
}
|
|
109
|
+
if (code !== 0) this.ui.info(` hook "${h.command}" exited with ${code}${stderr ? `: ${stderr.split('\n')[0]}` : ''}`);
|
|
110
|
+
if (stdout) outputs.push(stdout);
|
|
111
|
+
}
|
|
112
|
+
return { blocked: false, output: outputs.join('\n') };
|
|
113
|
+
}
|
|
114
|
+
}
|