@foldrun/core 24.7.2 → 24.8.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.
@@ -45,6 +45,16 @@ interface LoopOptions {
45
45
  * prefix ends: the tools, the system prompt, and the newest message — so
46
46
  * each turn reads everything before it from the cache and writes only
47
47
  * what is new. The conversation itself is never mutated. */
48
+ /** What a turn that asks for no tool comes to. Only a reply the model ended
49
+ * itself (`end_turn`, `stop_sequence`) finishes the step. Until 22 Nov 2026
50
+ * every such turn was "success" — a reply cut off at the output limit
51
+ * included, so a half-written answer passed as a finished step (FOL-211).
52
+ * The partial reply is still the result's text; `errors` says why it is not
53
+ * a finish, the way the SDK's error results do. */
54
+ export declare function endOf(stopReason: string | null, calls: number): {
55
+ subtype: string;
56
+ error?: string;
57
+ };
48
58
  export declare function buildRequest(o: Pick<LoopOptions, "model" | "systemPrompt" | "tools" | "env">, messages: {
49
59
  role: string;
50
60
  content: Block[];
@@ -139,6 +139,31 @@ function requestHeaders(env) {
139
139
  * prefix ends: the tools, the system prompt, and the newest message — so
140
140
  * each turn reads everything before it from the cache and writes only
141
141
  * what is new. The conversation itself is never mutated. */
142
+ /** What a turn that asks for no tool comes to. Only a reply the model ended
143
+ * itself (`end_turn`, `stop_sequence`) finishes the step. Until 22 Nov 2026
144
+ * every such turn was "success" — a reply cut off at the output limit
145
+ * included, so a half-written answer passed as a finished step (FOL-211).
146
+ * The partial reply is still the result's text; `errors` says why it is not
147
+ * a finish, the way the SDK's error results do. */
148
+ export function endOf(stopReason, calls) {
149
+ switch (stopReason) {
150
+ case "end_turn":
151
+ case "stop_sequence":
152
+ return { subtype: "success" };
153
+ case "max_tokens":
154
+ 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" };
155
+ case "refusal":
156
+ return { subtype: "error_refusal", error: "the model declined to answer (stop reason: refusal) — the step did not finish" };
157
+ case "model_context_window_exceeded":
158
+ return { subtype: "error_context_full", error: "the conversation filled the model's context window — the step did not finish" };
159
+ case "tool_use":
160
+ if (!calls)
161
+ return { subtype: "error_empty_tool_turn", error: "the model said it would call a tool and sent none — the step did not finish" };
162
+ return { subtype: "success" };
163
+ default:
164
+ 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` };
165
+ }
166
+ }
142
167
  export function buildRequest(o, messages) {
143
168
  const mark = { cache_control: { type: "ephemeral" } };
144
169
  const tools = o.tools.map((t, i) => ({
@@ -427,7 +452,10 @@ async function* run(prompt, o, signal, interrupted) {
427
452
  if (turn.stopReason === "pause_turn" && !calls.length)
428
453
  continue;
429
454
  if (turn.stopReason !== "tool_use" || !calls.length) {
430
- yield result("success", turn.stopReason);
455
+ const end = endOf(turn.stopReason, calls.length);
456
+ // A turn that did not finish carries ITS text, empty included — not an
457
+ // earlier turn's "I'll check" passed off as a refusal's words (Codex).
458
+ yield end.error ? { ...result(end.subtype, turn.stopReason), result: text, errors: [end.error] } : result(end.subtype, turn.stopReason);
431
459
  return;
432
460
  }
433
461
  const settle = async (block) => {
@@ -754,6 +754,15 @@ async function executeStepInner(opts, runQuery) {
754
754
  if (message.subtype === "error_max_turns") {
755
755
  emit("error", `stopped after ${opts.maxTurns ?? "its"} turns (max_turns: in the flow file) — the step did not finish`);
756
756
  }
757
+ else if (message.subtype !== "success" && opts.engine === "foldrun") {
758
+ // Why it did not finish, when foldrun's loop said: a reply cut off at
759
+ // the output limit, a refusal, a full context (engine-loop.ts endOf).
760
+ // The SDK's own error results are left as they were reported before.
761
+ for (const why of ("errors" in message && Array.isArray(message.errors) ? message.errors : [])) {
762
+ if (typeof why === "string" && why.trim())
763
+ emit("error", why.trim().slice(0, 500));
764
+ }
765
+ }
757
766
  costUsd = "total_cost_usd" in message ? (message.total_cost_usd ?? null) : null;
758
767
  stopReason = "stop_reason" in message && typeof message.stop_reason === "string" ? message.stop_reason : null;
759
768
  if ("num_turns" in message && typeof message.num_turns === "number")
@@ -132,6 +132,11 @@ export declare function toResponses(req: Json, opts: {
132
132
  /** What the endpoint can be shown (FOL-163); this shape takes both by default. */
133
133
  media?: TranslatorMedia;
134
134
  }, drop?: Dropped): Json;
135
+ /** A reply the provider did not finish in a way Anthropic's format can say:
136
+ * the gateway answers it as an error carrying the provider's own reason,
137
+ * never as a normal stop (FOL-211). */
138
+ export declare class UnfinishedReply extends Error {
139
+ }
135
140
  /** A finished Chat Completion as an Anthropic message. Pure. */
136
141
  export declare function fromChatCompletion(res: Json, requestedModel: string, stopSequences?: unknown, extras?: ToolCallExtras): Json;
137
142
  /**
@@ -169,6 +174,10 @@ export declare class StreamTranslator {
169
174
  private tools;
170
175
  /** The last choice's stop fields: finish_reason and any matched stop. */
171
176
  private finish;
177
+ /** The model declined (OpenAI's `delta.refusal`). */
178
+ private refused;
179
+ /** An `error` chunk the provider sent mid-stream: its words, said at the end. */
180
+ private failure;
172
181
  private usage;
173
182
  private id;
174
183
  private readonly model;
@@ -199,6 +208,8 @@ export declare class ResponsesStreamTranslator {
199
208
  private blocks;
200
209
  private usage;
201
210
  private incomplete;
211
+ /** The stream ended with `response.incomplete` (or a response whose status says so). */
212
+ private wasIncomplete;
202
213
  private sawTool;
203
214
  private sawRefusal;
204
215
  /** The stream's last word: completed or incomplete (an answer), or the
@@ -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.0",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
@@ -175,6 +175,31 @@ function requestHeaders(env: Record<string, string | undefined>): Record<string,
175
175
  * prefix ends: the tools, the system prompt, and the newest message — so
176
176
  * each turn reads everything before it from the cache and writes only
177
177
  * what is new. The conversation itself is never mutated. */
178
+ /** What a turn that asks for no tool comes to. Only a reply the model ended
179
+ * itself (`end_turn`, `stop_sequence`) finishes the step. Until 22 Nov 2026
180
+ * every such turn was "success" — a reply cut off at the output limit
181
+ * included, so a half-written answer passed as a finished step (FOL-211).
182
+ * The partial reply is still the result's text; `errors` says why it is not
183
+ * a finish, the way the SDK's error results do. */
184
+ export function endOf(stopReason: string | null, calls: number): { subtype: string; error?: string } {
185
+ switch (stopReason) {
186
+ case "end_turn":
187
+ case "stop_sequence":
188
+ return { subtype: "success" };
189
+ case "max_tokens":
190
+ 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" };
191
+ case "refusal":
192
+ return { subtype: "error_refusal", error: "the model declined to answer (stop reason: refusal) — the step did not finish" };
193
+ case "model_context_window_exceeded":
194
+ return { subtype: "error_context_full", error: "the conversation filled the model's context window — the step did not finish" };
195
+ case "tool_use":
196
+ 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" };
197
+ return { subtype: "success" };
198
+ default:
199
+ 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` };
200
+ }
201
+ }
202
+
178
203
  export function buildRequest(o: Pick<LoopOptions, "model" | "systemPrompt" | "tools" | "env">, messages: { role: string; content: Block[] }[]): Json {
179
204
  const mark = { cache_control: { type: "ephemeral" } };
180
205
  const tools = o.tools.map((t, i) => ({
@@ -445,7 +470,10 @@ async function* run(prompt: string, o: LoopOptions, signal: AbortSignal, interru
445
470
  // conversation back as it stands lets it carry on.
446
471
  if (turn.stopReason === "pause_turn" && !calls.length) continue;
447
472
  if (turn.stopReason !== "tool_use" || !calls.length) {
448
- yield result("success", turn.stopReason);
473
+ const end = endOf(turn.stopReason, calls.length);
474
+ // A turn that did not finish carries ITS text, empty included — not an
475
+ // earlier turn's "I'll check" passed off as a refusal's words (Codex).
476
+ yield end.error ? { ...result(end.subtype, turn.stopReason), result: text, errors: [end.error] } : result(end.subtype, turn.stopReason);
449
477
  return;
450
478
  }
451
479
 
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" });