reasonally 0.2.0 → 0.3.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 +124 -5
- package/dist/agent/accumulate.js +146 -0
- package/dist/agent/client.js +174 -0
- package/dist/agent/compact.js +79 -0
- package/dist/agent/cost.js +22 -0
- package/dist/agent/loop-constants.js +3 -0
- package/dist/agent/loop.js +559 -0
- package/dist/agent/mcp-config.js +72 -0
- package/dist/agent/mcp.js +194 -0
- package/dist/agent/permissions.js +116 -0
- package/dist/agent/prompt.js +98 -0
- package/dist/agent/session.js +196 -0
- package/dist/agent/sse.js +46 -0
- package/dist/agent/tools/bash.js +176 -0
- package/dist/agent/tools/diff.js +33 -0
- package/dist/agent/tools/files.js +270 -0
- package/dist/agent/tools/index.js +21 -0
- package/dist/agent/tools/paths.js +43 -0
- package/dist/agent/tools/search.js +288 -0
- package/dist/agent/tools/task.js +42 -0
- package/dist/agent/tools/todo.js +59 -0
- package/dist/agent/tools/types.js +57 -0
- package/dist/agent/types.js +2 -0
- package/dist/api.js +5 -1
- package/dist/catalog.js +12 -0
- package/dist/cli.js +37 -3
- package/dist/config.js +17 -4
- package/dist/tui/app.js +869 -0
- package/dist/tui/args.js +32 -0
- package/dist/tui/commands.js +38 -0
- package/dist/tui/components.js +375 -0
- package/dist/tui/format.js +116 -0
- package/dist/tui/node-version.js +7 -0
- package/dist/tui/start.js +135 -0
- package/dist/tui/theme.js +36 -0
- package/package.json +8 -3
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
import { MessageAccumulator } from "./accumulate.js";
|
|
2
|
+
import { retryDelayMs, StreamError, streamChat } from "./client.js";
|
|
3
|
+
import { compactedMessages, estimateTokens, isContextOverflow, shouldCompact, splitForCompaction, SUMMARY_REQUEST, SUMMARY_SYSTEM, transcriptForSummary, } from "./compact.js";
|
|
4
|
+
import { costMicros } from "./cost.js";
|
|
5
|
+
import { alwaysLabel, decide, rememberAllow, } from "./permissions.js";
|
|
6
|
+
import { toolSchemas } from "./tools/index.js";
|
|
7
|
+
import { HELPER_NOTE, MAX_PARALLEL_HELPERS } from "./tools/task.js";
|
|
8
|
+
import { ToolInputError, truncateMiddle, } from "./tools/types.js";
|
|
9
|
+
/** Per request; keeps credit holds modest when several requests run at once. */
|
|
10
|
+
export const MAX_OUTPUT_TOKENS = 32_000;
|
|
11
|
+
/** Model calls per user message before the agent stops and asks. */
|
|
12
|
+
export const MAX_STEPS = 200;
|
|
13
|
+
const MAX_TOOL_OUTPUT_CHARS = 50_000;
|
|
14
|
+
import { CONTINUE_PROMPT, INTERRUPTED_NOTE } from "./loop-constants.js";
|
|
15
|
+
export { CONTINUE_PROMPT, INTERRUPTED_NOTE };
|
|
16
|
+
/** Resolves after `ms`, or rejects with the abort reason. */
|
|
17
|
+
export function sleep(ms, signal) {
|
|
18
|
+
return new Promise((resolve, reject) => {
|
|
19
|
+
if (signal.aborted)
|
|
20
|
+
return reject(signal.reason);
|
|
21
|
+
const timer = setTimeout(() => {
|
|
22
|
+
signal.removeEventListener("abort", onAbort);
|
|
23
|
+
resolve();
|
|
24
|
+
}, ms);
|
|
25
|
+
const onAbort = () => {
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
reject(signal.reason);
|
|
28
|
+
};
|
|
29
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
/** The conversation as sent: our own display-only fields stay out of the request. */
|
|
33
|
+
export function wireMessages(messages) {
|
|
34
|
+
return messages.map((m) => {
|
|
35
|
+
if (m.role !== "assistant")
|
|
36
|
+
return m;
|
|
37
|
+
const out = { role: "assistant", content: m.content };
|
|
38
|
+
if (m.tool_calls?.length)
|
|
39
|
+
out.tool_calls = m.tool_calls;
|
|
40
|
+
if (m.reasoning_details?.length)
|
|
41
|
+
out.reasoning_details = m.reasoning_details;
|
|
42
|
+
return out;
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
const isAbort = (error, signal) => signal.aborted || error?.name === "AbortError";
|
|
46
|
+
export class Agent {
|
|
47
|
+
options;
|
|
48
|
+
messages;
|
|
49
|
+
/** What this conversation has cost so far, in micro-dollars (an estimate of what's billed). */
|
|
50
|
+
totalCostMicros = 0n;
|
|
51
|
+
/** The last request's usage: its prompt plus output is the context in use. */
|
|
52
|
+
lastUsage = null;
|
|
53
|
+
interrupted = false;
|
|
54
|
+
/** A token estimate after compaction, until the server reports usage again. */
|
|
55
|
+
estimatedTokens = null;
|
|
56
|
+
sleep;
|
|
57
|
+
constructor(options) {
|
|
58
|
+
this.options = options;
|
|
59
|
+
this.messages = [{ role: "system", content: options.systemPrompt }];
|
|
60
|
+
this.sleep = options.sleep ?? sleep;
|
|
61
|
+
}
|
|
62
|
+
get model() {
|
|
63
|
+
return this.options.model;
|
|
64
|
+
}
|
|
65
|
+
/** Tokens in the context after the last request (prompt + reply), or null before the first. */
|
|
66
|
+
get contextTokens() {
|
|
67
|
+
if (this.lastUsage)
|
|
68
|
+
return this.lastUsage.promptTokens + this.lastUsage.completionTokens;
|
|
69
|
+
return this.estimatedTokens;
|
|
70
|
+
}
|
|
71
|
+
append(message) {
|
|
72
|
+
this.messages.push(message);
|
|
73
|
+
this.options.onChange?.({ type: "append", message });
|
|
74
|
+
}
|
|
75
|
+
replaceAll(messages, reason) {
|
|
76
|
+
this.messages.splice(1, this.messages.length - 1, ...messages);
|
|
77
|
+
this.options.onChange?.({ type: "replace", reason, messages: this.messages.slice(1) });
|
|
78
|
+
}
|
|
79
|
+
/** Picks up a saved conversation (resume). Its earlier cost isn't counted again. */
|
|
80
|
+
restore(messages) {
|
|
81
|
+
this.messages.splice(1, this.messages.length - 1, ...messages);
|
|
82
|
+
this.lastUsage = null;
|
|
83
|
+
this.estimatedTokens = messages.length ? estimateTokens(this.messages) : null;
|
|
84
|
+
}
|
|
85
|
+
/** Adds the user's message and works on it until done, stopped or failed. */
|
|
86
|
+
async *send(text, signal) {
|
|
87
|
+
const content = this.interrupted ? `${INTERRUPTED_NOTE}\n\n${text}` : text;
|
|
88
|
+
this.interrupted = false;
|
|
89
|
+
const last = this.messages.at(-1);
|
|
90
|
+
// After a failed request the user's message is still last: add to it.
|
|
91
|
+
if (last?.role === "user") {
|
|
92
|
+
last.content = `${last.content}\n\n${content}`;
|
|
93
|
+
this.replaceAll(this.messages.slice(1), "merge");
|
|
94
|
+
}
|
|
95
|
+
else
|
|
96
|
+
this.append({ role: "user", content });
|
|
97
|
+
yield* this.work(signal);
|
|
98
|
+
}
|
|
99
|
+
/** Tries again after an error, without a new message (e.g. after adding credits). */
|
|
100
|
+
async *retry(signal) {
|
|
101
|
+
yield* this.work(signal);
|
|
102
|
+
}
|
|
103
|
+
/** Whether `retry` has something to do: the conversation ends with an unanswered message. */
|
|
104
|
+
get canRetry() {
|
|
105
|
+
const role = this.messages.at(-1)?.role;
|
|
106
|
+
return role === "user" || role === "tool";
|
|
107
|
+
}
|
|
108
|
+
async *work(signal) {
|
|
109
|
+
let continued = false;
|
|
110
|
+
let compacted = false;
|
|
111
|
+
for (let step = 0; step < MAX_STEPS; step++) {
|
|
112
|
+
if (!compacted && shouldCompact(this.contextTokens, this.model.contextLength)) {
|
|
113
|
+
compacted = true;
|
|
114
|
+
yield* this.compact(signal);
|
|
115
|
+
if (signal.aborted) {
|
|
116
|
+
yield { type: "done", reason: "aborted" };
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
yield { type: "model_start" };
|
|
121
|
+
const outcome = yield* this.callModel(signal);
|
|
122
|
+
const { acc } = outcome;
|
|
123
|
+
const cost = this.recordUsage(acc);
|
|
124
|
+
if (outcome.kind === "aborted") {
|
|
125
|
+
this.commitPartial(acc);
|
|
126
|
+
this.interrupted = true;
|
|
127
|
+
yield { type: "done", reason: "aborted" };
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (outcome.kind === "error" && !compacted && isContextOverflow(outcome.error)) {
|
|
131
|
+
// Too long for the model: summarize and try this step again.
|
|
132
|
+
compacted = true;
|
|
133
|
+
if (yield* this.compact(signal)) {
|
|
134
|
+
step--;
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (outcome.kind === "error") {
|
|
139
|
+
this.commitPartial(acc);
|
|
140
|
+
yield { type: "error", error: outcome.error };
|
|
141
|
+
yield { type: "done", reason: "error" };
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const cutOff = outcome.kind === "cut" || acc.finishReason === "length";
|
|
145
|
+
const message = acc.message({ dropIncomplete: cutOff });
|
|
146
|
+
const hasCalls = Boolean(message.tool_calls?.length);
|
|
147
|
+
if (message.content || hasCalls)
|
|
148
|
+
this.append(message);
|
|
149
|
+
yield { type: "model_done", message, usage: acc.usage, costMicros: cost };
|
|
150
|
+
if (hasCalls) {
|
|
151
|
+
const stop = yield* this.runTools(message.tool_calls, signal);
|
|
152
|
+
if (stop) {
|
|
153
|
+
yield { type: "done", reason: stop };
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
continued = false;
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
if (cutOff && !continued) {
|
|
160
|
+
continued = true;
|
|
161
|
+
yield {
|
|
162
|
+
type: "notice",
|
|
163
|
+
text: outcome.kind === "cut" && outcome.error.code === "timeout"
|
|
164
|
+
? "The response hit the time limit; continuing."
|
|
165
|
+
: outcome.kind === "cut"
|
|
166
|
+
? "The connection dropped mid-response; continuing."
|
|
167
|
+
: "The response hit its length limit; continuing.",
|
|
168
|
+
};
|
|
169
|
+
this.append({ role: "user", content: CONTINUE_PROMPT });
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
yield { type: "done", reason: "complete" };
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
yield {
|
|
176
|
+
type: "notice",
|
|
177
|
+
text: `Stopped after ${MAX_STEPS} steps. Send a message to let it keep going.`,
|
|
178
|
+
};
|
|
179
|
+
yield { type: "done", reason: "max_steps" };
|
|
180
|
+
}
|
|
181
|
+
/** Adds a request's cost to the total and reports it; returns the cost. */
|
|
182
|
+
recordUsage(acc) {
|
|
183
|
+
if (!acc.usage)
|
|
184
|
+
return 0n;
|
|
185
|
+
const cost = costMicros(acc.usage, this.model);
|
|
186
|
+
this.lastUsage = acc.usage;
|
|
187
|
+
this.estimatedTokens = null;
|
|
188
|
+
this.totalCostMicros += cost;
|
|
189
|
+
this.options.onChange?.({ type: "usage", usage: acc.usage, costMicros: cost });
|
|
190
|
+
return cost;
|
|
191
|
+
}
|
|
192
|
+
/** `/compact`: summarize now, as its own turn. */
|
|
193
|
+
async *compactNow(signal) {
|
|
194
|
+
const ok = yield* this.compact(signal);
|
|
195
|
+
yield { type: "done", reason: signal.aborted ? "aborted" : ok ? "complete" : "error" };
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Replaces everything before the latest user message with a summary written by the model.
|
|
199
|
+
* Returns whether it happened; failures leave the conversation as it was.
|
|
200
|
+
*/
|
|
201
|
+
async *compact(signal) {
|
|
202
|
+
const split = splitForCompaction(this.messages.slice(1));
|
|
203
|
+
if (!split) {
|
|
204
|
+
yield { type: "notice", text: "There's nothing earlier to summarize yet." };
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
const before = this.contextTokens ?? estimateTokens(this.messages);
|
|
208
|
+
yield { type: "compacting" };
|
|
209
|
+
const maxChars = Math.floor(this.model.contextLength * 0.6) * 4;
|
|
210
|
+
const body = {
|
|
211
|
+
model: this.model.id,
|
|
212
|
+
messages: [
|
|
213
|
+
{ role: "system", content: SUMMARY_SYSTEM },
|
|
214
|
+
{
|
|
215
|
+
role: "user",
|
|
216
|
+
content: `${transcriptForSummary(split.head, maxChars)}\n\n---\n\n${SUMMARY_REQUEST}`,
|
|
217
|
+
},
|
|
218
|
+
],
|
|
219
|
+
stream: true,
|
|
220
|
+
stream_options: { include_usage: true },
|
|
221
|
+
max_tokens: Math.min(this.model.maxOutput, 4000),
|
|
222
|
+
};
|
|
223
|
+
const acc = new MessageAccumulator();
|
|
224
|
+
try {
|
|
225
|
+
for await (const chunk of streamChat({
|
|
226
|
+
apiBaseUrl: this.options.apiBaseUrl,
|
|
227
|
+
apiKey: this.options.apiKey,
|
|
228
|
+
body,
|
|
229
|
+
signal,
|
|
230
|
+
fetch: this.options.fetch,
|
|
231
|
+
})) {
|
|
232
|
+
acc.apply(chunk);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
if (!isAbort(error, signal)) {
|
|
237
|
+
yield {
|
|
238
|
+
type: "notice",
|
|
239
|
+
text: `Couldn't summarize the conversation: ${error.message}`,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
return false;
|
|
243
|
+
}
|
|
244
|
+
finally {
|
|
245
|
+
if (acc.usage) {
|
|
246
|
+
const cost = costMicros(acc.usage, this.model);
|
|
247
|
+
this.totalCostMicros += cost;
|
|
248
|
+
this.options.onChange?.({ type: "usage", usage: acc.usage, costMicros: cost });
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
const summary = acc.content.trim();
|
|
252
|
+
if (!summary) {
|
|
253
|
+
yield { type: "notice", text: "Couldn't summarize the conversation: the reply was empty." };
|
|
254
|
+
return false;
|
|
255
|
+
}
|
|
256
|
+
this.replaceAll(compactedMessages(summary, split.tail, this.options.toolContext.todos), "compact");
|
|
257
|
+
this.lastUsage = null;
|
|
258
|
+
this.estimatedTokens = estimateTokens(this.messages);
|
|
259
|
+
yield { type: "compacted", beforeTokens: before, afterTokens: this.estimatedTokens };
|
|
260
|
+
return true;
|
|
261
|
+
}
|
|
262
|
+
/** Keeps whatever text arrived before a stop or failure; unfinished tool calls are dropped. */
|
|
263
|
+
commitPartial(acc) {
|
|
264
|
+
const partial = acc.message({ dropIncomplete: true });
|
|
265
|
+
if (partial.content)
|
|
266
|
+
this.append({ role: "assistant", content: partial.content });
|
|
267
|
+
}
|
|
268
|
+
async *callModel(signal) {
|
|
269
|
+
const body = {
|
|
270
|
+
model: this.model.id,
|
|
271
|
+
messages: wireMessages(this.messages),
|
|
272
|
+
tools: toolSchemas(this.options.tools),
|
|
273
|
+
stream: true,
|
|
274
|
+
stream_options: { include_usage: true },
|
|
275
|
+
max_tokens: Math.min(this.model.maxOutput, MAX_OUTPUT_TOKENS),
|
|
276
|
+
};
|
|
277
|
+
for (let attempt = 0;; attempt++) {
|
|
278
|
+
const acc = new MessageAccumulator();
|
|
279
|
+
let received = false;
|
|
280
|
+
try {
|
|
281
|
+
for await (const chunk of streamChat({
|
|
282
|
+
apiBaseUrl: this.options.apiBaseUrl,
|
|
283
|
+
apiKey: this.options.apiKey,
|
|
284
|
+
body,
|
|
285
|
+
signal,
|
|
286
|
+
fetch: this.options.fetch,
|
|
287
|
+
})) {
|
|
288
|
+
for (const delta of acc.apply(chunk)) {
|
|
289
|
+
received = true;
|
|
290
|
+
if (delta.type === "tool_call")
|
|
291
|
+
yield { type: "tool_call_streaming", name: delta.name };
|
|
292
|
+
else
|
|
293
|
+
yield delta;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
// A stream that ends without a finish reason was cut short.
|
|
297
|
+
if (!acc.finishReason && received) {
|
|
298
|
+
return { kind: "cut", acc, error: new StreamError("The reply ended early.", null) };
|
|
299
|
+
}
|
|
300
|
+
return { kind: "ok", acc };
|
|
301
|
+
}
|
|
302
|
+
catch (error) {
|
|
303
|
+
if (isAbort(error, signal))
|
|
304
|
+
return { kind: "aborted", acc };
|
|
305
|
+
if (received)
|
|
306
|
+
return { kind: "cut", acc, error: error };
|
|
307
|
+
const delay = retryDelayMs(error, attempt);
|
|
308
|
+
if (delay === null)
|
|
309
|
+
return { kind: "error", acc, error: error };
|
|
310
|
+
yield { type: "retry", attempt: attempt + 1, delayMs: delay, error: error };
|
|
311
|
+
try {
|
|
312
|
+
await this.sleep(delay, signal);
|
|
313
|
+
}
|
|
314
|
+
catch {
|
|
315
|
+
return { kind: "aborted", acc };
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
/** Runs each call in order. Returns why the turn stops early, or null to carry on. */
|
|
321
|
+
async *runTools(calls, signal) {
|
|
322
|
+
let stop = null;
|
|
323
|
+
for (let i = 0; i < calls.length; i++) {
|
|
324
|
+
const call = calls[i];
|
|
325
|
+
// Consecutive helper tasks run at the same time.
|
|
326
|
+
if (!stop && !signal.aborted && call.function.name === "task" && !this.options.isHelper) {
|
|
327
|
+
const batch = [call];
|
|
328
|
+
while (batch.length < MAX_PARALLEL_HELPERS &&
|
|
329
|
+
calls[i + batch.length]?.function.name === "task") {
|
|
330
|
+
batch.push(calls[i + batch.length]);
|
|
331
|
+
}
|
|
332
|
+
i += batch.length - 1;
|
|
333
|
+
const outcomes = yield* this.runConcurrently(batch, signal);
|
|
334
|
+
outcomes.forEach(({ result }, j) => {
|
|
335
|
+
this.append({
|
|
336
|
+
role: "tool",
|
|
337
|
+
tool_call_id: batch[j].id,
|
|
338
|
+
content: truncateMiddle(result.output, MAX_TOOL_OUTPUT_CHARS),
|
|
339
|
+
});
|
|
340
|
+
});
|
|
341
|
+
for (const [j, { result, title }] of outcomes.entries()) {
|
|
342
|
+
yield { type: "tool_done", id: batch[j].id, name: "task", title, result };
|
|
343
|
+
}
|
|
344
|
+
if (signal.aborted)
|
|
345
|
+
stop = "aborted";
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
if (stop || signal.aborted) {
|
|
349
|
+
stop ??= "aborted";
|
|
350
|
+
this.append({
|
|
351
|
+
role: "tool",
|
|
352
|
+
tool_call_id: call.id,
|
|
353
|
+
content: stop === "declined"
|
|
354
|
+
? "Not run: the user declined an earlier action."
|
|
355
|
+
: "Not run: the user interrupted.",
|
|
356
|
+
});
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
const { result, title, declined } = yield* this.runTool(call, signal);
|
|
360
|
+
this.append({
|
|
361
|
+
role: "tool",
|
|
362
|
+
tool_call_id: call.id,
|
|
363
|
+
content: truncateMiddle(result.output, MAX_TOOL_OUTPUT_CHARS),
|
|
364
|
+
});
|
|
365
|
+
yield { type: "tool_done", id: call.id, name: call.function.name, title, result };
|
|
366
|
+
if (signal.aborted)
|
|
367
|
+
stop = "aborted";
|
|
368
|
+
else if (declined)
|
|
369
|
+
stop = "declined";
|
|
370
|
+
}
|
|
371
|
+
if (stop === "aborted")
|
|
372
|
+
this.interrupted = true;
|
|
373
|
+
return stop;
|
|
374
|
+
}
|
|
375
|
+
/** Starts each call (yielding its tool_start), then lets them all finish together. */
|
|
376
|
+
async *runConcurrently(calls, signal) {
|
|
377
|
+
const finishing = [];
|
|
378
|
+
for (const call of calls) {
|
|
379
|
+
const run = this.runTool(call, signal);
|
|
380
|
+
const first = await run.next();
|
|
381
|
+
if (first.done) {
|
|
382
|
+
finishing.push(Promise.resolve(first.value));
|
|
383
|
+
continue;
|
|
384
|
+
}
|
|
385
|
+
yield first.value;
|
|
386
|
+
finishing.push((async () => {
|
|
387
|
+
for (;;) {
|
|
388
|
+
const next = await run.next();
|
|
389
|
+
if (next.done)
|
|
390
|
+
return next.value;
|
|
391
|
+
}
|
|
392
|
+
})());
|
|
393
|
+
}
|
|
394
|
+
return await Promise.all(finishing);
|
|
395
|
+
}
|
|
396
|
+
/** Runs helper agents for the `task` tool: same model and project, fresh conversation. */
|
|
397
|
+
helpers = {
|
|
398
|
+
run: async ({ description, prompt }, signal, progress) => {
|
|
399
|
+
const parent = this.options;
|
|
400
|
+
const helper = new Agent({
|
|
401
|
+
apiBaseUrl: parent.apiBaseUrl,
|
|
402
|
+
apiKey: parent.apiKey,
|
|
403
|
+
model: parent.model,
|
|
404
|
+
tools: parent.tools.filter((t) => t.name !== "task" && t.name !== "todo"),
|
|
405
|
+
systemPrompt: `${this.messages[0].content}\n\n${HELPER_NOTE}`,
|
|
406
|
+
toolContext: { ...parent.toolContext, todos: [] },
|
|
407
|
+
// Helpers read freely; their edits and commands ask unless the user chose "Don't ask".
|
|
408
|
+
permissions: {
|
|
409
|
+
get mode() {
|
|
410
|
+
return parent.permissions.mode === "full" ? "full" : "ask";
|
|
411
|
+
},
|
|
412
|
+
allows: parent.permissions.allows,
|
|
413
|
+
context: parent.permissions.context,
|
|
414
|
+
},
|
|
415
|
+
approve: (request, sig) => parent.approve({ ...request, title: `Helper "${description}": ${request.title}` }, sig),
|
|
416
|
+
fetch: parent.fetch,
|
|
417
|
+
sleep: parent.sleep,
|
|
418
|
+
isHelper: true,
|
|
419
|
+
onChange: (change) => {
|
|
420
|
+
// Its cost is this conversation's cost (and is saved with it).
|
|
421
|
+
if (change.type !== "usage")
|
|
422
|
+
return;
|
|
423
|
+
this.totalCostMicros += change.costMicros;
|
|
424
|
+
parent.onChange?.(change);
|
|
425
|
+
},
|
|
426
|
+
});
|
|
427
|
+
let steps = 0;
|
|
428
|
+
let failure = null;
|
|
429
|
+
let reason = "complete";
|
|
430
|
+
for await (const event of helper.send(prompt, signal)) {
|
|
431
|
+
if (event.type === "tool_start") {
|
|
432
|
+
steps++;
|
|
433
|
+
progress(event.title);
|
|
434
|
+
}
|
|
435
|
+
else if (event.type === "tool_done")
|
|
436
|
+
progress(event.result.summary);
|
|
437
|
+
else if (event.type === "error")
|
|
438
|
+
failure = event.error.message;
|
|
439
|
+
else if (event.type === "done")
|
|
440
|
+
reason = event.reason;
|
|
441
|
+
}
|
|
442
|
+
const report = [...helper.messages]
|
|
443
|
+
.reverse()
|
|
444
|
+
.find((m) => m.role === "assistant" && Boolean(m.content))?.content;
|
|
445
|
+
const stepsText = `${steps} ${steps === 1 ? "step" : "steps"}`;
|
|
446
|
+
if (reason === "aborted") {
|
|
447
|
+
return {
|
|
448
|
+
output: `The helper was stopped by the user.${report ? `\n\nIts last words:\n${report}` : ""}`,
|
|
449
|
+
summary: `Helper: ${description} · stopped`,
|
|
450
|
+
isError: true,
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
if (failure || !report) {
|
|
454
|
+
return {
|
|
455
|
+
output: `The helper couldn't finish${failure ? `: ${failure}` : "."}`,
|
|
456
|
+
summary: `Helper: ${description} · failed`,
|
|
457
|
+
isError: true,
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
return {
|
|
461
|
+
output: report,
|
|
462
|
+
summary: `Helper: ${description} · done in ${stepsText}`,
|
|
463
|
+
detail: report,
|
|
464
|
+
};
|
|
465
|
+
},
|
|
466
|
+
};
|
|
467
|
+
async *runTool(call, signal) {
|
|
468
|
+
const name = call.function.name;
|
|
469
|
+
const fail = (output, title = name) => ({
|
|
470
|
+
result: { output, summary: output.split("\n")[0], isError: true },
|
|
471
|
+
title,
|
|
472
|
+
declined: false,
|
|
473
|
+
});
|
|
474
|
+
const tool = this.options.tools.find((t) => t.name === name);
|
|
475
|
+
if (!tool)
|
|
476
|
+
return fail(`There is no tool called "${name}".`);
|
|
477
|
+
let args;
|
|
478
|
+
try {
|
|
479
|
+
const parsed = call.function.arguments.trim()
|
|
480
|
+
? JSON.parse(call.function.arguments)
|
|
481
|
+
: {};
|
|
482
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
483
|
+
throw new Error("not an object");
|
|
484
|
+
args = parsed;
|
|
485
|
+
}
|
|
486
|
+
catch {
|
|
487
|
+
return fail(`The arguments for ${name} weren't valid JSON. Send them as a JSON object.`);
|
|
488
|
+
}
|
|
489
|
+
const ctx = {
|
|
490
|
+
...this.options.toolContext,
|
|
491
|
+
signal,
|
|
492
|
+
progress: (text) => this.options.onProgress?.(call.id, text),
|
|
493
|
+
helpers: this.options.isHelper ? undefined : this.helpers,
|
|
494
|
+
};
|
|
495
|
+
let prepared;
|
|
496
|
+
try {
|
|
497
|
+
prepared = await tool.prepare(args, ctx);
|
|
498
|
+
}
|
|
499
|
+
catch (error) {
|
|
500
|
+
const message = error instanceof ToolInputError
|
|
501
|
+
? error.message
|
|
502
|
+
: `${name} failed: ${error.message}`;
|
|
503
|
+
return fail(message);
|
|
504
|
+
}
|
|
505
|
+
yield { type: "tool_start", id: call.id, name, title: prepared.title };
|
|
506
|
+
const request = {
|
|
507
|
+
tool: name,
|
|
508
|
+
kind: prepared.kind,
|
|
509
|
+
paths: prepared.paths,
|
|
510
|
+
command: prepared.command,
|
|
511
|
+
};
|
|
512
|
+
const { mode, allows, context } = this.options.permissions;
|
|
513
|
+
const decision = decide(request, mode, context, allows);
|
|
514
|
+
if (decision.kind === "deny") {
|
|
515
|
+
return { ...fail(decision.reason, prepared.title) };
|
|
516
|
+
}
|
|
517
|
+
if (decision.kind === "ask") {
|
|
518
|
+
let answer;
|
|
519
|
+
try {
|
|
520
|
+
answer = await this.options.approve({
|
|
521
|
+
tool: name,
|
|
522
|
+
kind: prepared.kind,
|
|
523
|
+
title: prepared.title,
|
|
524
|
+
preview: prepared.preview,
|
|
525
|
+
reason: decision.reason,
|
|
526
|
+
always: decision.canAlways ? alwaysLabel(request) : null,
|
|
527
|
+
}, signal);
|
|
528
|
+
}
|
|
529
|
+
catch {
|
|
530
|
+
answer = { kind: "no" };
|
|
531
|
+
}
|
|
532
|
+
if (signal.aborted) {
|
|
533
|
+
return { ...fail("Not run: the user interrupted.", prepared.title) };
|
|
534
|
+
}
|
|
535
|
+
if (answer.kind === "no") {
|
|
536
|
+
const feedback = answer.feedback?.trim();
|
|
537
|
+
return {
|
|
538
|
+
result: {
|
|
539
|
+
output: feedback
|
|
540
|
+
? `The user declined this action and said: ${feedback}`
|
|
541
|
+
: "The user declined this action.",
|
|
542
|
+
summary: `Declined: ${prepared.title}`,
|
|
543
|
+
isError: true,
|
|
544
|
+
},
|
|
545
|
+
title: prepared.title,
|
|
546
|
+
declined: !feedback,
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
if (answer.kind === "always")
|
|
550
|
+
rememberAllow(request, allows);
|
|
551
|
+
}
|
|
552
|
+
try {
|
|
553
|
+
return { result: await prepared.run(), title: prepared.title, declined: false };
|
|
554
|
+
}
|
|
555
|
+
catch (error) {
|
|
556
|
+
return fail(`${prepared.title} failed: ${error.message}`, prepared.title);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/** Reading `mcp.json`. No MCP SDK imports, so checking for servers stays cheap. */
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
export const mcpConfigPath = (configDir) => join(configDir, "mcp.json");
|
|
5
|
+
export const MCP_EXAMPLE = `{
|
|
6
|
+
"mcpServers": {
|
|
7
|
+
"github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"],
|
|
8
|
+
"env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "…" } },
|
|
9
|
+
"docs": { "url": "https://example.com/mcp", "headers": { "Authorization": "Bearer …" } }
|
|
10
|
+
}
|
|
11
|
+
}`;
|
|
12
|
+
const isStringRecord = (v) => Boolean(v) &&
|
|
13
|
+
typeof v === "object" &&
|
|
14
|
+
!Array.isArray(v) &&
|
|
15
|
+
Object.values(v).every((x) => typeof x === "string");
|
|
16
|
+
/**
|
|
17
|
+
* The servers in `mcp.json` (`{ "mcpServers": { name: {…} } }`). A missing file means none; a
|
|
18
|
+
* broken file or entry is reported, never thrown, so the agent still starts.
|
|
19
|
+
*/
|
|
20
|
+
export async function readMcpConfig(path) {
|
|
21
|
+
let text;
|
|
22
|
+
try {
|
|
23
|
+
text = await readFile(path, "utf8");
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return { servers: {}, errors: [] };
|
|
27
|
+
}
|
|
28
|
+
let parsed;
|
|
29
|
+
try {
|
|
30
|
+
parsed = JSON.parse(text);
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
return { servers: {}, errors: [`mcp.json isn't valid JSON (${error.message}).`] };
|
|
34
|
+
}
|
|
35
|
+
const raw = parsed?.mcpServers;
|
|
36
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
37
|
+
return { servers: {}, errors: ['mcp.json needs an "mcpServers" object.'] };
|
|
38
|
+
}
|
|
39
|
+
const servers = {};
|
|
40
|
+
const errors = [];
|
|
41
|
+
for (const [name, value] of Object.entries(raw)) {
|
|
42
|
+
const v = (value ?? {});
|
|
43
|
+
if (v.disabled === true)
|
|
44
|
+
continue;
|
|
45
|
+
if (typeof v.url === "string" && v.url) {
|
|
46
|
+
try {
|
|
47
|
+
new URL(v.url);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
errors.push(`MCP server "${name}": "${v.url}" isn't a valid URL.`);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
servers[name] = { url: v.url, headers: isStringRecord(v.headers) ? v.headers : undefined };
|
|
54
|
+
}
|
|
55
|
+
else if (typeof v.command === "string" && v.command) {
|
|
56
|
+
servers[name] = {
|
|
57
|
+
command: v.command,
|
|
58
|
+
args: Array.isArray(v.args) ? v.args.filter((a) => typeof a === "string") : [],
|
|
59
|
+
env: isStringRecord(v.env) ? v.env : undefined,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
errors.push(`MCP server "${name}" needs a "command" or a "url".`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return { servers, errors };
|
|
67
|
+
}
|
|
68
|
+
const clean = (s) => s.replace(/[^a-zA-Z0-9_-]+/g, "_");
|
|
69
|
+
/** "github" + "create_issue" → "github__create_issue" (letters, digits, _ and -; at most 64). */
|
|
70
|
+
export function toolName(server, tool) {
|
|
71
|
+
return `${clean(server)}__${clean(tool)}`.slice(0, 64);
|
|
72
|
+
}
|