@foldrun/core 18.5.0 → 19.0.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.
package/src/translator.ts CHANGED
@@ -30,7 +30,7 @@
30
30
 
31
31
  import http from "node:http";
32
32
  import crypto from "node:crypto";
33
- import { PROTECTED_PARAMS } from "./providers.ts";
33
+ import { PROTECTED_PARAMS, providerPreset } from "./providers.ts";
34
34
  import { viaEgress } from "./egress.ts";
35
35
  import { fetchUntrusted } from "./untrusted-fetch.ts";
36
36
  import { trimSlashes } from "./paths.ts";
@@ -74,6 +74,24 @@ function usageBlock(u: { input: number; cached: number; output: number } | null)
74
74
  * (FOL-95). A step never gets it (translatorSpecFor returns null there). */
75
75
  export type TranslatorWire = "chat" | "responses" | "anthropic";
76
76
 
77
+ /** What an endpoint can be shown — images, PDFs. Unset: the format's default. */
78
+ export interface TranslatorMedia {
79
+ images?: boolean;
80
+ pdf?: boolean;
81
+ }
82
+
83
+ /** What the model reads where a file could not be shown to it. */
84
+ export const NOT_SHOWN = {
85
+ image: "[an image was here, but this model endpoint cannot be shown images — it was not delivered]",
86
+ pdf: "[a PDF was here, but this model endpoint cannot be shown PDFs — it was not delivered; read it with a script if you need its text]",
87
+ } as const;
88
+
89
+ function pdfData(block: Json): { filename: string; data: string; mime: string } | null {
90
+ const src = block.source as Json | undefined;
91
+ if (src?.type !== "base64" || typeof src.data !== "string") return null;
92
+ return { filename: typeof block.title === "string" ? block.title : "document.pdf", data: src.data, mime: String(src.media_type ?? "application/pdf") };
93
+ }
94
+
77
95
  export interface TranslatorSpec {
78
96
  /** The provider's base, e.g. https://api.openai.com/v1 — `/chat/completions`
79
97
  * or `/responses` is appended, by `wire`. */
@@ -106,6 +124,11 @@ export interface TranslatorSpec {
106
124
  /** The step's own zone, from the clock cascade — what a reset time in a
107
125
  * refusal is told in. UTC when nothing said otherwise. */
108
126
  timezone?: string;
127
+ /** What the endpoint can be shown (FOL-163), from its preset. Images:
128
+ * yes unless said. PDFs: yes on `responses` (input_file), no on `chat`
129
+ * unless the preset says the endpoint takes Chat's `file` part. What it
130
+ * cannot be shown is not sent, and the model is told so in its place. */
131
+ media?: TranslatorMedia;
109
132
 
110
133
  }
111
134
 
@@ -211,9 +234,13 @@ export function toChatCompletions(
211
234
  params?: Record<string, unknown>;
212
235
  /** What the provider attached to earlier tool calls, to send back. */
213
236
  extras?: ToolCallExtras;
237
+ /** What the endpoint can be shown (FOL-163). */
238
+ media?: TranslatorMedia;
214
239
  },
215
240
  drop: Dropped = dropped(),
216
241
  ): Json {
242
+ const images = opts.media?.images !== false;
243
+ const pdfs = opts.media?.pdf === true;
217
244
  const out: Json = { model: req.model, stream: opts.stream };
218
245
  if (opts.cacheKey) out.prompt_cache_key = opts.cacheKey;
219
246
  const messages: Json[] = [];
@@ -221,9 +248,21 @@ export function toChatCompletions(
221
248
  const system = textOf(req.system);
222
249
  if (system) messages.push({ role: "system", content: system });
223
250
 
224
- for (const m of (Array.isArray(req.messages) ? req.messages : []) as Json[]) {
251
+ const all = (Array.isArray(req.messages) ? req.messages : []) as Json[];
252
+ // A user message's own parts (and the media lifted out of its tool
253
+ // results) wait while the next message is a user message still carrying
254
+ // tool results: Chat Completions wants every result of a turn before any
255
+ // user message (Codex review, FOL-163).
256
+ let carried: Json[] = [];
257
+ const hasToolResult = (x: Json | undefined) => x?.role === "user" && Array.isArray(x.content) && (x.content as Json[]).some((b) => b?.type === "tool_result");
258
+ for (let mi = 0; mi < all.length; mi++) {
259
+ const m = all[mi]!;
225
260
  const content = m.content;
226
261
  if (m.role === "assistant") {
262
+ if (carried.length) {
263
+ messages.push({ role: "user", content: carried.length === 1 && carried[0].type === "text" ? carried[0].text : carried });
264
+ carried = [];
265
+ }
227
266
  const text = textOf(content);
228
267
  const toolCalls: Json[] = [];
229
268
  for (const b of Array.isArray(content) ? (content as Json[]) : []) {
@@ -248,29 +287,76 @@ export function toChatCompletions(
248
287
  }
249
288
  // user
250
289
  if (typeof content === "string") {
251
- messages.push({ role: "user", content });
290
+ if (carried.length) {
291
+ messages.push({ role: "user", content: [...carried, { type: "text", text: content }] });
292
+ carried = [];
293
+ } else messages.push({ role: "user", content });
252
294
  continue;
253
295
  }
254
296
  const parts: Json[] = [];
297
+ // A tool message carries text alone, so what a tool returned that is not
298
+ // text — an image the agent opened, a PDF it read — follows the tool
299
+ // messages in one user message, each labelled with the call it came
300
+ // from (FOL-163). Where the endpoint cannot be shown it, the tool's own
301
+ // message says so, so the model never answers as though it had seen it.
302
+ const lifted: Json[] = [];
255
303
  for (const b of Array.isArray(content) ? (content as Json[]) : []) {
256
304
  if (b.type === "tool_result") {
257
305
  const inner = b.content;
258
306
  const text = typeof inner === "string" ? inner : textOf(inner);
307
+ const notes: string[] = [];
308
+ const attached: Json[] = [];
309
+ for (const x of Array.isArray(inner) ? (inner as Json[]) : []) {
310
+ if (x.type === "image") {
311
+ const p = images ? imagePart(x) : null;
312
+ if (p) attached.push(p);
313
+ else {
314
+ notes.push(NOT_SHOWN.image);
315
+ drop.add("images this endpoint cannot be shown");
316
+ }
317
+ } else if (x.type === "document") {
318
+ const d = pdfs ? pdfData(x) : null;
319
+ if (d) attached.push({ type: "file", file: { filename: d.filename, file_data: `data:${d.mime};base64,${d.data}` } });
320
+ else {
321
+ notes.push(NOT_SHOWN.pdf);
322
+ drop.add("PDFs (this endpoint cannot be shown them)");
323
+ }
324
+ }
325
+ }
326
+ if (attached.length) {
327
+ lifted.push({ type: "text", text: `What the tool call ${String(b.tool_use_id)} returned:` }, ...attached);
328
+ notes.push(`[${attached.length === 1 ? "the file it returned is" : `the ${attached.length} files it returned are`} attached in the next message]`);
329
+ }
330
+ const body = [text, ...notes].filter(Boolean).join("\n");
259
331
  messages.push({
260
332
  role: "tool",
261
333
  tool_call_id: String(b.tool_use_id),
262
- content: text || (b.is_error ? "error" : "ok"),
334
+ content: body || (b.is_error ? "error" : "ok"),
263
335
  });
264
- if (Array.isArray(inner) && (inner as Json[]).some((x) => x.type === "image")) drop.add("images inside tool results");
265
336
  } else if (b.type === "text") {
266
337
  parts.push({ type: "text", text: String(b.text ?? "") });
267
338
  } else if (b.type === "image") {
268
- const p = imagePart(b);
339
+ const p = images ? imagePart(b) : null;
269
340
  if (p) parts.push(p);
341
+ else {
342
+ parts.push({ type: "text", text: NOT_SHOWN.image });
343
+ drop.add("images this endpoint cannot be shown");
344
+ }
270
345
  } else if (b.type === "document") {
271
- drop.add("document blocks");
346
+ const d = pdfs ? pdfData(b) : null;
347
+ if (d) parts.push({ type: "file", file: { filename: d.filename, file_data: `data:${d.mime};base64,${d.data}` } });
348
+ else {
349
+ parts.push({ type: "text", text: NOT_SHOWN.pdf });
350
+ drop.add("PDFs (this endpoint cannot be shown them)");
351
+ }
272
352
  }
273
353
  }
354
+ parts.unshift(...carried, ...lifted);
355
+ carried = [];
356
+ if (parts.length && hasToolResult(all[mi + 1])) {
357
+ carried = parts;
358
+ continue;
359
+ }
274
360
  if (parts.length) {
275
361
  // A single text part reads as a plain string on every endpoint;
276
362
  // a list is only needed when an image is among them.
@@ -370,9 +456,13 @@ export function toResponses(
370
456
  stream: boolean;
371
457
  cacheKey?: string;
372
458
  params?: Record<string, unknown>;
459
+ /** What the endpoint can be shown (FOL-163); this shape takes both by default. */
460
+ media?: TranslatorMedia;
373
461
  },
374
462
  drop: Dropped = dropped(),
375
463
  ): Json {
464
+ const showImages = opts.media?.images !== false;
465
+ const showPdfs = opts.media?.pdf !== false;
376
466
  const out: Json = { model: req.model, stream: opts.stream, store: false };
377
467
  if (opts.cacheKey) out.prompt_cache_key = opts.cacheKey;
378
468
  const system = textOf(req.system);
@@ -402,20 +492,45 @@ export function toResponses(
402
492
  if (b.type === "tool_result") {
403
493
  const inner = b.content;
404
494
  const text = typeof inner === "string" ? inner : textOf(inner);
405
- // A tool result that holds images (a picture the agent opened) is
406
- // sent as a list of parts, which Responses takes in a tool output.
495
+ // A tool result that holds images (a picture the agent opened) or a
496
+ // PDF it read is sent as a list of parts, which Responses takes in a
497
+ // tool output (FOL-163: PDFs too). What this endpoint cannot be shown
498
+ // is said in its place.
499
+ const notes: string[] = [];
407
500
  const images = Array.isArray(inner)
408
- ? (inner as Json[]).flatMap((x) => {
409
- const src = x.type === "image" ? (x.source as Json | undefined) : undefined;
410
- if (src?.type === "base64" && typeof src.data === "string") return [{ type: "input_image", image_url: `data:${String(src.media_type ?? "image/png")};base64,${src.data}`, detail: "auto" }];
411
- if (src?.type === "url" && typeof src.url === "string") return [{ type: "input_image", image_url: src.url, detail: "auto" }];
501
+ ? (inner as Json[]).flatMap((x): Json[] => {
502
+ if (x.type === "image") {
503
+ const src = x.source as Json | undefined;
504
+ if (!showImages) {
505
+ notes.push(NOT_SHOWN.image);
506
+ drop.add("images this endpoint cannot be shown");
507
+ return [];
508
+ }
509
+ if (src?.type === "base64" && typeof src.data === "string") return [{ type: "input_image", image_url: `data:${String(src.media_type ?? "image/png")};base64,${src.data}`, detail: "auto" }];
510
+ if (src?.type === "url" && typeof src.url === "string") return [{ type: "input_image", image_url: src.url, detail: "auto" }];
511
+ return [];
512
+ }
513
+ if (x.type === "document") {
514
+ const d = showPdfs ? pdfData(x) : null;
515
+ if (d) return [{ type: "input_file", filename: d.filename, file_data: `data:${d.mime};base64,${d.data}` }];
516
+ notes.push(NOT_SHOWN.pdf);
517
+ drop.add("PDFs (this endpoint cannot be shown them)");
518
+ return [];
519
+ }
412
520
  return [];
413
521
  })
414
522
  : [];
415
- const output = images.length ? [...(text ? [{ type: "input_text", text }] : []), ...images] : text || (b.is_error ? "error" : "ok");
523
+ const said = [text, ...notes].filter(Boolean).join("\n");
524
+ const output = images.length ? [...(said ? [{ type: "input_text", text: said }] : []), ...images] : said || (b.is_error ? "error" : "ok");
416
525
  input.push({ type: "function_call_output", call_id: String(b.tool_use_id), output });
417
526
  } else if (b.type === "text") {
418
527
  parts.push({ type: "input_text", text: String(b.text ?? "") });
528
+ } else if (b.type === "image" && !showImages) {
529
+ parts.push({ type: "input_text", text: NOT_SHOWN.image });
530
+ drop.add("images this endpoint cannot be shown");
531
+ } else if (b.type === "document" && !showPdfs) {
532
+ parts.push({ type: "input_text", text: NOT_SHOWN.pdf });
533
+ drop.add("PDFs (this endpoint cannot be shown them)");
419
534
  } else if (b.type === "image") {
420
535
  const src = b.source as Json | undefined;
421
536
  if (src?.type === "base64" && typeof src.data === "string") {
@@ -1072,8 +1187,8 @@ export async function startTranslator(spec: TranslatorSpec): Promise<RunningTran
1072
1187
  const drop = dropped();
1073
1188
  const responses = spec.wire === "responses";
1074
1189
  const outbound = responses
1075
- ? toResponses(body, { reasoningEffort: spec.reasoningEffort, params: spec.params, cacheKey: spec.cacheKey, stream }, drop)
1076
- : toChatCompletions(body, { maxTokensParam: spec.maxTokensParam, reasoningEffort: spec.reasoningEffort, params: spec.params, cacheKey: spec.cacheKey, stream, extras }, drop);
1190
+ ? toResponses(body, { reasoningEffort: spec.reasoningEffort, params: spec.params, cacheKey: spec.cacheKey, stream, media: spec.media }, drop)
1191
+ : toChatCompletions(body, { maxTokensParam: spec.maxTokensParam, reasoningEffort: spec.reasoningEffort, params: spec.params, cacheKey: spec.cacheKey, stream, extras, media: spec.media }, drop);
1077
1192
  for (const line of drop.lines()) if (!log.includes(line)) log.push(line);
1078
1193
 
1079
1194
  let upstream: Response;
@@ -1325,6 +1440,8 @@ export function translatorSpecFor(spec: {
1325
1440
  maxTokensParam: spec.maxTokensParam,
1326
1441
  reasoningEffort: spec.reasoningEffort,
1327
1442
  ...(spec.cacheKey ? { cacheKey: spec.cacheKey } : {}),
1443
+ // What the endpoint can be shown, from its preset (FOL-163).
1444
+ ...(spec.name && providerPreset(spec.name)?.media ? { media: providerPreset(spec.name)!.media } : {}),
1328
1445
  label: spec.name ? `${spec.name} (${spec.baseUrl})` : spec.baseUrl,
1329
1446
  };
1330
1447
  }