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