@foldrun/core 24.2.2 → 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.
Files changed (64) hide show
  1. package/dist/src/account.js +2 -2
  2. package/dist/src/agent-import.js +2 -2
  3. package/dist/src/budget.js +1 -1
  4. package/dist/src/copy-back.js +2 -2
  5. package/dist/src/data-import.js +9 -9
  6. package/dist/src/deploy.js +2 -2
  7. package/dist/src/engine-loop.d.ts +45 -0
  8. package/dist/src/engine-loop.js +480 -0
  9. package/dist/src/engine-tools.d.ts +41 -0
  10. package/dist/src/engine-tools.js +579 -0
  11. package/dist/src/evals.js +1 -1
  12. package/dist/src/failure.js +1 -1
  13. package/dist/src/flow-lint.js +8 -8
  14. package/dist/src/frontmatter-fields.js +8 -8
  15. package/dist/src/mail.js +1 -1
  16. package/dist/src/manifest.js +1 -1
  17. package/dist/src/notify.js +2 -2
  18. package/dist/src/oauth-capabilities.js +1 -1
  19. package/dist/src/openapi.js +3 -3
  20. package/dist/src/package.js +2 -2
  21. package/dist/src/providers.js +2 -2
  22. package/dist/src/publish.js +2 -2
  23. package/dist/src/run-container.js +3 -3
  24. package/dist/src/scan.js +7 -7
  25. package/dist/src/secrets.js +7 -7
  26. package/dist/src/starter.js +18 -18
  27. package/dist/src/step-exec.d.ts +12 -1
  28. package/dist/src/step-exec.js +6 -2
  29. package/dist/src/storage.js +6 -6
  30. package/dist/src/store.js +16 -16
  31. package/dist/src/tool-test.js +1 -1
  32. package/dist/src/webhook.js +1 -1
  33. package/dist/src/workspace-revisions.js +2 -2
  34. package/package.json +1 -1
  35. package/src/account.ts +2 -2
  36. package/src/agent-import.ts +2 -2
  37. package/src/budget.ts +1 -1
  38. package/src/copy-back.ts +2 -2
  39. package/src/data-import.ts +9 -9
  40. package/src/deploy.ts +2 -2
  41. package/src/engine-loop.ts +495 -0
  42. package/src/engine-tools.ts +566 -0
  43. package/src/evals.ts +1 -1
  44. package/src/failure.ts +1 -1
  45. package/src/flow-lint.ts +8 -8
  46. package/src/frontmatter-fields.ts +8 -8
  47. package/src/mail.ts +1 -1
  48. package/src/manifest.ts +1 -1
  49. package/src/notify.ts +2 -2
  50. package/src/oauth-capabilities.ts +1 -1
  51. package/src/openapi.ts +3 -3
  52. package/src/package.ts +2 -2
  53. package/src/providers.ts +2 -2
  54. package/src/publish.ts +2 -2
  55. package/src/run-container.ts +3 -3
  56. package/src/scan.ts +7 -7
  57. package/src/secrets.ts +7 -7
  58. package/src/starter.ts +19 -19
  59. package/src/step-exec.ts +14 -2
  60. package/src/storage.ts +6 -6
  61. package/src/store.ts +16 -16
  62. package/src/tool-test.ts +1 -1
  63. package/src/webhook.ts +1 -1
  64. package/src/workspace-revisions.ts +2 -2
@@ -81,7 +81,7 @@ export function readAccountTree(accountRoot, only) {
81
81
  }
82
82
  const names = listWorkspaceDirs(root).filter((n) => (only ? n === only : true));
83
83
  if (only && names.length === 0) {
84
- throw new Error(`no workspace "${only}" in ${root} — have: ${listWorkspaceDirs(root).join(", ") || "none"}`);
84
+ throw new Error(`no project "${only}" in ${root} — have: ${listWorkspaceDirs(root).join(", ") || "none"}`);
85
85
  }
86
86
  const wsRoot = path.join(root, "workspaces");
87
87
  const legacy = path.join(root, "projects");
@@ -111,7 +111,7 @@ export function accountTreeFrom(from, only) {
111
111
  const dir = layout.workspaceDir;
112
112
  const name = path.basename(dir);
113
113
  if (only && only !== name)
114
- throw new Error(`${dir} is a single workspace called "${name}", not "${only}"`);
114
+ throw new Error(`${dir} is a single project called "${name}", not "${only}"`);
115
115
  return {
116
116
  layout,
117
117
  tree: {
@@ -45,9 +45,9 @@ export function importAgent(tenant, from, agent, to, opts = {}) {
45
45
  assertSafeName(name, "agent");
46
46
  const known = new Set(listWorkspaces(tenant).map((w) => w.name));
47
47
  if (!known.has(from))
48
- throw new AgentImportError(`no workspace called "${from}" in this account`, 404);
48
+ throw new AgentImportError(`no project called "${from}" in this account`, 404);
49
49
  if (!known.has(to))
50
- throw new AgentImportError(`no workspace called "${to}" in this account`, 404);
50
+ throw new AgentImportError(`no project called "${to}" in this account`, 404);
51
51
  if (from === to && name === agent) {
52
52
  throw new AgentImportError(`${agent} is already in ${to} — give the copy another name with "as"`, 409);
53
53
  }
@@ -89,7 +89,7 @@ export function budgetProblem(raw, allowed) {
89
89
  if (!allowed.includes(period)) {
90
90
  return period === "run"
91
91
  ? `budget: is per run here already — write the number alone`
92
- : `budget: "${period}" does not apply here — this cap is per run; a cap over time belongs in the workspace's or the account's AGENTS.md`;
92
+ : `budget: "${period}" does not apply here — this cap is per run; a cap over time belongs in the project's or the account's AGENTS.md`;
93
93
  }
94
94
  }
95
95
  return null;
@@ -69,6 +69,6 @@ export function keptLine(kept) {
69
69
  export function refusedLine(refused) {
70
70
  const shown = refused.slice(0, 20).map((r) => `${r.path} (${r.kind})`).join(", ");
71
71
  const more = refused.length > 20 ? ` and ${refused.length - 20} more` : "";
72
- return (`refused path: ${shown}${more} — a step cannot change the workspace's configuration or code; ` +
73
- `the workspace keeps its own copy. Propose the change instead (Proposed fixes), and a person applies it.`);
72
+ return (`refused path: ${shown}${more} — a step cannot change the project's configuration or code; ` +
73
+ `the project keeps its own copy. Propose the change instead (Proposed fixes), and a person applies it.`);
74
74
  }
@@ -137,9 +137,9 @@ const PLATFORM_MARKERS = {
137
137
  "trigger-log.jsonl.tmp": "trigger log temp file (not read here)",
138
138
  "hooks.json": "webhook tokens (platform file; not mapped)",
139
139
  "hook-deliveries.jsonl": "hook delivery log (not mapped)",
140
- ".repo.json": "platform file; not workspace content",
140
+ ".repo.json": "platform file; not project content",
141
141
  once: "operation markers (the unique keys decide now; not imported)",
142
- ".foldrun": "platform folder; not workspace content",
142
+ ".foldrun": "platform folder; not project content",
143
143
  storage: "workspace-local storage folder (the storage index moved in FOL-152; not read here)",
144
144
  };
145
145
  async function scanWorkspace(tenant, workspace, dir) {
@@ -183,7 +183,7 @@ async function scanWorkspace(tenant, workspace, dir) {
183
183
  top = fs.readdirSync(dir, { withFileTypes: true });
184
184
  }
185
185
  catch (err) {
186
- ws.error = `workspace folder unreadable (${err.code ?? "error"})`;
186
+ ws.error = `project folder unreadable (${err.code ?? "error"})`;
187
187
  return ws;
188
188
  }
189
189
  for (const e of top.sort(byName)) {
@@ -228,14 +228,14 @@ async function scanWorkspace(tenant, workspace, dir) {
228
228
  }
229
229
  else {
230
230
  const t = st.isDirectory() ? tally(abs) : { files: 1, bytes: st.size };
231
- ws.unmapped.push({ path: name, reason: "not part of a workspace manifest (in neither the authored nor the state list)", ...t });
231
+ ws.unmapped.push({ path: name, reason: "not part of a project manifest (in neither the authored nor the state list)", ...t });
232
232
  }
233
233
  }
234
234
  // Which of the found files can be a manifest path; case collisions.
235
235
  const mapped = [];
236
236
  for (const f of found) {
237
237
  if (isPlatformPath(f.rel)) {
238
- ws.unmapped.push({ path: f.rel, reason: "platform or engine file, not workspace content", files: 1, bytes: f.st.size });
238
+ ws.unmapped.push({ path: f.rel, reason: "platform or engine file, not project content", files: 1, bytes: f.st.size });
239
239
  continue;
240
240
  }
241
241
  try {
@@ -489,7 +489,7 @@ export async function planImport(scan, deps) {
489
489
  p.revisionsToMake = sides.size;
490
490
  const foreign = await foreignRevisions(deps, wsRef(w));
491
491
  if (foreign.length)
492
- p.note = `${foreign.length} revision(s) by someone else (latest by ${foreign[0].by}): an import skips this workspace unless --force`;
492
+ p.note = `${foreign.length} revision(s) by someone else (latest by ${foreign[0].by}): an import skips this project unless --force`;
493
493
  }
494
494
  catch (err) {
495
495
  p.note = `could not read the destination: ${err.message}`;
@@ -506,7 +506,7 @@ export function renderPlan(scan, plan) {
506
506
  let files = 0;
507
507
  let bytes = 0;
508
508
  for (const t of scan.tenants) {
509
- L.push(`account ${t.tenant} (${t.workspaces.length} workspace(s))`);
509
+ L.push(`account ${t.tenant} (${t.workspaces.length} project(s))`);
510
510
  for (const u of t.unmapped)
511
511
  L.push(` can't map ${u.path}: ${u.reason} (${u.files ?? 0} files, ${kb(u.bytes ?? 0)})`);
512
512
  for (const w of t.workspaces) {
@@ -523,7 +523,7 @@ export function renderPlan(scan, plan) {
523
523
  L.push(` can't map ${u.path}: ${u.reason}${u.files ? ` (${u.files} files, ${kb(u.bytes ?? 0)})` : ""}`);
524
524
  }
525
525
  }
526
- L.push("", `Total: ${files} workspace files, ${kb(bytes)}.`);
526
+ L.push("", `Total: ${files} project files, ${kb(bytes)}.`);
527
527
  return L.join("\n") + "\n";
528
528
  }
529
529
  /** Compare every workspace's heads with the folder, by path, sha256 and mode —
@@ -634,7 +634,7 @@ export function renderVerify(r) {
634
634
  for (const n of w.notes)
635
635
  L.push(` note: ${n}`);
636
636
  }
637
- L.push("", `${r.workspaces.filter((w) => w.pass).length} of ${r.workspaces.length} workspace(s) passed.`);
637
+ L.push("", `${r.workspaces.filter((w) => w.pass).length} of ${r.workspaces.length} project(s) passed.`);
638
638
  return L.join("\n") + "\n";
639
639
  }
640
640
  /** A path with every link resolved, for a folder that may not exist yet: the
@@ -113,7 +113,7 @@ export function readTree(dir, opts = {}) {
113
113
  }
114
114
  sourceBytes += bytes;
115
115
  if (opts.maxSourceBytes !== undefined && sourceBytes > opts.maxSourceBytes) {
116
- throw new TreeTooLarge(`the workspace's files other than state/ and memory/ are over ${Math.round(opts.maxSourceBytes / 1048576)} MiB — not read`);
116
+ throw new TreeTooLarge(`the project's files other than state/ and memory/ are over ${Math.round(opts.maxSourceBytes / 1048576)} MiB — not read`);
117
117
  }
118
118
  return true;
119
119
  };
@@ -383,7 +383,7 @@ function structuralWarnings(files, extraOutward = []) {
383
383
  const agentNames = [];
384
384
  const out = [];
385
385
  if (!files.some((f) => /^agents\/[^/]+\/agent\.md$/.test(f.path)) && !files.some((f) => /^\.(claude|agents)\/agents\/[^/]+\.md$/.test(f.path))) {
386
- out.push({ where: "agents/", message: "no agents yet — add one (agents/<name>/agent.md), or import one from another workspace" });
386
+ out.push({ where: "agents/", message: "no agents yet — add one (agents/<name>/agent.md), or import one from another project" });
387
387
  }
388
388
  // The web: warnings check prints — the old session: key, and a pinned
389
389
  // user agent behind the runner image's Chrome, which the platform knows
@@ -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
+ };