@foldrun/core 24.2.3 → 24.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/dist/src/engine-loop.d.ts +45 -0
- package/dist/src/engine-loop.js +480 -0
- package/dist/src/engine-tools.d.ts +41 -0
- package/dist/src/engine-tools.js +579 -0
- package/dist/src/evals.js +1 -1
- package/dist/src/step-exec.d.ts +12 -1
- package/dist/src/step-exec.js +6 -2
- package/package.json +1 -1
- package/src/engine-loop.ts +495 -0
- package/src/engine-tools.ts +566 -0
- package/src/evals.ts +1 -1
- package/src/step-exec.ts +14 -2
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
// foldrun's own agent loop: a model, its tools, and the turns between them.
|
|
2
|
+
//
|
|
3
|
+
// Until now every step's turns ran inside the Claude Agent SDK's `query()`,
|
|
4
|
+
// which starts the Claude Code binary. This is the same job done here: call
|
|
5
|
+
// the model, run the tools it asks for, hand back the results, repeat until
|
|
6
|
+
// it answers. It is a QueryFn (step-exec.ts), so executeStep drives it
|
|
7
|
+
// exactly as it drives the SDK — the same options in, the same messages out
|
|
8
|
+
// — and everything above the loop (hooks, limits, confinement, verify, the
|
|
9
|
+
// run record) is unchanged.
|
|
10
|
+
//
|
|
11
|
+
// It is NOT the default, and nothing a tenant writes can select it: the
|
|
12
|
+
// caller of executeStep passes `engine: "foldrun"` (ExecOptions), and no
|
|
13
|
+
// caller in the runner does yet. Deliberately not an environment variable —
|
|
14
|
+
// a step's environment carries its secrets under names the tenant chose
|
|
15
|
+
// (runner.ts), so a secret called after the switch would have thrown it.
|
|
16
|
+
// It moves to a written setting, and then to the default, only when it
|
|
17
|
+
// matches the SDK on the coding evals (foldrun-infra
|
|
18
|
+
// docs/coding-api-adr.md, "Build order").
|
|
19
|
+
//
|
|
20
|
+
// What this first slice does:
|
|
21
|
+
// - the turns, against an Anthropic-format Messages endpoint — the step's
|
|
22
|
+
// ANTHROPIC_BASE_URL, which is also what the translator (translator.ts)
|
|
23
|
+
// presents for every other provider;
|
|
24
|
+
// - Read, Write, Edit, Glob, Grep and Bash (engine-tools.ts);
|
|
25
|
+
// - the permission order the SDK kept: PreToolUse hooks, then canUseTool
|
|
26
|
+
// unless a hook allowed the call, then the tool, then PostToolUse;
|
|
27
|
+
// - prompt-cache marks on the system prompt, the tools and the newest turn;
|
|
28
|
+
// - interrupt and abort, which also end a running shell command.
|
|
29
|
+
//
|
|
30
|
+
// What it refuses, by name, rather than run without: MCP servers (so every
|
|
31
|
+
// tool that is not one of the six), sub-agents, and a shell on a host that
|
|
32
|
+
// asked for the SDK's OS sandbox, which this engine does not have (the
|
|
33
|
+
// caller may say `engineHostShell` for a person's own machine). It does
|
|
34
|
+
// not summarise a full context yet: the model's own stop reason comes back
|
|
35
|
+
// on the result, as it does from the SDK.
|
|
36
|
+
|
|
37
|
+
import crypto from "node:crypto";
|
|
38
|
+
import type { QueryFn, QueryLike } from "./step-exec.ts";
|
|
39
|
+
import { ENGINE_TOOLS, killGroups, type EngineTool, type ToolContext, type ToolOutcome } from "./engine-tools.ts";
|
|
40
|
+
|
|
41
|
+
/** Which loop runs a step's turns. */
|
|
42
|
+
export type Engine = "sdk" | "foldrun";
|
|
43
|
+
|
|
44
|
+
const DEFAULT_BASE = "https://api.anthropic.com";
|
|
45
|
+
const API_VERSION = "2023-06-01";
|
|
46
|
+
const DEFAULT_MAX_TOKENS = 16_000;
|
|
47
|
+
const MODEL_TRIES = 4;
|
|
48
|
+
const RETRY_AFTER_CAP_MS = 30_000;
|
|
49
|
+
|
|
50
|
+
/** The tier names an agent may write, where the environment names no model
|
|
51
|
+
* for them. The SDK's binary resolves these itself; here it is said. */
|
|
52
|
+
const TIER_DEFAULTS: Record<string, string> = {
|
|
53
|
+
haiku: "claude-haiku-5-5",
|
|
54
|
+
sonnet: "claude-sonnet-5-5",
|
|
55
|
+
opus: "claude-opus-5-5",
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
type Json = Record<string, unknown>;
|
|
59
|
+
type Block = Json & { type: string };
|
|
60
|
+
type HookFn = (input: Json, toolUseId?: string, extra?: { signal: AbortSignal }) => Promise<Json | undefined> | Json | undefined;
|
|
61
|
+
type CanUseTool = (name: string, input: Json, extra: { signal: AbortSignal; toolUseID: string }) =>
|
|
62
|
+
Promise<{ behavior: "allow"; updatedInput?: Json } | { behavior: "deny"; message: string }>;
|
|
63
|
+
|
|
64
|
+
interface Usage {
|
|
65
|
+
input_tokens: number;
|
|
66
|
+
output_tokens: number;
|
|
67
|
+
cache_creation_input_tokens: number;
|
|
68
|
+
cache_read_input_tokens: number;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
interface LoopOptions {
|
|
72
|
+
cwd: string;
|
|
73
|
+
env: Record<string, string | undefined>;
|
|
74
|
+
model: string;
|
|
75
|
+
systemPrompt: string;
|
|
76
|
+
tools: EngineTool[];
|
|
77
|
+
maxTurns: number | null;
|
|
78
|
+
partial: boolean;
|
|
79
|
+
pre: HookFn[];
|
|
80
|
+
post: HookFn[];
|
|
81
|
+
canUseTool: CanUseTool | null;
|
|
82
|
+
outer: AbortSignal | null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function hookFns(hooks: unknown, event: string): HookFn[] {
|
|
86
|
+
const groups = (hooks as Record<string, { hooks?: HookFn[] }[] | undefined> | undefined)?.[event];
|
|
87
|
+
return (groups ?? []).flatMap((g) => g.hooks ?? []);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The SDK's options, as this engine reads them. What it cannot honour it
|
|
91
|
+
* refuses here, before a model call is paid for. */
|
|
92
|
+
function readOptions(options: Json): LoopOptions {
|
|
93
|
+
const env = (options.env as Record<string, string | undefined> | undefined) ?? process.env;
|
|
94
|
+
const names = Array.isArray(options.tools) ? (options.tools as unknown[]).map(String) : [];
|
|
95
|
+
const unsupported = names.filter((n) => !ENGINE_TOOLS[n]);
|
|
96
|
+
if (unsupported.length) {
|
|
97
|
+
throw new Error(`the foldrun engine has no tool named ${unsupported.join(", ")} yet — it has ${Object.keys(ENGINE_TOOLS).join(", ")}. Run this agent on the default engine.`);
|
|
98
|
+
}
|
|
99
|
+
const servers = Object.keys((options.mcpServers as Json | undefined) ?? {});
|
|
100
|
+
if (servers.length) {
|
|
101
|
+
throw new Error(`the foldrun engine does not connect MCP servers yet (${servers.join(", ")}) — run this agent on the default engine.`);
|
|
102
|
+
}
|
|
103
|
+
if (options.agents && Object.keys(options.agents as Json).length) {
|
|
104
|
+
throw new Error("the foldrun engine does not run sub-agents yet — run this agent on the default engine.");
|
|
105
|
+
}
|
|
106
|
+
const sandbox = options.sandbox as { enabled?: boolean } | undefined;
|
|
107
|
+
// Never read from `env`: that is where a tenant's secrets live.
|
|
108
|
+
if (names.includes("Bash") && sandbox?.enabled !== false && options.engineHostShell !== true) {
|
|
109
|
+
throw new Error("the foldrun engine has no OS sandbox for the shell on this host — run the step in a container.");
|
|
110
|
+
}
|
|
111
|
+
const model = String(options.model ?? "");
|
|
112
|
+
if (!model) throw new Error("the foldrun engine needs a model");
|
|
113
|
+
return {
|
|
114
|
+
cwd: String(options.cwd ?? process.cwd()),
|
|
115
|
+
env,
|
|
116
|
+
model: env[`ANTHROPIC_DEFAULT_${model.toUpperCase()}_MODEL`] || TIER_DEFAULTS[model] || model,
|
|
117
|
+
systemPrompt: typeof options.systemPrompt === "string" ? options.systemPrompt : "",
|
|
118
|
+
tools: names.map((n) => ENGINE_TOOLS[n]),
|
|
119
|
+
maxTurns: typeof options.maxTurns === "number" && options.maxTurns > 0 ? options.maxTurns : null,
|
|
120
|
+
partial: options.includePartialMessages === true,
|
|
121
|
+
pre: hookFns(options.hooks, "PreToolUse"),
|
|
122
|
+
post: hookFns(options.hooks, "PostToolUse"),
|
|
123
|
+
canUseTool: typeof options.canUseTool === "function" ? (options.canUseTool as CanUseTool) : null,
|
|
124
|
+
outer: (options.abortController as AbortController | undefined)?.signal ?? null,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function requestHeaders(env: Record<string, string | undefined>): Record<string, string> {
|
|
129
|
+
const headers: Record<string, string> = { "content-type": "application/json", "anthropic-version": API_VERSION };
|
|
130
|
+
if (env.ANTHROPIC_API_KEY) headers["x-api-key"] = env.ANTHROPIC_API_KEY;
|
|
131
|
+
else if (env.ANTHROPIC_AUTH_TOKEN) headers.authorization = `Bearer ${env.ANTHROPIC_AUTH_TOKEN}`;
|
|
132
|
+
for (const line of (env.ANTHROPIC_CUSTOM_HEADERS ?? "").split("\n")) {
|
|
133
|
+
const at = line.indexOf(":");
|
|
134
|
+
if (at > 0) headers[line.slice(0, at).trim().toLowerCase()] = line.slice(at + 1).trim();
|
|
135
|
+
}
|
|
136
|
+
return headers;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** The request body for one turn. Cache marks go on the three places a
|
|
140
|
+
* prefix ends: the tools, the system prompt, and the newest message — so
|
|
141
|
+
* each turn reads everything before it from the cache and writes only
|
|
142
|
+
* what is new. The conversation itself is never mutated. */
|
|
143
|
+
export function buildRequest(o: Pick<LoopOptions, "model" | "systemPrompt" | "tools" | "env">, messages: { role: string; content: Block[] }[]): Json {
|
|
144
|
+
const mark = { cache_control: { type: "ephemeral" } };
|
|
145
|
+
const tools = o.tools.map((t, i) => ({
|
|
146
|
+
name: t.name,
|
|
147
|
+
description: t.description,
|
|
148
|
+
input_schema: t.input_schema,
|
|
149
|
+
...(i === o.tools.length - 1 ? mark : {}),
|
|
150
|
+
}));
|
|
151
|
+
const sent = messages.map((m, i) => {
|
|
152
|
+
if (i !== messages.length - 1 || !m.content.length) return m;
|
|
153
|
+
const last = m.content.length - 1;
|
|
154
|
+
return { ...m, content: m.content.map((b, j) => (j === last ? { ...b, ...mark } : b)) };
|
|
155
|
+
});
|
|
156
|
+
const asked = Number(o.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS);
|
|
157
|
+
return {
|
|
158
|
+
model: o.model,
|
|
159
|
+
max_tokens: Number.isFinite(asked) && asked > 0 ? asked : DEFAULT_MAX_TOKENS,
|
|
160
|
+
...(o.systemPrompt ? { system: [{ type: "text", text: o.systemPrompt, ...mark }] } : {}),
|
|
161
|
+
...(tools.length ? { tools } : {}),
|
|
162
|
+
messages: sent,
|
|
163
|
+
stream: true,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const sleep = (ms: number, signal: AbortSignal) =>
|
|
168
|
+
new Promise<void>((resolve) => {
|
|
169
|
+
if (signal.aborted) return resolve();
|
|
170
|
+
const t = setTimeout(resolve, ms);
|
|
171
|
+
signal.addEventListener("abort", () => { clearTimeout(t); resolve(); }, { once: true });
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
/** POST the turn, retrying what is worth retrying: a rate limit, an
|
|
175
|
+
* overloaded or failing upstream, a connection that never opened. Nothing
|
|
176
|
+
* is retried once a response has begun — the caller has seen part of it. */
|
|
177
|
+
async function openStream(o: LoopOptions, body: Json, signal: AbortSignal): Promise<Response> {
|
|
178
|
+
const base = (o.env.ANTHROPIC_BASE_URL || DEFAULT_BASE).replace(/\/+$/, "");
|
|
179
|
+
let lastError = "";
|
|
180
|
+
for (let attempt = 1; attempt <= MODEL_TRIES; attempt++) {
|
|
181
|
+
let res: Response | null = null;
|
|
182
|
+
try {
|
|
183
|
+
res = await fetch(`${base}/v1/messages`, { method: "POST", headers: requestHeaders(o.env), body: JSON.stringify(body), signal });
|
|
184
|
+
} catch (err) {
|
|
185
|
+
if (signal.aborted) throw err;
|
|
186
|
+
lastError = `the model endpoint could not be reached: ${(err as Error).message}`;
|
|
187
|
+
}
|
|
188
|
+
if (res?.ok && res.body) return res;
|
|
189
|
+
if (res) {
|
|
190
|
+
const text = (await res.text().catch(() => "")).slice(0, 500);
|
|
191
|
+
lastError = `the model endpoint answered ${res.status}: ${text}`;
|
|
192
|
+
const retryable = res.status === 408 || res.status === 409 || res.status === 429 || res.status >= 500;
|
|
193
|
+
if (!retryable) throw new Error(lastError);
|
|
194
|
+
const after = Number(res.headers.get("retry-after"));
|
|
195
|
+
if (attempt < MODEL_TRIES) await sleep(Math.min(RETRY_AFTER_CAP_MS, Number.isFinite(after) && after > 0 ? after * 1000 : 1000 * 2 ** (attempt - 1)), signal);
|
|
196
|
+
} else if (attempt < MODEL_TRIES) {
|
|
197
|
+
await sleep(1000 * 2 ** (attempt - 1), signal);
|
|
198
|
+
}
|
|
199
|
+
if (signal.aborted) throw new Error("aborted");
|
|
200
|
+
}
|
|
201
|
+
throw new Error(`${lastError} (after ${MODEL_TRIES} tries)`);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Server-sent events from a response body, one parsed `data:` at a time. */
|
|
205
|
+
async function* sse(res: Response): AsyncGenerator<Json> {
|
|
206
|
+
const decoder = new TextDecoder();
|
|
207
|
+
let buffer = "";
|
|
208
|
+
for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {
|
|
209
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
210
|
+
for (let at = buffer.search(/\r?\n\r?\n/); at >= 0; at = buffer.search(/\r?\n\r?\n/)) {
|
|
211
|
+
const frame = buffer.slice(0, at);
|
|
212
|
+
buffer = buffer.slice(at).replace(/^\r?\n\r?\n/, "");
|
|
213
|
+
const data = frame.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trimStart()).join("\n");
|
|
214
|
+
if (!data || data === "[DONE]") continue;
|
|
215
|
+
try {
|
|
216
|
+
yield JSON.parse(data) as Json;
|
|
217
|
+
} catch {
|
|
218
|
+
// a frame that is not JSON carries nothing this loop reads
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
interface Turn {
|
|
225
|
+
id: string;
|
|
226
|
+
model: string;
|
|
227
|
+
content: Block[];
|
|
228
|
+
stopReason: string | null;
|
|
229
|
+
usage: Usage;
|
|
230
|
+
/** tool_use ids whose arguments did not arrive as valid JSON. */
|
|
231
|
+
malformed: Set<string>;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const emptyUsage = (): Usage => ({ input_tokens: 0, output_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 });
|
|
235
|
+
|
|
236
|
+
function addUsage(into: Usage, u: Partial<Record<keyof Usage, unknown>> | undefined): void {
|
|
237
|
+
if (!u) return;
|
|
238
|
+
// The closing delta repeats the counts it knows; one that leaves the input
|
|
239
|
+
// side at zero is not saying the input was free.
|
|
240
|
+
for (const k of Object.keys(into) as (keyof Usage)[]) {
|
|
241
|
+
const v = u[k];
|
|
242
|
+
if (typeof v === "number" && (v > 0 || k === "output_tokens")) into[k] = v;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** One model call: yields the raw stream events, returns the whole turn. */
|
|
247
|
+
async function* modelTurn(o: LoopOptions, messages: { role: string; content: Block[] }[], signal: AbortSignal): AsyncGenerator<Json, Turn> {
|
|
248
|
+
const res = await openStream(o, buildRequest(o, messages), signal);
|
|
249
|
+
const turn: Turn = { id: "", model: o.model, content: [], stopReason: null, usage: emptyUsage(), malformed: new Set() };
|
|
250
|
+
const partialJson = new Map<number, string>();
|
|
251
|
+
const open = new Set<number>();
|
|
252
|
+
let stopped = false;
|
|
253
|
+
for await (const ev of sse(res)) {
|
|
254
|
+
const type = ev.type as string;
|
|
255
|
+
if (type === "error") {
|
|
256
|
+
const e = ev.error as { type?: string; message?: string } | undefined;
|
|
257
|
+
throw new Error(`the model stream failed: ${e?.type ?? "error"}${e?.message ? ` — ${e.message}` : ""}`);
|
|
258
|
+
}
|
|
259
|
+
if (type === "message_start") {
|
|
260
|
+
const m = ev.message as { id?: string; model?: string; usage?: Json } | undefined;
|
|
261
|
+
turn.id = m?.id ?? `msg_${crypto.randomUUID()}`;
|
|
262
|
+
if (m?.model) turn.model = m.model;
|
|
263
|
+
addUsage(turn.usage, m?.usage);
|
|
264
|
+
} else if (type === "content_block_start") {
|
|
265
|
+
const block = { ...(ev.content_block as Block) };
|
|
266
|
+
if (block.type === "tool_use") block.input = {};
|
|
267
|
+
turn.content[ev.index as number] = block;
|
|
268
|
+
open.add(ev.index as number);
|
|
269
|
+
} else if (type === "content_block_delta") {
|
|
270
|
+
const block = turn.content[ev.index as number];
|
|
271
|
+
const d = ev.delta as { type?: string; text?: string; partial_json?: string; thinking?: string; signature?: string } | undefined;
|
|
272
|
+
if (!block || !d) continue;
|
|
273
|
+
if (d.type === "text_delta") block.text = String(block.text ?? "") + (d.text ?? "");
|
|
274
|
+
else if (d.type === "input_json_delta") partialJson.set(ev.index as number, (partialJson.get(ev.index as number) ?? "") + (d.partial_json ?? ""));
|
|
275
|
+
else if (d.type === "thinking_delta") block.thinking = String(block.thinking ?? "") + (d.thinking ?? "");
|
|
276
|
+
else if (d.type === "signature_delta") block.signature = d.signature;
|
|
277
|
+
} else if (type === "content_block_stop") {
|
|
278
|
+
open.delete(ev.index as number);
|
|
279
|
+
const block = turn.content[ev.index as number];
|
|
280
|
+
if (block?.type === "tool_use") {
|
|
281
|
+
const raw = partialJson.get(ev.index as number) ?? "";
|
|
282
|
+
try {
|
|
283
|
+
const parsed: unknown = raw ? JSON.parse(raw) : {};
|
|
284
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) block.input = parsed;
|
|
285
|
+
else turn.malformed.add(String(block.id));
|
|
286
|
+
} catch {
|
|
287
|
+
turn.malformed.add(String(block.id));
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
} else if (type === "message_delta") {
|
|
291
|
+
const d = ev.delta as { stop_reason?: string | null } | undefined;
|
|
292
|
+
if (d?.stop_reason) turn.stopReason = d.stop_reason;
|
|
293
|
+
addUsage(turn.usage, ev.usage as Json | undefined);
|
|
294
|
+
} else if (type === "message_stop") stopped = true;
|
|
295
|
+
if (o.partial || type === "message_start" || type === "message_delta") yield ev;
|
|
296
|
+
}
|
|
297
|
+
if (!turn.id) throw new Error("the model stream ended before it began a message");
|
|
298
|
+
// A stream that just stops is not an answer: half a reply must not read
|
|
299
|
+
// as the model's last word, nor half a tool call as none.
|
|
300
|
+
if (!stopped || open.size || !turn.stopReason) throw new Error("the model stream ended part-way through a reply — the connection to the model was cut");
|
|
301
|
+
turn.content = turn.content.filter(Boolean);
|
|
302
|
+
return turn;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
interface Decision {
|
|
306
|
+
input: Json;
|
|
307
|
+
refusal: string | null;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** May this call run, and with what input? The order the SDK kept, which
|
|
311
|
+
* step-exec's checks are written against: every PreToolUse hook first — a
|
|
312
|
+
* deny ends it, an allow carries the input the hook settled on and skips
|
|
313
|
+
* the question below — then canUseTool, where confinement lives. */
|
|
314
|
+
async function decide(o: LoopOptions, name: string, id: string, input: Json, sessionId: string, signal: AbortSignal): Promise<Decision> {
|
|
315
|
+
let current = input;
|
|
316
|
+
let allowed = false;
|
|
317
|
+
for (const hook of o.pre) {
|
|
318
|
+
const out = await hook({ hook_event_name: "PreToolUse", session_id: sessionId, cwd: o.cwd, tool_name: name, tool_input: current, tool_use_id: id }, id, { signal });
|
|
319
|
+
const d = (out as { hookSpecificOutput?: { permissionDecision?: string; permissionDecisionReason?: string; updatedInput?: Json } } | undefined)?.hookSpecificOutput;
|
|
320
|
+
if (!d) continue;
|
|
321
|
+
if (d.permissionDecision === "deny") return { input: current, refusal: d.permissionDecisionReason || `${name} was refused` };
|
|
322
|
+
if (d.updatedInput) current = d.updatedInput;
|
|
323
|
+
if (d.permissionDecision === "allow") allowed = true;
|
|
324
|
+
}
|
|
325
|
+
if (!allowed && o.canUseTool) {
|
|
326
|
+
const r = await o.canUseTool(name, current, { signal, toolUseID: id });
|
|
327
|
+
if (r.behavior === "deny") return { input: current, refusal: r.message || `${name} was refused` };
|
|
328
|
+
if (r.updatedInput) current = r.updatedInput;
|
|
329
|
+
}
|
|
330
|
+
return { input: current, refusal: null };
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** After a call: tell the PostToolUse hooks, and collect what they add. */
|
|
334
|
+
async function after(o: LoopOptions, name: string, id: string, input: Json, outcome: ToolOutcome, sessionId: string, signal: AbortSignal): Promise<string[]> {
|
|
335
|
+
const added: string[] = [];
|
|
336
|
+
for (const hook of o.post) {
|
|
337
|
+
const out = await hook({ hook_event_name: "PostToolUse", session_id: sessionId, cwd: o.cwd, tool_name: name, tool_input: input, tool_response: outcome.text, tool_use_id: id }, id, { signal });
|
|
338
|
+
const context = (out as { hookSpecificOutput?: { additionalContext?: string } } | undefined)?.hookSpecificOutput?.additionalContext;
|
|
339
|
+
if (context) added.push(context);
|
|
340
|
+
}
|
|
341
|
+
return added;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interrupted: () => boolean): AsyncGenerator<Json> {
|
|
345
|
+
const sessionId = crypto.randomUUID();
|
|
346
|
+
const startedAt = Date.now();
|
|
347
|
+
const byName = new Map(o.tools.map((t) => [t.name, t]));
|
|
348
|
+
const ctx: ToolContext = { cwd: o.cwd, env: o.env, signal, reads: new Map(), groups: new Set() };
|
|
349
|
+
const messages: { role: string; content: Block[] }[] = [{ role: "user", content: [{ type: "text", text: prompt }] }];
|
|
350
|
+
const total = emptyUsage();
|
|
351
|
+
let turns = 0;
|
|
352
|
+
let lastText = "";
|
|
353
|
+
|
|
354
|
+
const result = (subtype: string, stopReason: string | null): Json => ({
|
|
355
|
+
type: "result",
|
|
356
|
+
subtype,
|
|
357
|
+
is_error: subtype !== "success",
|
|
358
|
+
result: lastText,
|
|
359
|
+
stop_reason: stopReason,
|
|
360
|
+
num_turns: turns,
|
|
361
|
+
duration_ms: Date.now() - startedAt,
|
|
362
|
+
usage: { ...total },
|
|
363
|
+
permission_denials: [],
|
|
364
|
+
session_id: sessionId,
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
yield { type: "system", subtype: "init", session_id: sessionId, cwd: o.cwd, model: o.model, tools: o.tools.map((t) => t.name), mcp_servers: [], engine: "foldrun" };
|
|
368
|
+
|
|
369
|
+
try {
|
|
370
|
+
for (;;) {
|
|
371
|
+
if (o.maxTurns !== null && turns >= o.maxTurns) {
|
|
372
|
+
yield result("error_max_turns", null);
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
let turn: Turn;
|
|
376
|
+
try {
|
|
377
|
+
const stream = modelTurn(o, messages, signal);
|
|
378
|
+
for (;;) {
|
|
379
|
+
const step = await stream.next();
|
|
380
|
+
if (step.done) {
|
|
381
|
+
turn = step.value;
|
|
382
|
+
break;
|
|
383
|
+
}
|
|
384
|
+
yield { type: "stream_event", event: step.value, parent_tool_use_id: null, session_id: sessionId };
|
|
385
|
+
}
|
|
386
|
+
} catch (err) {
|
|
387
|
+
// An interrupt we were asked for ends the loop quietly: the caller
|
|
388
|
+
// knows why and reports it. Anything else is the step's failure.
|
|
389
|
+
if (interrupted() || signal.aborted) return;
|
|
390
|
+
throw err;
|
|
391
|
+
}
|
|
392
|
+
turns++;
|
|
393
|
+
for (const k of Object.keys(total) as (keyof Usage)[]) total[k] += turn.usage[k];
|
|
394
|
+
const text = turn.content.filter((b) => b.type === "text").map((b) => String(b.text ?? "")).join("\n").trim();
|
|
395
|
+
if (text) lastText = text;
|
|
396
|
+
yield {
|
|
397
|
+
type: "assistant",
|
|
398
|
+
message: { id: turn.id, type: "message", role: "assistant", model: turn.model, content: turn.content, stop_reason: turn.stopReason, usage: { ...turn.usage } },
|
|
399
|
+
parent_tool_use_id: null,
|
|
400
|
+
session_id: sessionId,
|
|
401
|
+
};
|
|
402
|
+
messages.push({ role: "assistant", content: turn.content });
|
|
403
|
+
if (interrupted()) return;
|
|
404
|
+
|
|
405
|
+
const calls = turn.content.filter((b) => b.type === "tool_use");
|
|
406
|
+
// `pause_turn`: the provider stopped a long turn part-way; sending the
|
|
407
|
+
// conversation back as it stands lets it carry on.
|
|
408
|
+
if (turn.stopReason === "pause_turn" && !calls.length) continue;
|
|
409
|
+
if (turn.stopReason !== "tool_use" || !calls.length) {
|
|
410
|
+
yield result("success", turn.stopReason);
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// What each call comes to: refused, or run. A call is decided
|
|
415
|
+
// immediately before it runs, never ahead of a call that runs first: a
|
|
416
|
+
// command can change what a later path points at (a link it makes, a
|
|
417
|
+
// file it moves), and a check made before that would be a check of
|
|
418
|
+
// something else.
|
|
419
|
+
type Planned = { block: Block; tool: EngineTool | null; decision: Decision };
|
|
420
|
+
const settle = async (block: Block): Promise<Planned> => {
|
|
421
|
+
const name = String(block.name);
|
|
422
|
+
const id = String(block.id);
|
|
423
|
+
const tool = byName.get(name) ?? null;
|
|
424
|
+
if (!tool) return { block, tool, decision: { input: {}, refusal: `Tool ${name} is not enabled for this agent.` } };
|
|
425
|
+
if (turn.malformed.has(id)) return { block, tool, decision: { input: {}, refusal: `the arguments for ${name} were not valid JSON — send the call again` } };
|
|
426
|
+
return { block, tool, decision: await decide(o, name, id, (block.input ?? {}) as Json, sessionId, signal) };
|
|
427
|
+
};
|
|
428
|
+
const execute = async (p: Planned): Promise<{ outcome: ToolOutcome; context: string[] }> => {
|
|
429
|
+
if (p.decision.refusal || !p.tool) return { outcome: { text: p.decision.refusal ?? "refused", isError: true }, context: [] };
|
|
430
|
+
let outcome: ToolOutcome;
|
|
431
|
+
try {
|
|
432
|
+
outcome = await p.tool.run(p.decision.input, ctx);
|
|
433
|
+
} catch (err) {
|
|
434
|
+
outcome = { text: `${p.tool.name} failed: ${(err as Error).message}`, isError: true };
|
|
435
|
+
}
|
|
436
|
+
const context = await after(o, p.tool.name, String(p.block.id), p.decision.input, outcome, sessionId, signal);
|
|
437
|
+
return { outcome, context };
|
|
438
|
+
};
|
|
439
|
+
const planned: Planned[] = [];
|
|
440
|
+
const done: { outcome: ToolOutcome; context: string[] }[] = [];
|
|
441
|
+
if (calls.every((b) => byName.get(String(b.name))?.readOnly !== false)) {
|
|
442
|
+
// Only reads (or names that are refused anyway): none can change what
|
|
443
|
+
// another is checked against, so they are decided in the order asked
|
|
444
|
+
// — limits count in that order — and then run side by side.
|
|
445
|
+
for (const block of calls) planned.push(await settle(block));
|
|
446
|
+
done.push(...(await Promise.all(planned.map(execute))));
|
|
447
|
+
} else {
|
|
448
|
+
// Anything that changes a file or runs a command: one at a time, in
|
|
449
|
+
// the order asked, each decided just before it runs.
|
|
450
|
+
for (const block of calls) {
|
|
451
|
+
if (interrupted()) break;
|
|
452
|
+
const p = await settle(block);
|
|
453
|
+
planned.push(p);
|
|
454
|
+
done.push(await execute(p));
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
if (interrupted()) return;
|
|
458
|
+
|
|
459
|
+
const results: Block[] = planned.map((p, i) => ({
|
|
460
|
+
type: "tool_result",
|
|
461
|
+
tool_use_id: String(p.block.id),
|
|
462
|
+
content: done[i].outcome.text,
|
|
463
|
+
...(done[i].outcome.isError ? { is_error: true } : {}),
|
|
464
|
+
}));
|
|
465
|
+
const context = done.flatMap((d) => d.context);
|
|
466
|
+
const content: Block[] = [...results, ...context.map((c) => ({ type: "text", text: c }))];
|
|
467
|
+
messages.push({ role: "user", content });
|
|
468
|
+
yield { type: "user", message: { role: "user", content }, parent_tool_use_id: null, session_id: sessionId };
|
|
469
|
+
}
|
|
470
|
+
} finally {
|
|
471
|
+
// However the loop ended — an answer, a stop, a consumer that walked
|
|
472
|
+
// away — nothing a command started outlives the step.
|
|
473
|
+
killGroups(ctx);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/** The foldrun engine, as executeStep's model loop. */
|
|
478
|
+
export const foldrunQuery: QueryFn = ({ prompt, options }) => {
|
|
479
|
+
const o = readOptions(options);
|
|
480
|
+
const controller = new AbortController();
|
|
481
|
+
let interrupted = false;
|
|
482
|
+
if (o.outer) {
|
|
483
|
+
if (o.outer.aborted) controller.abort();
|
|
484
|
+
else o.outer.addEventListener("abort", () => controller.abort(), { once: true });
|
|
485
|
+
}
|
|
486
|
+
const stream = run(prompt, o, controller.signal, () => interrupted);
|
|
487
|
+
return Object.assign(stream, {
|
|
488
|
+
// Ends the model call in flight and any running command. The loop then
|
|
489
|
+
// returns without a result; the caller says why it asked.
|
|
490
|
+
async interrupt() {
|
|
491
|
+
interrupted = true;
|
|
492
|
+
controller.abort();
|
|
493
|
+
},
|
|
494
|
+
}) as QueryLike;
|
|
495
|
+
};
|