@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/input.js ADDED
@@ -0,0 +1,145 @@
1
+ // User input helpers: @file mentions and custom slash commands.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { spawnSync } from 'node:child_process';
6
+ import { HOME_DIR } from './config.js';
7
+
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
+ }
77
+
78
+ // "@src/app.js" in a message attaches that file's contents (or a directory listing).
79
+ export function expandMentions(text, cwd) {
80
+ const attached = [];
81
+ const blocks = [];
82
+ const seen = new Set();
83
+ for (const m of text.matchAll(/(^|\s)@((?:[^\s"'`]|\\ )+)/g)) {
84
+ const ref = m[2].replace(/\\ /g, ' ').replace(/[.,;:!?)]+$/, '');
85
+ if (seen.has(ref) || isImagePath(ref)) continue;
86
+ seen.add(ref);
87
+ const full = path.resolve(cwd, ref.startsWith('~/') ? path.join(process.env.HOME || '', ref.slice(2)) : ref);
88
+ let stat;
89
+ try {
90
+ stat = fs.statSync(full);
91
+ } catch {
92
+ continue;
93
+ }
94
+ if (stat.isDirectory()) {
95
+ const entries = fs.readdirSync(full, { withFileTypes: true }).map((e) => (e.isDirectory() ? `${e.name}/` : e.name)).sort();
96
+ blocks.push(`<directory path="${ref}">\n${entries.slice(0, 500).join('\n')}\n</directory>`);
97
+ attached.push(`${ref}/`);
98
+ } else if (stat.isFile()) {
99
+ const buf = fs.readFileSync(full);
100
+ if (buf.subarray(0, 8000).includes(0)) continue;
101
+ let body = buf.toString('utf8');
102
+ if (body.length > MAX_ATTACH) body = body.slice(0, MAX_ATTACH) + `\n… (truncated; file is ${body.length} characters, use read_file for the rest)`;
103
+ blocks.push(`<file path="${ref}">\n${body}\n</file>`);
104
+ attached.push(ref);
105
+ }
106
+ }
107
+ if (!blocks.length) return { text, attached };
108
+ return { text: `${text}\n\n${blocks.join('\n\n')}`, attached };
109
+ }
110
+
111
+ // Markdown files in .arrakis/commands (project) and ~/.arrakis/commands (global)
112
+ // become slash commands. $ARGUMENTS in the file is replaced with what follows.
113
+ export function loadCustomCommands(cwd) {
114
+ const dirs = [path.join(HOME_DIR, 'commands'), path.join(cwd, '.arrakis', 'commands')];
115
+ const commands = new Map();
116
+ for (const dir of dirs) {
117
+ let files = [];
118
+ try {
119
+ files = fs.readdirSync(dir).filter((f) => f.endsWith('.md'));
120
+ } catch {
121
+ continue;
122
+ }
123
+ for (const f of files) {
124
+ const body = fs.readFileSync(path.join(dir, f), 'utf8');
125
+ const name = f.slice(0, -3).toLowerCase().replace(/[^a-z0-9_-]/g, '-');
126
+ const firstLine = body.split('\n').find((l) => l.trim())?.replace(/^#+\s*/, '').trim() ?? '';
127
+ commands.set(name, { name, file: path.join(dir, f), body, description: firstLine.slice(0, 60) });
128
+ }
129
+ }
130
+ return commands;
131
+ }
132
+
133
+ export function renderCommand(cmd, args) {
134
+ return cmd.body.includes('$ARGUMENTS') ? cmd.body.replaceAll('$ARGUMENTS', args) : args ? `${cmd.body}\n\n${args}` : cmd.body;
135
+ }
136
+
137
+ export const INIT_PROMPT = `Look through this project and write an ARRAKIS.md file at the repository root that will help a coding agent work here in future sessions. Use sub-agents (task tool, explore) to survey large codebases in parallel.
138
+
139
+ Include, briefly:
140
+ - What the project is and how it's organized (key directories and entry points)
141
+ - How to install, build, run, test and lint (exact commands, from package files, Makefiles, CI config, READMEs)
142
+ - Code style and conventions you can see (language versions, formatting, naming, patterns to follow)
143
+ - Anything non-obvious: gotchas, generated files not to edit, environment setup
144
+
145
+ Keep it concise and specific to this repository; don't pad it with generic advice. If ARRAKIS.md or AGENTS.md already exists, improve it rather than replacing useful content.`;
package/src/jobs.js ADDED
@@ -0,0 +1,97 @@
1
+ // Background jobs: `arrakis bg "task"` runs a task in a detached process that
2
+ // keeps going after the terminal closes. Each job has a JSON record and a log
3
+ // in ~/.arrakis/jobs/, and its own session, so `arrakis -r <session>` can pick
4
+ // up the conversation afterwards.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import crypto from 'node:crypto';
8
+ import { spawn } from 'node:child_process';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { HOME_DIR } from './config.js';
11
+
12
+ export const JOBS_DIR = path.join(HOME_DIR, 'jobs');
13
+ const BIN = fileURLToPath(new URL('../bin/arrakis.js', import.meta.url));
14
+
15
+ const jobFile = (id) => path.join(JOBS_DIR, `${id}.json`);
16
+ export const jobLog = (id) => path.join(JOBS_DIR, `${id}.log`);
17
+
18
+ export function startJob({ prompt, cwd, flags = [] }) {
19
+ fs.mkdirSync(JOBS_DIR, { recursive: true });
20
+ const id = `job-${crypto.randomBytes(3).toString('hex')}`;
21
+ const out = fs.openSync(jobLog(id), 'a');
22
+ const child = spawn(process.execPath, [BIN, '-p', ...flags, prompt], {
23
+ cwd,
24
+ detached: true,
25
+ stdio: ['ignore', out, out],
26
+ env: { ...process.env, ARRAKIS_JOB_ID: id, NO_COLOR: '1' },
27
+ });
28
+ child.unref();
29
+ const job = { id, pid: child.pid, prompt, cwd, flags, started: Date.now(), status: 'running' };
30
+ fs.writeFileSync(jobFile(id), JSON.stringify(job, null, 2));
31
+ return job;
32
+ }
33
+
34
+ // Called inside the job process to record its session and final status.
35
+ export function updateJob(id, patch) {
36
+ try {
37
+ const job = JSON.parse(fs.readFileSync(jobFile(id), 'utf8'));
38
+ fs.writeFileSync(jobFile(id), JSON.stringify({ ...job, ...patch }, null, 2));
39
+ } catch {}
40
+ }
41
+
42
+ const alive = (pid) => {
43
+ try {
44
+ process.kill(pid, 0);
45
+ return true;
46
+ } catch {
47
+ return false;
48
+ }
49
+ };
50
+
51
+ export function listJobs() {
52
+ if (!fs.existsSync(JOBS_DIR)) return [];
53
+ return fs
54
+ .readdirSync(JOBS_DIR)
55
+ .filter((f) => f.endsWith('.json'))
56
+ .map((f) => {
57
+ try {
58
+ const job = JSON.parse(fs.readFileSync(path.join(JOBS_DIR, f), 'utf8'));
59
+ if (job.status === 'running' && !alive(job.pid)) job.status = 'stopped';
60
+ return job;
61
+ } catch {
62
+ return null;
63
+ }
64
+ })
65
+ .filter(Boolean)
66
+ .sort((a, b) => b.started - a.started);
67
+ }
68
+
69
+ export function findJob(idOrPrefix) {
70
+ const jobs = listJobs();
71
+ const job = jobs.find((j) => j.id === idOrPrefix) ?? jobs.filter((j) => j.id.startsWith(idOrPrefix) || j.id.slice(4).startsWith(idOrPrefix))[0];
72
+ if (!job) throw new Error(`No job "${idOrPrefix}". List jobs with: arrakis jobs`);
73
+ return job;
74
+ }
75
+
76
+ export function stopJob(idOrPrefix) {
77
+ const job = findJob(idOrPrefix);
78
+ if (job.status === 'running') {
79
+ try {
80
+ process.kill(-job.pid, 'SIGTERM');
81
+ } catch {
82
+ try {
83
+ process.kill(job.pid, 'SIGTERM');
84
+ } catch {}
85
+ }
86
+ updateJob(job.id, { status: 'stopped', finished: Date.now() });
87
+ }
88
+ return job;
89
+ }
90
+
91
+ export function readLog(id) {
92
+ try {
93
+ return fs.readFileSync(jobLog(id), 'utf8');
94
+ } catch {
95
+ return '';
96
+ }
97
+ }
@@ -0,0 +1,134 @@
1
+ // Streaming Markdown renderer for the terminal. Text arrives in chunks; each
2
+ // complete line is rendered as soon as its newline arrives. Tables are held
3
+ // until they end so their columns can be aligned.
4
+
5
+ const ANSI = /\x1b\[[0-9;]*m/g;
6
+ export const visibleLength = (s) => s.replace(ANSI, '').length;
7
+
8
+ const KEYWORDS = new Set(
9
+ ('abstract and as async await break case catch class const continue def default defer del delete do elif else enum export extends ' +
10
+ 'false final finally fn for from func function go if impl import in interface is lambda let loop match mod module mut new nil none ' +
11
+ 'not null or package pass private protected pub public raise return self static struct super switch this throw throws true try type ' +
12
+ 'typeof undefined use var void where while with yield None True False').split(' '),
13
+ );
14
+
15
+ export function highlight(line, c) {
16
+ const token = /(\/\/.*$|#(?![!{\[]).*$|--\s.*$)|("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`)|(\b\d+(?:\.\d+)?\b)|([A-Za-z_][A-Za-z0-9_]*)/g;
17
+ return line.replace(token, (m, comment, str, num, word) => {
18
+ if (comment) return c.gray(comment);
19
+ if (str) return c.green(str);
20
+ if (num) return c.yellow(num);
21
+ if (word && KEYWORDS.has(word)) return c.magenta(word);
22
+ return m;
23
+ });
24
+ }
25
+
26
+ export function renderInline(s, c) {
27
+ // Split out `code` spans first so nothing inside them is touched.
28
+ return s
29
+ .split(/(`[^`]+`)/)
30
+ .map((part) => {
31
+ if (/^`[^`]+`$/.test(part)) return c.cyan(part.slice(1, -1));
32
+ return part
33
+ .replace(/\*\*([^*]+)\*\*|__([^_]+)__/g, (_, a, b) => c.bold(a ?? b))
34
+ .replace(/(^|[\s(])\*([^*\s][^*]*)\*(?=$|[\s).,:;!?])/g, (_, pre, a) => pre + c.italic(a))
35
+ .replace(/(^|[\s(])_([^_\s][^_]*)_(?=$|[\s).,:;!?])/g, (_, pre, a) => pre + c.italic(a))
36
+ .replace(/~~([^~]+)~~/g, (_, a) => c.dim(a))
37
+ .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, text, url) => (text === url ? c.underline(url) : `${c.underline(text)} ${c.gray(`(${url})`)}`));
38
+ })
39
+ .join('');
40
+ }
41
+
42
+ export class MarkdownStream {
43
+ constructor(c, { width = 100 } = {}) {
44
+ this.c = c;
45
+ this.width = width;
46
+ this.buf = '';
47
+ this.inCode = false;
48
+ this.fence = '';
49
+ this.table = [];
50
+ }
51
+
52
+ push(chunk) {
53
+ this.buf += chunk;
54
+ let out = '';
55
+ let nl;
56
+ while ((nl = this.buf.indexOf('\n')) >= 0) {
57
+ out += this.line(this.buf.slice(0, nl));
58
+ this.buf = this.buf.slice(nl + 1);
59
+ }
60
+ return out;
61
+ }
62
+
63
+ flush() {
64
+ let out = '';
65
+ if (this.buf) {
66
+ out += this.line(this.buf);
67
+ this.buf = '';
68
+ }
69
+ out += this.flushTable();
70
+ if (this.inCode) {
71
+ out += this.c.gray(' ╰─') + '\n';
72
+ this.inCode = false;
73
+ }
74
+ return out;
75
+ }
76
+
77
+ line(raw) {
78
+ const c = this.c;
79
+ const fence = raw.match(/^\s*(```+|~~~+)\s*([\w+#.-]*)/);
80
+ if (fence && (!this.inCode || raw.trim().startsWith(this.fence))) {
81
+ const out = this.flushTable();
82
+ if (!this.inCode) {
83
+ this.inCode = true;
84
+ this.fence = fence[1];
85
+ return out + c.gray(` ╭─ ${fence[2] || 'code'}`) + '\n';
86
+ }
87
+ this.inCode = false;
88
+ return out + c.gray(' ╰─') + '\n';
89
+ }
90
+ if (this.inCode) return `${c.gray(' β”‚ ')}${highlight(raw, c)}\n`;
91
+
92
+ if (/^\s*\|.*\|\s*$/.test(raw)) {
93
+ this.table.push(raw);
94
+ return '';
95
+ }
96
+ let out = this.flushTable();
97
+
98
+ let m;
99
+ if ((m = raw.match(/^(#{1,6})\s+(.*)$/))) {
100
+ const text = renderInline(m[2].replace(/\s+#+\s*$/, ''), c);
101
+ return out + (m[1].length === 1 ? c.bold(c.underline(c.accent(text))) : m[1].length === 2 ? c.bold(c.accent(text)) : c.bold(text)) + '\n';
102
+ }
103
+ if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(raw)) return out + c.gray('─'.repeat(Math.min(this.width, 60))) + '\n';
104
+ if ((m = raw.match(/^\s*>\s?(.*)$/))) return out + `${c.gray('β”‚ ')}${c.italic(renderInline(m[1], c))}\n`;
105
+ if ((m = raw.match(/^(\s*)[-*+]\s+\[( |x|X)\]\s+(.*)$/))) {
106
+ const done = m[2].toLowerCase() === 'x';
107
+ return out + `${m[1]}${done ? c.green('β˜‘') : c.gray('☐')} ${done ? c.dim(renderInline(m[3], c)) : renderInline(m[3], c)}\n`;
108
+ }
109
+ if ((m = raw.match(/^(\s*)[-*+]\s+(.*)$/))) return out + `${m[1]}${c.accent('β€’')} ${renderInline(m[2], c)}\n`;
110
+ if ((m = raw.match(/^(\s*)(\d+)[.)]\s+(.*)$/))) return out + `${m[1]}${c.accent(m[2] + '.')} ${renderInline(m[3], c)}\n`;
111
+ return out + renderInline(raw, c) + '\n';
112
+ }
113
+
114
+ flushTable() {
115
+ if (!this.table.length) return '';
116
+ const c = this.c;
117
+ const rows = this.table
118
+ .map((l) => l.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((cell) => renderInline(cell.trim(), c)))
119
+ .filter((cells) => !cells.every((cell) => /^:?-{2,}:?$/.test(cell.replace(ANSI, ''))));
120
+ this.table = [];
121
+ if (!rows.length) return '';
122
+ const cols = Math.max(...rows.map((r) => r.length));
123
+ const widths = Array.from({ length: cols }, (_, i) => Math.max(3, ...rows.map((r) => visibleLength(r[i] ?? ''))));
124
+ const pad = (s, w) => s + ' '.repeat(Math.max(0, w - visibleLength(s)));
125
+ const rule = (l, mid, r) => c.gray(l + widths.map((w) => '─'.repeat(w + 2)).join(mid) + r);
126
+ const lines = [rule('β”Œ', '┬', '┐')];
127
+ rows.forEach((r, i) => {
128
+ lines.push(c.gray('β”‚') + widths.map((w, j) => ` ${i === 0 ? c.bold(pad(r[j] ?? '', w)) : pad(r[j] ?? '', w)} `).join(c.gray('β”‚')) + c.gray('β”‚'));
129
+ if (i === 0 && rows.length > 1) lines.push(rule('β”œ', 'β”Ό', '─'));
130
+ });
131
+ lines.push(rule('β””', 'β”΄', 'β”˜'));
132
+ return lines.join('\n') + '\n';
133
+ }
134
+ }