@mumbrane/arrakis 0.4.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,7 +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, loadCustomCommands, renderCommand, INIT_PROMPT } from './input.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';
15
25
 
16
26
  const HELP = `arrakis ${VERSION} — a coding agent for your terminal
17
27
 
@@ -22,6 +32,11 @@ Usage
22
32
  arrakis -r <id> Resume a session by id (or id prefix)
23
33
  arrakis setup Choose a provider, enter an API key and pick a model
24
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
25
40
  arrakis sessions List recent sessions
26
41
  arrakis config Show configuration
27
42
  arrakis config set <key> <v> Set a value (provider, baseUrl, apiKey, model, contextWindow, maxTokens)
@@ -45,6 +60,10 @@ const SLASH_HELP = `/help Show commands
45
60
  /plan Toggle plan mode: investigate and propose a plan, change nothing
46
61
  /init Write ARRAKIS.md project notes for this folder
47
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
48
67
  /clear Start a new session
49
68
  /compact Summarize history to free up context
50
69
  /model [name] Pick a model from your provider (or set one by name)
@@ -62,6 +81,9 @@ export async function main(argv) {
62
81
  if (argv[0] === 'sessions') return sessionsCommand();
63
82
  if (argv[0] === 'setup' || argv[0] === 'login') return setupCommand();
64
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));
65
87
  if (argv[0] === 'logout') {
66
88
  removeProviderKeys();
67
89
  return console.log(`Removed saved API keys from ${CONFIG_PATH}`);
@@ -113,29 +135,129 @@ export async function main(argv) {
113
135
  session = Session.latest(cwd);
114
136
  if (!session) throw new Error(`No previous session in ${cwd}. Start one with: arrakis`);
115
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 });
116
139
 
117
140
  const permissions = new Permissions({
118
141
  ui,
119
142
  mode: values.yolo ? 'yolo' : print ? 'deny' : 'ask',
120
143
  allow: values.allow ? values.allow.split(',').map((s) => s.trim()).filter(Boolean) : [],
121
144
  });
122
- 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 });
123
151
 
124
152
  if (print) {
125
153
  process.on('SIGINT', () => {
126
154
  agent.interrupt();
127
155
  process.exit(130);
128
156
  });
129
- const ok = await agent.send(expandMentions(prompt, cwd).text);
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() });
130
162
  process.exitCode = ok ? 0 : 1;
131
163
  return;
132
164
  }
133
- 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];
134
248
  }
135
249
 
136
- 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 }) {
137
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();
138
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 };
139
261
  let armedExit = false;
140
262
  ui.onInterrupt(() => {
141
263
  if (agent.busy) return agent.interrupt();
@@ -152,7 +274,9 @@ async function interactive({ agent, ui, prompts, config, cwd, firstPrompt }) {
152
274
  };
153
275
  ui.statusLine = () => {
154
276
  const used = Math.round((estimateTokens(agent.session.messages) / config.contextWindow) * 100);
277
+ const branch = gitBranch(cwd);
155
278
  const parts = [config.model, `${used}% context`];
279
+ if (branch) parts.push(`⎇ ${branch}`);
156
280
  if (agent.permissions.planMode) parts.push('plan mode');
157
281
  if (agent.permissions.mode === 'yolo') parts.push('yolo');
158
282
  parts.push('/help');
@@ -166,23 +290,40 @@ async function interactive({ agent, ui, prompts, config, cwd, firstPrompt }) {
166
290
  cwd,
167
291
  instructions: loadProjectInstructions(cwd).filter((i) => i.text.trim()).map((i) => i.file),
168
292
  resumed: agent.session.messages.length ? `resumed ${agent.session.id} (${agent.session.messages.length} messages)` : '',
293
+ mcp: mcpServers,
294
+ hooks,
295
+ update,
169
296
  });
170
297
 
171
298
  const send = async (text) => {
172
- const { text: full, attached } = expandMentions(text, cwd);
299
+ const { content, attached, errors } = buildMessage(text, cwd, state.pastedImages.splice(0));
300
+ for (const e of errors) ui.error(e);
173
301
  if (attached.length) ui.info(` Attached ${attached.join(', ')}`);
174
- await agent.send(full);
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
+ }
175
314
  };
176
315
 
177
316
  if (firstPrompt) await send(firstPrompt);
178
317
  while (true) {
318
+ reportJobs();
179
319
  const line = await ui.prompt();
180
320
  if (line === null) break;
181
321
  armedExit = false;
182
322
  const text = line.trim();
183
323
  if (!text) continue;
184
- if (text.startsWith('/') && !text.startsWith('//')) {
185
- const result = await slashCommand(text, { agent, ui, prompts, config, cwd });
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 });
186
327
  if (result === 'exit') break;
187
328
  if (result?.send) await send(result.send);
188
329
  continue;
@@ -190,10 +331,11 @@ async function interactive({ agent, ui, prompts, config, cwd, firstPrompt }) {
190
331
  await send(text);
191
332
  }
192
333
  ui.close();
334
+ state.mcpServers.forEach((s) => s.close());
193
335
  ui.write(ui.out, c.gray(`\nSession saved. Resume with: arrakis -r ${agent.session.id}\n`));
194
336
  }
195
337
 
196
- async function slashCommand(text, { agent, ui, prompts, config, cwd }) {
338
+ async function slashCommand(text, { agent, ui, prompts, config, cwd, state }) {
197
339
  const [cmd, ...rest] = text.slice(1).split(/\s+/);
198
340
  const arg = rest.join(' ');
199
341
  const c = ui.c;
@@ -217,6 +359,72 @@ async function slashCommand(text, { agent, ui, prompts, config, cwd }) {
217
359
  break;
218
360
  case 'init':
219
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
+ }
220
428
  case 'todos':
221
429
  if (agent.todos.length) ui.todos(agent.todos);
222
430
  else ui.info('No task list yet. arrakis makes one for multi-step work.');
@@ -226,6 +434,7 @@ async function slashCommand(text, { agent, ui, prompts, config, cwd }) {
226
434
  return 'exit';
227
435
  case 'clear':
228
436
  agent.session = Session.create({ cwd, model: config.model });
437
+ agent.checkpoints = new Checkpoints(agent.session.file);
229
438
  ui.info(`Started new session ${agent.session.id}.`);
230
439
  break;
231
440
  case 'compact': {
@@ -360,6 +569,109 @@ function printSessions(stream, limit) {
360
569
  stream.write(c.dim('\nResume with: arrakis -r <id>\n'));
361
570
  }
362
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
+
363
675
  async function readStdin() {
364
676
  let data = '';
365
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
+ }
package/src/input.js CHANGED
@@ -1,9 +1,79 @@
1
1
  // User input helpers: @file mentions and custom slash commands.
2
2
  import fs from 'node:fs';
3
+ import os from 'node:os';
3
4
  import path from 'node:path';
5
+ import { spawnSync } from 'node:child_process';
4
6
  import { HOME_DIR } from './config.js';
5
7
 
6
8
  const MAX_ATTACH = 100_000;
9
+ const MAX_IMAGE = 5 * 1024 * 1024;
10
+ const IMAGE_TYPES = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' };
11
+
12
+ export const isImagePath = (p) => Boolean(IMAGE_TYPES[path.extname(p).toLowerCase()]);
13
+
14
+ function imagePart(file) {
15
+ const buf = fs.readFileSync(file);
16
+ if (buf.length > MAX_IMAGE) throw new Error(`${path.basename(file)} is larger than 5 MB`);
17
+ return { type: 'image_url', image_url: { url: `data:${IMAGE_TYPES[path.extname(file).toLowerCase()]};base64,${buf.toString('base64')}` } };
18
+ }
19
+
20
+ // Turn a typed message into what the model receives: @file contents inlined,
21
+ // images (by @path, or a path dragged into the terminal) attached as image parts.
22
+ // Returns { content: string | parts[], attached: [labels], error? }.
23
+ export function buildMessage(text, cwd, extraImages = []) {
24
+ const { text: withFiles, attached } = expandMentions(text, cwd);
25
+ const images = [];
26
+ const labels = [...attached];
27
+ const errors = [];
28
+ const refs = new Set();
29
+ // @image.png mentions
30
+ for (const m of text.matchAll(/(^|\s)@((?:[^\s"'`]|\\ )+)/g)) refs.add(m[2].replace(/\\ /g, ' ').replace(/[,;:!?)]+$/, ''));
31
+ // Dragged-in paths: '/path/with spaces.png', "/x.png" or /path/with\ spaces.png
32
+ for (const m of text.matchAll(/'([^']+)'|"([^"]+)"|((?:\/|~\/)(?:[^\s\\]|\\ )+)/g)) refs.add((m[1] ?? m[2] ?? m[3]).replace(/\\ /g, ' '));
33
+ for (const ref of refs) {
34
+ if (!isImagePath(ref)) continue;
35
+ const full = path.resolve(cwd, ref.startsWith('~/') ? path.join(os.homedir(), ref.slice(2)) : ref);
36
+ if (!fs.existsSync(full)) continue;
37
+ try {
38
+ images.push(imagePart(full));
39
+ labels.push(`🖼 ${path.basename(full)}`);
40
+ } catch (err) {
41
+ errors.push(err.message);
42
+ }
43
+ }
44
+ for (const file of extraImages) {
45
+ try {
46
+ images.push(imagePart(file));
47
+ labels.push('🖼 pasted image');
48
+ } catch (err) {
49
+ errors.push(err.message);
50
+ }
51
+ }
52
+ const content = images.length ? [{ type: 'text', text: withFiles }, ...images] : withFiles;
53
+ return { content, attached: labels, errors };
54
+ }
55
+
56
+ // Save the image on the clipboard (macOS) to a file. Returns the path or null.
57
+ export function pasteClipboardImage() {
58
+ if (process.platform !== 'darwin') return { error: 'Pasting images works on macOS. Elsewhere, attach a file with @path/to/image.png.' };
59
+ const dir = path.join(HOME_DIR, 'tmp');
60
+ fs.mkdirSync(dir, { recursive: true });
61
+ const file = path.join(dir, `paste-${Date.now()}.png`);
62
+ const script = `set f to open for access POSIX file "${file}" with write permission
63
+ try
64
+ write (the clipboard as «class PNGf») to f
65
+ close access f
66
+ on error
67
+ close access f
68
+ error "no image"
69
+ end try`;
70
+ const r = spawnSync('osascript', ['-e', script], { encoding: 'utf8' });
71
+ if (r.status !== 0 || !fs.existsSync(file) || fs.statSync(file).size === 0) {
72
+ fs.rmSync(file, { force: true });
73
+ return { error: 'There is no image on the clipboard. Copy one first (Cmd+Ctrl+Shift+4 copies a screenshot).' };
74
+ }
75
+ return { file };
76
+ }
7
77
 
8
78
  // "@src/app.js" in a message attaches that file's contents (or a directory listing).
9
79
  export function expandMentions(text, cwd) {
@@ -12,7 +82,7 @@ export function expandMentions(text, cwd) {
12
82
  const seen = new Set();
13
83
  for (const m of text.matchAll(/(^|\s)@((?:[^\s"'`]|\\ )+)/g)) {
14
84
  const ref = m[2].replace(/\\ /g, ' ').replace(/[.,;:!?)]+$/, '');
15
- if (seen.has(ref)) continue;
85
+ if (seen.has(ref) || isImagePath(ref)) continue;
16
86
  seen.add(ref);
17
87
  const full = path.resolve(cwd, ref.startsWith('~/') ? path.join(process.env.HOME || '', ref.slice(2)) : ref);
18
88
  let stat;