@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.
@@ -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;
@@ -175,6 +62,31 @@ function requestHeaders(env: Record<string, string | undefined>): Record<string,
175
62
  * prefix ends: the tools, the system prompt, and the newest message — so
176
63
  * each turn reads everything before it from the cache and writes only
177
64
  * what is new. The conversation itself is never mutated. */
65
+ /** What a turn that asks for no tool comes to. Only a reply the model ended
66
+ * itself (`end_turn`, `stop_sequence`) finishes the step. Until 22 Nov 2026
67
+ * every such turn was "success" — a reply cut off at the output limit
68
+ * included, so a half-written answer passed as a finished step (FOL-211).
69
+ * The partial reply is still the result's text; `errors` says why it is not
70
+ * a finish, the way the SDK's error results do. */
71
+ export function endOf(stopReason: string | null, calls: number): { subtype: string; error?: string } {
72
+ switch (stopReason) {
73
+ case "end_turn":
74
+ case "stop_sequence":
75
+ return { subtype: "success" };
76
+ case "max_tokens":
77
+ return { subtype: "error_max_output", error: "the reply was cut off at the output limit (max_output_tokens: in the flow file raises it) — the step did not finish" };
78
+ case "refusal":
79
+ return { subtype: "error_refusal", error: "the model declined to answer (stop reason: refusal) — the step did not finish" };
80
+ case "model_context_window_exceeded":
81
+ return { subtype: "error_context_full", error: "the conversation filled the model's context window — the step did not finish" };
82
+ case "tool_use":
83
+ if (!calls) return { subtype: "error_empty_tool_turn", error: "the model said it would call a tool and sent none — the step did not finish" };
84
+ return { subtype: "success" };
85
+ default:
86
+ return { subtype: "error_unknown_stop", error: `the model stopped for a reason this engine does not know (${stopReason ?? "none given"}) — the step did not finish` };
87
+ }
88
+ }
89
+
178
90
  export function buildRequest(o: Pick<LoopOptions, "model" | "systemPrompt" | "tools" | "env">, messages: { role: string; content: Block[] }[]): Json {
179
91
  const mark = { cache_control: { type: "ephemeral" } };
180
92
  const tools = o.tools.map((t, i) => ({
@@ -240,18 +152,29 @@ async function openStream(o: LoopOptions, body: Json, signal: AbortSignal): Prom
240
152
  async function* sse(res: Response): AsyncGenerator<Json> {
241
153
  const decoder = new TextDecoder();
242
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 = "";
243
159
  for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {
244
- buffer += decoder.decode(chunk, { stream: true });
245
- 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")) {
246
165
  const frame = buffer.slice(0, at);
247
- buffer = buffer.slice(at).replace(/^\r?\n\r?\n/, "");
248
- 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");
249
168
  if (!data || data === "[DONE]") continue;
169
+ let parsed: Json;
250
170
  try {
251
- yield JSON.parse(data) as Json;
171
+ parsed = JSON.parse(data) as Json;
252
172
  } catch {
253
- // 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");
254
176
  }
177
+ yield parsed;
255
178
  }
256
179
  }
257
180
  }
@@ -266,18 +189,6 @@ interface Turn {
266
189
  malformed: Set<string>;
267
190
  }
268
191
 
269
- const emptyUsage = (): Usage => ({ input_tokens: 0, output_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 });
270
-
271
- function addUsage(into: Usage, u: Partial<Record<keyof Usage, unknown>> | undefined): void {
272
- if (!u) return;
273
- // The closing delta repeats the counts it knows; one that leaves the input
274
- // side at zero is not saying the input was free.
275
- for (const k of Object.keys(into) as (keyof Usage)[]) {
276
- const v = u[k];
277
- if (typeof v === "number" && (v > 0 || k === "output_tokens")) into[k] = v;
278
- }
279
- }
280
-
281
192
  /** One model call: yields the raw stream events, returns the whole turn. */
282
193
  async function* modelTurn(o: LoopOptions, messages: { role: string; content: Block[] }[], signal: AbortSignal): AsyncGenerator<Json, Turn> {
283
194
  const res = await openStream(o, buildRequest(o, messages), signal);
@@ -337,45 +248,6 @@ async function* modelTurn(o: LoopOptions, messages: { role: string; content: Blo
337
248
  return turn;
338
249
  }
339
250
 
340
- interface Decision {
341
- input: Json;
342
- refusal: string | null;
343
- }
344
-
345
- /** May this call run, and with what input? The order the SDK kept, which
346
- * step-exec's checks are written against: every PreToolUse hook first — a
347
- * deny ends it, an allow carries the input the hook settled on and skips
348
- * the question below — then canUseTool, where confinement lives. */
349
- async function decide(o: LoopOptions, name: string, id: string, input: Json, sessionId: string, signal: AbortSignal): Promise<Decision> {
350
- let current = input;
351
- let allowed = false;
352
- for (const hook of o.pre) {
353
- 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 });
354
- const d = (out as { hookSpecificOutput?: { permissionDecision?: string; permissionDecisionReason?: string; updatedInput?: Json } } | undefined)?.hookSpecificOutput;
355
- if (!d) continue;
356
- if (d.permissionDecision === "deny") return { input: current, refusal: d.permissionDecisionReason || `${name} was refused` };
357
- if (d.updatedInput) current = d.updatedInput;
358
- if (d.permissionDecision === "allow") allowed = true;
359
- }
360
- if (!allowed && o.canUseTool) {
361
- const r = await o.canUseTool(name, current, { signal, toolUseID: id });
362
- if (r.behavior === "deny") return { input: current, refusal: r.message || `${name} was refused` };
363
- if (r.updatedInput) current = r.updatedInput;
364
- }
365
- return { input: current, refusal: null };
366
- }
367
-
368
- /** After a call: tell the PostToolUse hooks, and collect what they add. */
369
- async function after(o: LoopOptions, name: string, id: string, input: Json, outcome: ToolOutcome, sessionId: string, signal: AbortSignal): Promise<string[]> {
370
- const added: string[] = [];
371
- for (const hook of o.post) {
372
- 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 });
373
- const context = (out as { hookSpecificOutput?: { additionalContext?: string } } | undefined)?.hookSpecificOutput?.additionalContext;
374
- if (context) added.push(context);
375
- }
376
- return added;
377
- }
378
-
379
251
  async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interrupted: () => boolean): AsyncGenerator<Json> {
380
252
  const sessionId = crypto.randomUUID();
381
253
  const startedAt = Date.now();
@@ -445,7 +317,10 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
445
317
  // conversation back as it stands lets it carry on.
446
318
  if (turn.stopReason === "pause_turn" && !calls.length) continue;
447
319
  if (turn.stopReason !== "tool_use" || !calls.length) {
448
- yield result("success", turn.stopReason);
320
+ const end = endOf(turn.stopReason, calls.length);
321
+ // A turn that did not finish carries ITS text, empty included — not an
322
+ // earlier turn's "I'll check" passed off as a refusal's words (Codex).
323
+ yield end.error ? { ...result(end.subtype, turn.stopReason), result: text, errors: [end.error] } : result(end.subtype, turn.stopReason);
449
324
  return;
450
325
  }
451
326
 
package/src/step-exec.ts CHANGED
@@ -941,6 +941,13 @@ async function executeStepInner(opts: ExecOptions, runQuery: QueryFn): Promise<E
941
941
  }
942
942
  if (message.subtype === "error_max_turns") {
943
943
  emit("error", `stopped after ${opts.maxTurns ?? "its"} turns (max_turns: in the flow file) — the step did not finish`);
944
+ } else if (message.subtype !== "success" && opts.engine === "foldrun") {
945
+ // Why it did not finish, when foldrun's loop said: a reply cut off at
946
+ // the output limit, a refusal, a full context (engine-loop.ts endOf).
947
+ // The SDK's own error results are left as they were reported before.
948
+ for (const why of ("errors" in message && Array.isArray(message.errors) ? message.errors : [])) {
949
+ if (typeof why === "string" && why.trim()) emit("error", why.trim().slice(0, 500));
950
+ }
944
951
  }
945
952
  costUsd = "total_cost_usd" in message ? (message.total_cost_usd ?? null) : null;
946
953
  stopReason = "stop_reason" in message && typeof message.stop_reason === "string" ? message.stop_reason : null;
package/src/translator.ts CHANGED
@@ -631,21 +631,52 @@ type Stop = { reason: string; sequence: string | null };
631
631
  * request asked for; plain OpenAI says `stop` either way, which reads as
632
632
  * end_turn. pause_turn has no counterpart: server-side tools are dropped.
633
633
  */
634
- function chatStop(choice: Json, sawTool: boolean, stops: readonly string[]): Stop {
635
- const finish = choice.finish_reason;
636
- if (finish === "content_filter") return { reason: "refusal", sequence: null };
634
+ function chatStop(choice: Json, sawTool: boolean, stops: readonly string[], sawRefusal = false): Stop | null {
635
+ const finish = typeof choice.finish_reason === "string" ? choice.finish_reason.toLowerCase() : choice.finish_reason;
636
+ // OpenAI's `message.refusal` / `delta.refusal` (FOL-211, Codex review):
637
+ // a declined reply came back as an empty end_turn until 22 Nov 2026.
638
+ if (sawRefusal || finish === "content_filter") return { reason: "refusal", sequence: null };
637
639
  if (finish === "length") return { reason: "max_tokens", sequence: null };
638
640
  if (finish === "model_length") return { reason: "model_context_window_exceeded", sequence: null };
639
- if (sawTool || finish === "tool_calls" || finish === "function_call") return { reason: "tool_use", sequence: null };
641
+ if (finish === "tool_calls" || finish === "function_call") return { reason: "tool_use", sequence: null };
642
+ // Only a finish the provider SAID is one (FOL-211, Codex review, 22 Nov
643
+ // 2026): vLLM, SGLang and Gemini's OpenAI endpoint all send a reason on a
644
+ // normal finish. Until then a missing or unknown one read as end_turn, or
645
+ // as tool_use dispatching a call the provider never confirmed. `stop` with
646
+ // tool calls in it is Gemini's way of ending a tool turn, and stays one.
647
+ if (finish !== "stop") return null;
648
+ if (sawTool) return { reason: "tool_use", sequence: null };
640
649
  const matched = typeof choice.stop_reason === "string" ? choice.stop_reason : choice.matched_stop;
641
650
  if (typeof matched === "string" && stops.includes(matched)) return { reason: "stop_sequence", sequence: matched };
642
651
  return { reason: "end_turn", sequence: null };
643
652
  }
644
653
 
645
- /** Why a Response stopped: a refusal part or a content filter is a refusal. */
646
- function responsesStop(incomplete: unknown, sawTool: boolean, sawRefusal: boolean): string {
654
+ /** A reply the provider did not finish in a way Anthropic's format can say:
655
+ * the gateway answers it as an error carrying the provider's own reason,
656
+ * never as a normal stop (FOL-211). */
657
+ export class UnfinishedReply extends Error {}
658
+
659
+ function unfinishedResponse(reason: unknown): string {
660
+ return `the provider ended the response incomplete (${typeof reason === "string" && reason ? `reason: ${reason.slice(0, 60)}` : "no reason given"})`;
661
+ }
662
+
663
+ function unfinishedChat(choice: Json): string {
664
+ const r = choice.finish_reason;
665
+ 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)";
666
+ }
667
+
668
+ /** Why a Response stopped: a refusal part or a content filter is a refusal.
669
+ * An incomplete response is never a finish: with a reason this does not
670
+ * know, or none, it is null — an error naming it. It was a finish
671
+ * (`end_turn`, or `tool_use` dispatching a half-made call) until 22 Nov
672
+ * 2026 (FOL-211, Codex review). */
673
+ function responsesStop(incomplete: unknown, sawTool: boolean, sawRefusal: boolean, wasIncomplete = false): string | null {
647
674
  if (sawRefusal || incomplete === "content_filter") return "refusal";
648
675
  if (incomplete === "max_output_tokens") return "max_tokens";
676
+ // Incomplete for a reason this does not know, or none: an error with that
677
+ // reason — not max_tokens, which would tell a person to raise a limit the
678
+ // provider never named (Codex review, 22 Nov 2026).
679
+ if (wasIncomplete || (typeof incomplete === "string" && incomplete)) return null;
649
680
  if (sawTool) return "tool_use";
650
681
  return "end_turn";
651
682
  }
@@ -670,6 +701,8 @@ export function fromChatCompletion(res: Json, requestedModel: string, stopSequen
670
701
  const content: Json[] = [];
671
702
  const text = typeof msg.content === "string" ? msg.content : textOf(msg.content);
672
703
  if (text) content.push({ type: "text", text });
704
+ const refusal = typeof msg.refusal === "string" && msg.refusal.trim() ? msg.refusal : null;
705
+ if (refusal) content.push({ type: "text", text: refusal });
673
706
  for (const tc of (Array.isArray(msg.tool_calls) ? msg.tool_calls : []) as Json[]) {
674
707
  const fn = (tc.function as Json | undefined) ?? {};
675
708
  const id = String(tc.id ?? `call_${crypto.randomBytes(6).toString("hex")}`);
@@ -682,7 +715,8 @@ export function fromChatCompletion(res: Json, requestedModel: string, stopSequen
682
715
  });
683
716
  }
684
717
  const usage = (res.usage as Json | undefined) ?? {};
685
- const stop = chatStop(choice, content.some((c) => c.type === "tool_use"), stopList(stopSequences));
718
+ const stop = chatStop(choice, content.some((c) => c.type === "tool_use"), stopList(stopSequences), refusal !== null);
719
+ if (!stop) throw new UnfinishedReply(unfinishedChat(choice));
686
720
  return {
687
721
  id: String(res.id ?? `msg_${crypto.randomBytes(8).toString("hex")}`),
688
722
  type: "message",
@@ -745,6 +779,10 @@ export class StreamTranslator {
745
779
  private tools = new Map<number, { block: number; argsSeen: boolean; id: string }>();
746
780
  /** The last choice's stop fields: finish_reason and any matched stop. */
747
781
  private finish: Json = {};
782
+ /** The model declined (OpenAI's `delta.refusal`). */
783
+ private refused = false;
784
+ /** An `error` chunk the provider sent mid-stream: its words, said at the end. */
785
+ private failure: string | null = null;
748
786
  private usage: { input: number; cached: number; output: number } | null = null;
749
787
  private id = `msg_${crypto.randomBytes(8).toString("hex")}`;
750
788
  private readonly model: string;
@@ -795,12 +833,18 @@ export class StreamTranslator {
795
833
  if (u && (u.prompt_tokens !== undefined || u.completion_tokens !== undefined)) {
796
834
  this.usage = anthropicUsage(u, "chat");
797
835
  }
836
+ // An error chunk (`{"error": {...}}`, no choices): kept, so the end says
837
+ // the provider's own words, not "no finish_reason" (Codex, FOL-211).
838
+ const failed = chunk.error as Json | undefined;
839
+ if (failed && typeof failed === "object") this.failure = typeof failed.message === "string" && failed.message ? failed.message.slice(0, 300) : "the provider sent an error mid-stream";
798
840
  const choice = ((chunk.choices as Json[] | undefined) ?? [])[0];
799
841
  if (!choice) return out;
800
842
  if (choice.finish_reason) this.finish = { finish_reason: choice.finish_reason, stop_reason: choice.stop_reason, matched_stop: choice.matched_stop };
801
843
  const delta = (choice.delta as Json | undefined) ?? {};
802
844
 
803
- const text = typeof delta.content === "string" ? delta.content : "";
845
+ // A refusal's words stream as text, so the reader sees why (FOL-211).
846
+ if (typeof delta.refusal === "string" && delta.refusal) this.refused = true;
847
+ const text = (typeof delta.content === "string" ? delta.content : "") + (typeof delta.refusal === "string" ? delta.refusal : "");
804
848
  if (text) {
805
849
  if (this.textIndex === null) {
806
850
  this.textIndex = this.nextIndex++;
@@ -878,7 +922,13 @@ export class StreamTranslator {
878
922
  }
879
923
  out.push(this.event("content_block_stop", { type: "content_block_stop", index: entry.block }));
880
924
  }
881
- const stop = chatStop(this.finish, this.tools.size > 0, this.stops);
925
+ const stop = chatStop(this.finish, this.tools.size > 0, this.stops, this.refused);
926
+ // Not a finish the provider said: an Anthropic error event, which a
927
+ // client reads as a failed request, with the provider's own reason.
928
+ if (this.failure || !stop) {
929
+ out.push(this.event("error", { type: "error", error: { type: "api_error", message: this.failure ? `the provider sent an error: ${this.failure}` : unfinishedChat(this.finish) } }));
930
+ return out;
931
+ }
882
932
  out.push(
883
933
  this.event("message_delta", {
884
934
  type: "message_delta",
@@ -915,7 +965,14 @@ export function fromResponses(res: Json, requestedModel: string): Json {
915
965
  const refused = (Array.isArray(res.output) ? (res.output as Json[]) : []).some(
916
966
  (item) => item.type === "message" && Array.isArray(item.content) && (item.content as Json[]).some((c) => c.type === "refusal"),
917
967
  );
918
- const stop = responsesStop(incomplete, content.some((c) => c.type === "tool_use"), refused);
968
+ // A failed response is the provider's error, never a stop (Codex, FOL-211):
969
+ // it read as end_turn here though the stream already said failed.
970
+ if (res.status === "failed") {
971
+ const err = (res.error as Json | undefined) ?? {};
972
+ 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");
973
+ }
974
+ const stop = responsesStop(incomplete, content.some((c) => c.type === "tool_use"), refused, res.status === "incomplete" || typeof incomplete === "string");
975
+ if (stop === null) throw new UnfinishedReply(unfinishedResponse(incomplete));
919
976
  return {
920
977
  id: String(res.id ?? `msg_${crypto.randomBytes(8).toString("hex")}`),
921
978
  type: "message",
@@ -942,6 +999,8 @@ export class ResponsesStreamTranslator {
942
999
  private blocks = new Map<number, { block: number; kind: "text" | "tool"; argsSeen: boolean }>();
943
1000
  private usage: { input: number; cached: number; output: number } | null = null;
944
1001
  private incomplete: string | null = null;
1002
+ /** The stream ended with `response.incomplete` (or a response whose status says so). */
1003
+ private wasIncomplete = false;
945
1004
  private sawTool = false;
946
1005
  private sawRefusal = false;
947
1006
  /** The stream's last word: completed or incomplete (an answer), or the
@@ -1049,6 +1108,7 @@ export class ResponsesStreamTranslator {
1049
1108
  if (u) this.usage = anthropicUsage(u, "responses");
1050
1109
  const reason = (r.incomplete_details as Json | undefined)?.reason;
1051
1110
  if (typeof reason === "string") this.incomplete = reason;
1111
+ if (type === "response.incomplete" || r.status === "incomplete") this.wasIncomplete = true;
1052
1112
  if (type === "response.failed") {
1053
1113
  // A failure is not an answer (Codex review, 10 Nov 2026): it was
1054
1114
  // ended as a normal stop, so the caller read a failed reply as done.
@@ -1082,7 +1142,11 @@ export class ResponsesStreamTranslator {
1082
1142
  out.push(this.event("error", { type: "error", error: { type: "api_error", message } }));
1083
1143
  return out;
1084
1144
  }
1085
- const reason = responsesStop(this.incomplete, this.sawTool, this.sawRefusal);
1145
+ const reason = responsesStop(this.incomplete, this.sawTool, this.sawRefusal, this.wasIncomplete);
1146
+ if (reason === null) {
1147
+ out.push(this.event("error", { type: "error", error: { type: "api_error", message: unfinishedResponse(this.incomplete) } }));
1148
+ return out;
1149
+ }
1086
1150
  out.push(
1087
1151
  this.event("message_delta", {
1088
1152
  type: "message_delta",
@@ -1258,7 +1322,15 @@ export async function startTranslator(spec: TranslatorSpec): Promise<RunningTran
1258
1322
  return send(502, errorBody(502, `translator: ${label} answered with something that is not JSON`));
1259
1323
  }
1260
1324
  log.push(`POST ${label} → 200 (${Date.now() - started}ms, ${model})`);
1261
- return send(200, JSON.stringify(responses ? fromResponses(parsed, model) : fromChatCompletion(parsed, model, body.stop_sequences, extras)));
1325
+ let reply: Json;
1326
+ try {
1327
+ reply = responses ? fromResponses(parsed, model) : fromChatCompletion(parsed, model, body.stop_sequences, extras);
1328
+ } catch (err) {
1329
+ // A reply the provider did not finish is the provider's error, not a 200 (FOL-211).
1330
+ if (err instanceof UnfinishedReply) return send(502, errorBody(502, `translator: ${label}: ${err.message}`));
1331
+ throw err;
1332
+ }
1333
+ return send(200, JSON.stringify(reply));
1262
1334
  }
1263
1335
 
1264
1336
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" });