@foldrun/core 24.7.2 → 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.
@@ -575,27 +575,59 @@ export function toResponses(req, opts, drop = dropped()) {
575
575
  * request asked for; plain OpenAI says `stop` either way, which reads as
576
576
  * end_turn. pause_turn has no counterpart: server-side tools are dropped.
577
577
  */
578
- function chatStop(choice, sawTool, stops) {
579
- const finish = choice.finish_reason;
580
- if (finish === "content_filter")
578
+ function chatStop(choice, sawTool, stops, sawRefusal = false) {
579
+ const finish = typeof choice.finish_reason === "string" ? choice.finish_reason.toLowerCase() : choice.finish_reason;
580
+ // OpenAI's `message.refusal` / `delta.refusal` (FOL-211, Codex review):
581
+ // a declined reply came back as an empty end_turn until 22 Nov 2026.
582
+ if (sawRefusal || finish === "content_filter")
581
583
  return { reason: "refusal", sequence: null };
582
584
  if (finish === "length")
583
585
  return { reason: "max_tokens", sequence: null };
584
586
  if (finish === "model_length")
585
587
  return { reason: "model_context_window_exceeded", sequence: null };
586
- if (sawTool || finish === "tool_calls" || finish === "function_call")
588
+ if (finish === "tool_calls" || finish === "function_call")
589
+ return { reason: "tool_use", sequence: null };
590
+ // Only a finish the provider SAID is one (FOL-211, Codex review, 22 Nov
591
+ // 2026): vLLM, SGLang and Gemini's OpenAI endpoint all send a reason on a
592
+ // normal finish. Until then a missing or unknown one read as end_turn, or
593
+ // as tool_use dispatching a call the provider never confirmed. `stop` with
594
+ // tool calls in it is Gemini's way of ending a tool turn, and stays one.
595
+ if (finish !== "stop")
596
+ return null;
597
+ if (sawTool)
587
598
  return { reason: "tool_use", sequence: null };
588
599
  const matched = typeof choice.stop_reason === "string" ? choice.stop_reason : choice.matched_stop;
589
600
  if (typeof matched === "string" && stops.includes(matched))
590
601
  return { reason: "stop_sequence", sequence: matched };
591
602
  return { reason: "end_turn", sequence: null };
592
603
  }
593
- /** Why a Response stopped: a refusal part or a content filter is a refusal. */
594
- function responsesStop(incomplete, sawTool, sawRefusal) {
604
+ /** A reply the provider did not finish in a way Anthropic's format can say:
605
+ * the gateway answers it as an error carrying the provider's own reason,
606
+ * never as a normal stop (FOL-211). */
607
+ export class UnfinishedReply extends Error {
608
+ }
609
+ function unfinishedResponse(reason) {
610
+ return `the provider ended the response incomplete (${typeof reason === "string" && reason ? `reason: ${reason.slice(0, 60)}` : "no reason given"})`;
611
+ }
612
+ function unfinishedChat(choice) {
613
+ const r = choice.finish_reason;
614
+ return typeof r === "string" && r ? `the provider ended the reply with a reason this gateway does not know (finish_reason: ${r.slice(0, 60)})` : "the provider ended the reply without saying it had finished (no finish_reason)";
615
+ }
616
+ /** Why a Response stopped: a refusal part or a content filter is a refusal.
617
+ * An incomplete response is never a finish: with a reason this does not
618
+ * know, or none, it is null — an error naming it. It was a finish
619
+ * (`end_turn`, or `tool_use` dispatching a half-made call) until 22 Nov
620
+ * 2026 (FOL-211, Codex review). */
621
+ function responsesStop(incomplete, sawTool, sawRefusal, wasIncomplete = false) {
595
622
  if (sawRefusal || incomplete === "content_filter")
596
623
  return "refusal";
597
624
  if (incomplete === "max_output_tokens")
598
625
  return "max_tokens";
626
+ // Incomplete for a reason this does not know, or none: an error with that
627
+ // reason — not max_tokens, which would tell a person to raise a limit the
628
+ // provider never named (Codex review, 22 Nov 2026).
629
+ if (wasIncomplete || (typeof incomplete === "string" && incomplete))
630
+ return null;
599
631
  if (sawTool)
600
632
  return "tool_use";
601
633
  return "end_turn";
@@ -621,6 +653,9 @@ export function fromChatCompletion(res, requestedModel, stopSequences, extras) {
621
653
  const text = typeof msg.content === "string" ? msg.content : textOf(msg.content);
622
654
  if (text)
623
655
  content.push({ type: "text", text });
656
+ const refusal = typeof msg.refusal === "string" && msg.refusal.trim() ? msg.refusal : null;
657
+ if (refusal)
658
+ content.push({ type: "text", text: refusal });
624
659
  for (const tc of (Array.isArray(msg.tool_calls) ? msg.tool_calls : [])) {
625
660
  const fn = tc.function ?? {};
626
661
  const id = String(tc.id ?? `call_${crypto.randomBytes(6).toString("hex")}`);
@@ -633,7 +668,9 @@ export function fromChatCompletion(res, requestedModel, stopSequences, extras) {
633
668
  });
634
669
  }
635
670
  const usage = res.usage ?? {};
636
- const stop = chatStop(choice, content.some((c) => c.type === "tool_use"), stopList(stopSequences));
671
+ const stop = chatStop(choice, content.some((c) => c.type === "tool_use"), stopList(stopSequences), refusal !== null);
672
+ if (!stop)
673
+ throw new UnfinishedReply(unfinishedChat(choice));
637
674
  return {
638
675
  id: String(res.id ?? `msg_${crypto.randomBytes(8).toString("hex")}`),
639
676
  type: "message",
@@ -696,6 +733,10 @@ export class StreamTranslator {
696
733
  tools = new Map();
697
734
  /** The last choice's stop fields: finish_reason and any matched stop. */
698
735
  finish = {};
736
+ /** The model declined (OpenAI's `delta.refusal`). */
737
+ refused = false;
738
+ /** An `error` chunk the provider sent mid-stream: its words, said at the end. */
739
+ failure = null;
699
740
  usage = null;
700
741
  id = `msg_${crypto.randomBytes(8).toString("hex")}`;
701
742
  model;
@@ -745,13 +786,21 @@ export class StreamTranslator {
745
786
  if (u && (u.prompt_tokens !== undefined || u.completion_tokens !== undefined)) {
746
787
  this.usage = anthropicUsage(u, "chat");
747
788
  }
789
+ // An error chunk (`{"error": {...}}`, no choices): kept, so the end says
790
+ // the provider's own words, not "no finish_reason" (Codex, FOL-211).
791
+ const failed = chunk.error;
792
+ if (failed && typeof failed === "object")
793
+ this.failure = typeof failed.message === "string" && failed.message ? failed.message.slice(0, 300) : "the provider sent an error mid-stream";
748
794
  const choice = (chunk.choices ?? [])[0];
749
795
  if (!choice)
750
796
  return out;
751
797
  if (choice.finish_reason)
752
798
  this.finish = { finish_reason: choice.finish_reason, stop_reason: choice.stop_reason, matched_stop: choice.matched_stop };
753
799
  const delta = choice.delta ?? {};
754
- const text = typeof delta.content === "string" ? delta.content : "";
800
+ // A refusal's words stream as text, so the reader sees why (FOL-211).
801
+ if (typeof delta.refusal === "string" && delta.refusal)
802
+ this.refused = true;
803
+ const text = (typeof delta.content === "string" ? delta.content : "") + (typeof delta.refusal === "string" ? delta.refusal : "");
755
804
  if (text) {
756
805
  if (this.textIndex === null) {
757
806
  this.textIndex = this.nextIndex++;
@@ -817,7 +866,13 @@ export class StreamTranslator {
817
866
  }
818
867
  out.push(this.event("content_block_stop", { type: "content_block_stop", index: entry.block }));
819
868
  }
820
- const stop = chatStop(this.finish, this.tools.size > 0, this.stops);
869
+ const stop = chatStop(this.finish, this.tools.size > 0, this.stops, this.refused);
870
+ // Not a finish the provider said: an Anthropic error event, which a
871
+ // client reads as a failed request, with the provider's own reason.
872
+ if (this.failure || !stop) {
873
+ out.push(this.event("error", { type: "error", error: { type: "api_error", message: this.failure ? `the provider sent an error: ${this.failure}` : unfinishedChat(this.finish) } }));
874
+ return out;
875
+ }
821
876
  out.push(this.event("message_delta", {
822
877
  type: "message_delta",
823
878
  delta: { stop_reason: stop.reason, stop_sequence: stop.sequence },
@@ -851,7 +906,15 @@ export function fromResponses(res, requestedModel) {
851
906
  const usage = res.usage ?? {};
852
907
  const incomplete = res.incomplete_details?.reason;
853
908
  const refused = (Array.isArray(res.output) ? res.output : []).some((item) => item.type === "message" && Array.isArray(item.content) && item.content.some((c) => c.type === "refusal"));
854
- const stop = responsesStop(incomplete, content.some((c) => c.type === "tool_use"), refused);
909
+ // A failed response is the provider's error, never a stop (Codex, FOL-211):
910
+ // it read as end_turn here though the stream already said failed.
911
+ if (res.status === "failed") {
912
+ const err = res.error ?? {};
913
+ throw new UnfinishedReply(typeof err.message === "string" && err.message ? `the provider reported the response failed: ${err.message.slice(0, 300)}` : "the provider reported the response failed");
914
+ }
915
+ const stop = responsesStop(incomplete, content.some((c) => c.type === "tool_use"), refused, res.status === "incomplete" || typeof incomplete === "string");
916
+ if (stop === null)
917
+ throw new UnfinishedReply(unfinishedResponse(incomplete));
855
918
  return {
856
919
  id: String(res.id ?? `msg_${crypto.randomBytes(8).toString("hex")}`),
857
920
  type: "message",
@@ -877,6 +940,8 @@ export class ResponsesStreamTranslator {
877
940
  blocks = new Map();
878
941
  usage = null;
879
942
  incomplete = null;
943
+ /** The stream ended with `response.incomplete` (or a response whose status says so). */
944
+ wasIncomplete = false;
880
945
  sawTool = false;
881
946
  sawRefusal = false;
882
947
  /** The stream's last word: completed or incomplete (an answer), or the
@@ -985,6 +1050,8 @@ export class ResponsesStreamTranslator {
985
1050
  const reason = r.incomplete_details?.reason;
986
1051
  if (typeof reason === "string")
987
1052
  this.incomplete = reason;
1053
+ if (type === "response.incomplete" || r.status === "incomplete")
1054
+ this.wasIncomplete = true;
988
1055
  if (type === "response.failed") {
989
1056
  // A failure is not an answer (Codex review, 10 Nov 2026): it was
990
1057
  // ended as a normal stop, so the caller read a failed reply as done.
@@ -1020,7 +1087,11 @@ export class ResponsesStreamTranslator {
1020
1087
  out.push(this.event("error", { type: "error", error: { type: "api_error", message } }));
1021
1088
  return out;
1022
1089
  }
1023
- const reason = responsesStop(this.incomplete, this.sawTool, this.sawRefusal);
1090
+ const reason = responsesStop(this.incomplete, this.sawTool, this.sawRefusal, this.wasIncomplete);
1091
+ if (reason === null) {
1092
+ out.push(this.event("error", { type: "error", error: { type: "api_error", message: unfinishedResponse(this.incomplete) } }));
1093
+ return out;
1094
+ }
1024
1095
  out.push(this.event("message_delta", {
1025
1096
  type: "message_delta",
1026
1097
  delta: { stop_reason: reason, stop_sequence: null },
@@ -1194,7 +1265,17 @@ export async function startTranslator(spec) {
1194
1265
  return send(502, errorBody(502, `translator: ${label} answered with something that is not JSON`));
1195
1266
  }
1196
1267
  log.push(`POST ${label} → 200 (${Date.now() - started}ms, ${model})`);
1197
- return send(200, JSON.stringify(responses ? fromResponses(parsed, model) : fromChatCompletion(parsed, model, body.stop_sequences, extras)));
1268
+ let reply;
1269
+ try {
1270
+ reply = responses ? fromResponses(parsed, model) : fromChatCompletion(parsed, model, body.stop_sequences, extras);
1271
+ }
1272
+ catch (err) {
1273
+ // A reply the provider did not finish is the provider's error, not a 200 (FOL-211).
1274
+ if (err instanceof UnfinishedReply)
1275
+ return send(502, errorBody(502, `translator: ${label}: ${err.message}`));
1276
+ throw err;
1277
+ }
1278
+ return send(200, JSON.stringify(reply));
1198
1279
  }
1199
1280
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" });
1200
1281
  const machine = responses ? new ResponsesStreamTranslator(model) : new StreamTranslator(model, body.stop_sequences, extras);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "24.7.2",
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
+