@foldrun/core 24.8.0 → 24.8.1

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,75 @@
1
+ import { type EngineTool, type ToolOutcome } from "./engine-tools.ts";
2
+ export declare const DEFAULT_MAX_TOKENS = 16000;
3
+ export interface Usage {
4
+ input_tokens: number;
5
+ output_tokens: number;
6
+ cache_creation_input_tokens: number;
7
+ cache_read_input_tokens: number;
8
+ }
9
+ export declare const emptyUsage: () => Usage;
10
+ export declare function addUsage(into: Usage, u: Partial<Record<keyof Usage, unknown>> | undefined): void;
11
+ /** The tier names an agent may write, where the environment names no model
12
+ * for them. The SDK's binary resolves these itself; here it is said. */
13
+ export declare const TIER_DEFAULTS: Record<string, string>;
14
+ export type Json = Record<string, unknown>;
15
+ export type Block = Json & {
16
+ type: string;
17
+ };
18
+ export type HookFn = (input: Json, toolUseId?: string, extra?: {
19
+ signal: AbortSignal;
20
+ }) => Promise<Json | undefined> | Json | undefined;
21
+ export type CanUseTool = (name: string, input: Json, extra: {
22
+ signal: AbortSignal;
23
+ toolUseID: string;
24
+ }) => Promise<{
25
+ behavior: "allow";
26
+ updatedInput?: Json;
27
+ } | {
28
+ behavior: "deny";
29
+ message: string;
30
+ }>;
31
+ export interface LoopOptions {
32
+ cwd: string;
33
+ env: Record<string, string | undefined>;
34
+ /** What the tools (Bash) get; `env` when not given. foldrun code passes
35
+ * the person's own environment here, so the model key stays with the loop. */
36
+ shellEnv: Record<string, string | undefined>;
37
+ model: string;
38
+ systemPrompt: string;
39
+ tools: EngineTool[];
40
+ maxTurns: number | null;
41
+ partial: boolean;
42
+ pre: HookFn[];
43
+ post: HookFn[];
44
+ canUseTool: CanUseTool | null;
45
+ outer: AbortSignal | null;
46
+ /** The conversation so far, before this prompt: earlier user turns, the
47
+ * model's replies and tool results, as the loop yielded them. */
48
+ history: {
49
+ role: string;
50
+ content: Block[];
51
+ }[];
52
+ }
53
+ export declare function hookFns(hooks: unknown, event: string): HookFn[];
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
+ /** `engine` names the loop in what it refuses. */
57
+ export declare function readOptions(options: Json, engine?: string): LoopOptions;
58
+ /** An earlier conversation, checked: user and assistant turns that
59
+ * alternate, starting with the user's, each a list of content blocks. A
60
+ * turn that is not one is refused, not sent half-right to the model. */
61
+ export declare function readHistory(raw: unknown): {
62
+ role: string;
63
+ content: Block[];
64
+ }[];
65
+ export interface Decision {
66
+ input: Json;
67
+ refusal: string | null;
68
+ }
69
+ /** May this call run, and with what input? The order the SDK kept, which
70
+ * step-exec's checks are written against: every PreToolUse hook first — a
71
+ * deny ends it, an allow carries the input the hook settled on and skips
72
+ * the question below — then canUseTool, where confinement lives. */
73
+ export declare function decide(o: LoopOptions, name: string, id: string, input: Json, sessionId: string, signal: AbortSignal): Promise<Decision>;
74
+ /** After a call: tell the PostToolUse hooks, and collect what they add. */
75
+ export declare function after(o: LoopOptions, name: string, id: string, input: Json, outcome: ToolOutcome, sessionId: string, signal: AbortSignal): Promise<string[]>;
@@ -0,0 +1,142 @@
1
+ // What any loop behind executeStep reads the same way (engine-loop.ts
2
+ // today): the SDK's options, what it refuses before a model call is paid
3
+ // for, the permission order every tool call goes through, and token usage.
4
+ // One copy, so a second loop (a bake-off, FOL-213) cannot hold a hook,
5
+ // limit or confinement check differently. Internal: not part of
6
+ // @foldrun/core's public API.
7
+ import { ENGINE_TOOLS } from "./engine-tools.js";
8
+ export const DEFAULT_MAX_TOKENS = 16_000;
9
+ export const emptyUsage = () => ({ input_tokens: 0, output_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 });
10
+ export function addUsage(into, u) {
11
+ if (!u)
12
+ return;
13
+ // The closing delta repeats the counts it knows; one that leaves the input
14
+ // side at zero is not saying the input was free.
15
+ for (const k of Object.keys(into)) {
16
+ const v = u[k];
17
+ if (typeof v === "number" && (v > 0 || k === "output_tokens"))
18
+ into[k] = v;
19
+ }
20
+ }
21
+ /** The tier names an agent may write, where the environment names no model
22
+ * for them. The SDK's binary resolves these itself; here it is said. */
23
+ export const TIER_DEFAULTS = {
24
+ haiku: "claude-haiku-5-5",
25
+ sonnet: "claude-sonnet-5-5",
26
+ opus: "claude-opus-5-5",
27
+ };
28
+ export function hookFns(hooks, event) {
29
+ const groups = hooks?.[event];
30
+ return (groups ?? []).flatMap((g) => g.hooks ?? []);
31
+ }
32
+ /** The SDK's options, as this engine reads them. What it cannot honour it
33
+ * refuses here, before a model call is paid for. */
34
+ /** `engine` names the loop in what it refuses. */
35
+ export function readOptions(options, engine = "foldrun") {
36
+ const env = options.env ?? process.env;
37
+ const names = Array.isArray(options.tools) ? options.tools.map(String) : [];
38
+ const unsupported = names.filter((n) => !ENGINE_TOOLS[n]);
39
+ if (unsupported.length) {
40
+ throw new Error(`the ${engine} engine has no tool named ${unsupported.join(", ")} yet — it has ${Object.keys(ENGINE_TOOLS).join(", ")}. Run this agent on the default engine.`);
41
+ }
42
+ const servers = Object.keys(options.mcpServers ?? {});
43
+ if (servers.length) {
44
+ throw new Error(`the ${engine} engine does not connect MCP servers yet (${servers.join(", ")}) — run this agent on the default engine.`);
45
+ }
46
+ if (options.agents && Object.keys(options.agents).length) {
47
+ throw new Error(`the ${engine} engine does not run sub-agents yet — run this agent on the default engine.`);
48
+ }
49
+ const sandbox = options.sandbox;
50
+ // Never read from `env`: that is where a tenant's secrets live.
51
+ if (names.includes("Bash") && sandbox?.enabled !== false && options.engineHostShell !== true) {
52
+ throw new Error(`the ${engine} engine has no OS sandbox for the shell on this host — run the step in a container.`);
53
+ }
54
+ const model = String(options.model ?? "");
55
+ if (!model)
56
+ throw new Error(`the ${engine} engine needs a model`);
57
+ // Tools the host brings, as EngineTool objects: they sit beside the
58
+ // built-in ones and go through canUseTool and the hooks like them.
59
+ // foldrun code's cloud_agents is one. A name may not shadow a built-in.
60
+ const extra = [];
61
+ for (const t of Array.isArray(options.extraTools) ? options.extraTools : []) {
62
+ const tool = t;
63
+ if (!tool || typeof tool.name !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(tool.name) || typeof tool.run !== "function" || typeof tool.input_schema !== "object") {
64
+ throw new Error("extraTools: each needs a name (letters, digits, _ and -), an input_schema and a run function");
65
+ }
66
+ if (ENGINE_TOOLS[tool.name] || extra.some((x) => x.name === tool.name))
67
+ throw new Error(`extraTools: ${tool.name} is already a tool`);
68
+ extra.push({ name: tool.name, description: String(tool.description ?? ""), input_schema: tool.input_schema, readOnly: tool.readOnly === true, run: tool.run });
69
+ }
70
+ return {
71
+ cwd: String(options.cwd ?? process.cwd()),
72
+ env,
73
+ shellEnv: options.shellEnv && typeof options.shellEnv === "object" ? options.shellEnv : env,
74
+ model: env[`ANTHROPIC_DEFAULT_${model.toUpperCase()}_MODEL`] || TIER_DEFAULTS[model] || model,
75
+ systemPrompt: typeof options.systemPrompt === "string" ? options.systemPrompt : "",
76
+ tools: [...names.map((n) => ENGINE_TOOLS[n]), ...extra],
77
+ maxTurns: typeof options.maxTurns === "number" && options.maxTurns > 0 ? options.maxTurns : null,
78
+ partial: options.includePartialMessages === true,
79
+ pre: hookFns(options.hooks, "PreToolUse"),
80
+ post: hookFns(options.hooks, "PostToolUse"),
81
+ canUseTool: typeof options.canUseTool === "function" ? options.canUseTool : null,
82
+ outer: options.abortController?.signal ?? null,
83
+ history: readHistory(options.history),
84
+ };
85
+ }
86
+ /** An earlier conversation, checked: user and assistant turns that
87
+ * alternate, starting with the user's, each a list of content blocks. A
88
+ * turn that is not one is refused, not sent half-right to the model. */
89
+ export function readHistory(raw) {
90
+ if (raw == null)
91
+ return [];
92
+ if (!Array.isArray(raw))
93
+ throw new Error("history must be a list of turns");
94
+ return raw.map((t, i) => {
95
+ const role = t?.role;
96
+ const content = t?.content;
97
+ if (role !== (i % 2 === 0 ? "user" : "assistant"))
98
+ throw new Error(`history turn ${i + 1} must be the ${i % 2 === 0 ? "user's" : "model's"}`);
99
+ if (!Array.isArray(content) || !content.every((b) => b && typeof b.type === "string"))
100
+ throw new Error(`history turn ${i + 1} has no content blocks`);
101
+ return { role: String(role), content: content };
102
+ });
103
+ }
104
+ /** May this call run, and with what input? The order the SDK kept, which
105
+ * step-exec's checks are written against: every PreToolUse hook first — a
106
+ * deny ends it, an allow carries the input the hook settled on and skips
107
+ * the question below — then canUseTool, where confinement lives. */
108
+ export async function decide(o, name, id, input, sessionId, signal) {
109
+ let current = input;
110
+ let allowed = false;
111
+ for (const hook of o.pre) {
112
+ 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 });
113
+ const d = out?.hookSpecificOutput;
114
+ if (!d)
115
+ continue;
116
+ if (d.permissionDecision === "deny")
117
+ return { input: current, refusal: d.permissionDecisionReason || `${name} was refused` };
118
+ if (d.updatedInput)
119
+ current = d.updatedInput;
120
+ if (d.permissionDecision === "allow")
121
+ allowed = true;
122
+ }
123
+ if (!allowed && o.canUseTool) {
124
+ const r = await o.canUseTool(name, current, { signal, toolUseID: id });
125
+ if (r.behavior === "deny")
126
+ return { input: current, refusal: r.message || `${name} was refused` };
127
+ if (r.updatedInput)
128
+ current = r.updatedInput;
129
+ }
130
+ return { input: current, refusal: null };
131
+ }
132
+ /** After a call: tell the PostToolUse hooks, and collect what they add. */
133
+ export async function after(o, name, id, input, outcome, sessionId, signal) {
134
+ const added = [];
135
+ for (const hook of o.post) {
136
+ 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 });
137
+ const context = out?.hookSpecificOutput?.additionalContext;
138
+ if (context)
139
+ added.push(context);
140
+ }
141
+ return added;
142
+ }
@@ -1,46 +1,7 @@
1
1
  import type { QueryFn } from "./step-exec.ts";
2
- import { type EngineTool } from "./engine-tools.ts";
2
+ import { type Json, type Block, type LoopOptions } from "./engine-common.ts";
3
3
  /** Which loop runs a step's turns. */
4
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
- /** What the tools (Bash) get; `env` when not given. foldrun code passes
26
- * the person's own environment here, so the model key stays with the loop. */
27
- shellEnv: Record<string, string | undefined>;
28
- model: string;
29
- systemPrompt: string;
30
- tools: EngineTool[];
31
- maxTurns: number | null;
32
- partial: boolean;
33
- pre: HookFn[];
34
- post: HookFn[];
35
- canUseTool: CanUseTool | null;
36
- outer: AbortSignal | null;
37
- /** The conversation so far, before this prompt: earlier user turns, the
38
- * model's replies and tool results, as the loop yielded them. */
39
- history: {
40
- role: string;
41
- content: Block[];
42
- }[];
43
- }
44
5
  /** The request body for one turn. Cache marks go on the three places a
45
6
  * prefix ends: the tools, the system prompt, and the newest message — so
46
7
  * each turn reads everything before it from the cache and writes only
@@ -61,4 +22,3 @@ export declare function buildRequest(o: Pick<LoopOptions, "model" | "systemPromp
61
22
  }[]): Json;
62
23
  /** The foldrun engine, as executeStep's model loop. */
63
24
  export declare const foldrunQuery: QueryFn;
64
- export {};
@@ -34,94 +34,12 @@
34
34
  // not summarise a full context yet: the model's own stop reason comes back
35
35
  // on the result, as it does from the SDK.
36
36
  import crypto from "node:crypto";
37
- import { ENGINE_TOOLS, killGroups } from "./engine-tools.js";
37
+ import { killGroups } from "./engine-tools.js";
38
+ import { DEFAULT_MAX_TOKENS, readOptions, decide, after, emptyUsage, addUsage } from "./engine-common.js";
38
39
  const DEFAULT_BASE = "https://api.anthropic.com";
39
40
  const API_VERSION = "2023-06-01";
40
- const DEFAULT_MAX_TOKENS = 16_000;
41
41
  const MODEL_TRIES = 4;
42
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
- // Tools the host brings, as EngineTool objects: they sit beside the
79
- // built-in ones and go through canUseTool and the hooks like them.
80
- // foldrun code's cloud_agents is one. A name may not shadow a built-in.
81
- const extra = [];
82
- for (const t of Array.isArray(options.extraTools) ? options.extraTools : []) {
83
- const tool = t;
84
- if (!tool || typeof tool.name !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(tool.name) || typeof tool.run !== "function" || typeof tool.input_schema !== "object") {
85
- throw new Error("extraTools: each needs a name (letters, digits, _ and -), an input_schema and a run function");
86
- }
87
- if (ENGINE_TOOLS[tool.name] || extra.some((x) => x.name === tool.name))
88
- throw new Error(`extraTools: ${tool.name} is already a tool`);
89
- extra.push({ name: tool.name, description: String(tool.description ?? ""), input_schema: tool.input_schema, readOnly: tool.readOnly === true, run: tool.run });
90
- }
91
- return {
92
- cwd: String(options.cwd ?? process.cwd()),
93
- env,
94
- shellEnv: options.shellEnv && typeof options.shellEnv === "object" ? options.shellEnv : env,
95
- model: env[`ANTHROPIC_DEFAULT_${model.toUpperCase()}_MODEL`] || TIER_DEFAULTS[model] || model,
96
- systemPrompt: typeof options.systemPrompt === "string" ? options.systemPrompt : "",
97
- tools: [...names.map((n) => ENGINE_TOOLS[n]), ...extra],
98
- maxTurns: typeof options.maxTurns === "number" && options.maxTurns > 0 ? options.maxTurns : null,
99
- partial: options.includePartialMessages === true,
100
- pre: hookFns(options.hooks, "PreToolUse"),
101
- post: hookFns(options.hooks, "PostToolUse"),
102
- canUseTool: typeof options.canUseTool === "function" ? options.canUseTool : null,
103
- outer: options.abortController?.signal ?? null,
104
- history: readHistory(options.history),
105
- };
106
- }
107
- /** An earlier conversation, checked: user and assistant turns that
108
- * alternate, starting with the user's, each a list of content blocks. A
109
- * turn that is not one is refused, not sent half-right to the model. */
110
- function readHistory(raw) {
111
- if (raw == null)
112
- return [];
113
- if (!Array.isArray(raw))
114
- throw new Error("history must be a list of turns");
115
- return raw.map((t, i) => {
116
- const role = t?.role;
117
- const content = t?.content;
118
- if (role !== (i % 2 === 0 ? "user" : "assistant"))
119
- throw new Error(`history turn ${i + 1} must be the ${i % 2 === 0 ? "user's" : "model's"}`);
120
- if (!Array.isArray(content) || !content.every((b) => b && typeof b.type === "string"))
121
- throw new Error(`history turn ${i + 1} has no content blocks`);
122
- return { role: String(role), content: content };
123
- });
124
- }
125
43
  function requestHeaders(env) {
126
44
  const headers = { "content-type": "application/json", "anthropic-version": API_VERSION };
127
45
  if (env.ANTHROPIC_API_KEY)
@@ -234,35 +152,35 @@ async function openStream(o, body, signal) {
234
152
  async function* sse(res) {
235
153
  const decoder = new TextDecoder();
236
154
  let buffer = "";
155
+ // SSE ends a line with CRLF, LF or a bare CR (WHATWG). Every one becomes
156
+ // LF here; a CR at the end of a chunk waits for the next, in case it is
157
+ // the first half of a CRLF split across them.
158
+ let held = "";
237
159
  for await (const chunk of res.body) {
238
- buffer += decoder.decode(chunk, { stream: true });
239
- for (let at = buffer.search(/\r?\n\r?\n/); at >= 0; at = buffer.search(/\r?\n\r?\n/)) {
160
+ let text = held + decoder.decode(chunk, { stream: true });
161
+ held = text.endsWith("\r") ? "\r" : "";
162
+ if (held)
163
+ text = text.slice(0, -1);
164
+ buffer += text.replace(/\r\n?/g, "\n");
165
+ for (let at = buffer.indexOf("\n\n"); at >= 0; at = buffer.indexOf("\n\n")) {
240
166
  const frame = buffer.slice(0, at);
241
- buffer = buffer.slice(at).replace(/^\r?\n\r?\n/, "");
242
- const data = frame.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trimStart()).join("\n");
167
+ buffer = buffer.slice(at + 2);
168
+ const data = frame.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).replace(/^ /, "")).join("\n");
243
169
  if (!data || data === "[DONE]")
244
170
  continue;
171
+ let parsed;
245
172
  try {
246
- yield JSON.parse(data);
173
+ parsed = JSON.parse(data);
247
174
  }
248
175
  catch {
249
- // a frame that is not JSON carries nothing this loop reads
176
+ // A frame that is not JSON may be a lost piece of the reply: a reply
177
+ // missing words would otherwise pass as whole (Codex, 22 Nov 2026).
178
+ throw new Error("the model stream sent a frame that is not JSON — the reply cannot be trusted whole");
250
179
  }
180
+ yield parsed;
251
181
  }
252
182
  }
253
183
  }
254
- const emptyUsage = () => ({ input_tokens: 0, output_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 });
255
- function addUsage(into, u) {
256
- if (!u)
257
- return;
258
- // The closing delta repeats the counts it knows; one that leaves the input
259
- // side at zero is not saying the input was free.
260
- for (const k of Object.keys(into)) {
261
- const v = u[k];
262
- if (typeof v === "number" && (v > 0 || k === "output_tokens"))
263
- into[k] = v;
264
- }
265
- }
266
184
  /** One model call: yields the raw stream events, returns the whole turn. */
267
185
  async function* modelTurn(o, messages, signal) {
268
186
  const res = await openStream(o, buildRequest(o, messages), signal);
@@ -341,45 +259,6 @@ async function* modelTurn(o, messages, signal) {
341
259
  turn.content = turn.content.filter(Boolean);
342
260
  return turn;
343
261
  }
344
- /** May this call run, and with what input? The order the SDK kept, which
345
- * step-exec's checks are written against: every PreToolUse hook first — a
346
- * deny ends it, an allow carries the input the hook settled on and skips
347
- * the question below — then canUseTool, where confinement lives. */
348
- async function decide(o, name, id, input, sessionId, signal) {
349
- let current = input;
350
- let allowed = false;
351
- for (const hook of o.pre) {
352
- 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 });
353
- const d = out?.hookSpecificOutput;
354
- if (!d)
355
- continue;
356
- if (d.permissionDecision === "deny")
357
- return { input: current, refusal: d.permissionDecisionReason || `${name} was refused` };
358
- if (d.updatedInput)
359
- current = d.updatedInput;
360
- if (d.permissionDecision === "allow")
361
- allowed = true;
362
- }
363
- if (!allowed && o.canUseTool) {
364
- const r = await o.canUseTool(name, current, { signal, toolUseID: id });
365
- if (r.behavior === "deny")
366
- return { input: current, refusal: r.message || `${name} was refused` };
367
- if (r.updatedInput)
368
- current = r.updatedInput;
369
- }
370
- return { input: current, refusal: null };
371
- }
372
- /** After a call: tell the PostToolUse hooks, and collect what they add. */
373
- async function after(o, name, id, input, outcome, sessionId, signal) {
374
- const added = [];
375
- for (const hook of o.post) {
376
- 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 });
377
- const context = out?.hookSpecificOutput?.additionalContext;
378
- if (context)
379
- added.push(context);
380
- }
381
- return added;
382
- }
383
262
  async function* run(prompt, o, signal, interrupted) {
384
263
  const sessionId = crypto.randomUUID();
385
264
  const startedAt = Date.now();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "24.8.0",
3
+ "version": "24.8.1",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
@@ -0,0 +1,176 @@
1
+ // What any loop behind executeStep reads the same way (engine-loop.ts
2
+ // today): the SDK's options, what it refuses before a model call is paid
3
+ // for, the permission order every tool call goes through, and token usage.
4
+ // One copy, so a second loop (a bake-off, FOL-213) cannot hold a hook,
5
+ // limit or confinement check differently. Internal: not part of
6
+ // @foldrun/core's public API.
7
+
8
+ import { ENGINE_TOOLS, type EngineTool, type ToolOutcome } from "./engine-tools.ts";
9
+
10
+ export const DEFAULT_MAX_TOKENS = 16_000;
11
+
12
+ export interface Usage {
13
+ input_tokens: number;
14
+ output_tokens: number;
15
+ cache_creation_input_tokens: number;
16
+ cache_read_input_tokens: number;
17
+ }
18
+
19
+ export const emptyUsage = (): Usage => ({ input_tokens: 0, output_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 });
20
+
21
+ export function addUsage(into: Usage, u: Partial<Record<keyof Usage, unknown>> | undefined): void {
22
+ if (!u) return;
23
+ // The closing delta repeats the counts it knows; one that leaves the input
24
+ // side at zero is not saying the input was free.
25
+ for (const k of Object.keys(into) as (keyof Usage)[]) {
26
+ const v = u[k];
27
+ if (typeof v === "number" && (v > 0 || k === "output_tokens")) into[k] = v;
28
+ }
29
+ }
30
+
31
+ /** The tier names an agent may write, where the environment names no model
32
+ * for them. The SDK's binary resolves these itself; here it is said. */
33
+ export const TIER_DEFAULTS: Record<string, string> = {
34
+ haiku: "claude-haiku-5-5",
35
+ sonnet: "claude-sonnet-5-5",
36
+ opus: "claude-opus-5-5",
37
+ };
38
+
39
+ export type Json = Record<string, unknown>;
40
+ export type Block = Json & { type: string };
41
+ export type HookFn = (input: Json, toolUseId?: string, extra?: { signal: AbortSignal }) => Promise<Json | undefined> | Json | undefined;
42
+ export type CanUseTool = (name: string, input: Json, extra: { signal: AbortSignal; toolUseID: string }) =>
43
+ Promise<{ behavior: "allow"; updatedInput?: Json } | { behavior: "deny"; message: string }>;
44
+
45
+ export interface LoopOptions {
46
+ cwd: string;
47
+ env: Record<string, string | undefined>;
48
+ /** What the tools (Bash) get; `env` when not given. foldrun code passes
49
+ * the person's own environment here, so the model key stays with the loop. */
50
+ shellEnv: Record<string, string | undefined>;
51
+ model: string;
52
+ systemPrompt: string;
53
+ tools: EngineTool[];
54
+ maxTurns: number | null;
55
+ partial: boolean;
56
+ pre: HookFn[];
57
+ post: HookFn[];
58
+ canUseTool: CanUseTool | null;
59
+ outer: AbortSignal | null;
60
+ /** The conversation so far, before this prompt: earlier user turns, the
61
+ * model's replies and tool results, as the loop yielded them. */
62
+ history: { role: string; content: Block[] }[];
63
+ }
64
+
65
+ export function hookFns(hooks: unknown, event: string): HookFn[] {
66
+ const groups = (hooks as Record<string, { hooks?: HookFn[] }[] | undefined> | undefined)?.[event];
67
+ return (groups ?? []).flatMap((g) => g.hooks ?? []);
68
+ }
69
+
70
+ /** The SDK's options, as this engine reads them. What it cannot honour it
71
+ * refuses here, before a model call is paid for. */
72
+ /** `engine` names the loop in what it refuses. */
73
+ export function readOptions(options: Json, engine = "foldrun"): LoopOptions {
74
+ const env = (options.env as Record<string, string | undefined> | undefined) ?? process.env;
75
+ const names = Array.isArray(options.tools) ? (options.tools as unknown[]).map(String) : [];
76
+ const unsupported = names.filter((n) => !ENGINE_TOOLS[n]);
77
+ if (unsupported.length) {
78
+ throw new Error(`the ${engine} engine has no tool named ${unsupported.join(", ")} yet — it has ${Object.keys(ENGINE_TOOLS).join(", ")}. Run this agent on the default engine.`);
79
+ }
80
+ const servers = Object.keys((options.mcpServers as Json | undefined) ?? {});
81
+ if (servers.length) {
82
+ throw new Error(`the ${engine} engine does not connect MCP servers yet (${servers.join(", ")}) — run this agent on the default engine.`);
83
+ }
84
+ if (options.agents && Object.keys(options.agents as Json).length) {
85
+ throw new Error(`the ${engine} engine does not run sub-agents yet — run this agent on the default engine.`);
86
+ }
87
+ const sandbox = options.sandbox as { enabled?: boolean } | undefined;
88
+ // Never read from `env`: that is where a tenant's secrets live.
89
+ if (names.includes("Bash") && sandbox?.enabled !== false && options.engineHostShell !== true) {
90
+ throw new Error(`the ${engine} engine has no OS sandbox for the shell on this host — run the step in a container.`);
91
+ }
92
+ const model = String(options.model ?? "");
93
+ if (!model) throw new Error(`the ${engine} engine needs a model`);
94
+ // Tools the host brings, as EngineTool objects: they sit beside the
95
+ // built-in ones and go through canUseTool and the hooks like them.
96
+ // foldrun code's cloud_agents is one. A name may not shadow a built-in.
97
+ const extra: EngineTool[] = [];
98
+ for (const t of Array.isArray(options.extraTools) ? (options.extraTools as unknown[]) : []) {
99
+ const tool = t as Partial<EngineTool> | null;
100
+ if (!tool || typeof tool.name !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(tool.name) || typeof tool.run !== "function" || typeof tool.input_schema !== "object") {
101
+ throw new Error("extraTools: each needs a name (letters, digits, _ and -), an input_schema and a run function");
102
+ }
103
+ if (ENGINE_TOOLS[tool.name] || extra.some((x) => x.name === tool.name)) throw new Error(`extraTools: ${tool.name} is already a tool`);
104
+ extra.push({ name: tool.name, description: String(tool.description ?? ""), input_schema: tool.input_schema as Record<string, unknown>, readOnly: tool.readOnly === true, run: tool.run });
105
+ }
106
+ return {
107
+ cwd: String(options.cwd ?? process.cwd()),
108
+ env,
109
+ shellEnv: options.shellEnv && typeof options.shellEnv === "object" ? (options.shellEnv as Record<string, string | undefined>) : env,
110
+ model: env[`ANTHROPIC_DEFAULT_${model.toUpperCase()}_MODEL`] || TIER_DEFAULTS[model] || model,
111
+ systemPrompt: typeof options.systemPrompt === "string" ? options.systemPrompt : "",
112
+ tools: [...names.map((n) => ENGINE_TOOLS[n]), ...extra],
113
+ maxTurns: typeof options.maxTurns === "number" && options.maxTurns > 0 ? options.maxTurns : null,
114
+ partial: options.includePartialMessages === true,
115
+ pre: hookFns(options.hooks, "PreToolUse"),
116
+ post: hookFns(options.hooks, "PostToolUse"),
117
+ canUseTool: typeof options.canUseTool === "function" ? (options.canUseTool as CanUseTool) : null,
118
+ outer: (options.abortController as AbortController | undefined)?.signal ?? null,
119
+ history: readHistory(options.history),
120
+ };
121
+ }
122
+
123
+ /** An earlier conversation, checked: user and assistant turns that
124
+ * alternate, starting with the user's, each a list of content blocks. A
125
+ * turn that is not one is refused, not sent half-right to the model. */
126
+ export function readHistory(raw: unknown): { role: string; content: Block[] }[] {
127
+ if (raw == null) return [];
128
+ if (!Array.isArray(raw)) throw new Error("history must be a list of turns");
129
+ return raw.map((t, i) => {
130
+ const role = (t as Json)?.role;
131
+ const content = (t as Json)?.content;
132
+ if (role !== (i % 2 === 0 ? "user" : "assistant")) throw new Error(`history turn ${i + 1} must be the ${i % 2 === 0 ? "user's" : "model's"}`);
133
+ if (!Array.isArray(content) || !content.every((b) => b && typeof (b as Json).type === "string")) throw new Error(`history turn ${i + 1} has no content blocks`);
134
+ return { role: String(role), content: content as Block[] };
135
+ });
136
+ }
137
+
138
+ export interface Decision {
139
+ input: Json;
140
+ refusal: string | null;
141
+ }
142
+
143
+ /** May this call run, and with what input? The order the SDK kept, which
144
+ * step-exec's checks are written against: every PreToolUse hook first — a
145
+ * deny ends it, an allow carries the input the hook settled on and skips
146
+ * the question below — then canUseTool, where confinement lives. */
147
+ export async function decide(o: LoopOptions, name: string, id: string, input: Json, sessionId: string, signal: AbortSignal): Promise<Decision> {
148
+ let current = input;
149
+ let allowed = false;
150
+ for (const hook of o.pre) {
151
+ 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 });
152
+ const d = (out as { hookSpecificOutput?: { permissionDecision?: string; permissionDecisionReason?: string; updatedInput?: Json } } | undefined)?.hookSpecificOutput;
153
+ if (!d) continue;
154
+ if (d.permissionDecision === "deny") return { input: current, refusal: d.permissionDecisionReason || `${name} was refused` };
155
+ if (d.updatedInput) current = d.updatedInput;
156
+ if (d.permissionDecision === "allow") allowed = true;
157
+ }
158
+ if (!allowed && o.canUseTool) {
159
+ const r = await o.canUseTool(name, current, { signal, toolUseID: id });
160
+ if (r.behavior === "deny") return { input: current, refusal: r.message || `${name} was refused` };
161
+ if (r.updatedInput) current = r.updatedInput;
162
+ }
163
+ return { input: current, refusal: null };
164
+ }
165
+
166
+ /** After a call: tell the PostToolUse hooks, and collect what they add. */
167
+ export async function after(o: LoopOptions, name: string, id: string, input: Json, outcome: ToolOutcome, sessionId: string, signal: AbortSignal): Promise<string[]> {
168
+ const added: string[] = [];
169
+ for (const hook of o.post) {
170
+ 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 });
171
+ const context = (out as { hookSpecificOutput?: { additionalContext?: string } } | undefined)?.hookSpecificOutput?.additionalContext;
172
+ if (context) added.push(context);
173
+ }
174
+ return added;
175
+ }
176
+
@@ -36,130 +36,17 @@
36
36
 
37
37
  import crypto from "node:crypto";
38
38
  import type { QueryFn, QueryLike } from "./step-exec.ts";
39
- import { ENGINE_TOOLS, killGroups, type EngineTool, type ToolContext, type ToolOutcome } from "./engine-tools.ts";
39
+ import { killGroups, type EngineTool, type ToolContext, type ToolOutcome } from "./engine-tools.ts";
40
+ import { DEFAULT_MAX_TOKENS, readOptions, decide, after, emptyUsage, addUsage, type Json, type Block, type LoopOptions, type Decision, type Usage } from "./engine-common.ts";
40
41
 
41
42
  /** Which loop runs a step's turns. */
42
43
  export type Engine = "sdk" | "foldrun";
43
44
 
44
45
  const DEFAULT_BASE = "https://api.anthropic.com";
45
46
  const API_VERSION = "2023-06-01";
46
- const DEFAULT_MAX_TOKENS = 16_000;
47
47
  const MODEL_TRIES = 4;
48
48
  const RETRY_AFTER_CAP_MS = 30_000;
49
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
- /** What the tools (Bash) get; `env` when not given. foldrun code passes
75
- * the person's own environment here, so the model key stays with the loop. */
76
- shellEnv: Record<string, string | undefined>;
77
- model: string;
78
- systemPrompt: string;
79
- tools: EngineTool[];
80
- maxTurns: number | null;
81
- partial: boolean;
82
- pre: HookFn[];
83
- post: HookFn[];
84
- canUseTool: CanUseTool | null;
85
- outer: AbortSignal | null;
86
- /** The conversation so far, before this prompt: earlier user turns, the
87
- * model's replies and tool results, as the loop yielded them. */
88
- history: { role: string; content: Block[] }[];
89
- }
90
-
91
- function hookFns(hooks: unknown, event: string): HookFn[] {
92
- const groups = (hooks as Record<string, { hooks?: HookFn[] }[] | undefined> | undefined)?.[event];
93
- return (groups ?? []).flatMap((g) => g.hooks ?? []);
94
- }
95
-
96
- /** The SDK's options, as this engine reads them. What it cannot honour it
97
- * refuses here, before a model call is paid for. */
98
- function readOptions(options: Json): LoopOptions {
99
- const env = (options.env as Record<string, string | undefined> | undefined) ?? process.env;
100
- const names = Array.isArray(options.tools) ? (options.tools as unknown[]).map(String) : [];
101
- const unsupported = names.filter((n) => !ENGINE_TOOLS[n]);
102
- if (unsupported.length) {
103
- 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.`);
104
- }
105
- const servers = Object.keys((options.mcpServers as Json | undefined) ?? {});
106
- if (servers.length) {
107
- throw new Error(`the foldrun engine does not connect MCP servers yet (${servers.join(", ")}) — run this agent on the default engine.`);
108
- }
109
- if (options.agents && Object.keys(options.agents as Json).length) {
110
- throw new Error("the foldrun engine does not run sub-agents yet — run this agent on the default engine.");
111
- }
112
- const sandbox = options.sandbox as { enabled?: boolean } | undefined;
113
- // Never read from `env`: that is where a tenant's secrets live.
114
- if (names.includes("Bash") && sandbox?.enabled !== false && options.engineHostShell !== true) {
115
- throw new Error("the foldrun engine has no OS sandbox for the shell on this host — run the step in a container.");
116
- }
117
- const model = String(options.model ?? "");
118
- if (!model) throw new Error("the foldrun engine needs a model");
119
- // Tools the host brings, as EngineTool objects: they sit beside the
120
- // built-in ones and go through canUseTool and the hooks like them.
121
- // foldrun code's cloud_agents is one. A name may not shadow a built-in.
122
- const extra: EngineTool[] = [];
123
- for (const t of Array.isArray(options.extraTools) ? (options.extraTools as unknown[]) : []) {
124
- const tool = t as Partial<EngineTool> | null;
125
- if (!tool || typeof tool.name !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(tool.name) || typeof tool.run !== "function" || typeof tool.input_schema !== "object") {
126
- throw new Error("extraTools: each needs a name (letters, digits, _ and -), an input_schema and a run function");
127
- }
128
- if (ENGINE_TOOLS[tool.name] || extra.some((x) => x.name === tool.name)) throw new Error(`extraTools: ${tool.name} is already a tool`);
129
- extra.push({ name: tool.name, description: String(tool.description ?? ""), input_schema: tool.input_schema as Record<string, unknown>, readOnly: tool.readOnly === true, run: tool.run });
130
- }
131
- return {
132
- cwd: String(options.cwd ?? process.cwd()),
133
- env,
134
- shellEnv: options.shellEnv && typeof options.shellEnv === "object" ? (options.shellEnv as Record<string, string | undefined>) : env,
135
- model: env[`ANTHROPIC_DEFAULT_${model.toUpperCase()}_MODEL`] || TIER_DEFAULTS[model] || model,
136
- systemPrompt: typeof options.systemPrompt === "string" ? options.systemPrompt : "",
137
- tools: [...names.map((n) => ENGINE_TOOLS[n]), ...extra],
138
- maxTurns: typeof options.maxTurns === "number" && options.maxTurns > 0 ? options.maxTurns : null,
139
- partial: options.includePartialMessages === true,
140
- pre: hookFns(options.hooks, "PreToolUse"),
141
- post: hookFns(options.hooks, "PostToolUse"),
142
- canUseTool: typeof options.canUseTool === "function" ? (options.canUseTool as CanUseTool) : null,
143
- outer: (options.abortController as AbortController | undefined)?.signal ?? null,
144
- history: readHistory(options.history),
145
- };
146
- }
147
-
148
- /** An earlier conversation, checked: user and assistant turns that
149
- * alternate, starting with the user's, each a list of content blocks. A
150
- * turn that is not one is refused, not sent half-right to the model. */
151
- function readHistory(raw: unknown): { role: string; content: Block[] }[] {
152
- if (raw == null) return [];
153
- if (!Array.isArray(raw)) throw new Error("history must be a list of turns");
154
- return raw.map((t, i) => {
155
- const role = (t as Json)?.role;
156
- const content = (t as Json)?.content;
157
- if (role !== (i % 2 === 0 ? "user" : "assistant")) throw new Error(`history turn ${i + 1} must be the ${i % 2 === 0 ? "user's" : "model's"}`);
158
- if (!Array.isArray(content) || !content.every((b) => b && typeof (b as Json).type === "string")) throw new Error(`history turn ${i + 1} has no content blocks`);
159
- return { role: String(role), content: content as Block[] };
160
- });
161
- }
162
-
163
50
  function requestHeaders(env: Record<string, string | undefined>): Record<string, string> {
164
51
  const headers: Record<string, string> = { "content-type": "application/json", "anthropic-version": API_VERSION };
165
52
  if (env.ANTHROPIC_API_KEY) headers["x-api-key"] = env.ANTHROPIC_API_KEY;
@@ -265,18 +152,29 @@ async function openStream(o: LoopOptions, body: Json, signal: AbortSignal): Prom
265
152
  async function* sse(res: Response): AsyncGenerator<Json> {
266
153
  const decoder = new TextDecoder();
267
154
  let buffer = "";
155
+ // SSE ends a line with CRLF, LF or a bare CR (WHATWG). Every one becomes
156
+ // LF here; a CR at the end of a chunk waits for the next, in case it is
157
+ // the first half of a CRLF split across them.
158
+ let held = "";
268
159
  for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {
269
- buffer += decoder.decode(chunk, { stream: true });
270
- for (let at = buffer.search(/\r?\n\r?\n/); at >= 0; at = buffer.search(/\r?\n\r?\n/)) {
160
+ let text = held + decoder.decode(chunk, { stream: true });
161
+ held = text.endsWith("\r") ? "\r" : "";
162
+ if (held) text = text.slice(0, -1);
163
+ buffer += text.replace(/\r\n?/g, "\n");
164
+ for (let at = buffer.indexOf("\n\n"); at >= 0; at = buffer.indexOf("\n\n")) {
271
165
  const frame = buffer.slice(0, at);
272
- buffer = buffer.slice(at).replace(/^\r?\n\r?\n/, "");
273
- const data = frame.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trimStart()).join("\n");
166
+ buffer = buffer.slice(at + 2);
167
+ const data = frame.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).replace(/^ /, "")).join("\n");
274
168
  if (!data || data === "[DONE]") continue;
169
+ let parsed: Json;
275
170
  try {
276
- yield JSON.parse(data) as Json;
171
+ parsed = JSON.parse(data) as Json;
277
172
  } catch {
278
- // a frame that is not JSON carries nothing this loop reads
173
+ // A frame that is not JSON may be a lost piece of the reply: a reply
174
+ // missing words would otherwise pass as whole (Codex, 22 Nov 2026).
175
+ throw new Error("the model stream sent a frame that is not JSON — the reply cannot be trusted whole");
279
176
  }
177
+ yield parsed;
280
178
  }
281
179
  }
282
180
  }
@@ -291,18 +189,6 @@ interface Turn {
291
189
  malformed: Set<string>;
292
190
  }
293
191
 
294
- const emptyUsage = (): Usage => ({ input_tokens: 0, output_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 });
295
-
296
- function addUsage(into: Usage, u: Partial<Record<keyof Usage, unknown>> | undefined): void {
297
- if (!u) return;
298
- // The closing delta repeats the counts it knows; one that leaves the input
299
- // side at zero is not saying the input was free.
300
- for (const k of Object.keys(into) as (keyof Usage)[]) {
301
- const v = u[k];
302
- if (typeof v === "number" && (v > 0 || k === "output_tokens")) into[k] = v;
303
- }
304
- }
305
-
306
192
  /** One model call: yields the raw stream events, returns the whole turn. */
307
193
  async function* modelTurn(o: LoopOptions, messages: { role: string; content: Block[] }[], signal: AbortSignal): AsyncGenerator<Json, Turn> {
308
194
  const res = await openStream(o, buildRequest(o, messages), signal);
@@ -362,45 +248,6 @@ async function* modelTurn(o: LoopOptions, messages: { role: string; content: Blo
362
248
  return turn;
363
249
  }
364
250
 
365
- interface Decision {
366
- input: Json;
367
- refusal: string | null;
368
- }
369
-
370
- /** May this call run, and with what input? The order the SDK kept, which
371
- * step-exec's checks are written against: every PreToolUse hook first — a
372
- * deny ends it, an allow carries the input the hook settled on and skips
373
- * the question below — then canUseTool, where confinement lives. */
374
- async function decide(o: LoopOptions, name: string, id: string, input: Json, sessionId: string, signal: AbortSignal): Promise<Decision> {
375
- let current = input;
376
- let allowed = false;
377
- for (const hook of o.pre) {
378
- 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 });
379
- const d = (out as { hookSpecificOutput?: { permissionDecision?: string; permissionDecisionReason?: string; updatedInput?: Json } } | undefined)?.hookSpecificOutput;
380
- if (!d) continue;
381
- if (d.permissionDecision === "deny") return { input: current, refusal: d.permissionDecisionReason || `${name} was refused` };
382
- if (d.updatedInput) current = d.updatedInput;
383
- if (d.permissionDecision === "allow") allowed = true;
384
- }
385
- if (!allowed && o.canUseTool) {
386
- const r = await o.canUseTool(name, current, { signal, toolUseID: id });
387
- if (r.behavior === "deny") return { input: current, refusal: r.message || `${name} was refused` };
388
- if (r.updatedInput) current = r.updatedInput;
389
- }
390
- return { input: current, refusal: null };
391
- }
392
-
393
- /** After a call: tell the PostToolUse hooks, and collect what they add. */
394
- async function after(o: LoopOptions, name: string, id: string, input: Json, outcome: ToolOutcome, sessionId: string, signal: AbortSignal): Promise<string[]> {
395
- const added: string[] = [];
396
- for (const hook of o.post) {
397
- 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 });
398
- const context = (out as { hookSpecificOutput?: { additionalContext?: string } } | undefined)?.hookSpecificOutput?.additionalContext;
399
- if (context) added.push(context);
400
- }
401
- return added;
402
- }
403
-
404
251
  async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interrupted: () => boolean): AsyncGenerator<Json> {
405
252
  const sessionId = crypto.randomUUID();
406
253
  const startedAt = Date.now();