reasonally 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,734 @@
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, MODE_LABELS, rememberAllow, } from "./permissions.js";
6
+ import { toolSchemas } from "./tools/index.js";
7
+ import { MAX_PLAN_CHARS, partialPlan, PLAN_OUTCOME_LABELS, PLAN_TOOL, } from "./tools/plan.js";
8
+ import { HELPER_NOTE, MAX_PARALLEL_HELPERS } from "./tools/task.js";
9
+ import { ToolInputError, truncateMiddle, } from "./tools/types.js";
10
+ /** Per request; keeps credit holds modest when several requests run at once. */
11
+ export const MAX_OUTPUT_TOKENS = 32_000;
12
+ /** Model calls per user message before the agent stops and asks. */
13
+ export const MAX_STEPS = 200;
14
+ const MAX_TOOL_OUTPUT_CHARS = 50_000;
15
+ import { CONTINUE_PROMPT, HELPER_PLAN_ON_NOTE, INTERRUPTED_NOTE, PLAN_APPROVED, PLAN_OFF_NOTE, PLAN_ON_NOTE, } from "./loop-constants.js";
16
+ export { CONTINUE_PROMPT, INTERRUPTED_NOTE };
17
+ /** Plan drafts are sent to the screen at most this often while the model writes. */
18
+ const PLAN_DRAFT_EVERY_MS = 50;
19
+ /**
20
+ * Whether the conversation last told the model Plan mode was on: the latest mode note, or an
21
+ * approved plan (which switched it off). False when it was never mentioned.
22
+ */
23
+ export function lastToldPlan(messages) {
24
+ for (let i = messages.length - 1; i >= 0; i--) {
25
+ const m = messages[i];
26
+ if ((m.role !== "user" && m.role !== "tool") || typeof m.content !== "string")
27
+ continue;
28
+ const on = Math.max(m.content.lastIndexOf(PLAN_ON_NOTE), m.content.lastIndexOf(HELPER_PLAN_ON_NOTE));
29
+ const off = Math.max(m.content.lastIndexOf(PLAN_OFF_NOTE), m.content.startsWith(PLAN_APPROVED) ? 0 : -1);
30
+ if (on !== -1 || off !== -1)
31
+ return on > off;
32
+ }
33
+ return false;
34
+ }
35
+ /** Resolves after `ms`, or rejects with the abort reason. */
36
+ export function sleep(ms, signal) {
37
+ return new Promise((resolve, reject) => {
38
+ if (signal.aborted)
39
+ return reject(signal.reason);
40
+ const timer = setTimeout(() => {
41
+ signal.removeEventListener("abort", onAbort);
42
+ resolve();
43
+ }, ms);
44
+ const onAbort = () => {
45
+ clearTimeout(timer);
46
+ reject(signal.reason);
47
+ };
48
+ signal.addEventListener("abort", onAbort, { once: true });
49
+ });
50
+ }
51
+ /** The conversation as sent: our own display-only fields stay out of the request. */
52
+ export function wireMessages(messages) {
53
+ return messages.map((m) => {
54
+ if (m.role !== "assistant")
55
+ return m;
56
+ const out = { role: "assistant", content: m.content };
57
+ if (m.tool_calls?.length)
58
+ out.tool_calls = m.tool_calls;
59
+ if (m.reasoning_details?.length)
60
+ out.reasoning_details = m.reasoning_details;
61
+ return out;
62
+ });
63
+ }
64
+ const isAbort = (error, signal) => signal.aborted || error?.name === "AbortError";
65
+ export class Agent {
66
+ options;
67
+ messages;
68
+ /** What this conversation has cost so far, in micro-dollars (an estimate of what's billed). */
69
+ totalCostMicros = 0n;
70
+ /** The last request's usage: its prompt plus output is the context in use. */
71
+ lastUsage = null;
72
+ interrupted = false;
73
+ /** Whether the model was last told Plan mode is on (see `modeNote`). */
74
+ toldPlan = false;
75
+ /** Whether the current model call has shown a plan draft. */
76
+ planDrafted = false;
77
+ /** A token estimate after compaction, until the server reports usage again. */
78
+ estimatedTokens = null;
79
+ sleep;
80
+ constructor(options) {
81
+ this.options = options;
82
+ this.messages = [{ role: "system", content: options.systemPrompt }];
83
+ this.sleep = options.sleep ?? sleep;
84
+ }
85
+ get model() {
86
+ return this.options.model;
87
+ }
88
+ /** Tokens in the context after the last request (prompt + reply), or null before the first. */
89
+ get contextTokens() {
90
+ if (this.lastUsage)
91
+ return this.lastUsage.promptTokens + this.lastUsage.completionTokens;
92
+ return this.estimatedTokens;
93
+ }
94
+ append(message) {
95
+ this.messages.push(message);
96
+ this.options.onChange?.({ type: "append", message });
97
+ }
98
+ replaceAll(messages, reason) {
99
+ this.messages.splice(1, this.messages.length - 1, ...messages);
100
+ this.options.onChange?.({ type: "replace", reason, messages: this.messages.slice(1) });
101
+ }
102
+ /** Picks up a saved conversation (resume). Its earlier cost isn't counted again. */
103
+ restore(messages) {
104
+ this.messages.splice(1, this.messages.length - 1, ...messages);
105
+ this.toldPlan = lastToldPlan(messages);
106
+ this.lastUsage = null;
107
+ this.estimatedTokens = messages.length ? estimateTokens(this.messages) : null;
108
+ }
109
+ /** Adds the user's message and works on it until done, stopped or failed. */
110
+ async *send(text, signal) {
111
+ const content = this.interrupted ? `${INTERRUPTED_NOTE}\n\n${text}` : text;
112
+ this.interrupted = false;
113
+ const note = this.modeNote();
114
+ const last = this.messages.at(-1);
115
+ // After a failed request the user's message is still last: add to it.
116
+ if (last?.role === "user") {
117
+ const merged = `${last.content}\n\n${content}`;
118
+ last.content = note ? `${note}\n\n${merged}` : merged;
119
+ this.replaceAll(this.messages.slice(1), "merge");
120
+ }
121
+ else
122
+ this.append({ role: "user", content: note ? `${note}\n\n${content}` : content });
123
+ yield* this.work(signal);
124
+ }
125
+ /**
126
+ * A note for the model when Plan mode starts or stops applying, else null. The note goes in
127
+ * front of the next user message or after the next tool result, so the system prompt and the
128
+ * tool list never change (which keeps the provider's prompt cache).
129
+ */
130
+ modeNote() {
131
+ const planning = this.options.permissions.mode === "plan";
132
+ if (planning === this.toldPlan)
133
+ return null;
134
+ this.toldPlan = planning;
135
+ if (!planning)
136
+ return PLAN_OFF_NOTE;
137
+ return this.options.isHelper ? HELPER_PLAN_ON_NOTE : PLAN_ON_NOTE;
138
+ }
139
+ /** Adds a tool result (with a mode note when the mode changed since the model last heard). */
140
+ appendToolResult(callId, output) {
141
+ const content = truncateMiddle(output, MAX_TOOL_OUTPUT_CHARS);
142
+ const note = this.modeNote();
143
+ this.append({
144
+ role: "tool",
145
+ tool_call_id: callId,
146
+ content: note ? `${content}\n\n${note}` : content,
147
+ });
148
+ }
149
+ /** Tries again after an error, without a new message (e.g. after adding credits). */
150
+ async *retry(signal) {
151
+ yield* this.work(signal);
152
+ }
153
+ /** Whether `retry` has something to do: the conversation ends with an unanswered message. */
154
+ get canRetry() {
155
+ const role = this.messages.at(-1)?.role;
156
+ return role === "user" || role === "tool";
157
+ }
158
+ async *work(signal) {
159
+ let continued = false;
160
+ let compacted = false;
161
+ for (let step = 0; step < MAX_STEPS; step++) {
162
+ if (!compacted && shouldCompact(this.contextTokens, this.model.contextLength)) {
163
+ compacted = true;
164
+ yield* this.compact(signal);
165
+ if (signal.aborted) {
166
+ yield { type: "done", reason: "aborted" };
167
+ return;
168
+ }
169
+ }
170
+ yield { type: "model_start" };
171
+ this.planDrafted = false;
172
+ const outcome = yield* this.callModel(signal);
173
+ const { acc } = outcome;
174
+ const cost = this.recordUsage(acc);
175
+ if (this.planDrafted) {
176
+ const kept = outcome.kind === "ok" || outcome.kind === "cut";
177
+ const calls = kept ? acc.message({ dropIncomplete: true }).tool_calls : undefined;
178
+ if (!calls?.some((c) => c.function.name === PLAN_TOOL)) {
179
+ yield { type: "plan_draft_dropped" };
180
+ }
181
+ }
182
+ if (outcome.kind === "aborted") {
183
+ this.commitPartial(acc);
184
+ this.interrupted = true;
185
+ yield { type: "done", reason: "aborted" };
186
+ return;
187
+ }
188
+ if (outcome.kind === "error" && !compacted && isContextOverflow(outcome.error)) {
189
+ // Too long for the model: summarize and try this step again.
190
+ compacted = true;
191
+ if (yield* this.compact(signal)) {
192
+ step--;
193
+ continue;
194
+ }
195
+ }
196
+ if (outcome.kind === "error") {
197
+ this.commitPartial(acc);
198
+ yield { type: "error", error: outcome.error };
199
+ yield { type: "done", reason: "error" };
200
+ return;
201
+ }
202
+ const cutOff = outcome.kind === "cut" || acc.finishReason === "length";
203
+ const message = acc.message({ dropIncomplete: cutOff });
204
+ const hasCalls = Boolean(message.tool_calls?.length);
205
+ if (message.content || hasCalls)
206
+ this.append(message);
207
+ yield { type: "model_done", message, usage: acc.usage, costMicros: cost };
208
+ if (hasCalls) {
209
+ const stop = yield* this.runTools(message.tool_calls, signal);
210
+ if (stop) {
211
+ yield { type: "done", reason: stop };
212
+ return;
213
+ }
214
+ continued = false;
215
+ continue;
216
+ }
217
+ if (cutOff && !continued) {
218
+ continued = true;
219
+ yield {
220
+ type: "notice",
221
+ text: outcome.kind === "cut" && outcome.error.code === "timeout"
222
+ ? "The response hit the time limit; continuing."
223
+ : outcome.kind === "cut"
224
+ ? "The connection dropped mid-response; continuing."
225
+ : "The response hit its length limit; continuing.",
226
+ };
227
+ this.append({ role: "user", content: CONTINUE_PROMPT });
228
+ continue;
229
+ }
230
+ yield { type: "done", reason: "complete" };
231
+ return;
232
+ }
233
+ yield {
234
+ type: "notice",
235
+ text: `Stopped after ${MAX_STEPS} steps. Send a message to let it keep going.`,
236
+ };
237
+ yield { type: "done", reason: "max_steps" };
238
+ }
239
+ /** Adds a request's cost to the total and reports it; returns the cost. */
240
+ recordUsage(acc) {
241
+ if (!acc.usage)
242
+ return 0n;
243
+ const cost = costMicros(acc.usage, this.model);
244
+ this.lastUsage = acc.usage;
245
+ this.estimatedTokens = null;
246
+ this.totalCostMicros += cost;
247
+ this.options.onChange?.({ type: "usage", usage: acc.usage, costMicros: cost });
248
+ return cost;
249
+ }
250
+ /** `/compact`: summarize now, as its own turn. */
251
+ async *compactNow(signal) {
252
+ const ok = yield* this.compact(signal);
253
+ yield { type: "done", reason: signal.aborted ? "aborted" : ok ? "complete" : "error" };
254
+ }
255
+ /**
256
+ * Replaces everything before the latest user message with a summary written by the model.
257
+ * Returns whether it happened; failures leave the conversation as it was.
258
+ */
259
+ async *compact(signal) {
260
+ const split = splitForCompaction(this.messages.slice(1));
261
+ if (!split) {
262
+ yield { type: "notice", text: "There's nothing earlier to summarize yet." };
263
+ return false;
264
+ }
265
+ const before = this.contextTokens ?? estimateTokens(this.messages);
266
+ yield { type: "compacting" };
267
+ const maxChars = Math.floor(this.model.contextLength * 0.6) * 4;
268
+ const body = {
269
+ model: this.model.id,
270
+ messages: [
271
+ { role: "system", content: SUMMARY_SYSTEM },
272
+ {
273
+ role: "user",
274
+ content: `${transcriptForSummary(split.head, maxChars)}\n\n---\n\n${SUMMARY_REQUEST}`,
275
+ },
276
+ ],
277
+ stream: true,
278
+ stream_options: { include_usage: true },
279
+ max_tokens: Math.min(this.model.maxOutput, 4000),
280
+ };
281
+ const acc = new MessageAccumulator();
282
+ try {
283
+ for await (const chunk of streamChat({
284
+ apiBaseUrl: this.options.apiBaseUrl,
285
+ apiKey: this.options.apiKey,
286
+ body,
287
+ signal,
288
+ fetch: this.options.fetch,
289
+ client: this.options.client,
290
+ })) {
291
+ acc.apply(chunk);
292
+ }
293
+ }
294
+ catch (error) {
295
+ if (!isAbort(error, signal)) {
296
+ yield {
297
+ type: "notice",
298
+ text: `Couldn't summarize the conversation: ${error.message}`,
299
+ };
300
+ }
301
+ return false;
302
+ }
303
+ finally {
304
+ if (acc.usage) {
305
+ const cost = costMicros(acc.usage, this.model);
306
+ this.totalCostMicros += cost;
307
+ this.options.onChange?.({ type: "usage", usage: acc.usage, costMicros: cost });
308
+ }
309
+ }
310
+ const summary = acc.content.trim();
311
+ if (!summary) {
312
+ yield { type: "notice", text: "Couldn't summarize the conversation: the reply was empty." };
313
+ return false;
314
+ }
315
+ this.replaceAll(compactedMessages(summary, split.tail, this.options.toolContext.todos), "compact");
316
+ // Notes that were summarized away no longer count: say it again if it matters.
317
+ this.toldPlan = lastToldPlan(this.messages);
318
+ this.lastUsage = null;
319
+ this.estimatedTokens = estimateTokens(this.messages);
320
+ yield { type: "compacted", beforeTokens: before, afterTokens: this.estimatedTokens };
321
+ return true;
322
+ }
323
+ /** Keeps whatever text arrived before a stop or failure; unfinished tool calls are dropped. */
324
+ commitPartial(acc) {
325
+ const partial = acc.message({ dropIncomplete: true });
326
+ if (partial.content)
327
+ this.append({ role: "assistant", content: partial.content });
328
+ }
329
+ async *callModel(signal) {
330
+ const body = {
331
+ model: this.model.id,
332
+ messages: wireMessages(this.messages),
333
+ tools: toolSchemas(this.options.tools),
334
+ stream: true,
335
+ stream_options: { include_usage: true },
336
+ max_tokens: Math.min(this.model.maxOutput, MAX_OUTPUT_TOKENS),
337
+ };
338
+ for (let attempt = 0;; attempt++) {
339
+ const acc = new MessageAccumulator();
340
+ let received = false;
341
+ // The plan being written (Plan mode only), shown as it arrives.
342
+ let planIndex = null;
343
+ let draft = "";
344
+ let draftAt = 0;
345
+ const nextDraft = (force) => {
346
+ if (planIndex === null)
347
+ return null;
348
+ const text = partialPlan(acc.argumentsOf(planIndex))?.trimStart() ?? "";
349
+ const now = Date.now();
350
+ if (!text || text === draft || (!force && now - draftAt < PLAN_DRAFT_EVERY_MS))
351
+ return null;
352
+ draft = text;
353
+ draftAt = now;
354
+ this.planDrafted = true;
355
+ return { type: "plan_draft", text };
356
+ };
357
+ try {
358
+ for await (const chunk of streamChat({
359
+ apiBaseUrl: this.options.apiBaseUrl,
360
+ apiKey: this.options.apiKey,
361
+ body,
362
+ signal,
363
+ fetch: this.options.fetch,
364
+ client: this.options.client,
365
+ })) {
366
+ for (const delta of acc.apply(chunk)) {
367
+ received = true;
368
+ if (delta.type === "tool_call") {
369
+ const planning = this.options.permissions.mode === "plan" && !this.options.isHelper;
370
+ if (delta.name === PLAN_TOOL && planning && planIndex === null) {
371
+ planIndex = delta.index;
372
+ }
373
+ yield { type: "tool_call_streaming", name: delta.name };
374
+ }
375
+ else
376
+ yield delta;
377
+ }
378
+ const drafted = nextDraft(false);
379
+ if (drafted)
380
+ yield drafted;
381
+ }
382
+ const last = nextDraft(true);
383
+ if (last)
384
+ yield last;
385
+ // A stream that ends without a finish reason was cut short.
386
+ if (!acc.finishReason && received) {
387
+ return { kind: "cut", acc, error: new StreamError("The reply ended early.", null) };
388
+ }
389
+ return { kind: "ok", acc };
390
+ }
391
+ catch (error) {
392
+ if (isAbort(error, signal))
393
+ return { kind: "aborted", acc };
394
+ if (received)
395
+ return { kind: "cut", acc, error: error };
396
+ const delay = retryDelayMs(error, attempt);
397
+ if (delay === null)
398
+ return { kind: "error", acc, error: error };
399
+ yield { type: "retry", attempt: attempt + 1, delayMs: delay, error: error };
400
+ try {
401
+ await this.sleep(delay, signal);
402
+ }
403
+ catch {
404
+ return { kind: "aborted", acc };
405
+ }
406
+ }
407
+ }
408
+ }
409
+ /** Runs each call in order. Returns why the turn stops early, or null to carry on. */
410
+ async *runTools(calls, signal) {
411
+ let stop = null;
412
+ /** Calls after a presented plan wait for the user's answer to it, so they're not run. */
413
+ let afterPlan = false;
414
+ for (let i = 0; i < calls.length; i++) {
415
+ const call = calls[i];
416
+ if (afterPlan && !stop && !signal.aborted) {
417
+ this.appendToolResult(call.id, "Not run: present_plan has to be the last call in a reply. Carry on from the user's answer.");
418
+ continue;
419
+ }
420
+ // Consecutive helper tasks run at the same time.
421
+ if (!stop && !signal.aborted && call.function.name === "task" && !this.options.isHelper) {
422
+ const batch = [call];
423
+ while (batch.length < MAX_PARALLEL_HELPERS &&
424
+ calls[i + batch.length]?.function.name === "task") {
425
+ batch.push(calls[i + batch.length]);
426
+ }
427
+ i += batch.length - 1;
428
+ const outcomes = yield* this.runConcurrently(batch, signal);
429
+ outcomes.forEach(({ result }, j) => this.appendToolResult(batch[j].id, result.output));
430
+ for (const [j, { result, title }] of outcomes.entries()) {
431
+ yield { type: "tool_done", id: batch[j].id, name: "task", title, result };
432
+ }
433
+ if (signal.aborted)
434
+ stop = "aborted";
435
+ continue;
436
+ }
437
+ if (stop || signal.aborted) {
438
+ stop ??= "aborted";
439
+ this.appendToolResult(call.id, stop === "declined"
440
+ ? "Not run: the user declined an earlier action."
441
+ : "Not run: the user interrupted.");
442
+ continue;
443
+ }
444
+ const { result, title, declined } = yield* this.runTool(call, signal);
445
+ // The mode it switched to (if approved) comes first, so screens show both together.
446
+ if (result.plan?.outcome === "approved-ask" || result.plan?.outcome === "approved-auto") {
447
+ yield {
448
+ type: "mode_changed",
449
+ mode: result.plan.outcome === "approved-auto" ? "auto-edit" : "ask",
450
+ };
451
+ }
452
+ this.appendToolResult(call.id, result.output);
453
+ yield { type: "tool_done", id: call.id, name: call.function.name, title, result };
454
+ if (call.function.name === PLAN_TOOL && result.plan)
455
+ afterPlan = true;
456
+ if (signal.aborted)
457
+ stop = "aborted";
458
+ else if (declined)
459
+ stop = "declined";
460
+ }
461
+ if (stop === "aborted")
462
+ this.interrupted = true;
463
+ return stop;
464
+ }
465
+ /** Starts each call (yielding its tool_start), then lets them all finish together. */
466
+ async *runConcurrently(calls, signal) {
467
+ const finishing = [];
468
+ for (const call of calls) {
469
+ const run = this.runTool(call, signal);
470
+ const first = await run.next();
471
+ if (first.done) {
472
+ finishing.push(Promise.resolve(first.value));
473
+ continue;
474
+ }
475
+ yield first.value;
476
+ finishing.push((async () => {
477
+ for (;;) {
478
+ const next = await run.next();
479
+ if (next.done)
480
+ return next.value;
481
+ }
482
+ })());
483
+ }
484
+ return await Promise.all(finishing);
485
+ }
486
+ /** Runs helper agents for the `task` tool: same model and project, fresh conversation. */
487
+ helpers = {
488
+ run: async ({ description, prompt, callId: taskCallId }, signal, progress) => {
489
+ const parent = this.options;
490
+ const helper = new Agent({
491
+ apiBaseUrl: parent.apiBaseUrl,
492
+ apiKey: parent.apiKey,
493
+ model: parent.model,
494
+ tools: parent.tools.filter((t) => t.name !== "task" && t.name !== "todo" && t.name !== PLAN_TOOL),
495
+ systemPrompt: `${this.messages[0].content}\n\n${HELPER_NOTE}`,
496
+ toolContext: { ...parent.toolContext, todos: [] },
497
+ // Helpers read freely; their edits and commands ask unless the user chose "Don't ask",
498
+ // and in Plan mode they change nothing.
499
+ permissions: {
500
+ get mode() {
501
+ const mode = parent.permissions.mode;
502
+ return mode === "full" || mode === "plan" ? mode : "ask";
503
+ },
504
+ allows: parent.permissions.allows,
505
+ context: parent.permissions.context,
506
+ },
507
+ approve: (request, sig, origin) => parent.approve({ ...request, title: `Helper "${description}": ${request.title}` }, sig, {
508
+ callId: origin?.callId ?? "",
509
+ helper: { description, callId: taskCallId },
510
+ }),
511
+ fetch: parent.fetch,
512
+ sleep: parent.sleep,
513
+ onProcess: parent.onProcess,
514
+ client: parent.client,
515
+ isHelper: true,
516
+ onChange: (change) => {
517
+ // Its cost is this conversation's cost (and is saved with it).
518
+ if (change.type !== "usage")
519
+ return;
520
+ this.totalCostMicros += change.costMicros;
521
+ parent.onChange?.(change);
522
+ },
523
+ });
524
+ let steps = 0;
525
+ let failure = null;
526
+ let reason = "complete";
527
+ for await (const event of helper.send(prompt, signal)) {
528
+ if (event.type === "tool_start") {
529
+ steps++;
530
+ progress(event.title);
531
+ }
532
+ else if (event.type === "tool_done")
533
+ progress(event.result.summary);
534
+ else if (event.type === "error")
535
+ failure = event.error.message;
536
+ else if (event.type === "done")
537
+ reason = event.reason;
538
+ }
539
+ const report = [...helper.messages]
540
+ .reverse()
541
+ .find((m) => m.role === "assistant" && Boolean(m.content))?.content;
542
+ const stepsText = `${steps} ${steps === 1 ? "step" : "steps"}`;
543
+ if (reason === "aborted") {
544
+ return {
545
+ output: `The helper was stopped by the user.${report ? `\n\nIts last words:\n${report}` : ""}`,
546
+ summary: `Helper: ${description} · stopped`,
547
+ isError: true,
548
+ };
549
+ }
550
+ if (failure || !report) {
551
+ return {
552
+ output: `The helper couldn't finish${failure ? `: ${failure}` : "."}`,
553
+ summary: `Helper: ${description} · failed`,
554
+ isError: true,
555
+ };
556
+ }
557
+ return {
558
+ output: report,
559
+ summary: `Helper: ${description} · done in ${stepsText}`,
560
+ detail: report,
561
+ };
562
+ },
563
+ };
564
+ async *runTool(call, signal) {
565
+ const name = call.function.name;
566
+ const fail = (output, title = name) => ({
567
+ result: { output, summary: output.split("\n")[0], isError: true },
568
+ title,
569
+ declined: false,
570
+ });
571
+ const tool = this.options.tools.find((t) => t.name === name);
572
+ if (!tool)
573
+ return fail(`There is no tool called "${name}".`);
574
+ let args;
575
+ try {
576
+ const parsed = call.function.arguments.trim()
577
+ ? JSON.parse(call.function.arguments)
578
+ : {};
579
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
580
+ throw new Error("not an object");
581
+ args = parsed;
582
+ }
583
+ catch {
584
+ return fail(`The arguments for ${name} weren't valid JSON. Send them as a JSON object.`);
585
+ }
586
+ const ctx = {
587
+ ...this.options.toolContext,
588
+ signal,
589
+ callId: call.id,
590
+ progress: (text) => this.options.onProgress?.(call.id, text),
591
+ output: this.options.onOutput && ((chunk) => this.options.onOutput?.(call.id, chunk)),
592
+ process: this.options.onProcess,
593
+ helpers: this.options.isHelper ? undefined : this.helpers,
594
+ };
595
+ let prepared;
596
+ try {
597
+ prepared = await tool.prepare(args, ctx);
598
+ }
599
+ catch (error) {
600
+ const message = error instanceof ToolInputError
601
+ ? error.message
602
+ : `${name} failed: ${error.message}`;
603
+ return fail(message);
604
+ }
605
+ yield { type: "tool_start", id: call.id, name, title: prepared.title };
606
+ if (name === PLAN_TOOL)
607
+ return await this.presentPlan(prepared, call.id, signal);
608
+ const request = {
609
+ tool: name,
610
+ kind: prepared.kind,
611
+ paths: prepared.paths,
612
+ command: prepared.command,
613
+ readOnlyPaths: prepared.readOnlyPaths,
614
+ };
615
+ const { mode, allows, context } = this.options.permissions;
616
+ const decision = decide(request, mode, context, allows);
617
+ if (decision.kind === "deny") {
618
+ return { ...fail(decision.reason, prepared.title) };
619
+ }
620
+ if (decision.kind === "ask") {
621
+ let answer;
622
+ try {
623
+ answer = await this.options.approve({
624
+ tool: name,
625
+ kind: prepared.kind,
626
+ title: prepared.title,
627
+ preview: prepared.preview,
628
+ reason: decision.reason,
629
+ always: decision.canAlways ? alwaysLabel(request) : null,
630
+ }, signal, { callId: call.id });
631
+ }
632
+ catch {
633
+ answer = { kind: "no" };
634
+ }
635
+ if (signal.aborted) {
636
+ return { ...fail("Not run: the user interrupted.", prepared.title) };
637
+ }
638
+ if (answer.kind === "no") {
639
+ const feedback = answer.feedback?.trim();
640
+ return {
641
+ result: {
642
+ output: feedback
643
+ ? `The user declined this action and said: ${feedback}`
644
+ : "The user declined this action.",
645
+ summary: `Declined: ${prepared.title}`,
646
+ isError: true,
647
+ },
648
+ title: prepared.title,
649
+ declined: !feedback,
650
+ };
651
+ }
652
+ if (answer.kind === "always")
653
+ rememberAllow(request, allows);
654
+ }
655
+ try {
656
+ return { result: await prepared.run(), title: prepared.title, declined: false };
657
+ }
658
+ catch (error) {
659
+ return fail(`${prepared.title} failed: ${error.message}`, prepared.title);
660
+ }
661
+ }
662
+ /** Shows a plan and waits for the user's answer. Approving switches the mode to the one chosen. */
663
+ async presentPlan(prepared, callId, signal) {
664
+ const title = prepared.title;
665
+ const original = prepared.preview ?? "";
666
+ if (this.options.permissions.mode !== "plan") {
667
+ return {
668
+ result: {
669
+ output: "Plan mode is off, so there's nothing to approve: go ahead with the work (the user " +
670
+ "approves edits and commands as usual).",
671
+ summary: "Plan mode is off",
672
+ isError: true,
673
+ },
674
+ title,
675
+ declined: false,
676
+ };
677
+ }
678
+ let answer;
679
+ try {
680
+ answer = await this.options.approve({
681
+ tool: PLAN_TOOL,
682
+ kind: "meta",
683
+ title,
684
+ preview: original,
685
+ reason: null,
686
+ always: "yes, auto-accept edits",
687
+ }, signal, { callId });
688
+ }
689
+ catch {
690
+ answer = { kind: "no" };
691
+ }
692
+ const edited = editedPlan(answer.plan, original);
693
+ const text = edited ?? original;
694
+ const finish = (outcome, output, feedback = null) => {
695
+ const plan = { text, edited: edited !== null, outcome, feedback };
696
+ const failed = outcome === "not-approved" || outcome === "stopped";
697
+ return {
698
+ result: {
699
+ output,
700
+ summary: PLAN_OUTCOME_LABELS[outcome],
701
+ detail: text,
702
+ isError: failed,
703
+ plan,
704
+ },
705
+ title,
706
+ declined: outcome === "not-approved",
707
+ };
708
+ };
709
+ if (signal.aborted)
710
+ return finish("stopped", "Not run: the user interrupted.");
711
+ if (answer.kind === "no") {
712
+ const feedback = answer.feedback?.trim();
713
+ if (!feedback)
714
+ return finish("not-approved", "The user didn't approve the plan.");
715
+ return finish("sent-back", `The user wants changes before you start: ${feedback}` +
716
+ (edited ? `\n\nThey also edited your plan. Start from their version:\n\n${edited}` : "") +
717
+ "\n\nRevise the plan (look into anything you need first) and present it again with present_plan.", feedback);
718
+ }
719
+ const mode = answer.kind === "always" ? "auto-edit" : "ask";
720
+ this.options.permissions.mode = mode;
721
+ this.toldPlan = false;
722
+ const how = mode === "auto-edit"
723
+ ? "edits in this project run without asking; commands still ask"
724
+ : "the user approves each edit and command";
725
+ return finish(mode === "auto-edit" ? "approved-auto" : "approved-ask", `${PLAN_APPROVED}${edited ? " after editing it" : ""}. The mode is now "${MODE_LABELS[mode]}": ` +
726
+ `${how}. Carry out the plan now${edited ? ", following their version below" : ""}, and ` +
727
+ `keep the todo list up to date as you go.${edited ? `\n\n${edited}` : ""}`);
728
+ }
729
+ }
730
+ /** The user's edited plan, when it really differs from the original (trimmed, capped), else null. */
731
+ export function editedPlan(edit, original) {
732
+ const text = edit?.trim().slice(0, MAX_PLAN_CHARS);
733
+ return text && text !== original.trim() ? text : null;
734
+ }