@mumbrane/arrakis 0.6.0 → 0.7.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 +15 -0
- package/package.json +5 -2
- package/src/agent.js +95 -32
- package/src/anthropic.js +186 -0
- package/src/cli.js +92 -5
- package/src/client.js +6 -0
- package/src/config.js +3 -0
- package/src/pricing.js +59 -0
- package/src/prompt.js +1 -5
- package/src/providers.js +0 -1
- package/src/tools.js +21 -0
- package/src/tui.js +78 -10
package/README.md
CHANGED
|
@@ -10,6 +10,7 @@ A coding agent for your terminal, built by Mumbrane. It reads your code, edits f
|
|
|
10
10
|
- **Images:** attach screenshots and mockups
|
|
11
11
|
- **Background jobs:** hand off a task and close the terminal
|
|
12
12
|
- **Hooks:** run your own scripts before or after the agent's actions
|
|
13
|
+
- **Native Claude support:** prompt caching, visible thinking, effort control and cost tracking
|
|
13
14
|
- **Crash-safe sessions:** every step is logged; pick up exactly where you left off
|
|
14
15
|
|
|
15
16
|
## Install
|
|
@@ -56,6 +57,10 @@ In a session:
|
|
|
56
57
|
| `/plan` | Plan mode: investigate and propose, change nothing; `/plan` again to approve |
|
|
57
58
|
| `/init` | Write `ARRAKIS.md` project notes for this folder |
|
|
58
59
|
| `/todos` | Show the current task list |
|
|
60
|
+
| `/cost` | Tokens, cache hits and estimated cost for this session |
|
|
61
|
+
| `/effort [level]` | How hard Claude thinks: `low` to `max` |
|
|
62
|
+
| `/resume` | Switch to an earlier session |
|
|
63
|
+
| `/export [file]` | Save the conversation as Markdown |
|
|
59
64
|
| `/undo [n]` | Revert arrakis's file changes from the last turn (or pick a turn) |
|
|
60
65
|
| `/paste` | Attach the image on your clipboard (macOS) |
|
|
61
66
|
| `/mcp` | Show connected MCP servers and their tools |
|
|
@@ -86,6 +91,16 @@ Sub-agents of type `explore` (the default) can only read and search. `general` s
|
|
|
86
91
|
|
|
87
92
|
`-p` mode denies tools that need permission unless you pass `--yolo` or `--allow edit_file,write_file,bash`.
|
|
88
93
|
|
|
94
|
+
## Claude
|
|
95
|
+
|
|
96
|
+
With the Anthropic provider, arrakis talks to the Claude API directly (through Anthropic's official SDK):
|
|
97
|
+
|
|
98
|
+
- **Prompt caching** is on automatically, so each turn re-reads the conversation from cache at a fraction of the price. `/cost` shows how much was served from cache.
|
|
99
|
+
- **Thinking** summaries appear, dimmed, above Claude's replies.
|
|
100
|
+
- **Effort** (`/effort`, or `arrakis config set effort high`) trades thoroughness for speed and cost.
|
|
101
|
+
- **Fallbacks:** on models that support it, if Claude declines a request, the API can retry it on another Claude model.
|
|
102
|
+
- Sessions stay append-only: the system prompt is fixed for the session and Claude's responses are replayed exactly, which keeps the cache warm and Claude's earlier reasoning valid.
|
|
103
|
+
|
|
89
104
|
## Undo
|
|
90
105
|
|
|
91
106
|
Before arrakis writes or edits a file, it saves the original. `/undo` reverts the last turn's changes; with several turns it lets you pick how far back to go. Checkpoints are stored with the session, so undo still works after `arrakis -c`. Changes made by shell commands (`bash`) aren't tracked, so use git for those.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mumbrane/arrakis",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Arrakis: a coding agent for your terminal, built by Mumbrane",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
|
@@ -35,5 +35,8 @@
|
|
|
35
35
|
"coding-agent",
|
|
36
36
|
"cli",
|
|
37
37
|
"terminal"
|
|
38
|
-
]
|
|
38
|
+
],
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"@anthropic-ai/sdk": "^1.10.0"
|
|
41
|
+
}
|
|
39
42
|
}
|
package/src/agent.js
CHANGED
|
@@ -2,6 +2,8 @@ import { streamChat, completeText } from './client.js';
|
|
|
2
2
|
import { toolSchemas, executeToolCall, truncate, READ_ONLY_TOOLS, PARALLEL_SAFE } from './tools.js';
|
|
3
3
|
import { buildSystemPrompt } from './prompt.js';
|
|
4
4
|
import { Session } from './session.js';
|
|
5
|
+
import { isNativeAnthropic, streamAnthropic, completeAnthropic } from './anthropic.js';
|
|
6
|
+
import { Usage } from './pricing.js';
|
|
5
7
|
|
|
6
8
|
const MAX_STEPS = 400;
|
|
7
9
|
const MAX_SUB_STEPS = 150;
|
|
@@ -24,7 +26,7 @@ const textOf = (content) => (Array.isArray(content) ? content.map((p) => (p.type
|
|
|
24
26
|
|
|
25
27
|
export class Agent {
|
|
26
28
|
// depth 0 is the agent the user talks to; sub-agents have depth >= 1.
|
|
27
|
-
constructor({ config, session, ui, permissions, cwd, depth = 0, label = '', toolFilter = null, checkpoints = null, hooks = null }) {
|
|
29
|
+
constructor({ config, session, ui, permissions, cwd, depth = 0, label = '', toolFilter = null, checkpoints = null, hooks = null, usage = null }) {
|
|
28
30
|
this.config = config;
|
|
29
31
|
this.session = session;
|
|
30
32
|
this.ui = ui;
|
|
@@ -36,6 +38,10 @@ export class Agent {
|
|
|
36
38
|
this.checkpoints = checkpoints;
|
|
37
39
|
this.hooks = hooks;
|
|
38
40
|
this.notes = []; // things to tell the model with the next message (e.g. an undo)
|
|
41
|
+
this.usage = usage ?? new Usage();
|
|
42
|
+
// The system prompt is built once and then frozen: changing it mid-session
|
|
43
|
+
// invalidates the prompt cache (and, on Claude, earlier thinking blocks).
|
|
44
|
+
this.systemPrompt = null;
|
|
39
45
|
this.abort = null;
|
|
40
46
|
this.todos = [];
|
|
41
47
|
this.toolCount = 0;
|
|
@@ -163,6 +169,7 @@ export class Agent {
|
|
|
163
169
|
toolFilter: readOnly ? (name) => READ_ONLY_TOOLS.has(name) : null,
|
|
164
170
|
checkpoints: this.checkpoints,
|
|
165
171
|
hooks: this.hooks,
|
|
172
|
+
usage: this.usage,
|
|
166
173
|
});
|
|
167
174
|
sub.subagentType = readOnly ? 'explore' : 'general';
|
|
168
175
|
const started = Date.now();
|
|
@@ -176,44 +183,97 @@ export class Agent {
|
|
|
176
183
|
return { content: report || '(The sub-agent returned no report.)', display: `${description}: done (${stats})` };
|
|
177
184
|
}
|
|
178
185
|
|
|
179
|
-
|
|
180
|
-
|
|
186
|
+
// Turn plan mode on or off. Told to the model as a note on the next message,
|
|
187
|
+
// so the system prompt (and the prompt cache) stays unchanged.
|
|
188
|
+
setPlanMode(on) {
|
|
189
|
+
if (this.permissions.planMode === on) return;
|
|
190
|
+
this.permissions.planMode = on;
|
|
191
|
+
this.notes.push(
|
|
192
|
+
on
|
|
193
|
+
? '[Plan mode is ON. The user wants a plan before any changes. Investigate with read-only tools (read_file, grep, list_files, web_fetch, explore sub-agents). Do not edit files or run commands; those tools are blocked. Then present a concise, concrete plan: files to change, what changes, how you will verify it, and stop.]'
|
|
194
|
+
: '[Plan mode is OFF. You may make changes now.]',
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
get system() {
|
|
199
|
+
this.systemPrompt ??= buildSystemPrompt({
|
|
181
200
|
cwd: this.cwd,
|
|
182
201
|
model: this.config.model,
|
|
183
|
-
planMode: this.permissions.planMode,
|
|
184
202
|
subagent: this.depth > 0 ? { type: this.subagentType } : null,
|
|
185
203
|
});
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
204
|
+
return this.systemPrompt;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async callModel(signal) {
|
|
208
|
+
const history = [{ role: 'system', content: this.system }, ...this.session.messages];
|
|
209
|
+
const tools = toolSchemas((n) => this.allowsTool(n));
|
|
189
210
|
if (!this.silent) {
|
|
190
211
|
this.ui.startResponse();
|
|
191
212
|
this.ui.startSpinner();
|
|
192
213
|
}
|
|
193
214
|
try {
|
|
194
|
-
|
|
195
|
-
const delta = event.choices?.[0]?.delta;
|
|
196
|
-
if (!delta) continue;
|
|
197
|
-
const reasoning = delta.reasoning_content ?? delta.reasoning;
|
|
198
|
-
if (reasoning && !this.silent) this.ui.thinking(reasoning);
|
|
199
|
-
if (delta.content) {
|
|
200
|
-
content += delta.content;
|
|
201
|
-
if (!this.silent) this.ui.text(delta.content);
|
|
202
|
-
}
|
|
203
|
-
for (const tc of delta.tool_calls ?? []) {
|
|
204
|
-
const idx = tc.index ?? (tc.id ? calls.length : Math.max(0, calls.length - 1));
|
|
205
|
-
const c = (calls[idx] ??= { id: '', type: 'function', function: { name: '', arguments: '' } });
|
|
206
|
-
if (tc.id) c.id = tc.id;
|
|
207
|
-
if (tc.function?.name && !c.function.name) c.function.name = tc.function.name;
|
|
208
|
-
if (tc.function?.arguments) {
|
|
209
|
-
c.function.arguments += tc.function.arguments;
|
|
210
|
-
if (!this.silent) this.ui.addTokens?.(tc.function.arguments.length / 4);
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
}
|
|
215
|
+
return isNativeAnthropic(this.config) ? await this.callAnthropic(history, tools, signal) : await this.callOpenAI(history, tools, signal);
|
|
214
216
|
} finally {
|
|
215
217
|
if (!this.silent) this.ui.endText();
|
|
216
218
|
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async callAnthropic(history, tools, signal) {
|
|
222
|
+
let final = null;
|
|
223
|
+
for await (const ev of streamAnthropic({ config: this.config, history, tools, signal })) {
|
|
224
|
+
if (ev.type === 'done') final = ev.message;
|
|
225
|
+
if (this.silent) continue;
|
|
226
|
+
if (ev.type === 'text') this.ui.text(ev.text);
|
|
227
|
+
else if (ev.type === 'thinking') this.ui.thinking(ev.text);
|
|
228
|
+
else if (ev.type === 'tool_input') this.ui.addTokens?.(ev.text.length / 4);
|
|
229
|
+
else if (ev.type === 'retry') this.ui.info(' (Claude sent a malformed tool call; retrying)');
|
|
230
|
+
}
|
|
231
|
+
this.usage.add(final.model ?? this.config.model, final.usage);
|
|
232
|
+
let blocks = final.content ?? [];
|
|
233
|
+
const text = blocks.filter((b) => b.type === 'text').map((b) => b.text).join('');
|
|
234
|
+
let toolUses = blocks.filter((b) => b.type === 'tool_use');
|
|
235
|
+
// Never run a tool call that was cut off or declined part-way.
|
|
236
|
+
if (final.stop_reason === 'refusal' || (final.stop_reason === 'max_tokens' && toolUses.length)) {
|
|
237
|
+
blocks = blocks.filter((b) => b.type !== 'tool_use');
|
|
238
|
+
toolUses = [];
|
|
239
|
+
const why = final.stop_reason === 'refusal'
|
|
240
|
+
? `Claude declined to continue${final.stop_details?.category ? ` (${final.stop_details.category})` : ''}. Try rephrasing the request.`
|
|
241
|
+
: 'The response hit the output limit in the middle of a tool call. Ask for smaller steps, or raise it with: arrakis config set maxTokens 128000';
|
|
242
|
+
this.lastError = why;
|
|
243
|
+
if (!this.silent) this.ui.error(why);
|
|
244
|
+
}
|
|
245
|
+
const msg = { role: 'assistant', content: text || (toolUses.length ? null : ''), anthropic: blocks };
|
|
246
|
+
if (toolUses.length) {
|
|
247
|
+
msg.tool_calls = toolUses.map((b) => ({ id: b.id, type: 'function', function: { name: b.name, arguments: JSON.stringify(b.input ?? {}) } }));
|
|
248
|
+
}
|
|
249
|
+
this.session.add(msg);
|
|
250
|
+
return msg;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async callOpenAI(messages, tools, signal) {
|
|
254
|
+
let content = '';
|
|
255
|
+
const calls = [];
|
|
256
|
+
for await (const event of streamChat({ config: this.config, messages, tools, signal })) {
|
|
257
|
+
if (event.usage) this.usage.add(this.config.model, event.usage);
|
|
258
|
+
const delta = event.choices?.[0]?.delta;
|
|
259
|
+
if (!delta) continue;
|
|
260
|
+
const reasoning = delta.reasoning_content ?? delta.reasoning;
|
|
261
|
+
if (reasoning && !this.silent) this.ui.thinking(reasoning);
|
|
262
|
+
if (delta.content) {
|
|
263
|
+
content += delta.content;
|
|
264
|
+
if (!this.silent) this.ui.text(delta.content);
|
|
265
|
+
}
|
|
266
|
+
for (const tc of delta.tool_calls ?? []) {
|
|
267
|
+
const idx = tc.index ?? (tc.id ? calls.length : Math.max(0, calls.length - 1));
|
|
268
|
+
const c = (calls[idx] ??= { id: '', type: 'function', function: { name: '', arguments: '' } });
|
|
269
|
+
if (tc.id) c.id = tc.id;
|
|
270
|
+
if (tc.function?.name && !c.function.name) c.function.name = tc.function.name;
|
|
271
|
+
if (tc.function?.arguments) {
|
|
272
|
+
c.function.arguments += tc.function.arguments;
|
|
273
|
+
if (!this.silent) this.ui.addTokens?.(tc.function.arguments.length / 4);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
217
277
|
const toolCalls = calls.filter(Boolean).map((c, i) => ({ ...c, id: c.id || `call_${Date.now()}_${i}` }));
|
|
218
278
|
const msg = { role: 'assistant', content: content || (toolCalls.length ? null : '') };
|
|
219
279
|
if (toolCalls.length) msg.tool_calls = toolCalls;
|
|
@@ -221,6 +281,10 @@ export class Agent {
|
|
|
221
281
|
return msg;
|
|
222
282
|
}
|
|
223
283
|
|
|
284
|
+
complete(messages, signal) {
|
|
285
|
+
return isNativeAnthropic(this.config) ? completeAnthropic({ config: this.config, messages, signal }) : completeText({ config: this.config, messages, signal });
|
|
286
|
+
}
|
|
287
|
+
|
|
224
288
|
async maybeCompact(signal, force = false) {
|
|
225
289
|
const messages = this.session.messages;
|
|
226
290
|
if (!force && estimateTokens(messages) < this.config.contextWindow * COMPACT_AT) return false;
|
|
@@ -239,17 +303,16 @@ export class Agent {
|
|
|
239
303
|
if (cut <= 0) return this.trimToolResults();
|
|
240
304
|
if (!this.silent) this.ui.info('Compacting conversation history to free up context…');
|
|
241
305
|
const transcript = messages.slice(0, cut).map(renderForSummary).join('\n\n');
|
|
242
|
-
const summary = await
|
|
243
|
-
|
|
244
|
-
signal,
|
|
245
|
-
messages: [
|
|
306
|
+
const summary = await this.complete(
|
|
307
|
+
[
|
|
246
308
|
{ role: 'system', content: 'You summarize coding-agent conversations so the work can continue with less context.' },
|
|
247
309
|
{
|
|
248
310
|
role: 'user',
|
|
249
311
|
content: `Summarize this conversation between a user and a coding agent. Keep: the user's goals and instructions, decisions made, files read or changed (with paths), commands run and their important results, errors hit, the current task list, and what is left to do. Be specific and concise.\n\n<conversation>\n${truncate(transcript, 400000)}\n</conversation>`,
|
|
250
312
|
},
|
|
251
313
|
],
|
|
252
|
-
|
|
314
|
+
signal,
|
|
315
|
+
);
|
|
253
316
|
this.session.compact(summary.trim() || '(no summary produced)', cut);
|
|
254
317
|
if (estimateTokens(this.session.messages) >= this.config.contextWindow * COMPACT_AT) this.trimToolResults();
|
|
255
318
|
return true;
|
package/src/anthropic.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
// Native Claude API client (used when the provider is Anthropic).
|
|
2
|
+
//
|
|
3
|
+
// Compared with the OpenAI-compatible endpoint this gives prompt caching
|
|
4
|
+
// (long sessions re-read the conversation at a fraction of the price),
|
|
5
|
+
// visible thinking summaries, effort control, token usage, and server-side
|
|
6
|
+
// fallback when a request is declined.
|
|
7
|
+
//
|
|
8
|
+
// Arrakis keeps the conversation in an OpenAI-style shape internally. Each
|
|
9
|
+
// assistant turn from Claude also stores its exact content blocks (thinking,
|
|
10
|
+
// text, tool_use) and they are replayed unchanged, because Claude's thinking
|
|
11
|
+
// blocks are only valid while the history stays exactly as it was sent.
|
|
12
|
+
import Anthropic from '@anthropic-ai/sdk';
|
|
13
|
+
|
|
14
|
+
const clients = new Map();
|
|
15
|
+
|
|
16
|
+
function client(config) {
|
|
17
|
+
const baseURL = config.baseUrl.replace(/\/v1\/?$/, '');
|
|
18
|
+
const key = `${baseURL}|${config.apiKey}`;
|
|
19
|
+
if (!clients.has(key)) clients.set(key, new Anthropic({ apiKey: config.apiKey, baseURL, maxRetries: 3 }));
|
|
20
|
+
return clients.get(key);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const isNativeAnthropic = (config) => config.provider === 'anthropic' && process.env.ARRAKIS_ANTHROPIC_COMPAT !== '1';
|
|
24
|
+
|
|
25
|
+
// What each model family accepts.
|
|
26
|
+
export function modelTraits(model) {
|
|
27
|
+
const m = String(model);
|
|
28
|
+
return {
|
|
29
|
+
// Adaptive thinking (Claude 4.6 and later).
|
|
30
|
+
adaptive: /claude-(fable|mythos|opus-5|opus-4-[6-9]|sonnet-5|sonnet-4-6|haiku-5)/.test(m),
|
|
31
|
+
// Models whose thinking blocks are bound to the conversation ("preserved thinking").
|
|
32
|
+
bound: /claude-(fable-5-[12]|mythos-5-[12]|opus-5-5|sonnet-5-5|haiku-5-5)/.test(m),
|
|
33
|
+
// Server-side fallback when the model declines a request.
|
|
34
|
+
fallbacks: /claude-(fable-5-[12]|opus-5-5|opus-5(?![-\d])|sonnet-5-5)/.test(m),
|
|
35
|
+
effort: /claude-(fable|mythos|opus-5|opus-4-[5-9]|sonnet-5|haiku-5)/.test(m),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const dataUrl = /^data:([^;]+);base64,(.*)$/s;
|
|
40
|
+
|
|
41
|
+
function userBlocks(content) {
|
|
42
|
+
if (typeof content === 'string') return content ? [{ type: 'text', text: content }] : [];
|
|
43
|
+
const blocks = [];
|
|
44
|
+
for (const p of content ?? []) {
|
|
45
|
+
if (p.type === 'text' && p.text) blocks.push({ type: 'text', text: p.text });
|
|
46
|
+
else if (p.type === 'image_url') {
|
|
47
|
+
const m = p.image_url?.url?.match(dataUrl);
|
|
48
|
+
if (m) blocks.push({ type: 'image', source: { type: 'base64', media_type: m[1], data: m[2] } });
|
|
49
|
+
else if (p.image_url?.url) blocks.push({ type: 'image', source: { type: 'url', url: p.image_url.url } });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return blocks;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Internal (OpenAI-style) history -> Messages API { system, messages }.
|
|
56
|
+
// Deterministic: the same history always produces the same request.
|
|
57
|
+
export function toAnthropic(history) {
|
|
58
|
+
let system;
|
|
59
|
+
const out = [];
|
|
60
|
+
const push = (role, blocks) => {
|
|
61
|
+
if (!blocks.length) return;
|
|
62
|
+
const last = out.at(-1);
|
|
63
|
+
if (last && last.role === role) last.content.push(...blocks);
|
|
64
|
+
else out.push({ role, content: [...blocks] });
|
|
65
|
+
};
|
|
66
|
+
for (const m of history) {
|
|
67
|
+
if (m.role === 'system') {
|
|
68
|
+
if (system === undefined) system = String(m.content ?? '');
|
|
69
|
+
else push('user', [{ type: 'text', text: String(m.content ?? '') }]);
|
|
70
|
+
} else if (m.role === 'user') push('user', userBlocks(m.content));
|
|
71
|
+
else if (m.role === 'tool') {
|
|
72
|
+
const text = String(m.content ?? '');
|
|
73
|
+
push('user', [{ type: 'tool_result', tool_use_id: m.tool_call_id, content: text || '(no output)', ...(/^(Error|Permission denied|Blocked)/.test(text) ? { is_error: true } : {}) }]);
|
|
74
|
+
} else if (m.role === 'assistant') {
|
|
75
|
+
if (Array.isArray(m.anthropic) && m.anthropic.length) {
|
|
76
|
+
push('assistant', m.anthropic);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
const blocks = [];
|
|
80
|
+
if (m.content) blocks.push({ type: 'text', text: String(m.content) });
|
|
81
|
+
for (const c of m.tool_calls ?? []) {
|
|
82
|
+
let input = {};
|
|
83
|
+
try {
|
|
84
|
+
input = c.function.arguments ? JSON.parse(c.function.arguments) : {};
|
|
85
|
+
} catch {}
|
|
86
|
+
blocks.push({ type: 'tool_use', id: c.id, name: c.function.name, input });
|
|
87
|
+
}
|
|
88
|
+
push('assistant', blocks);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
// The conversation must start with a user turn.
|
|
92
|
+
if (out[0]?.role === 'assistant') out.unshift({ role: 'user', content: [{ type: 'text', text: '(continued)' }] });
|
|
93
|
+
return { system, messages: out };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function buildRequest({ config, history, tools }) {
|
|
97
|
+
const { system, messages } = toAnthropic(history);
|
|
98
|
+
const traits = modelTraits(config.model);
|
|
99
|
+
const params = {
|
|
100
|
+
model: config.model,
|
|
101
|
+
max_tokens: config.maxTokens || 64000,
|
|
102
|
+
messages,
|
|
103
|
+
// Automatic prompt caching: the longest stable prefix is cached each turn.
|
|
104
|
+
cache_control: { type: 'ephemeral' },
|
|
105
|
+
};
|
|
106
|
+
if (system) params.system = system;
|
|
107
|
+
if (tools?.length) {
|
|
108
|
+
params.tools = tools.map((t) => ({
|
|
109
|
+
name: t.function.name,
|
|
110
|
+
description: t.function.description,
|
|
111
|
+
input_schema: t.function.parameters ?? { type: 'object', properties: {} },
|
|
112
|
+
eager_input_streaming: true,
|
|
113
|
+
}));
|
|
114
|
+
}
|
|
115
|
+
const betas = [];
|
|
116
|
+
if (traits.adaptive) {
|
|
117
|
+
params.thinking = { type: 'adaptive', display: 'summarized' };
|
|
118
|
+
if (traits.bound) {
|
|
119
|
+
// If the history ever changes under a thinking block, drop that block instead of failing.
|
|
120
|
+
params.thinking.block_binding = { prefix_mismatch_behavior: 'drop_block' };
|
|
121
|
+
betas.push('thinking-binding-controls-2026-08-01');
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const effort = config.effort || (/claude-opus-5-5/.test(config.model) ? 'high' : '');
|
|
125
|
+
if (effort && traits.effort) params.output_config = { effort };
|
|
126
|
+
if (traits.fallbacks && process.env.ARRAKIS_NO_FALLBACK !== '1') {
|
|
127
|
+
params.fallbacks = 'default';
|
|
128
|
+
betas.push('server-side-fallback-2026-07-01');
|
|
129
|
+
}
|
|
130
|
+
if (betas.length) params.betas = betas;
|
|
131
|
+
return params;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Stream one model turn. Yields { type: 'text' | 'thinking' | 'tool', ... } events,
|
|
135
|
+
// then a final { type: 'done', message } with the complete API message.
|
|
136
|
+
export async function* streamAnthropic({ config, history, tools, signal }) {
|
|
137
|
+
const params = buildRequest({ config, history, tools });
|
|
138
|
+
for (let attempt = 0; ; attempt++) {
|
|
139
|
+
const stream = client(config).beta.messages.stream(params, { signal });
|
|
140
|
+
try {
|
|
141
|
+
for await (const ev of stream) {
|
|
142
|
+
if (ev.type === 'content_block_start' && ev.content_block.type === 'tool_use') {
|
|
143
|
+
yield { type: 'tool', name: ev.content_block.name };
|
|
144
|
+
} else if (ev.type === 'content_block_start' && ev.content_block.type === 'thinking') {
|
|
145
|
+
yield { type: 'thinking_start' };
|
|
146
|
+
} else if (ev.type === 'content_block_delta') {
|
|
147
|
+
const d = ev.delta;
|
|
148
|
+
if (d.type === 'text_delta') yield { type: 'text', text: d.text };
|
|
149
|
+
else if (d.type === 'thinking_delta') yield { type: 'thinking', text: d.thinking };
|
|
150
|
+
else if (d.type === 'input_json_delta') yield { type: 'tool_input', text: d.partial_json };
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const message = await stream.finalMessage();
|
|
154
|
+
yield { type: 'done', message };
|
|
155
|
+
return;
|
|
156
|
+
} catch (err) {
|
|
157
|
+
// With eager input streaming, a tool input Claude emitted as broken JSON
|
|
158
|
+
// makes the SDK throw. Re-issue the turn a couple of times; rethrow API errors.
|
|
159
|
+
if (err instanceof Anthropic.APIError || err.name === 'AbortError' || signal?.aborted || attempt >= 2) throw err;
|
|
160
|
+
yield { type: 'retry', reason: err.message };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export async function completeAnthropic({ config, messages, signal }) {
|
|
166
|
+
let text = '';
|
|
167
|
+
for await (const ev of streamAnthropic({ config: { ...config, effort: config.effort || 'low' }, history: messages, tools: [], signal })) {
|
|
168
|
+
if (ev.type === 'text') text += ev.text;
|
|
169
|
+
}
|
|
170
|
+
return text;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export async function listAnthropicModels(config) {
|
|
174
|
+
const out = [];
|
|
175
|
+
try {
|
|
176
|
+
for await (const m of client(config).models.list({ limit: 1000 })) out.push(m);
|
|
177
|
+
} catch (err) {
|
|
178
|
+
if (err instanceof Anthropic.APIConnectionError) {
|
|
179
|
+
const e = new Error(`Could not reach ${config.baseUrl}.`);
|
|
180
|
+
e.unreachable = true;
|
|
181
|
+
throw e;
|
|
182
|
+
}
|
|
183
|
+
throw err;
|
|
184
|
+
}
|
|
185
|
+
return out;
|
|
186
|
+
}
|
package/src/cli.js
CHANGED
|
@@ -22,6 +22,8 @@ import { Hooks, loadHooks, projectHasHooks, projectSettingsFile } from './hooks.
|
|
|
22
22
|
import { startJob, listJobs, findJob, stopJob, readLog, updateJob, jobLog } from './jobs.js';
|
|
23
23
|
import { checkForUpdate } from './update.js';
|
|
24
24
|
import { setExtraTools } from './tools.js';
|
|
25
|
+
import { formatCost, formatTokens, priceFor } from './pricing.js';
|
|
26
|
+
import { isNativeAnthropic, modelTraits } from './anthropic.js';
|
|
25
27
|
import { isTrustedProject, trustProject, HOME_DIR } from './config.js';
|
|
26
28
|
|
|
27
29
|
const HELP = `arrakis ${VERSION} — a coding agent for your terminal
|
|
@@ -62,6 +64,10 @@ const SLASH_HELP = `/help Show commands
|
|
|
62
64
|
/init Write ARRAKIS.md project notes for this folder
|
|
63
65
|
/todos Show the current task list
|
|
64
66
|
/undo [n] Revert arrakis's file changes from the last turn (or back to turn n)
|
|
67
|
+
/cost Tokens used, cache hits and estimated cost this session
|
|
68
|
+
/effort [level] How hard Claude thinks: low, medium, high, xhigh, max
|
|
69
|
+
/resume Switch to an earlier session
|
|
70
|
+
/export [file] Save this conversation as Markdown
|
|
65
71
|
/paste Attach the image on your clipboard to your next message
|
|
66
72
|
/mcp Show connected MCP servers and tools
|
|
67
73
|
/bg <task> Start a background job; /jobs to check on it
|
|
@@ -248,7 +254,7 @@ function completer(line, cwd, commands) {
|
|
|
248
254
|
return [[], line];
|
|
249
255
|
}
|
|
250
256
|
|
|
251
|
-
const BUILTIN_COMMANDS = ['/help', '/plan', '/init', '/todos', '/undo', '/paste', '/mcp', '/bg', '/jobs', '/clear', '/compact', '/model', '/provider', '/sessions', '/status', '/yolo', '/exit'];
|
|
257
|
+
const BUILTIN_COMMANDS = ['/help', '/plan', '/init', '/todos', '/undo', '/cost', '/effort', '/resume', '/export', '/paste', '/mcp', '/bg', '/jobs', '/clear', '/compact', '/model', '/provider', '/sessions', '/status', '/yolo', '/exit'];
|
|
252
258
|
|
|
253
259
|
async function interactive({ agent, ui, prompts, config, cwd, firstPrompt, mcpServers = [], hooks = 0 }) {
|
|
254
260
|
const c = ui.c;
|
|
@@ -264,10 +270,10 @@ async function interactive({ agent, ui, prompts, config, cwd, firstPrompt, mcpSe
|
|
|
264
270
|
];
|
|
265
271
|
const p = agent.permissions;
|
|
266
272
|
ui.onCycleMode = () => {
|
|
267
|
-
if (p.planMode)
|
|
273
|
+
if (p.planMode) agent.setPlanMode(false);
|
|
268
274
|
else if (p.acceptEdits) {
|
|
269
275
|
p.acceptEdits = false;
|
|
270
|
-
|
|
276
|
+
agent.setPlanMode(true);
|
|
271
277
|
} else p.acceptEdits = true;
|
|
272
278
|
};
|
|
273
279
|
ui.modeLabel = () =>
|
|
@@ -297,7 +303,8 @@ async function interactive({ agent, ui, prompts, config, cwd, firstPrompt, mcpSe
|
|
|
297
303
|
ui.statusLine = () => {
|
|
298
304
|
const used = Math.round((estimateTokens(agent.session.messages) / config.contextWindow) * 100);
|
|
299
305
|
const branch = gitBranch(cwd);
|
|
300
|
-
|
|
306
|
+
const cost = agent.usage.requests && agent.usage.priced && priceFor(config.model) ? formatCost(agent.usage.cost) : '';
|
|
307
|
+
if (ui instanceof FancyUI) return [config.model, branch ? `⎇ ${branch}` : '', `${used}% context`, cost].filter(Boolean).join(' · ');
|
|
301
308
|
const parts = [config.model, `${used}% context`];
|
|
302
309
|
if (branch) parts.push(`⎇ ${branch}`);
|
|
303
310
|
if (agent.permissions.planMode) parts.push('plan mode');
|
|
@@ -373,7 +380,7 @@ async function slashCommand(text, { agent, ui, prompts, config, cwd, state }) {
|
|
|
373
380
|
break;
|
|
374
381
|
}
|
|
375
382
|
case 'plan':
|
|
376
|
-
agent.
|
|
383
|
+
agent.setPlanMode(!agent.permissions.planMode);
|
|
377
384
|
if (agent.permissions.planMode) ui.info('Plan mode on: arrakis will investigate and propose a plan without changing anything. /plan again to approve and let it work.');
|
|
378
385
|
else {
|
|
379
386
|
ui.info('Plan mode off: arrakis can make changes now.');
|
|
@@ -382,6 +389,85 @@ async function slashCommand(text, { agent, ui, prompts, config, cwd, state }) {
|
|
|
382
389
|
break;
|
|
383
390
|
case 'init':
|
|
384
391
|
return { send: INIT_PROMPT };
|
|
392
|
+
case 'cost': {
|
|
393
|
+
const u = agent.usage;
|
|
394
|
+
if (!u.requests) {
|
|
395
|
+
ui.info('No requests yet in this session.');
|
|
396
|
+
break;
|
|
397
|
+
}
|
|
398
|
+
const rows = [
|
|
399
|
+
['requests', String(u.requests)],
|
|
400
|
+
['input', formatTokens(u.input)],
|
|
401
|
+
['output', formatTokens(u.output)],
|
|
402
|
+
['cache reads', `${formatTokens(u.cacheRead)}${u.cacheRead ? c.gray(` (${Math.round(u.cacheHitRate * 100)}% of prompt tokens served from cache)`) : ''}`],
|
|
403
|
+
['cache writes', formatTokens(u.cacheWrite)],
|
|
404
|
+
['est. cost', u.priced && priceFor(config.model) ? `${formatCost(u.cost)} ${c.gray('(at list prices)')}` : c.gray('unknown for this model')],
|
|
405
|
+
];
|
|
406
|
+
for (const [k, v] of rows) ui.write(ui.out, ` ${c.gray(k.padEnd(13))} ${v}\n`);
|
|
407
|
+
if (!isNativeAnthropic(config) && u.requests && !u.total) ui.info(' This provider does not report token usage.');
|
|
408
|
+
break;
|
|
409
|
+
}
|
|
410
|
+
case 'effort': {
|
|
411
|
+
const levels = ['low', 'medium', 'high', 'xhigh', 'max'];
|
|
412
|
+
if (!isNativeAnthropic(config) || !modelTraits(config.model).effort) {
|
|
413
|
+
ui.info('Effort applies to Claude models on the Anthropic provider.');
|
|
414
|
+
break;
|
|
415
|
+
}
|
|
416
|
+
let level = arg.toLowerCase();
|
|
417
|
+
if (!level) {
|
|
418
|
+
level = await prompts.select({
|
|
419
|
+
title: 'Effort',
|
|
420
|
+
items: [
|
|
421
|
+
...levels.map((l) => ({ label: l, value: l, hint: { low: 'fastest, cheapest', medium: 'balanced', high: 'thorough (good for coding)', xhigh: 'deeper reasoning', max: 'slowest, most thorough' }[l] })),
|
|
422
|
+
{ label: 'default', value: 'default', hint: "the model's own default" },
|
|
423
|
+
],
|
|
424
|
+
initial: Math.max(0, levels.indexOf(config.effort || 'high')),
|
|
425
|
+
});
|
|
426
|
+
if (!level) break;
|
|
427
|
+
}
|
|
428
|
+
if (level !== 'default' && !levels.includes(level)) {
|
|
429
|
+
ui.error(`Effort must be one of: ${levels.join(', ')}, default`);
|
|
430
|
+
break;
|
|
431
|
+
}
|
|
432
|
+
config.effort = level === 'default' ? '' : level;
|
|
433
|
+
if (config.provider) saveProvider(config.provider, { effort: config.effort || undefined });
|
|
434
|
+
ui.success(`Effort: ${level}.`);
|
|
435
|
+
break;
|
|
436
|
+
}
|
|
437
|
+
case 'resume': {
|
|
438
|
+
const sessions = listSessions().filter((x) => x.id !== agent.session.id && x.messages > 0).slice(0, 30);
|
|
439
|
+
if (!sessions.length) {
|
|
440
|
+
ui.info('No other sessions to resume.');
|
|
441
|
+
break;
|
|
442
|
+
}
|
|
443
|
+
const pick = arg || await prompts.select({
|
|
444
|
+
title: 'Resume',
|
|
445
|
+
items: sessions.map((x) => ({ label: x.title || '(untitled)', value: x.id, hint: `${new Date(x.updated).toLocaleString()} · ${x.messages} msgs${x.cwd === cwd ? '' : ` · ${x.cwd}`}` })),
|
|
446
|
+
});
|
|
447
|
+
if (!pick) break;
|
|
448
|
+
agent.session = Session.load(pick);
|
|
449
|
+
agent.checkpoints = new Checkpoints(agent.session.file);
|
|
450
|
+
agent.systemPrompt = null;
|
|
451
|
+
const last = [...agent.session.messages].reverse().find((m) => m.role === 'assistant' && m.content);
|
|
452
|
+
ui.success(`Resumed ${agent.session.id} (${agent.session.messages.length} messages).`);
|
|
453
|
+
if (last) ui.info(` Last reply: ${String(last.content).replace(/\s+/g, ' ').slice(0, 160)}…`);
|
|
454
|
+
break;
|
|
455
|
+
}
|
|
456
|
+
case 'export': {
|
|
457
|
+
const file = path.resolve(cwd, arg || `arrakis-${agent.session.id}.md`);
|
|
458
|
+
const lines = [`# arrakis session ${agent.session.id}`, '', `- model: ${config.model}`, `- folder: ${cwd}`, ''];
|
|
459
|
+
for (const m of agent.session.messages) {
|
|
460
|
+
const text = Array.isArray(m.content) ? m.content.filter((p) => p.type === 'text').map((p) => p.text).join('\n') : String(m.content ?? '');
|
|
461
|
+
if (m.role === 'user') lines.push('## You', '', text, '');
|
|
462
|
+
else if (m.role === 'assistant') {
|
|
463
|
+
if (text) lines.push('## arrakis', '', text, '');
|
|
464
|
+
for (const t of m.tool_calls ?? []) lines.push(`> **${t.function.name}** \`${t.function.arguments.slice(0, 300)}\``, '');
|
|
465
|
+
} else if (m.role === 'tool') lines.push('```', text.slice(0, 2000), '```', '');
|
|
466
|
+
}
|
|
467
|
+
fs.writeFileSync(file, lines.join('\n'));
|
|
468
|
+
ui.success(`Exported to ${path.relative(cwd, file) || file}`);
|
|
469
|
+
break;
|
|
470
|
+
}
|
|
385
471
|
case 'undo': {
|
|
386
472
|
const turns = agent.checkpoints?.list() ?? [];
|
|
387
473
|
if (!turns.length) {
|
|
@@ -458,6 +544,7 @@ async function slashCommand(text, { agent, ui, prompts, config, cwd, state }) {
|
|
|
458
544
|
case 'clear':
|
|
459
545
|
agent.session = Session.create({ cwd, model: config.model });
|
|
460
546
|
agent.checkpoints = new Checkpoints(agent.session.file);
|
|
547
|
+
agent.systemPrompt = null;
|
|
461
548
|
ui.info(`Started new session ${agent.session.id}.`);
|
|
462
549
|
break;
|
|
463
550
|
case 'compact': {
|
package/src/client.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
// Minimal client for OpenAI-compatible /chat/completions with streaming and tool calls.
|
|
2
2
|
import { getProvider, normalizeModels } from './providers.js';
|
|
3
|
+
import { isNativeAnthropic, listAnthropicModels } from './anthropic.js';
|
|
4
|
+
|
|
5
|
+
// Providers known to support stream_options.include_usage.
|
|
6
|
+
const USAGE_PROVIDERS = new Set(['openai', 'openrouter']);
|
|
3
7
|
|
|
4
8
|
function headers(config) {
|
|
5
9
|
const h = { 'content-type': 'application/json' };
|
|
@@ -51,6 +55,7 @@ export async function* streamChat({ config, messages, tools, signal }) {
|
|
|
51
55
|
const body = { model: config.model, messages, stream: true };
|
|
52
56
|
if (tools?.length) body.tools = tools;
|
|
53
57
|
if (config.maxTokens) body.max_tokens = config.maxTokens;
|
|
58
|
+
if (USAGE_PROVIDERS.has(config.provider)) body.stream_options = { include_usage: true };
|
|
54
59
|
const res = await request(config, '/chat/completions', { method: 'POST', body: JSON.stringify(body), signal });
|
|
55
60
|
|
|
56
61
|
const decoder = new TextDecoder();
|
|
@@ -87,6 +92,7 @@ export async function completeText({ config, messages, signal }) {
|
|
|
87
92
|
|
|
88
93
|
// List the chat models the provider offers, newest first when it says.
|
|
89
94
|
export async function listModels(config) {
|
|
95
|
+
if (isNativeAnthropic(config) && config.apiKey) return normalizeModels({ data: await listAnthropicModels(config) });
|
|
90
96
|
const provider = getProvider(config.provider);
|
|
91
97
|
const extraHeaders = provider?.modelsHeaders && config.apiKey ? provider.modelsHeaders(config.apiKey) : undefined;
|
|
92
98
|
const res = await request(config, `/models${provider?.modelsQuery ?? ''}`, { method: 'GET' }, { retries: 1, extraHeaders });
|
package/src/config.js
CHANGED
|
@@ -21,6 +21,7 @@ export const CONFIG_KEYS = {
|
|
|
21
21
|
apiKey: { env: 'ARRAKIS_API_KEY', help: 'API key for the active provider', secret: true },
|
|
22
22
|
model: { env: 'ARRAKIS_MODEL', help: 'Model name' },
|
|
23
23
|
contextWindow: { env: 'ARRAKIS_CONTEXT_WINDOW', help: 'Context window in tokens; history is compacted near 80%', number: true },
|
|
24
|
+
effort: { env: 'ARRAKIS_EFFORT', help: 'Claude effort: low, medium, high, xhigh, max (Anthropic only)' },
|
|
24
25
|
maxTokens: { env: 'ARRAKIS_MAX_TOKENS', help: 'Max output tokens per response (0 = provider default)', number: true, global: true },
|
|
25
26
|
};
|
|
26
27
|
|
|
@@ -68,12 +69,14 @@ export function loadConfig(overrides = {}) {
|
|
|
68
69
|
baseUrl: saved.baseUrl || provider?.baseUrl || '',
|
|
69
70
|
apiKey: saved.apiKey || '',
|
|
70
71
|
model: saved.model || '',
|
|
72
|
+
effort: saved.effort || '',
|
|
71
73
|
contextWindow: Number(saved.contextWindow) || provider?.contextWindow || DEFAULT_CONTEXT,
|
|
72
74
|
maxTokens: Number(file.maxTokens) || provider?.maxTokens || 0,
|
|
73
75
|
};
|
|
74
76
|
if (env.ARRAKIS_BASE_URL) config.baseUrl = env.ARRAKIS_BASE_URL;
|
|
75
77
|
if (env.ARRAKIS_API_KEY) config.apiKey = env.ARRAKIS_API_KEY;
|
|
76
78
|
if (env.ARRAKIS_MODEL) config.model = env.ARRAKIS_MODEL;
|
|
79
|
+
if (env.ARRAKIS_EFFORT) config.effort = env.ARRAKIS_EFFORT;
|
|
77
80
|
if (Number(env.ARRAKIS_CONTEXT_WINDOW)) config.contextWindow = Number(env.ARRAKIS_CONTEXT_WINDOW);
|
|
78
81
|
if (Number(env.ARRAKIS_MAX_TOKENS)) config.maxTokens = Number(env.ARRAKIS_MAX_TOKENS);
|
|
79
82
|
if (overrides.baseUrl) config.baseUrl = overrides.baseUrl;
|
package/src/pricing.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Approximate list prices in USD per million tokens, for the session cost
|
|
2
|
+
// estimate. [input, output, cache read, cache write (5 min)]
|
|
3
|
+
const PRICES = [
|
|
4
|
+
[/claude-(fable|mythos)-5-2/, [8, 40, 0.2, 10]],
|
|
5
|
+
[/claude-(fable|mythos)-5(-1)?\b/, [10, 50, 0.25, 12.5]],
|
|
6
|
+
[/claude-opus-5-5/, [4, 20, 0.2, 5]],
|
|
7
|
+
[/claude-opus-(5|4-[5-9])\b/, [5, 25, 0.5, 6.25]],
|
|
8
|
+
[/claude-sonnet-5-5/, [2, 10, 0.1, 2.5]],
|
|
9
|
+
[/claude-sonnet-5\b/, [2, 10, 0.2, 2.5]],
|
|
10
|
+
[/claude-sonnet-4/, [3, 15, 0.3, 3.75]],
|
|
11
|
+
[/claude-haiku-5-5/, [0.1, 0.5, 0.01, 0.125]],
|
|
12
|
+
[/claude-haiku-4-5/, [1, 5, 0.1, 1.25]],
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
export function priceFor(model) {
|
|
16
|
+
return PRICES.find(([re]) => re.test(model))?.[1] ?? null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class Usage {
|
|
20
|
+
constructor() {
|
|
21
|
+
this.input = 0;
|
|
22
|
+
this.output = 0;
|
|
23
|
+
this.cacheRead = 0;
|
|
24
|
+
this.cacheWrite = 0;
|
|
25
|
+
this.requests = 0;
|
|
26
|
+
this.cost = 0;
|
|
27
|
+
this.priced = true;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Accepts Anthropic usage ({input_tokens, output_tokens, cache_*}) or
|
|
31
|
+
// OpenAI usage ({prompt_tokens, completion_tokens}).
|
|
32
|
+
add(model, u) {
|
|
33
|
+
if (!u) return;
|
|
34
|
+
const read = u.cache_read_input_tokens ?? u.prompt_tokens_details?.cached_tokens ?? 0;
|
|
35
|
+
const input = u.input_tokens ?? Math.max(0, (u.prompt_tokens ?? 0) - (u.prompt_tokens_details?.cached_tokens ?? 0));
|
|
36
|
+
const output = u.output_tokens ?? u.completion_tokens ?? 0;
|
|
37
|
+
const write = u.cache_creation_input_tokens ?? 0;
|
|
38
|
+
this.input += input;
|
|
39
|
+
this.output += output;
|
|
40
|
+
this.cacheRead += read;
|
|
41
|
+
this.cacheWrite += write;
|
|
42
|
+
this.requests++;
|
|
43
|
+
const p = priceFor(model);
|
|
44
|
+
if (p) this.cost += (input * p[0] + output * p[1] + read * p[2] + write * p[3]) / 1e6;
|
|
45
|
+
else this.priced = false;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
get total() {
|
|
49
|
+
return this.input + this.output + this.cacheRead + this.cacheWrite;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
get cacheHitRate() {
|
|
53
|
+
const prompt = this.input + this.cacheRead + this.cacheWrite;
|
|
54
|
+
return prompt ? this.cacheRead / prompt : 0;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export const formatCost = (usd) => (usd < 0.01 ? '<$0.01' : `$${usd.toFixed(2)}`);
|
|
59
|
+
export const formatTokens = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(2)}M` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
|
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, 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.
|
|
@@ -80,10 +80,6 @@ export function buildSystemPrompt({ cwd, model, planMode = false, subagent = nul
|
|
|
80
80
|
- Reference code as path:line.
|
|
81
81
|
- When done, say briefly what changed and anything left unverified.`;
|
|
82
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
83
|
if (subagent) {
|
|
88
84
|
prompt += `\n\n# You are a sub-agent
|
|
89
85
|
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.
|
package/src/providers.js
CHANGED
|
@@ -20,7 +20,6 @@ export const PROVIDERS = [
|
|
|
20
20
|
keyUrl: 'https://platform.claude.com/settings/keys',
|
|
21
21
|
defaultModel: 'claude-opus-5-5',
|
|
22
22
|
contextWindow: 1000000,
|
|
23
|
-
maxTokens: 32000,
|
|
24
23
|
modelsHeaders: (key) => ({ 'x-api-key': key, 'anthropic-version': '2023-06-01' }),
|
|
25
24
|
modelsQuery: '?limit=1000',
|
|
26
25
|
},
|
package/src/tools.js
CHANGED
|
@@ -514,6 +514,9 @@ export async function executeToolCall(call, ctx) {
|
|
|
514
514
|
} catch {
|
|
515
515
|
return `Error: tool arguments were not valid JSON: ${String(call.function.arguments).slice(0, 200)}`;
|
|
516
516
|
}
|
|
517
|
+
// Tool input may arrive malformed or cut short; check it against the schema first.
|
|
518
|
+
const problem = checkArgs(tool.parameters, args);
|
|
519
|
+
if (problem) return `Error: invalid input for ${tool.name}: ${problem}. Fix the arguments and call the tool again.`;
|
|
517
520
|
const sub = (ctx.depth ?? 0) > 0;
|
|
518
521
|
ctx.ui.toolStart(tool.label ?? tool.name, safe(() => tool.summary?.(args)) ?? '', { prefix: sub ? `${ctx.label}` : '' });
|
|
519
522
|
try {
|
|
@@ -553,6 +556,24 @@ export async function executeToolCall(call, ctx) {
|
|
|
553
556
|
}
|
|
554
557
|
}
|
|
555
558
|
|
|
559
|
+
function checkArgs(schema, args) {
|
|
560
|
+
if (!args || typeof args !== 'object' || Array.isArray(args)) return 'arguments must be a JSON object';
|
|
561
|
+
for (const key of schema?.required ?? []) if (args[key] === undefined || args[key] === null) return `missing required "${key}"`;
|
|
562
|
+
for (const [key, spec] of Object.entries(schema?.properties ?? {})) {
|
|
563
|
+
const v = args[key];
|
|
564
|
+
if (v === undefined || v === null || !spec?.type) continue;
|
|
565
|
+
const ok = spec.type === 'string' ? typeof v === 'string'
|
|
566
|
+
: spec.type === 'integer' ? Number.isInteger(v)
|
|
567
|
+
: spec.type === 'number' ? typeof v === 'number'
|
|
568
|
+
: spec.type === 'boolean' ? typeof v === 'boolean'
|
|
569
|
+
: spec.type === 'array' ? Array.isArray(v)
|
|
570
|
+
: spec.type === 'object' ? typeof v === 'object' && !Array.isArray(v)
|
|
571
|
+
: true;
|
|
572
|
+
if (!ok) return `"${key}" must be ${spec.type === 'integer' ? 'an integer' : `a ${spec.type}`}`;
|
|
573
|
+
}
|
|
574
|
+
return null;
|
|
575
|
+
}
|
|
576
|
+
|
|
556
577
|
function safe(fn) {
|
|
557
578
|
try {
|
|
558
579
|
return fn();
|
package/src/tui.js
CHANGED
|
@@ -45,7 +45,15 @@ export class FancyUI extends UI {
|
|
|
45
45
|
this.cwd = process.cwd();
|
|
46
46
|
this.fileCache = null;
|
|
47
47
|
this.onKey = (str, key) => this.handleKey(str, key ?? {});
|
|
48
|
-
|
|
48
|
+
// Everything printed above the input box, so it can be reprinted when the
|
|
49
|
+
// terminal width changes (old lines re-wrap unpredictably otherwise).
|
|
50
|
+
this.transcript = [];
|
|
51
|
+
this.transcriptSize = 0;
|
|
52
|
+
this.lastCols = this.out.columns;
|
|
53
|
+
this.onResize = () => {
|
|
54
|
+
clearTimeout(this.resizeTimer);
|
|
55
|
+
this.resizeTimer = setTimeout(() => this.handleResize(), 60);
|
|
56
|
+
};
|
|
49
57
|
process.once('exit', () => this.cleanup());
|
|
50
58
|
}
|
|
51
59
|
|
|
@@ -67,7 +75,6 @@ export class FancyUI extends UI {
|
|
|
67
75
|
this.historyList = fs.readFileSync(this.historyFile, 'utf8').split('\n').filter(Boolean).slice(-1000);
|
|
68
76
|
} catch {}
|
|
69
77
|
}
|
|
70
|
-
this.render();
|
|
71
78
|
}
|
|
72
79
|
|
|
73
80
|
suspend() {
|
|
@@ -82,6 +89,7 @@ export class FancyUI extends UI {
|
|
|
82
89
|
|
|
83
90
|
resume() {
|
|
84
91
|
this.start();
|
|
92
|
+
this.render();
|
|
85
93
|
}
|
|
86
94
|
|
|
87
95
|
close() {
|
|
@@ -504,6 +512,11 @@ export class FancyUI extends UI {
|
|
|
504
512
|
|
|
505
513
|
// Print complete lines above the live region.
|
|
506
514
|
printAbove(s) {
|
|
515
|
+
this.lastBlank = s.endsWith('\n\n') || (s === '\n' && this.lastEndsNewline);
|
|
516
|
+
this.lastEndsNewline = s.endsWith('\n');
|
|
517
|
+
this.transcript.push(s);
|
|
518
|
+
this.transcriptSize += s.length;
|
|
519
|
+
while (this.transcriptSize > 2_000_000 && this.transcript.length > 1) this.transcriptSize -= this.transcript.shift().length;
|
|
507
520
|
if (!this.active) {
|
|
508
521
|
this.out.write(s);
|
|
509
522
|
return;
|
|
@@ -513,6 +526,16 @@ export class FancyUI extends UI {
|
|
|
513
526
|
this.drawRegion();
|
|
514
527
|
}
|
|
515
528
|
|
|
529
|
+
handleResize() {
|
|
530
|
+
const cols = this.out.columns;
|
|
531
|
+
if (cols === this.lastCols || !this.active) return this.render();
|
|
532
|
+
this.lastCols = cols;
|
|
533
|
+
// Clear screen and scrollback, reprint the conversation at the new width.
|
|
534
|
+
this.out.write('\x1b[?25l\x1b[2J\x1b[3J\x1b[H' + this.transcript.join(''));
|
|
535
|
+
this.regionRows = 0;
|
|
536
|
+
this.drawRegion();
|
|
537
|
+
}
|
|
538
|
+
|
|
516
539
|
write(stream, s) {
|
|
517
540
|
if (!s) return;
|
|
518
541
|
this.partial += s;
|
|
@@ -540,7 +563,10 @@ export class FancyUI extends UI {
|
|
|
540
563
|
|
|
541
564
|
text(s) {
|
|
542
565
|
this.addTokens(s.length / 4);
|
|
543
|
-
if (this.mode === 'thinking')
|
|
566
|
+
if (this.mode === 'thinking') {
|
|
567
|
+
this.flushThinking();
|
|
568
|
+
this.mode = null;
|
|
569
|
+
}
|
|
544
570
|
if (this.mode !== 'text') {
|
|
545
571
|
this.md = new MarkdownStream(this.c, { width: this.width - 2 });
|
|
546
572
|
this.firstLine = true;
|
|
@@ -564,9 +590,31 @@ export class FancyUI extends UI {
|
|
|
564
590
|
thinking(s) {
|
|
565
591
|
this.addTokens(s.length / 4);
|
|
566
592
|
if (this.spinner) this.spinner.label = 'Thinking';
|
|
593
|
+
if (this.mode === 'text') this.endText();
|
|
594
|
+
this.mode = 'thinking';
|
|
595
|
+
this.thinkBuf = (this.thinkBuf ?? '') + s;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
// Print the thinking summary, dim, above the reply.
|
|
599
|
+
flushThinking() {
|
|
600
|
+
const text = (this.thinkBuf ?? '').trim();
|
|
601
|
+
this.thinkBuf = '';
|
|
602
|
+
if (!text) return;
|
|
603
|
+
const c = this.c;
|
|
604
|
+
const width = Math.max(20, this.width - 4);
|
|
605
|
+
const rows = [];
|
|
606
|
+
for (const para of text.split('\n')) {
|
|
607
|
+
if (!para.trim()) continue;
|
|
608
|
+
for (let i = 0; i < para.length; i += width) rows.push(para.slice(i, i + width));
|
|
609
|
+
}
|
|
610
|
+
const shown = rows.slice(0, 10);
|
|
611
|
+
const out = shown.map((r, i) => `${i === 0 ? c.gray('✻ ') : ' '}${c.gray(c.italic(r))}`);
|
|
612
|
+
if (rows.length > shown.length) out.push(` ${c.gray(`… ${rows.length - shown.length} more lines of thinking`)}`);
|
|
613
|
+
this.printAbove((this.lastBlank ? '' : '\n') + out.join('\n') + '\n\n');
|
|
567
614
|
}
|
|
568
615
|
|
|
569
616
|
endText() {
|
|
617
|
+
if (this.thinkBuf) this.flushThinking();
|
|
570
618
|
if (this.md) {
|
|
571
619
|
this.emitText(this.md.flush());
|
|
572
620
|
this.md = null;
|
|
@@ -623,21 +671,37 @@ export class FancyUI extends UI {
|
|
|
623
671
|
|
|
624
672
|
// ---- live region ---------------------------------------------------------
|
|
625
673
|
|
|
674
|
+
// How many screen rows the cursor is below the top of the drawn region.
|
|
675
|
+
// If the terminal got narrower since we drew, long lines have re-wrapped
|
|
676
|
+
// onto extra rows, so count them at the current width.
|
|
677
|
+
rowsAboveCursor() {
|
|
678
|
+
const cols = Math.max(1, this.out.columns || 100);
|
|
679
|
+
let rows = 0;
|
|
680
|
+
for (let i = 0; i < this.regionCursorRow; i++) rows += Math.max(1, Math.ceil((this.regionWidths[i] ?? 0) / cols));
|
|
681
|
+
return rows + Math.floor((this.regionCursorCol ?? 0) / cols);
|
|
682
|
+
}
|
|
683
|
+
|
|
626
684
|
eraseRegion() {
|
|
627
685
|
if (!this.regionRows) return;
|
|
628
|
-
|
|
629
|
-
this.out.write('\r\x1b[J
|
|
686
|
+
const up = this.rowsAboveCursor();
|
|
687
|
+
this.out.write(`${up ? `\x1b[${up}A` : ''}\r\x1b[J`);
|
|
630
688
|
this.regionRows = 0;
|
|
631
689
|
this.regionCursorRow = 0;
|
|
690
|
+
this.regionCursorCol = 0;
|
|
691
|
+
this.regionWidths = [];
|
|
632
692
|
}
|
|
633
693
|
|
|
634
694
|
render() {
|
|
635
695
|
if (!this.active) return;
|
|
636
696
|
const { lines, cursorRow, cursorCol } = this.layout();
|
|
637
697
|
let s = '\x1b[?25l';
|
|
638
|
-
if (this.regionRows
|
|
698
|
+
if (this.regionRows) {
|
|
699
|
+
const up = this.rowsAboveCursor();
|
|
700
|
+
if (up) s += `\x1b[${up}A`;
|
|
701
|
+
}
|
|
639
702
|
s += '\r';
|
|
640
|
-
|
|
703
|
+
const max = Math.max(1, (this.out.columns || 100) - 1);
|
|
704
|
+
s += lines.map((l) => `\x1b[2K${visibleLength(l) > max ? truncate(l, max) : l}`).join('\n') + '\x1b[J';
|
|
641
705
|
const up = lines.length - 1 - cursorRow;
|
|
642
706
|
if (up > 0) s += `\x1b[${up}A`;
|
|
643
707
|
s += `\r${cursorCol > 0 ? `\x1b[${cursorCol}C` : ''}`;
|
|
@@ -645,17 +709,21 @@ export class FancyUI extends UI {
|
|
|
645
709
|
this.out.write(s);
|
|
646
710
|
this.regionRows = lines.length;
|
|
647
711
|
this.regionCursorRow = cursorRow ?? lines.length - 1;
|
|
712
|
+
this.regionCursorCol = cursorCol;
|
|
713
|
+
this.regionWidths = lines.map((l) => Math.min(visibleLength(l), max));
|
|
648
714
|
}
|
|
649
715
|
|
|
650
716
|
drawRegion() {
|
|
651
717
|
this.regionRows = 0;
|
|
652
718
|
this.regionCursorRow = 0;
|
|
719
|
+
this.regionCursorCol = 0;
|
|
720
|
+
this.regionWidths = [];
|
|
653
721
|
this.render();
|
|
654
722
|
}
|
|
655
723
|
|
|
656
724
|
layout() {
|
|
657
725
|
const c = this.c;
|
|
658
|
-
const cols = Math.max(30, this.out.columns || 100);
|
|
726
|
+
const cols = Math.max(30, (this.out.columns || 100) - 1);
|
|
659
727
|
const lines = [];
|
|
660
728
|
if (this.spinner) {
|
|
661
729
|
const s = this.spinner;
|
|
@@ -687,7 +755,7 @@ export class FancyUI extends UI {
|
|
|
687
755
|
const placeholder = !this.buffer && !this.pending?.label ? (this.busy ? 'Type to queue a message…' : 'Ask arrakis anything, / for commands, @ for files') : '';
|
|
688
756
|
rows.forEach((r, i) => {
|
|
689
757
|
const prefix = i === 0 ? c.accent('> ') : ' ';
|
|
690
|
-
const body = placeholder && i === 0 ? c.gray(placeholder) : r.text;
|
|
758
|
+
const body = placeholder && i === 0 ? c.gray(truncate(placeholder, width)) : r.text;
|
|
691
759
|
const pad = Math.max(0, width - visibleLength(body));
|
|
692
760
|
lines.push(`${border('│')} ${prefix}${body}${' '.repeat(pad)} ${border('│')}`);
|
|
693
761
|
if (this.cursor >= r.start && this.cursor <= r.end && cursorRow === null) {
|
|
@@ -771,7 +839,7 @@ export class FancyUI extends UI {
|
|
|
771
839
|
if (resumed) rows.push(c.gray(` session: ${resumed}`));
|
|
772
840
|
if (mcp.length) rows.push(c.gray(` mcp: ${mcp.map((s) => (s.status === 'connected' ? `${s.name} (${s.tools.length} tools)` : `${s.name} (failed)`)).join(', ')}`));
|
|
773
841
|
if (hooks) rows.push(c.gray(` hooks: ${hooks} active`));
|
|
774
|
-
const cols = Math.max(30, this.out.columns || 100);
|
|
842
|
+
const cols = Math.max(30, (this.out.columns || 100) - 1);
|
|
775
843
|
const inner = Math.min(cols - 4, Math.max(46, ...rows.map(visibleLength)));
|
|
776
844
|
const line = (s) => `${c.accent('│')} ${truncate(s, inner)}${' '.repeat(Math.max(0, inner - visibleLength(truncate(s, inner))))} ${c.accent('│')}`;
|
|
777
845
|
let out = `\n${c.accent(`╭${'─'.repeat(inner + 2)}╮`)}\n${rows.map(line).join('\n')}\n${c.accent(`╰${'─'.repeat(inner + 2)}╯`)}\n`;
|