@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/README.md +72 -4
- package/package.json +1 -1
- package/src/agent.js +171 -28
- package/src/checkpoints.js +83 -0
- package/src/cli.js +383 -21
- package/src/config.js +11 -0
- package/src/hooks.js +114 -0
- package/src/input.js +145 -0
- package/src/jobs.js +97 -0
- package/src/markdown.js +134 -0
- package/src/mcp.js +343 -0
- package/src/permissions.js +16 -6
- package/src/prompt.js +17 -1
- package/src/session.js +12 -1
- package/src/tools.js +200 -15
- package/src/ui.js +267 -30
- package/src/update.js +33 -0
package/src/mcp.js
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
// Model Context Protocol client. Connects to MCP servers (local processes over
|
|
2
|
+
// stdio, or remote servers over Streamable HTTP) and exposes their tools to the
|
|
3
|
+
// agent as mcp__<server>__<tool>.
|
|
4
|
+
//
|
|
5
|
+
// Config uses the common "mcpServers" shape, read from (later wins):
|
|
6
|
+
// ~/.arrakis/mcp.json your servers, everywhere
|
|
7
|
+
// <project>/.mcp.json shared project servers (asks before first use)
|
|
8
|
+
// <project>/.arrakis/mcp.json project servers for arrakis (asks before first use)
|
|
9
|
+
// {
|
|
10
|
+
// "mcpServers": {
|
|
11
|
+
// "github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "env": { "GITHUB_TOKEN": "..." } },
|
|
12
|
+
// "docs": { "url": "https://example.com/mcp", "headers": { "Authorization": "Bearer ..." } }
|
|
13
|
+
// }
|
|
14
|
+
// }
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import { spawn } from 'node:child_process';
|
|
18
|
+
import readline from 'node:readline';
|
|
19
|
+
import { HOME_DIR } from './config.js';
|
|
20
|
+
import { VERSION } from './version.js';
|
|
21
|
+
|
|
22
|
+
const PROTOCOL = '2025-06-18';
|
|
23
|
+
const CONNECT_TIMEOUT = 20000;
|
|
24
|
+
const CALL_TIMEOUT = 300000;
|
|
25
|
+
|
|
26
|
+
export function mcpConfigFiles(cwd) {
|
|
27
|
+
return {
|
|
28
|
+
user: [path.join(HOME_DIR, 'mcp.json')],
|
|
29
|
+
project: [path.join(cwd, '.mcp.json'), path.join(cwd, '.arrakis', 'mcp.json')],
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function readServers(file) {
|
|
34
|
+
try {
|
|
35
|
+
const json = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
36
|
+
return json.mcpServers ?? json.servers ?? {};
|
|
37
|
+
} catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Returns { servers: {name: {...cfg, source}}, projectFiles: [files that exist] }
|
|
43
|
+
export function loadMcpConfig(cwd, { includeProject = true } = {}) {
|
|
44
|
+
const { user, project } = mcpConfigFiles(cwd);
|
|
45
|
+
const servers = {};
|
|
46
|
+
const projectFiles = [];
|
|
47
|
+
for (const file of user) for (const [name, cfg] of Object.entries(readServers(file) ?? {})) servers[name] = { ...cfg, source: file };
|
|
48
|
+
for (const file of project) {
|
|
49
|
+
const found = readServers(file);
|
|
50
|
+
if (!found) continue;
|
|
51
|
+
projectFiles.push(file);
|
|
52
|
+
if (includeProject) for (const [name, cfg] of Object.entries(found)) servers[name] = { ...cfg, source: file };
|
|
53
|
+
}
|
|
54
|
+
return { servers, projectFiles };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Expand ${VAR} references from the environment in strings.
|
|
58
|
+
const expand = (v) => (typeof v === 'string' ? v.replace(/\$\{(\w+)\}/g, (_, k) => process.env[k] ?? '') : v);
|
|
59
|
+
const expandAll = (obj) => Object.fromEntries(Object.entries(obj ?? {}).map(([k, v]) => [k, expand(v)]));
|
|
60
|
+
|
|
61
|
+
class StdioTransport {
|
|
62
|
+
constructor(cfg, cwd) {
|
|
63
|
+
this.cfg = cfg;
|
|
64
|
+
this.cwd = cwd;
|
|
65
|
+
this.pending = new Map();
|
|
66
|
+
this.nextId = 1;
|
|
67
|
+
this.stderr = '';
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async start() {
|
|
71
|
+
const { command, args = [], env = {} } = this.cfg;
|
|
72
|
+
this.proc = spawn(expand(command), args.map(expand), {
|
|
73
|
+
cwd: this.cfg.cwd ? path.resolve(this.cwd, this.cfg.cwd) : this.cwd,
|
|
74
|
+
env: { ...process.env, ...expandAll(env) },
|
|
75
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
76
|
+
});
|
|
77
|
+
this.proc.stderr.on('data', (d) => {
|
|
78
|
+
this.stderr = (this.stderr + d).slice(-4000);
|
|
79
|
+
});
|
|
80
|
+
const exited = new Promise((_, reject) => {
|
|
81
|
+
this.proc.on('error', (err) => reject(new Error(`could not start "${command}": ${err.message}`)));
|
|
82
|
+
this.proc.on('exit', (code) => {
|
|
83
|
+
const err = new Error(`server exited (code ${code})${this.stderr ? `: ${this.stderr.trim().split('\n').slice(-3).join(' ')}` : ''}`);
|
|
84
|
+
for (const { reject: r } of this.pending.values()) r(err);
|
|
85
|
+
this.pending.clear();
|
|
86
|
+
this.closed = err;
|
|
87
|
+
reject(err);
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
exited.catch(() => {});
|
|
91
|
+
this.exited = exited;
|
|
92
|
+
readline.createInterface({ input: this.proc.stdout }).on('line', (line) => this.onLine(line));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
onLine(line) {
|
|
96
|
+
let msg;
|
|
97
|
+
try {
|
|
98
|
+
msg = JSON.parse(line);
|
|
99
|
+
} catch {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (msg.id !== undefined && (msg.result !== undefined || msg.error !== undefined)) {
|
|
103
|
+
const p = this.pending.get(msg.id);
|
|
104
|
+
if (!p) return;
|
|
105
|
+
this.pending.delete(msg.id);
|
|
106
|
+
if (msg.error) p.reject(new Error(msg.error.message ?? JSON.stringify(msg.error)));
|
|
107
|
+
else p.resolve(msg.result);
|
|
108
|
+
} else if (msg.id !== undefined && msg.method) {
|
|
109
|
+
// Server-to-client request: answer ping, refuse the rest politely.
|
|
110
|
+
const reply = msg.method === 'ping' ? { jsonrpc: '2.0', id: msg.id, result: {} } : { jsonrpc: '2.0', id: msg.id, error: { code: -32601, message: 'Not supported by arrakis' } };
|
|
111
|
+
this.send(reply);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
send(obj) {
|
|
116
|
+
if (this.closed) throw this.closed;
|
|
117
|
+
this.proc.stdin.write(JSON.stringify(obj) + '\n');
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
request(method, params, { timeout = CALL_TIMEOUT, signal } = {}) {
|
|
121
|
+
const id = this.nextId++;
|
|
122
|
+
return new Promise((resolve, reject) => {
|
|
123
|
+
const timer = setTimeout(() => {
|
|
124
|
+
this.pending.delete(id);
|
|
125
|
+
reject(new Error(`${method} timed out`));
|
|
126
|
+
}, timeout);
|
|
127
|
+
const done = (fn) => (v) => {
|
|
128
|
+
clearTimeout(timer);
|
|
129
|
+
fn(v);
|
|
130
|
+
};
|
|
131
|
+
this.pending.set(id, { resolve: done(resolve), reject: done(reject) });
|
|
132
|
+
signal?.addEventListener('abort', () => {
|
|
133
|
+
this.pending.delete(id);
|
|
134
|
+
clearTimeout(timer);
|
|
135
|
+
try {
|
|
136
|
+
this.send({ jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId: id } });
|
|
137
|
+
} catch {}
|
|
138
|
+
reject(new DOMException('Aborted', 'AbortError'));
|
|
139
|
+
}, { once: true });
|
|
140
|
+
try {
|
|
141
|
+
this.send({ jsonrpc: '2.0', id, method, params });
|
|
142
|
+
} catch (err) {
|
|
143
|
+
this.pending.delete(id);
|
|
144
|
+
clearTimeout(timer);
|
|
145
|
+
reject(err);
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
notify(method, params) {
|
|
151
|
+
this.send({ jsonrpc: '2.0', method, params });
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
close() {
|
|
155
|
+
try {
|
|
156
|
+
this.proc?.stdin.end();
|
|
157
|
+
this.proc?.kill();
|
|
158
|
+
} catch {}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
class HttpTransport {
|
|
163
|
+
constructor(cfg) {
|
|
164
|
+
this.url = expand(cfg.url);
|
|
165
|
+
this.headers = expandAll(cfg.headers);
|
|
166
|
+
this.nextId = 1;
|
|
167
|
+
this.sessionId = null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async start() {}
|
|
171
|
+
|
|
172
|
+
async post(body, signal) {
|
|
173
|
+
const headers = { 'content-type': 'application/json', accept: 'application/json, text/event-stream', ...this.headers };
|
|
174
|
+
if (this.sessionId) headers['mcp-session-id'] = this.sessionId;
|
|
175
|
+
if (this.protocol) headers['mcp-protocol-version'] = this.protocol;
|
|
176
|
+
const res = await fetch(this.url, { method: 'POST', headers, body: JSON.stringify(body), signal });
|
|
177
|
+
const sid = res.headers.get('mcp-session-id');
|
|
178
|
+
if (sid) this.sessionId = sid;
|
|
179
|
+
if (!res.ok && res.status !== 202) {
|
|
180
|
+
const text = await res.text().catch(() => '');
|
|
181
|
+
throw new Error(`HTTP ${res.status}${res.status === 401 ? ' (unauthorized: check the headers in your MCP config)' : ''}: ${text.slice(0, 200)}`);
|
|
182
|
+
}
|
|
183
|
+
return res;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async request(method, params, { timeout = CALL_TIMEOUT, signal } = {}) {
|
|
187
|
+
const id = this.nextId++;
|
|
188
|
+
const ac = new AbortController();
|
|
189
|
+
const timer = setTimeout(() => ac.abort(), timeout);
|
|
190
|
+
signal?.addEventListener('abort', () => ac.abort(), { once: true });
|
|
191
|
+
try {
|
|
192
|
+
const res = await this.post({ jsonrpc: '2.0', id, method, params }, ac.signal);
|
|
193
|
+
const type = res.headers.get('content-type') ?? '';
|
|
194
|
+
const messages = [];
|
|
195
|
+
if (type.includes('text/event-stream')) {
|
|
196
|
+
const decoder = new TextDecoder();
|
|
197
|
+
let buf = '';
|
|
198
|
+
outer: for await (const chunk of res.body) {
|
|
199
|
+
buf += decoder.decode(chunk, { stream: true });
|
|
200
|
+
let i;
|
|
201
|
+
while ((i = buf.indexOf('\n\n')) >= 0) {
|
|
202
|
+
const event = buf.slice(0, i);
|
|
203
|
+
buf = buf.slice(i + 2);
|
|
204
|
+
const data = event.split('\n').filter((l) => l.startsWith('data:')).map((l) => l.slice(5).trim()).join('\n');
|
|
205
|
+
if (!data) continue;
|
|
206
|
+
try {
|
|
207
|
+
const msg = JSON.parse(data);
|
|
208
|
+
messages.push(msg);
|
|
209
|
+
if (msg.id === id) break outer;
|
|
210
|
+
} catch {}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
} else {
|
|
214
|
+
const json = await res.json();
|
|
215
|
+
messages.push(...(Array.isArray(json) ? json : [json]));
|
|
216
|
+
}
|
|
217
|
+
const reply = messages.find((m) => m.id === id);
|
|
218
|
+
if (!reply) throw new Error(`no response to ${method}`);
|
|
219
|
+
if (reply.error) throw new Error(reply.error.message ?? JSON.stringify(reply.error));
|
|
220
|
+
return reply.result;
|
|
221
|
+
} catch (err) {
|
|
222
|
+
if (err.name === 'AbortError' && !signal?.aborted) throw new Error(`${method} timed out`);
|
|
223
|
+
throw err;
|
|
224
|
+
} finally {
|
|
225
|
+
clearTimeout(timer);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async notify(method, params) {
|
|
230
|
+
await this.post({ jsonrpc: '2.0', method, params }).catch(() => {});
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
close() {
|
|
234
|
+
if (this.sessionId) fetch(this.url, { method: 'DELETE', headers: { 'mcp-session-id': this.sessionId, ...this.headers } }).catch(() => {});
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export class McpServer {
|
|
239
|
+
constructor(name, cfg, cwd) {
|
|
240
|
+
this.name = name;
|
|
241
|
+
this.cfg = cfg;
|
|
242
|
+
this.cwd = cwd;
|
|
243
|
+
this.status = 'pending';
|
|
244
|
+
this.error = null;
|
|
245
|
+
this.tools = [];
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async connect() {
|
|
249
|
+
this.transport = this.cfg.url ? new HttpTransport(this.cfg) : new StdioTransport(this.cfg, this.cwd);
|
|
250
|
+
try {
|
|
251
|
+
if (!this.cfg.url && !this.cfg.command) throw new Error('needs "command" (local server) or "url" (remote server)');
|
|
252
|
+
await this.transport.start();
|
|
253
|
+
const init = this.transport.request('initialize', {
|
|
254
|
+
protocolVersion: PROTOCOL,
|
|
255
|
+
capabilities: {},
|
|
256
|
+
clientInfo: { name: 'arrakis', version: VERSION },
|
|
257
|
+
}, { timeout: CONNECT_TIMEOUT });
|
|
258
|
+
const info = await (this.transport.exited ? Promise.race([init, this.transport.exited]) : init);
|
|
259
|
+
this.transport.protocol = info?.protocolVersion ?? PROTOCOL;
|
|
260
|
+
this.serverInfo = info?.serverInfo;
|
|
261
|
+
this.instructions = info?.instructions;
|
|
262
|
+
await this.transport.notify('notifications/initialized', {});
|
|
263
|
+
const tools = [];
|
|
264
|
+
let cursor;
|
|
265
|
+
do {
|
|
266
|
+
const page = await this.transport.request('tools/list', cursor ? { cursor } : {}, { timeout: CONNECT_TIMEOUT });
|
|
267
|
+
tools.push(...(page?.tools ?? []));
|
|
268
|
+
cursor = page?.nextCursor;
|
|
269
|
+
} while (cursor);
|
|
270
|
+
this.tools = tools;
|
|
271
|
+
this.status = 'connected';
|
|
272
|
+
} catch (err) {
|
|
273
|
+
this.status = 'failed';
|
|
274
|
+
this.error = err.message;
|
|
275
|
+
this.transport.close();
|
|
276
|
+
}
|
|
277
|
+
return this;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
async callTool(name, args, signal) {
|
|
281
|
+
const result = await this.transport.request('tools/call', { name, arguments: args ?? {} }, { signal });
|
|
282
|
+
const parts = [];
|
|
283
|
+
for (const c of result?.content ?? []) {
|
|
284
|
+
if (c.type === 'text') parts.push(c.text);
|
|
285
|
+
else if (c.type === 'image') parts.push(`[image ${c.mimeType ?? ''} omitted]`);
|
|
286
|
+
else if (c.type === 'resource') parts.push(c.resource?.text ?? `[resource ${c.resource?.uri ?? ''}]`);
|
|
287
|
+
else if (c.type === 'resource_link') parts.push(`[resource ${c.uri}]`);
|
|
288
|
+
else parts.push(JSON.stringify(c));
|
|
289
|
+
}
|
|
290
|
+
if (!parts.length && result?.structuredContent) parts.push(JSON.stringify(result.structuredContent, null, 2));
|
|
291
|
+
return { text: parts.join('\n') || '(no output)', isError: Boolean(result?.isError) };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
close() {
|
|
295
|
+
this.transport?.close();
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const toolId = (server, tool) => `mcp__${server}__${tool}`.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64);
|
|
300
|
+
|
|
301
|
+
// Turn connected servers' tools into arrakis tool definitions.
|
|
302
|
+
export function mcpTools(servers) {
|
|
303
|
+
const out = [];
|
|
304
|
+
for (const server of servers) {
|
|
305
|
+
if (server.status !== 'connected') continue;
|
|
306
|
+
for (const t of server.tools) {
|
|
307
|
+
const readOnly = t.annotations?.readOnlyHint === true;
|
|
308
|
+
out.push({
|
|
309
|
+
name: toolId(server.name, t.name),
|
|
310
|
+
label: `${server.name}:${t.name}`,
|
|
311
|
+
description: `[MCP server "${server.name}"] ${t.description ?? t.title ?? t.name}`.slice(0, 1024),
|
|
312
|
+
parameters: t.inputSchema && typeof t.inputSchema === 'object' ? { type: 'object', properties: {}, ...t.inputSchema } : { type: 'object', properties: {} },
|
|
313
|
+
needsPermission: !readOnly,
|
|
314
|
+
writes: !readOnly,
|
|
315
|
+
mcp: true,
|
|
316
|
+
summary: (a) => {
|
|
317
|
+
const s = JSON.stringify(a ?? {});
|
|
318
|
+
return s === '{}' ? '' : s.length > 80 ? s.slice(0, 80) + '…' : s;
|
|
319
|
+
},
|
|
320
|
+
preview: (a) => ({
|
|
321
|
+
title: `${server.name} → ${t.name}`,
|
|
322
|
+
lines: JSON.stringify(a ?? {}, null, 2).split('\n').slice(0, 12).map((text) => ({ sign: ' ', text })),
|
|
323
|
+
}),
|
|
324
|
+
async run(a, ctx) {
|
|
325
|
+
const { text, isError } = await server.callTool(t.name, a, ctx.signal);
|
|
326
|
+
if (isError) throw new Error(text);
|
|
327
|
+
return text;
|
|
328
|
+
},
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return out;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export async function connectAll(cwd, { includeProject }) {
|
|
336
|
+
const { servers } = loadMcpConfig(cwd, { includeProject });
|
|
337
|
+
const list = Object.entries(servers)
|
|
338
|
+
.filter(([, cfg]) => cfg.disabled !== true)
|
|
339
|
+
.map(([name, cfg]) => new McpServer(name, cfg, cwd));
|
|
340
|
+
await Promise.all(list.map((s) => s.connect()));
|
|
341
|
+
process.once('exit', () => list.forEach((s) => s.close()));
|
|
342
|
+
return list;
|
|
343
|
+
}
|
package/src/permissions.js
CHANGED
|
@@ -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
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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`;
|
package/src/session.js
CHANGED
|
@@ -59,12 +59,18 @@ export class Session {
|
|
|
59
59
|
return session;
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
+
// A session that lives only in memory (used by sub-agents).
|
|
63
|
+
static memory() {
|
|
64
|
+
return new Session({ id: 'memory', file: null, meta: {} });
|
|
65
|
+
}
|
|
66
|
+
|
|
62
67
|
static latest(cwd) {
|
|
63
68
|
const s = listSessions().find((x) => x.cwd === cwd);
|
|
64
69
|
return s ? Session.load(s.id) : null;
|
|
65
70
|
}
|
|
66
71
|
|
|
67
72
|
append(event) {
|
|
73
|
+
if (!this.file) return;
|
|
68
74
|
const line = JSON.stringify({ ...event, t: event.t ?? Date.now() }) + '\n';
|
|
69
75
|
const fd = fs.openSync(this.file, 'a', 0o600);
|
|
70
76
|
try {
|
|
@@ -89,6 +95,11 @@ export class Session {
|
|
|
89
95
|
this.append({ type: 'compact', messages: this.messages });
|
|
90
96
|
}
|
|
91
97
|
|
|
98
|
+
replace(messages) {
|
|
99
|
+
this.messages = messages;
|
|
100
|
+
this.append({ type: 'compact', messages });
|
|
101
|
+
}
|
|
102
|
+
|
|
92
103
|
// Every assistant tool call needs a matching tool result, or the API rejects
|
|
93
104
|
// the history. After an interrupt or crash, fill in the missing ones.
|
|
94
105
|
repair() {
|
|
@@ -134,7 +145,7 @@ export function listSessions() {
|
|
|
134
145
|
model: meta.model,
|
|
135
146
|
updated: fs.statSync(file).mtimeMs,
|
|
136
147
|
messages: count,
|
|
137
|
-
title: typeof firstUser?.message.content === 'string' ? firstUser.message.content.replace(/\s+/g, ' ').slice(0, 70)
|
|
148
|
+
title: (typeof firstUser?.message.content === 'string' ? firstUser.message.content : Array.isArray(firstUser?.message.content) ? firstUser.message.content.find((p) => p.type === 'text')?.text ?? '' : '').replace(/\s+/g, ' ').slice(0, 70),
|
|
138
149
|
});
|
|
139
150
|
}
|
|
140
151
|
return out.sort((a, b) => b.updated - a.updated);
|