@foldrun/core 18.5.0 → 19.1.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/store.ts CHANGED
@@ -72,6 +72,7 @@ import { providerPreset, looksOpenAiShaped, PROTECTED_PARAMS, type WireFormat, t
72
72
  import { starterFiles, accountFiles, blankWorkspaceFiles } from "./starter.ts";
73
73
  import { trimSlashes, MAX_EDITABLE_FILE } from "./paths.ts";
74
74
  import type { RunContext, RunInput, ConversationRecord } from "./conversation.ts";
75
+ import type { RunInputFile } from "./storage.ts";
75
76
 
76
77
  // Where workspaces live. The hosted app keeps many under data/; the CLI runs
77
78
  // against one folder, which is what `foldrun run ./my-desk` has to mean.
@@ -3803,6 +3804,11 @@ export interface StepRecord {
3803
3804
  /** What that step was given, written when it starts: which runs, how many
3804
3805
  * did not fit, and a hash of the block (conversation.ts). Never the text. */
3805
3806
  history?: ConversationRecord;
3807
+ /** FOL-163: this step is handed the run's `inputs`, staged at
3808
+ * agents/<name>/inputs/. Set when the run is made on the step the task
3809
+ * reaches; fan-out instances and an on-fail rescue inherit it; a re-run
3810
+ * sets it on the first step it runs. */
3811
+ inputsTurn?: boolean;
3806
3812
  /** On an isolated sub-agent's run: the workspace paths its sandbox's
3807
3813
  * changes were applied to — what its delegating step is told it wrote. */
3808
3814
  wrote?: string[];
@@ -4024,6 +4030,13 @@ export interface RunRecord {
4024
4030
  * an A2A message's text and data. Kept on a run with a `context`, so a
4025
4031
  * later turn reads the question, never a step's decorated instruction. */
4026
4032
  input?: RunInput;
4033
+ /** FOL-163: the files the run was handed — storage paths and the blob each
4034
+ * named when the run was made (held for it; storage.ts holdRunInputs). */
4035
+ inputs?: RunInputFile[];
4036
+ /** FOL-168: which of the partner's own users this run is for — an opaque
4037
+ * id the partner maps (customer.ts). Limits, blocks and the provider's
4038
+ * end-user id follow it. Set when the run is made, carried on a re-run. */
4039
+ customer?: string;
4027
4040
  steps: StepRecord[];
4028
4041
  }
4029
4042
 
@@ -4095,7 +4108,13 @@ export function deleteRun(tenant: string, workspace: string, runId: string, opts
4095
4108
  const file = runFilePath(tenant, workspace, runId);
4096
4109
  const dir = path.join(workspaceDir(tenant, workspace), "runs", runId);
4097
4110
  const port = records(tenant, workspace);
4098
- const had = port ? port.runGet(tenant, workspace, runId) !== null : fs.existsSync(file);
4111
+ let prior: RunRecord | null = null;
4112
+ try {
4113
+ prior = port ? port.runGet(tenant, workspace, runId) : fs.existsSync(file) ? (JSON.parse(fs.readFileSync(file, "utf8")) as RunRecord) : null;
4114
+ } catch {
4115
+ prior = null; // a half-written record still goes
4116
+ }
4117
+ const had = port ? prior !== null : fs.existsSync(file);
4099
4118
  if (!had && !fs.existsSync(dir)) return false;
4100
4119
  // The folder first (archived outputs, captured calls), the record last:
4101
4120
  // a delete that fails halfway leaves the record, so a retry finds the run
@@ -4107,6 +4126,12 @@ export function deleteRun(tenant: string, workspace: string, runId: string, opts
4107
4126
  fs.rmSync(file, { force: true });
4108
4127
  noteRunDeleted(path.dirname(file), runId);
4109
4128
  }
4129
+ // Its held inputs go with it (FOL-163): a blob nothing else names is
4130
+ // collected. Asynchronous, and never the delete's failure — storage's own
4131
+ // sweep (sweepHeldInputs) finds any a crash left behind.
4132
+ if (prior?.inputs?.length) {
4133
+ void import("./storage.ts").then((m) => m.releaseRunInputs(tenant, workspace, runId)).catch(() => {});
4134
+ }
4110
4135
  if (!had) return true;
4111
4136
  // The retention window's prune (`pruned`) is policy, not a person erasing
4112
4137
  // history: no per-run ledger note. The charge stands either way.
@@ -4428,6 +4453,8 @@ export interface RunSummary {
4428
4453
  a2a?: { task: string; key: string };
4429
4454
  /** RunRecord.context: the conversation it belongs to (FOL-162). */
4430
4455
  context?: RunContext;
4456
+ /** RunRecord.customer (FOL-168). */
4457
+ customer?: string;
4431
4458
  steps: RunSummaryStep[];
4432
4459
  }
4433
4460
 
@@ -4473,6 +4500,7 @@ export function summarizeRun(run: RunRecord): RunSummary {
4473
4500
  ...(run.trigger ? { trigger: run.trigger } : {}),
4474
4501
  ...(run.a2a ? { a2a: run.a2a } : {}),
4475
4502
  ...(run.context ? { context: run.context } : {}),
4503
+ ...(run.customer ? { customer: run.customer } : {}),
4476
4504
  awaitingApproval: run.steps.some((s) => s.status === "awaiting-approval" && s.waitFor !== "event"),
4477
4505
  steps: run.steps.map((s) => {
4478
4506
  // A failed step's last error — and, on a run that failed between
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
  }