@mumbrane/arrakis 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // Minimal client for OpenAI-compatible /chat/completions with streaming and tool calls.
2
+ import { getProvider, normalizeModels } from './providers.js';
2
3
 
3
4
  function headers(config) {
4
5
  const h = { 'content-type': 'application/json' };
@@ -6,19 +7,21 @@ function headers(config) {
6
7
  return h;
7
8
  }
8
9
 
9
- async function request(config, pathname, init, { retries = 3 } = {}) {
10
+ async function request(config, pathname, init, { retries = 3, extraHeaders } = {}) {
10
11
  const url = `${config.baseUrl}${pathname}`;
11
12
  for (let attempt = 0; ; attempt++) {
12
13
  let res;
13
14
  try {
14
- res = await fetch(url, { ...init, headers: headers(config) });
15
+ res = await fetch(url, { ...init, headers: extraHeaders ? { 'content-type': 'application/json', ...extraHeaders } : headers(config) });
15
16
  } catch (err) {
16
17
  if (err.name === 'AbortError') throw err;
17
18
  if (attempt < retries) {
18
19
  await sleep(500 * 2 ** attempt, init.signal);
19
20
  continue;
20
21
  }
21
- throw new Error(`Could not reach ${config.baseUrl} (${err.cause?.code || err.message}). Check baseUrl with: arrakis config`);
22
+ const e = new Error(`Could not reach ${config.baseUrl} (${err.cause?.code || err.message}).`);
23
+ e.unreachable = true;
24
+ throw e;
22
25
  }
23
26
  if (res.ok) return res;
24
27
  const retryable = res.status === 429 || res.status >= 500;
@@ -28,7 +31,9 @@ async function request(config, pathname, init, { retries = 3 } = {}) {
28
31
  continue;
29
32
  }
30
33
  const body = await res.text().catch(() => '');
31
- throw new Error(`API error ${res.status} from ${url}: ${body.slice(0, 500)}`);
34
+ const e = new Error(`API error ${res.status} from ${url}: ${body.slice(0, 500)}`);
35
+ e.status = res.status;
36
+ throw e;
32
37
  }
33
38
  }
34
39
 
@@ -80,11 +85,17 @@ export async function completeText({ config, messages, signal }) {
80
85
  return text;
81
86
  }
82
87
 
88
+ // List the chat models the provider offers, newest first when it says.
89
+ export async function listModels(config) {
90
+ const provider = getProvider(config.provider);
91
+ const extraHeaders = provider?.modelsHeaders && config.apiKey ? provider.modelsHeaders(config.apiKey) : undefined;
92
+ const res = await request(config, `/models${provider?.modelsQuery ?? ''}`, { method: 'GET' }, { retries: 1, extraHeaders });
93
+ return normalizeModels(await res.json());
94
+ }
95
+
83
96
  export async function resolveModel(config) {
84
97
  if (config.model) return config.model;
85
- const res = await request(config, '/models', { method: 'GET' }, { retries: 1 });
86
- const json = await res.json();
87
- const id = json.data?.[0]?.id;
88
- if (!id) throw new Error(`No model configured and ${config.baseUrl}/models listed none. Set one with: arrakis config set model <name>`);
89
- return id;
98
+ const models = await listModels(config);
99
+ if (!models.length) throw new Error(`No model configured and ${config.baseUrl}/models listed none. Pick one with: arrakis setup`);
100
+ return models[0].id;
90
101
  }
package/src/config.js CHANGED
@@ -1,60 +1,133 @@
1
1
  import fs from 'node:fs';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
+ import { getProvider } from './providers.js';
4
5
 
5
6
  export const HOME_DIR = process.env.ARRAKIS_HOME || path.join(os.homedir(), '.arrakis');
6
7
  export const CONFIG_PATH = path.join(HOME_DIR, 'config.json');
7
8
  export const SESSIONS_DIR = path.join(HOME_DIR, 'sessions');
8
9
 
10
+ // Config file shape:
11
+ // {
12
+ // "provider": "anthropic",
13
+ // "providers": { "anthropic": { "apiKey": "...", "model": "...", "contextWindow": 1000000 } },
14
+ // "maxTokens": 0
15
+ // }
16
+ // Each provider keeps its own key and last-used model, so switching back is instant.
17
+
9
18
  export const CONFIG_KEYS = {
10
- baseUrl: { env: 'ARRAKIS_BASE_URL', help: 'OpenAI-compatible API base URL, e.g. https://api.example.com/v1' },
11
- apiKey: { env: 'ARRAKIS_API_KEY', help: 'API key, sent as a Bearer token', secret: true },
12
- model: { env: 'ARRAKIS_MODEL', help: 'Model name (default: first model from /models)' },
19
+ provider: { env: 'ARRAKIS_PROVIDER', help: 'Active provider id (see: arrakis setup)', global: true },
20
+ baseUrl: { env: 'ARRAKIS_BASE_URL', help: 'API base URL (custom provider)' },
21
+ apiKey: { env: 'ARRAKIS_API_KEY', help: 'API key for the active provider', secret: true },
22
+ model: { env: 'ARRAKIS_MODEL', help: 'Model name' },
13
23
  contextWindow: { env: 'ARRAKIS_CONTEXT_WINDOW', help: 'Context window in tokens; history is compacted near 80%', number: true },
14
- maxTokens: { env: 'ARRAKIS_MAX_TOKENS', help: 'Max output tokens per response (optional)', number: true },
24
+ maxTokens: { env: 'ARRAKIS_MAX_TOKENS', help: 'Max output tokens per response (0 = provider default)', number: true, global: true },
15
25
  };
16
26
 
17
- const DEFAULTS = {
18
- baseUrl: 'http://localhost:8000/v1',
19
- apiKey: '',
20
- model: '',
21
- contextWindow: 128000,
22
- maxTokens: 0,
23
- };
27
+ const DEFAULT_CONTEXT = 128000;
24
28
 
25
29
  export function readConfigFile() {
30
+ let file;
26
31
  try {
27
- return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
32
+ file = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
28
33
  } catch {
29
- return {};
34
+ return { providers: {} };
35
+ }
36
+ file.providers ??= {};
37
+ // Migrate the flat 0.2 format ({ baseUrl, apiKey, model }) to a custom provider.
38
+ if (!file.provider && file.baseUrl) {
39
+ file.providers.custom = { baseUrl: file.baseUrl, apiKey: file.apiKey, model: file.model, contextWindow: file.contextWindow };
40
+ file.provider = 'custom';
30
41
  }
42
+ delete file.baseUrl;
43
+ delete file.apiKey;
44
+ delete file.model;
45
+ delete file.contextWindow;
46
+ return file;
47
+ }
48
+
49
+ function writeConfigFile(file) {
50
+ fs.mkdirSync(HOME_DIR, { recursive: true });
51
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(file, null, 2) + '\n', { mode: 0o600 });
52
+ fs.chmodSync(CONFIG_PATH, 0o600);
31
53
  }
32
54
 
33
55
  export function loadConfig(overrides = {}) {
34
56
  const file = readConfigFile();
35
- const config = { ...DEFAULTS };
36
- for (const [key, spec] of Object.entries(CONFIG_KEYS)) {
37
- let value = config[key];
38
- if (file[key] !== undefined && file[key] !== '') value = file[key];
39
- if (process.env[spec.env]) value = process.env[spec.env];
40
- if (overrides[key] !== undefined && overrides[key] !== '') value = overrides[key];
41
- config[key] = spec.number ? Number(value) || 0 : value;
42
- }
57
+ const env = process.env;
58
+ let providerId = overrides.provider || env.ARRAKIS_PROVIDER || file.provider || null;
59
+ // A base URL from the environment or flags without a provider means a custom API.
60
+ if (!providerId && (env.ARRAKIS_BASE_URL || overrides.baseUrl)) providerId = 'custom';
61
+ const provider = providerId ? getProvider(providerId) : null;
62
+ if (providerId && !provider) throw new Error(`Unknown provider "${providerId}". Run: arrakis setup`);
63
+ const saved = (providerId && file.providers[providerId]) || {};
64
+
65
+ const config = {
66
+ provider: providerId,
67
+ providerName: provider?.name ?? '',
68
+ baseUrl: saved.baseUrl || provider?.baseUrl || '',
69
+ apiKey: saved.apiKey || '',
70
+ model: saved.model || '',
71
+ contextWindow: Number(saved.contextWindow) || provider?.contextWindow || DEFAULT_CONTEXT,
72
+ maxTokens: Number(file.maxTokens) || provider?.maxTokens || 0,
73
+ };
74
+ if (env.ARRAKIS_BASE_URL) config.baseUrl = env.ARRAKIS_BASE_URL;
75
+ if (env.ARRAKIS_API_KEY) config.apiKey = env.ARRAKIS_API_KEY;
76
+ if (env.ARRAKIS_MODEL) config.model = env.ARRAKIS_MODEL;
77
+ if (Number(env.ARRAKIS_CONTEXT_WINDOW)) config.contextWindow = Number(env.ARRAKIS_CONTEXT_WINDOW);
78
+ if (Number(env.ARRAKIS_MAX_TOKENS)) config.maxTokens = Number(env.ARRAKIS_MAX_TOKENS);
79
+ if (overrides.baseUrl) config.baseUrl = overrides.baseUrl;
80
+ if (overrides.model) config.model = overrides.model;
43
81
  config.baseUrl = String(config.baseUrl).replace(/\/+$/, '');
44
- if (!config.contextWindow) config.contextWindow = DEFAULTS.contextWindow;
82
+ config.configured = Boolean(config.provider && config.baseUrl && (config.apiKey || provider?.noKey || provider?.custom || env.ARRAKIS_BASE_URL));
45
83
  return config;
46
84
  }
47
85
 
86
+ // Save settings for one provider and (by default) make it the active one.
87
+ export function saveProvider(providerId, patch, { activate = true } = {}) {
88
+ const file = readConfigFile();
89
+ const current = file.providers[providerId] ?? {};
90
+ const next = { ...current, ...patch };
91
+ for (const k of Object.keys(next)) if (next[k] === undefined || next[k] === '') delete next[k];
92
+ file.providers[providerId] = next;
93
+ if (activate) file.provider = providerId;
94
+ writeConfigFile(file);
95
+ }
96
+
97
+ export function savedProviderSettings(providerId) {
98
+ return readConfigFile().providers[providerId] ?? {};
99
+ }
100
+
101
+ // `arrakis config set <key> <value>`
48
102
  export function setConfigValue(key, value) {
49
- if (!CONFIG_KEYS[key]) throw new Error(`Unknown config key "${key}". Keys: ${Object.keys(CONFIG_KEYS).join(', ')}`);
103
+ const spec = CONFIG_KEYS[key];
104
+ if (!spec) throw new Error(`Unknown config key "${key}". Keys: ${Object.keys(CONFIG_KEYS).join(', ')}`);
50
105
  const file = readConfigFile();
51
- if (value === undefined || value === '') delete file[key];
52
- else file[key] = CONFIG_KEYS[key].number ? Number(value) : value;
53
- fs.mkdirSync(HOME_DIR, { recursive: true });
54
- fs.writeFileSync(CONFIG_PATH, JSON.stringify(file, null, 2) + '\n', { mode: 0o600 });
106
+ const v = value === undefined || value === '' ? undefined : spec.number ? Number(value) : value;
107
+ if (key === 'provider') {
108
+ if (v && !getProvider(v)) throw new Error(`Unknown provider "${v}".`);
109
+ if (v) file.provider = v;
110
+ else delete file.provider;
111
+ } else if (spec.global) {
112
+ if (v === undefined) delete file[key];
113
+ else file[key] = v;
114
+ } else {
115
+ const id = file.provider ?? 'custom';
116
+ file.provider = id;
117
+ file.providers[id] ??= {};
118
+ if (v === undefined) delete file.providers[id][key];
119
+ else file.providers[id][key] = v;
120
+ }
121
+ writeConfigFile(file);
122
+ }
123
+
124
+ export function removeProviderKeys() {
125
+ const file = readConfigFile();
126
+ for (const p of Object.values(file.providers)) delete p.apiKey;
127
+ writeConfigFile(file);
55
128
  }
56
129
 
57
130
  export function maskSecret(value) {
58
131
  if (!value) return '(not set)';
59
- return value.length <= 8 ? '****' : `${value.slice(0, 4)}…${value.slice(-4)}`;
132
+ return value.length <= 10 ? '****' : `${value.slice(0, 6)}…${value.slice(-4)}`;
60
133
  }
package/src/input.js ADDED
@@ -0,0 +1,75 @@
1
+ // User input helpers: @file mentions and custom slash commands.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { HOME_DIR } from './config.js';
5
+
6
+ const MAX_ATTACH = 100_000;
7
+
8
+ // "@src/app.js" in a message attaches that file's contents (or a directory listing).
9
+ export function expandMentions(text, cwd) {
10
+ const attached = [];
11
+ const blocks = [];
12
+ const seen = new Set();
13
+ for (const m of text.matchAll(/(^|\s)@((?:[^\s"'`]|\\ )+)/g)) {
14
+ const ref = m[2].replace(/\\ /g, ' ').replace(/[.,;:!?)]+$/, '');
15
+ if (seen.has(ref)) continue;
16
+ seen.add(ref);
17
+ const full = path.resolve(cwd, ref.startsWith('~/') ? path.join(process.env.HOME || '', ref.slice(2)) : ref);
18
+ let stat;
19
+ try {
20
+ stat = fs.statSync(full);
21
+ } catch {
22
+ continue;
23
+ }
24
+ if (stat.isDirectory()) {
25
+ const entries = fs.readdirSync(full, { withFileTypes: true }).map((e) => (e.isDirectory() ? `${e.name}/` : e.name)).sort();
26
+ blocks.push(`<directory path="${ref}">\n${entries.slice(0, 500).join('\n')}\n</directory>`);
27
+ attached.push(`${ref}/`);
28
+ } else if (stat.isFile()) {
29
+ const buf = fs.readFileSync(full);
30
+ if (buf.subarray(0, 8000).includes(0)) continue;
31
+ let body = buf.toString('utf8');
32
+ if (body.length > MAX_ATTACH) body = body.slice(0, MAX_ATTACH) + `\n… (truncated; file is ${body.length} characters, use read_file for the rest)`;
33
+ blocks.push(`<file path="${ref}">\n${body}\n</file>`);
34
+ attached.push(ref);
35
+ }
36
+ }
37
+ if (!blocks.length) return { text, attached };
38
+ return { text: `${text}\n\n${blocks.join('\n\n')}`, attached };
39
+ }
40
+
41
+ // Markdown files in .arrakis/commands (project) and ~/.arrakis/commands (global)
42
+ // become slash commands. $ARGUMENTS in the file is replaced with what follows.
43
+ export function loadCustomCommands(cwd) {
44
+ const dirs = [path.join(HOME_DIR, 'commands'), path.join(cwd, '.arrakis', 'commands')];
45
+ const commands = new Map();
46
+ for (const dir of dirs) {
47
+ let files = [];
48
+ try {
49
+ files = fs.readdirSync(dir).filter((f) => f.endsWith('.md'));
50
+ } catch {
51
+ continue;
52
+ }
53
+ for (const f of files) {
54
+ const body = fs.readFileSync(path.join(dir, f), 'utf8');
55
+ const name = f.slice(0, -3).toLowerCase().replace(/[^a-z0-9_-]/g, '-');
56
+ const firstLine = body.split('\n').find((l) => l.trim())?.replace(/^#+\s*/, '').trim() ?? '';
57
+ commands.set(name, { name, file: path.join(dir, f), body, description: firstLine.slice(0, 60) });
58
+ }
59
+ }
60
+ return commands;
61
+ }
62
+
63
+ export function renderCommand(cmd, args) {
64
+ return cmd.body.includes('$ARGUMENTS') ? cmd.body.replaceAll('$ARGUMENTS', args) : args ? `${cmd.body}\n\n${args}` : cmd.body;
65
+ }
66
+
67
+ 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.
68
+
69
+ Include, briefly:
70
+ - What the project is and how it's organized (key directories and entry points)
71
+ - How to install, build, run, test and lint (exact commands, from package files, Makefiles, CI config, READMEs)
72
+ - Code style and conventions you can see (language versions, formatting, naming, patterns to follow)
73
+ - Anything non-obvious: gotchas, generated files not to edit, environment setup
74
+
75
+ 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.`;
@@ -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
+ }
@@ -1,17 +1,27 @@
1
1
  // Modes: 'ask' prompts for each write/command; 'yolo' allows everything;
2
2
  // 'deny' refuses anything that needs permission (non-interactive default).
3
+ // planMode (separate flag) blocks every tool that changes files or runs commands.
4
+ // Prompts are serialized, so parallel sub-agents ask one question at a time.
3
5
  export class Permissions {
4
6
  constructor({ ui, mode = 'ask', allow = [] }) {
5
7
  this.ui = ui;
6
8
  this.mode = mode;
9
+ this.planMode = false;
7
10
  this.allowed = new Set(allow);
11
+ this.lock = Promise.resolve();
8
12
  }
9
13
 
10
- async check(toolName, preview) {
11
- if (this.mode === 'yolo' || this.allowed.has(toolName)) return true;
12
- if (this.mode === 'deny') return false;
13
- const answer = await this.ui.confirm(preview);
14
- if (answer === 'always') this.allowed.add(toolName);
15
- return answer !== 'no';
14
+ check(toolName, preview) {
15
+ const decide = async () => {
16
+ if (this.mode === 'yolo' || this.allowed.has(toolName)) return true;
17
+ if (this.mode === 'deny') return false;
18
+ if (preview) preview.shown = true;
19
+ const answer = await this.ui.confirm(preview);
20
+ if (answer === 'always') this.allowed.add(toolName);
21
+ return answer !== 'no';
22
+ };
23
+ const result = this.lock.then(decide, decide);
24
+ this.lock = result.catch(() => {});
25
+ return result;
16
26
  }
17
27
  }
package/src/prompt.js CHANGED
@@ -46,7 +46,7 @@ export function loadProjectInstructions(cwd) {
46
46
  });
47
47
  }
48
48
 
49
- export function buildSystemPrompt({ cwd, model }) {
49
+ export function buildSystemPrompt({ cwd, model, planMode = false, subagent = null }) {
50
50
  const git = findUp(cwd, '.git');
51
51
  const instructions = loadProjectInstructions(cwd).filter((i) => i.text.trim());
52
52
  let prompt = `You are Arrakis, a coding agent built by Mumbrane that runs in the user's terminal. You help with software engineering: reading and changing code, running commands, debugging, and explaining.
@@ -68,11 +68,27 @@ export function buildSystemPrompt({ cwd, model }) {
68
68
  - If the user denies a tool call, don't retry it; ask how they want to proceed.
69
69
  - Never print or exfiltrate secrets such as API keys or tokens.
70
70
 
71
+ # Bigger tasks
72
+ - For work with several steps, keep a task list with todo_write: one item in_progress at a time, marked completed as soon as it's done. It shows the user where you are.
73
+ - Use the task tool to hand self-contained jobs to sub-agents with fresh context: searching a big codebase, researching a question, or independent pieces of work. Call it several times in one response to run sub-agents in parallel. Give each one complete instructions, since they can't see this conversation. Prefer agent_type "explore" unless the job needs edits.
74
+ - Use read-only tools (read_file, grep, list_files) in parallel when you need several files; they run at the same time.
75
+ - Use web_fetch for documentation or pages the task needs.
76
+ - For large changes, make them in steps and verify as you go rather than all at once.
77
+
71
78
  # Style
72
79
  - Be concise and direct. Lead with the answer or result; skip preamble.
73
80
  - Reference code as path:line.
74
81
  - When done, say briefly what changed and anything left unverified.`;
75
82
 
83
+ if (planMode) {
84
+ prompt += `\n\n# Plan mode is ON
85
+ The user wants a plan before any changes. Investigate with read-only tools (read_file, grep, list_files, web_fetch, sub-agents of type explore). Do not edit files or run commands; those tools are blocked. When you understand the problem, present a concise, concrete plan: the files to change, what changes, and how you'll verify it. Then stop and wait. The user approves by turning plan mode off with /plan.`;
86
+ }
87
+ if (subagent) {
88
+ prompt += `\n\n# You are a sub-agent
89
+ The main agent started you to do one job. You can't see its conversation and you can't ask the user anything, so work autonomously with what's in your instructions.
90
+ ${subagent.type === 'explore' ? "You are read-only: search and read, don't try to change anything.\n" : ''}When you're done, reply with a concise report: what you found or did, with file paths and line numbers, and anything uncertain. That report is all the main agent sees, so include the details it needs.`;
91
+ }
76
92
  if (instructions.length) {
77
93
  prompt += `\n\n# Project instructions\nThese come from instruction files the user wrote. Follow them.\n`;
78
94
  for (const { file, text } of instructions) prompt += `\n## ${file}\n${text.trim()}\n`;