@mumbrane/arrakis 0.3.0 → 0.5.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/src/cli.js CHANGED
@@ -11,6 +11,17 @@ 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, buildMessage, pasteClipboardImage, loadCustomCommands, renderCommand, INIT_PROMPT } from './input.js';
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import os from 'node:os';
18
+ import { Checkpoints } from './checkpoints.js';
19
+ import { connectAll, mcpTools, loadMcpConfig, mcpConfigFiles } from './mcp.js';
20
+ import { Hooks, loadHooks, projectHasHooks, projectSettingsFile } from './hooks.js';
21
+ import { startJob, listJobs, findJob, stopJob, readLog, updateJob, jobLog } from './jobs.js';
22
+ import { checkForUpdate } from './update.js';
23
+ import { setExtraTools } from './tools.js';
24
+ import { isTrustedProject, trustProject, HOME_DIR } from './config.js';
14
25
 
15
26
  const HELP = `arrakis ${VERSION} — a coding agent for your terminal
16
27
 
@@ -21,6 +32,11 @@ Usage
21
32
  arrakis -r <id> Resume a session by id (or id prefix)
22
33
  arrakis setup Choose a provider, enter an API key and pick a model
23
34
  arrakis models List the models your provider offers
35
+ arrakis bg "task" Run a task in the background (add --yolo or --allow to let it edit)
36
+ arrakis jobs [log|stop <id>] List background jobs, read a job's log, or stop one
37
+ arrakis mcp Show MCP servers and their tools
38
+ arrakis mcp add <name> -- <command...> Add a local MCP server (or: --url <url>)
39
+ arrakis mcp remove <name> Remove an MCP server
24
40
  arrakis sessions List recent sessions
25
41
  arrakis config Show configuration
26
42
  arrakis config set <key> <v> Set a value (provider, baseUrl, apiKey, model, contextWindow, maxTokens)
@@ -41,6 +57,13 @@ Environment (overrides the config file)
41
57
  ARRAKIS_PROVIDER, ARRAKIS_BASE_URL, ARRAKIS_API_KEY, ARRAKIS_MODEL, ARRAKIS_CONTEXT_WINDOW, ARRAKIS_HOME`;
42
58
 
43
59
  const SLASH_HELP = `/help Show commands
60
+ /plan Toggle plan mode: investigate and propose a plan, change nothing
61
+ /init Write ARRAKIS.md project notes for this folder
62
+ /todos Show the current task list
63
+ /undo [n] Revert arrakis's file changes from the last turn (or back to turn n)
64
+ /paste Attach the image on your clipboard to your next message
65
+ /mcp Show connected MCP servers and tools
66
+ /bg <task> Start a background job; /jobs to check on it
44
67
  /clear Start a new session
45
68
  /compact Summarize history to free up context
46
69
  /model [name] Pick a model from your provider (or set one by name)
@@ -50,13 +73,17 @@ const SLASH_HELP = `/help Show commands
50
73
  /yolo Toggle allowing all tool calls without asking
51
74
  /exit Quit (or Ctrl-D)
52
75
 
53
- End a line with \\ to continue on the next line. Ctrl-C interrupts the model.`;
76
+ Type @path to attach a file or folder. End a line with \\ to continue on the next line.
77
+ Esc or Ctrl-C interrupts the model. Add your own commands as .arrakis/commands/<name>.md.`;
54
78
 
55
79
  export async function main(argv) {
56
80
  if (argv[0] === 'config') return configCommand(argv.slice(1));
57
81
  if (argv[0] === 'sessions') return sessionsCommand();
58
82
  if (argv[0] === 'setup' || argv[0] === 'login') return setupCommand();
59
83
  if (argv[0] === 'models') return modelsCommand();
84
+ if (argv[0] === 'bg') return bgCommand(argv.slice(1));
85
+ if (argv[0] === 'jobs') return jobsCommand(argv.slice(1));
86
+ if (argv[0] === 'mcp') return mcpCommand(argv.slice(1));
60
87
  if (argv[0] === 'logout') {
61
88
  removeProviderKeys();
62
89
  return console.log(`Removed saved API keys from ${CONFIG_PATH}`);
@@ -108,29 +135,129 @@ export async function main(argv) {
108
135
  session = Session.latest(cwd);
109
136
  if (!session) throw new Error(`No previous session in ${cwd}. Start one with: arrakis`);
110
137
  } else session = Session.create({ cwd, model: config.model });
138
+ if (process.env.ARRAKIS_JOB_ID) updateJob(process.env.ARRAKIS_JOB_ID, { sessionId: session.id });
111
139
 
112
140
  const permissions = new Permissions({
113
141
  ui,
114
142
  mode: values.yolo ? 'yolo' : print ? 'deny' : 'ask',
115
143
  allow: values.allow ? values.allow.split(',').map((s) => s.trim()).filter(Boolean) : [],
116
144
  });
117
- const agent = new Agent({ config, session, ui, permissions, cwd });
145
+
146
+ // Project MCP servers and hooks run commands, so ask before trusting a folder.
147
+ const trusted = await checkProjectTrust({ cwd, ui, prompts, print });
148
+ const mcpServers = await connectMcp({ cwd, ui, includeProject: trusted });
149
+ const hookSet = new Hooks(loadHooks(cwd, { includeProject: trusted }), { cwd, ui });
150
+ const agent = new Agent({ config, session, ui, permissions, cwd, checkpoints: new Checkpoints(session.file), hooks: hookSet.count ? hookSet : null });
118
151
 
119
152
  if (print) {
120
153
  process.on('SIGINT', () => {
121
154
  agent.interrupt();
122
155
  process.exit(130);
123
156
  });
124
- const ok = await agent.send(prompt);
157
+ const { content, errors } = buildMessage(prompt, cwd);
158
+ for (const e of errors) ui.error(e);
159
+ const ok = await agent.send(content);
160
+ mcpServers.forEach((s) => s.close());
161
+ if (process.env.ARRAKIS_JOB_ID) updateJob(process.env.ARRAKIS_JOB_ID, { status: ok ? 'done' : 'failed', finished: Date.now() });
125
162
  process.exitCode = ok ? 0 : 1;
126
163
  return;
127
164
  }
128
- await interactive({ agent, ui, prompts, config, cwd, firstPrompt: prompt });
165
+ await interactive({ agent, ui, prompts, config, cwd, firstPrompt: prompt, mcpServers, hooks: hookSet.count });
166
+ }
167
+
168
+ async function checkProjectTrust({ cwd, ui, prompts, print }) {
169
+ const { projectFiles } = loadMcpConfig(cwd, { includeProject: true });
170
+ const hasHooks = projectHasHooks(cwd);
171
+ if (!projectFiles.length && !hasHooks) return true;
172
+ if (isTrustedProject(cwd)) return true;
173
+ if (cwd === os.homedir()) return false;
174
+ const what = [...projectFiles.map((f) => path.relative(cwd, f)), ...(hasHooks ? [path.relative(cwd, projectSettingsFile(cwd)) + ' (hooks)'] : [])];
175
+ if (print) {
176
+ ui.info(`Skipping project MCP servers/hooks in ${what.join(', ')} (not trusted yet; run arrakis here once to allow them).`);
177
+ return false;
178
+ }
179
+ ui.start();
180
+ const { servers } = loadMcpConfig(cwd, { includeProject: true });
181
+ const c = ui.c;
182
+ ui.write(ui.out, `\n${c.yellow('!')} ${c.bold('This folder configures tools that run commands on your computer:')}\n`);
183
+ for (const [name, cfg] of Object.entries(servers)) {
184
+ if (!projectFiles.includes(cfg.source)) continue;
185
+ ui.write(ui.out, ` ${c.bold(name)} ${c.gray(cfg.url ?? [cfg.command, ...(cfg.args ?? [])].join(' '))}\n`);
186
+ }
187
+ if (hasHooks) ui.write(ui.out, ` ${c.bold('hooks')} ${c.gray(path.relative(cwd, projectSettingsFile(cwd)))}\n`);
188
+ const answer = await prompts.select({
189
+ title: 'Allow them?',
190
+ items: [
191
+ { label: 'Yes, trust this folder', value: 'yes' },
192
+ { label: 'No, not this time', value: 'no' },
193
+ ],
194
+ initial: 1,
195
+ });
196
+ if (answer === 'yes') {
197
+ trustProject(cwd);
198
+ return true;
199
+ }
200
+ return false;
201
+ }
202
+
203
+ async function connectMcp({ cwd, ui, includeProject }) {
204
+ const { servers } = loadMcpConfig(cwd, { includeProject });
205
+ if (!Object.keys(servers).length) return [];
206
+ ui.startSpinner('Connecting MCP servers');
207
+ const list = await connectAll(cwd, { includeProject });
208
+ ui.stopSpinner();
209
+ setExtraTools(mcpTools(list));
210
+ for (const s of list) if (s.status === 'failed') ui.error(`MCP server "${s.name}" failed to start: ${s.error}`);
211
+ return list;
212
+ }
213
+
214
+ function gitBranch(cwd) {
215
+ let dir = cwd;
216
+ while (true) {
217
+ try {
218
+ const head = fs.readFileSync(path.join(dir, '.git', 'HEAD'), 'utf8').trim();
219
+ return head.startsWith('ref: refs/heads/') ? head.slice(16) : head.slice(0, 7);
220
+ } catch {}
221
+ const parent = path.dirname(dir);
222
+ if (parent === dir) return null;
223
+ dir = parent;
224
+ }
225
+ }
226
+
227
+ function completer(line, cwd, commands) {
228
+ if (/^\/\S*$/.test(line)) {
229
+ const hits = commands.filter((c) => c.startsWith(line));
230
+ return [hits.length ? hits : commands, line];
231
+ }
232
+ const m = line.match(/@([^\s]*)$/);
233
+ if (m) {
234
+ const partial = m[1];
235
+ const dirPart = partial.includes('/') ? partial.slice(0, partial.lastIndexOf('/') + 1) : '';
236
+ const base = partial.slice(dirPart.length);
237
+ try {
238
+ const entries = fs.readdirSync(path.resolve(cwd, dirPart || '.'), { withFileTypes: true })
239
+ .filter((e) => e.name.startsWith(base) && (base.startsWith('.') || !e.name.startsWith('.')) && e.name !== 'node_modules')
240
+ .map((e) => `@${dirPart}${e.name}${e.isDirectory() ? '/' : ''}`)
241
+ .sort();
242
+ return [entries, `@${partial}`];
243
+ } catch {
244
+ return [[], `@${partial}`];
245
+ }
246
+ }
247
+ return [[], line];
129
248
  }
130
249
 
131
- async function interactive({ agent, ui, prompts, config, cwd, firstPrompt }) {
250
+ const BUILTIN_COMMANDS = ['/help', '/plan', '/init', '/todos', '/undo', '/paste', '/mcp', '/bg', '/jobs', '/clear', '/compact', '/model', '/provider', '/sessions', '/status', '/yolo', '/exit'];
251
+
252
+ async function interactive({ agent, ui, prompts, config, cwd, firstPrompt, mcpServers = [], hooks = 0 }) {
132
253
  const c = ui.c;
254
+ ui.historyFile = path.join(HOME_DIR, 'history');
255
+ ui.completer = (line) => completer(line, cwd, [...BUILTIN_COMMANDS, ...[...loadCustomCommands(cwd).keys()].map((k) => `/${k}`)]);
256
+ // Recreate the line reader so it picks up completion and history.
257
+ if (ui.fancy) ui.suspend();
133
258
  ui.start();
259
+ const update = await checkForUpdate().catch(() => null);
260
+ const state = { pastedImages: [], jobsSeen: new Map(listJobs().map((j) => [j.id, j.status])), mcpServers };
134
261
  let armedExit = false;
135
262
  ui.onInterrupt(() => {
136
263
  if (agent.busy) return agent.interrupt();
@@ -139,48 +266,175 @@ async function interactive({ agent, ui, prompts, config, cwd, firstPrompt }) {
139
266
  process.exit(0);
140
267
  }
141
268
  armedExit = true;
142
- ui.write(ui.out, `\n${c.dim('(Press Ctrl-C again to exit)')}\n`);
269
+ ui.write(ui.out, `\n${c.gray('(Press Ctrl-C again to exit)')}\n`);
143
270
  ui.rl?.prompt();
144
271
  });
272
+ ui.onEscape = () => {
273
+ if (agent.busy) agent.interrupt();
274
+ };
275
+ ui.statusLine = () => {
276
+ const used = Math.round((estimateTokens(agent.session.messages) / config.contextWindow) * 100);
277
+ const branch = gitBranch(cwd);
278
+ const parts = [config.model, `${used}% context`];
279
+ if (branch) parts.push(`⎇ ${branch}`);
280
+ if (agent.permissions.planMode) parts.push('plan mode');
281
+ if (agent.permissions.mode === 'yolo') parts.push('yolo');
282
+ parts.push('/help');
283
+ return parts.join(' · ');
284
+ };
145
285
 
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'));
286
+ ui.banner({
287
+ version: VERSION,
288
+ model: config.model,
289
+ provider: config.providerName || config.baseUrl,
290
+ cwd,
291
+ instructions: loadProjectInstructions(cwd).filter((i) => i.text.trim()).map((i) => i.file),
292
+ resumed: agent.session.messages.length ? `resumed ${agent.session.id} (${agent.session.messages.length} messages)` : '',
293
+ mcp: mcpServers,
294
+ hooks,
295
+ update,
296
+ });
297
+
298
+ const send = async (text) => {
299
+ const { content, attached, errors } = buildMessage(text, cwd, state.pastedImages.splice(0));
300
+ for (const e of errors) ui.error(e);
301
+ if (attached.length) ui.info(` Attached ${attached.join(', ')}`);
302
+ await agent.send(content);
303
+ };
304
+
305
+ // Mention background jobs that finished since the last prompt.
306
+ const reportJobs = () => {
307
+ for (const job of listJobs()) {
308
+ const before = state.jobsSeen.get(job.id);
309
+ if (before === 'running' && job.status !== 'running') {
310
+ ui.info(`${job.status === 'done' ? '✓' : '✗'} Background job ${job.id} ${job.status}: ${job.prompt.slice(0, 60)} (arrakis jobs log ${job.id})`);
311
+ }
312
+ state.jobsSeen.set(job.id, job.status);
313
+ }
314
+ };
152
315
 
153
- if (firstPrompt) await agent.send(firstPrompt);
316
+ if (firstPrompt) await send(firstPrompt);
154
317
  while (true) {
318
+ reportJobs();
155
319
  const line = await ui.prompt();
156
320
  if (line === null) break;
157
321
  armedExit = false;
158
322
  const text = line.trim();
159
323
  if (!text) continue;
160
- if (text.startsWith('/')) {
161
- if ((await slashCommand(text, { agent, ui, prompts, config, cwd })) === 'exit') break;
324
+ // "/name args" is a command; "/Users/me/shot.png what's this?" is a dragged-in path.
325
+ if (/^\/[\w-]+(\s|$)/.test(text) && !/^\/[\w-]+\//.test(text)) {
326
+ const result = await slashCommand(text, { agent, ui, prompts, config, cwd, state });
327
+ if (result === 'exit') break;
328
+ if (result?.send) await send(result.send);
162
329
  continue;
163
330
  }
164
- await agent.send(text);
165
- ui.write(ui.out, '\n');
331
+ await send(text);
166
332
  }
167
333
  ui.close();
168
- ui.write(ui.out, c.dim(`Session saved. Resume with: arrakis -r ${agent.session.id}\n`));
334
+ state.mcpServers.forEach((s) => s.close());
335
+ ui.write(ui.out, c.gray(`\nSession saved. Resume with: arrakis -r ${agent.session.id}\n`));
169
336
  }
170
337
 
171
- async function slashCommand(text, { agent, ui, prompts, config, cwd }) {
338
+ async function slashCommand(text, { agent, ui, prompts, config, cwd, state }) {
172
339
  const [cmd, ...rest] = text.slice(1).split(/\s+/);
173
340
  const arg = rest.join(' ');
174
341
  const c = ui.c;
175
342
  switch (cmd) {
176
- case 'help':
343
+ case 'help': {
177
344
  ui.write(ui.out, SLASH_HELP + '\n');
345
+ const custom = loadCustomCommands(cwd);
346
+ if (custom.size) {
347
+ ui.write(ui.out, `\n${c.bold('Your commands')}\n`);
348
+ for (const cmd of custom.values()) ui.write(ui.out, `/${cmd.name.padEnd(17)} ${c.gray(cmd.description)}\n`);
349
+ }
350
+ break;
351
+ }
352
+ case 'plan':
353
+ agent.permissions.planMode = !agent.permissions.planMode;
354
+ 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.');
355
+ else {
356
+ ui.info('Plan mode off: arrakis can make changes now.');
357
+ if (agent.session.messages.length) return { send: 'Plan mode is off and the plan is approved. Go ahead and carry it out.' };
358
+ }
359
+ break;
360
+ case 'init':
361
+ return { send: INIT_PROMPT };
362
+ case 'undo': {
363
+ const turns = agent.checkpoints?.list() ?? [];
364
+ if (!turns.length) {
365
+ ui.info('Nothing to undo: arrakis has not changed any files in this session. (Changes made by shell commands are not tracked.)');
366
+ break;
367
+ }
368
+ let target = turns.at(-1).id;
369
+ if (arg) {
370
+ target = Number(arg);
371
+ if (!turns.some((t) => t.id === target)) {
372
+ ui.error(`No turn ${arg}. Turns with changes: ${turns.map((t) => t.id).join(', ')}`);
373
+ break;
374
+ }
375
+ } else if (turns.length > 1) {
376
+ const pick = await prompts.select({
377
+ title: 'Undo back to before',
378
+ 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()}` })),
379
+ });
380
+ if (pick === null) break;
381
+ target = pick;
382
+ }
383
+ const restored = agent.checkpoints.undo(target);
384
+ for (const r of restored) ui.write(ui.log, ` ${c.green('↺')} ${r.action} ${path.relative(cwd, r.file) || r.file}\n`);
385
+ 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.]`);
386
+ ui.success(`Reverted ${restored.length} file${restored.length === 1 ? '' : 's'}.`);
387
+ break;
388
+ }
389
+ case 'paste': {
390
+ const { file, error } = pasteClipboardImage();
391
+ if (error) ui.error(error);
392
+ else {
393
+ state.pastedImages.push(file);
394
+ ui.success('Image from clipboard will be attached to your next message.');
395
+ }
396
+ break;
397
+ }
398
+ case 'mcp': {
399
+ const servers = state.mcpServers;
400
+ if (!servers.length) {
401
+ ui.info(`No MCP servers configured. Add one with: arrakis mcp add <name> -- <command>\nConfig files: ${[...mcpConfigFiles(cwd).user, ...mcpConfigFiles(cwd).project].join(', ')}`);
402
+ break;
403
+ }
404
+ for (const s of servers) {
405
+ 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`);
406
+ if (s.status === 'connected') ui.write(ui.out, c.gray(` ${s.tools.map((t) => t.name).join(', ')}\n`));
407
+ }
408
+ break;
409
+ }
410
+ case 'bg': {
411
+ if (!arg) {
412
+ ui.info('Usage: /bg <task>. The job runs in the background; check it with /jobs.');
413
+ break;
414
+ }
415
+ const flags = agent.permissions.mode === 'yolo' ? ['--yolo'] : agent.permissions.allowed.size ? ['--allow', [...agent.permissions.allowed].join(',')] : [];
416
+ const job = startJob({ prompt: arg, cwd, flags });
417
+ state.jobsSeen.set(job.id, 'running');
418
+ 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).'}`);
419
+ break;
420
+ }
421
+ case 'jobs': {
422
+ const jobs = listJobs().slice(0, 10);
423
+ if (!jobs.length) ui.info('No background jobs. Start one with /bg <task>.');
424
+ 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`);
425
+ if (jobs.length) ui.info('Read a log with: arrakis jobs log <id>');
426
+ break;
427
+ }
428
+ case 'todos':
429
+ if (agent.todos.length) ui.todos(agent.todos);
430
+ else ui.info('No task list yet. arrakis makes one for multi-step work.');
178
431
  break;
179
432
  case 'exit':
180
433
  case 'quit':
181
434
  return 'exit';
182
435
  case 'clear':
183
436
  agent.session = Session.create({ cwd, model: config.model });
437
+ agent.checkpoints = new Checkpoints(agent.session.file);
184
438
  ui.info(`Started new session ${agent.session.id}.`);
185
439
  break;
186
440
  case 'compact': {
@@ -233,6 +487,8 @@ async function slashCommand(text, { agent, ui, prompts, config, cwd }) {
233
487
  `provider ${config.providerName || 'custom'} (${config.baseUrl})`,
234
488
  `model ${config.model}`,
235
489
  `context ~${used.toLocaleString()} / ${config.contextWindow.toLocaleString()} tokens (${Math.round((used / config.contextWindow) * 100)}%)`,
490
+ `plan mode ${agent.permissions.planMode ? 'on' : 'off'}`,
491
+ `todos ${agent.todos.length ? `${agent.todos.filter((t) => t.status === 'completed').length}/${agent.todos.length} done` : 'none'}`,
236
492
  `permissions ${agent.permissions.mode}${agent.permissions.allowed.size ? ` (always allowed: ${[...agent.permissions.allowed].join(', ')})` : ''}`,
237
493
  `tools ${TOOLS.map((t) => t.name).join(', ')}`,
238
494
  ].join('\n') + '\n');
@@ -242,8 +498,11 @@ async function slashCommand(text, { agent, ui, prompts, config, cwd }) {
242
498
  agent.permissions.mode = agent.permissions.mode === 'yolo' ? 'ask' : 'yolo';
243
499
  ui.info(agent.permissions.mode === 'yolo' ? 'YOLO on: tool calls run without asking.' : 'YOLO off: writes and commands ask first.');
244
500
  break;
245
- default:
501
+ default: {
502
+ const custom = loadCustomCommands(cwd).get(cmd.toLowerCase());
503
+ if (custom) return { send: renderCommand(custom, arg) };
246
504
  ui.write(ui.out, c.red(`Unknown command /${cmd}. Try /help.\n`));
505
+ }
247
506
  }
248
507
  }
249
508
 
@@ -310,6 +569,109 @@ function printSessions(stream, limit) {
310
569
  stream.write(c.dim('\nResume with: arrakis -r <id>\n'));
311
570
  }
312
571
 
572
+ const jobMark = (j, c) => (j.status === 'running' ? c.accent('●') : j.status === 'done' ? c.green('✓') : c.red('✗'));
573
+
574
+ function bgCommand(args) {
575
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { yolo: { type: 'boolean' }, allow: { type: 'string' } } });
576
+ const prompt = positionals.join(' ').trim();
577
+ if (!prompt) throw new Error('Usage: arrakis bg [--yolo | --allow edit_file,bash] "task"');
578
+ const flags = values.yolo ? ['--yolo'] : values.allow ? ['--allow', values.allow] : [];
579
+ const job = startJob({ prompt, cwd: process.cwd(), flags });
580
+ console.log(`Started ${job.id} (pid ${job.pid}).`);
581
+ if (!flags.length) console.log('It can read and search but not change files. Add --yolo or --allow to let it edit.');
582
+ console.log(`Follow it with: arrakis jobs log ${job.id} -f`);
583
+ }
584
+
585
+ async function jobsCommand(args) {
586
+ const c = colors(process.stdout);
587
+ const [sub, id, flag] = args;
588
+ if (sub === 'log') {
589
+ if (!id) throw new Error('Usage: arrakis jobs log <id> [-f]');
590
+ const job = findJob(id);
591
+ process.stdout.write(readLog(job.id));
592
+ if (flag === '-f' || flag === '--follow') {
593
+ let size = fs.statSync(jobLog(job.id)).size;
594
+ while (findJob(job.id).status === 'running') {
595
+ await new Promise((r) => setTimeout(r, 500));
596
+ const now = fs.statSync(jobLog(job.id)).size;
597
+ if (now > size) {
598
+ const fd = fs.openSync(jobLog(job.id), 'r');
599
+ const buf = Buffer.alloc(now - size);
600
+ fs.readSync(fd, buf, 0, buf.length, size);
601
+ fs.closeSync(fd);
602
+ process.stdout.write(buf);
603
+ size = now;
604
+ }
605
+ }
606
+ }
607
+ const final = findJob(job.id);
608
+ if (final.sessionId) console.log(c.gray(`\n[${final.status}] Continue the conversation with: arrakis -r ${final.sessionId}`));
609
+ return;
610
+ }
611
+ if (sub === 'stop') {
612
+ if (!id) throw new Error('Usage: arrakis jobs stop <id>');
613
+ const job = stopJob(id);
614
+ return console.log(`Stopped ${job.id}.`);
615
+ }
616
+ const jobs = listJobs();
617
+ if (!jobs.length) return console.log('No background jobs. Start one with: arrakis bg "task"');
618
+ for (const j of jobs.slice(0, 20)) {
619
+ 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)}`);
620
+ }
621
+ }
622
+
623
+ async function mcpCommand(args) {
624
+ const c = colors(process.stdout);
625
+ const file = path.join(HOME_DIR, 'mcp.json');
626
+ const read = () => {
627
+ try {
628
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
629
+ } catch {
630
+ return { mcpServers: {} };
631
+ }
632
+ };
633
+ const write = (json) => {
634
+ fs.mkdirSync(HOME_DIR, { recursive: true });
635
+ fs.writeFileSync(file, JSON.stringify(json, null, 2) + '\n', { mode: 0o600 });
636
+ };
637
+ const [sub, name, ...rest] = args;
638
+ if (sub === 'add') {
639
+ if (!name) throw new Error('Usage: arrakis mcp add <name> -- <command> [args...] or arrakis mcp add <name> --url <url>');
640
+ const json = read();
641
+ json.mcpServers ??= {};
642
+ const urlAt = rest.indexOf('--url');
643
+ if (urlAt >= 0) json.mcpServers[name] = { url: rest[urlAt + 1] };
644
+ else {
645
+ const cmd = rest[0] === '--' ? rest.slice(1) : rest;
646
+ 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');
647
+ json.mcpServers[name] = { command: cmd[0], args: cmd.slice(1) };
648
+ }
649
+ write(json);
650
+ return console.log(`Added MCP server "${name}" to ${file}. Add any keys it needs under "env" (or "headers" for a URL) in that file.`);
651
+ }
652
+ if (sub === 'remove') {
653
+ const json = read();
654
+ if (!json.mcpServers?.[name]) throw new Error(`No MCP server "${name}" in ${file}`);
655
+ delete json.mcpServers[name];
656
+ write(json);
657
+ return console.log(`Removed "${name}".`);
658
+ }
659
+ const cwd = process.cwd();
660
+ const trusted = isTrustedProject(cwd);
661
+ const { servers } = loadMcpConfig(cwd, { includeProject: trusted });
662
+ if (!Object.keys(servers).length) {
663
+ return console.log(`No MCP servers configured.\nAdd one: arrakis mcp add <name> -- <command>\nConfig files: ${[...mcpConfigFiles(cwd).user, ...mcpConfigFiles(cwd).project].join(', ')}`);
664
+ }
665
+ console.log(c.gray('Connecting…'));
666
+ const list = await connectAll(cwd, { includeProject: trusted });
667
+ for (const s of list) {
668
+ console.log(`${s.status === 'connected' ? c.green('●') : c.red('●')} ${c.bold(s.name)} ${c.gray(servers[s.name].source)}`);
669
+ 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)}`) : ''}`);
670
+ else console.log(c.red(` ${s.error}`));
671
+ }
672
+ list.forEach((s) => s.close());
673
+ }
674
+
313
675
  async function readStdin() {
314
676
  let data = '';
315
677
  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
+ }