@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.
@@ -142,6 +142,152 @@ export function assertFilePath(rel) {
142
142
  throw new Error(`illegal file path: ${rel}`);
143
143
  return norm;
144
144
  }
145
+ // ---------- foldrun's own records: a run's held inputs (FOL-163) ----------
146
+ //
147
+ // A run with `inputs` reads the files as they were when it was made, not as
148
+ // they are when its step starts: an overwrite or a delete in between changes
149
+ // nothing it reads. Each input is held by a record of foldrun's own under
150
+ // `.foldrun/run-inputs/<runId>/<path>`, naming the same blob — zero copies,
151
+ // and the collector (collectLocked) keeps a blob while any record names it,
152
+ // so nothing new had to learn about holds. Those records are never listed,
153
+ // mirrored into a sandbox or harvested, and no person's write, upload or
154
+ // delete may name the prefix; they go when the run's record does.
155
+ const RESERVED = ".foldrun";
156
+ export const RUN_INPUTS_PREFIX = `${RESERVED}/run-inputs/`;
157
+ /** A path under foldrun's own prefix. */
158
+ export function isReservedPath(rel) {
159
+ return rel === RESERVED || rel.startsWith(`${RESERVED}/`);
160
+ }
161
+ /** Refuse foldrun's own prefix on a person's or a run's write. */
162
+ export function assertNotReserved(norm) {
163
+ if (isReservedPath(norm))
164
+ throw new Error(`${norm}: storage/${RESERVED}/ is foldrun's own — choose another path`);
165
+ return norm;
166
+ }
167
+ /** An input path that names no stored file (or a reserved one). */
168
+ export class MissingInput extends Error {
169
+ path;
170
+ constructor(path) {
171
+ super(`no stored file ${path}`);
172
+ this.path = path;
173
+ }
174
+ }
175
+ const heldPath = (runId, rel) => `${RUN_INPUTS_PREFIX}${runId}/${rel}`;
176
+ /**
177
+ * Resolve `paths` (storage-relative, as GET …/storage lists them) to the
178
+ * blob each names now. Throws MissingInput for a path with no record.
179
+ * Returns them in the order given, duplicates dropped. Holds nothing:
180
+ * holdRunInputs does, once the run exists.
181
+ */
182
+ export function resolveRunInputs(tenant, workspace, paths) {
183
+ const files = readIndex(tenant, workspace).files;
184
+ const out = [];
185
+ const seen = new Set();
186
+ for (const p of paths) {
187
+ let norm;
188
+ try {
189
+ norm = assertFilePath(p);
190
+ }
191
+ catch {
192
+ throw new MissingInput(p);
193
+ }
194
+ if (isReservedPath(norm))
195
+ throw new MissingInput(norm);
196
+ if (seen.has(norm))
197
+ continue;
198
+ seen.add(norm);
199
+ const rec = files.find((f) => f.path === norm);
200
+ if (!rec)
201
+ throw new MissingInput(norm);
202
+ out.push({ path: norm, sha: rec.sha, size: rec.size, mime: rec.mime });
203
+ }
204
+ return out;
205
+ }
206
+ /**
207
+ * Hold `inputs` for `runId`, under the workspace's lock: from here no
208
+ * overwrite or delete can take the bytes the run will read. Each blob must
209
+ * still be named by some record — the file itself, or another run's hold (a
210
+ * re-run reads what its source read). Throws MissingInput for one that is
211
+ * gone; nothing is held then.
212
+ */
213
+ export async function holdRunInputs(tenant, workspace, runId, inputs) {
214
+ assertSafeName(runId, "run id");
215
+ await withFileStoreLock(tenant, workspace, async () => {
216
+ const shas = new Set(readIndex(tenant, workspace).files.map((f) => f.sha));
217
+ for (const i of inputs)
218
+ if (!shas.has(i.sha))
219
+ throw new MissingInput(i.path);
220
+ holdLocked(tenant, workspace, runId, inputs);
221
+ });
222
+ }
223
+ function holdLocked(tenant, workspace, runId, inputs) {
224
+ const now = new Date().toISOString();
225
+ for (const i of inputs) {
226
+ // Re-read each time: the file store rewrites the whole index per put.
227
+ indexPut(tenant, workspace, readIndex(tenant, workspace), { path: heldPath(runId, i.path), sha: i.sha, size: i.size, mime: i.mime, updatedAt: now, by: `run:${runId}:inputs` });
228
+ }
229
+ }
230
+ /** Let go of a run's held inputs; a blob nothing else names is collected. */
231
+ export async function releaseRunInputs(tenant, workspace, runId) {
232
+ if (!fileStoreEnabled())
233
+ return 0;
234
+ const prefix = `${RUN_INPUTS_PREFIX}${runId}/`;
235
+ return withFileStoreLock(tenant, workspace, async () => {
236
+ const held = readIndex(tenant, workspace).files.filter((f) => f.path.startsWith(prefix));
237
+ for (const f of held)
238
+ indexRemove(tenant, workspace, readIndex(tenant, workspace), f.path);
239
+ for (const sha of new Set(held.map((f) => f.sha)))
240
+ await collectLocked(tenant, workspace, sha);
241
+ return held.length;
242
+ });
243
+ }
244
+ /** Let go of the holds of runs that no longer exist — what a crash between
245
+ * a run's delete and its release left. `alive` says whether a run is there.
246
+ * Returns how many runs' holds went. */
247
+ export async function sweepHeldInputs(tenant, workspace, alive) {
248
+ if (!fileStoreEnabled())
249
+ return 0;
250
+ const runs = new Set(readIndex(tenant, workspace)
251
+ .files.filter((f) => f.path.startsWith(RUN_INPUTS_PREFIX))
252
+ .map((f) => f.path.slice(RUN_INPUTS_PREFIX.length).split("/")[0])
253
+ .filter(Boolean));
254
+ let gone = 0;
255
+ for (const runId of runs) {
256
+ if (alive(runId))
257
+ continue;
258
+ if ((await releaseRunInputs(tenant, workspace, runId)) > 0)
259
+ gone++;
260
+ }
261
+ return gone;
262
+ }
263
+ /**
264
+ * Write a run's held inputs into `intoDir` (made fresh: whatever was there
265
+ * is removed first, so a folder of the same name never mixes in), each at
266
+ * its storage path. Reads the blob each input named when the run was made,
267
+ * never the path again. Throws when one is gone.
268
+ */
269
+ export async function stageRunInputs(tenant, workspace, runId, inputs, intoDir) {
270
+ fs.rmSync(intoDir, { recursive: true, force: true });
271
+ fs.mkdirSync(intoDir, { recursive: true });
272
+ const held = new Set(readIndex(tenant, workspace).files.filter((f) => f.path.startsWith(`${RUN_INPUTS_PREFIX}${runId}/`)).map((f) => f.sha));
273
+ const driver = driverFor(tenant, workspace);
274
+ let bytes = 0;
275
+ for (const i of inputs) {
276
+ const norm = assertFilePath(i.path);
277
+ if (!held.has(i.sha))
278
+ throw new MissingInput(norm);
279
+ const body = await driver.get(blobKey(tenant, workspace, i.sha));
280
+ if (sha256(body) !== i.sha)
281
+ throw new Error(`input ${norm}: the stored bytes do not match what the run was given`);
282
+ const abs = path.join(intoDir, norm);
283
+ if (!abs.startsWith(intoDir + path.sep))
284
+ throw new MissingInput(norm);
285
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
286
+ fs.writeFileSync(abs, body, { flag: "wx" });
287
+ bytes += body.length;
288
+ }
289
+ return { files: inputs.length, bytes };
290
+ }
145
291
  // ---------- mime ----------
146
292
  const MIME = {
147
293
  ".pdf": "application/pdf",
@@ -215,7 +361,8 @@ function indexRemove(tenant, workspace, index, rel) {
215
361
  writeIndex(tenant, workspace, { version: 1, files: index.files.filter((f) => f.path !== rel) });
216
362
  }
217
363
  export function listStorage(tenant, workspace) {
218
- return readIndex(tenant, workspace).files.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
364
+ // foldrun's own records (a run's held inputs) are not the workspace's files.
365
+ return readIndex(tenant, workspace).files.filter((f) => !isReservedPath(f.path)).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
219
366
  }
220
367
  export function getFile(tenant, workspace, rel) {
221
368
  const norm = assertFilePath(rel);
@@ -766,7 +913,7 @@ export async function putFile(tenant, workspace, rel, body, by) {
766
913
  return record;
767
914
  }
768
915
  async function putFileQuietly(tenant, workspace, rel, body, by) {
769
- const norm = assertFilePath(rel);
916
+ const norm = assertNotReserved(assertFilePath(rel));
770
917
  if (body.length > maxBytes()) {
771
918
  throw new Error(`${norm} is ${Math.round(body.length / 1e6)}MB — the limit is ${maxBytes() / 1e6}MB`);
772
919
  }
@@ -828,7 +975,7 @@ async function putFileQuietly(tenant, workspace, rel, body, by) {
828
975
  * claim, so an object registered as 0 bytes (or -1e12) sat outside every
829
976
  * limit and lowered the quota line for everything after it. */
830
977
  export async function registerUpload(tenant, workspace, rel, sha, _claimed, by) {
831
- const norm = assertFilePath(rel);
978
+ const norm = assertNotReserved(assertFilePath(rel));
832
979
  if (!/^[0-9a-f]{64}$/.test(sha))
833
980
  throw new Error("expected a sha256");
834
981
  requireWorkspace(tenant, workspace);
@@ -909,7 +1056,7 @@ export async function openFile(tenant, workspace, rel, range) {
909
1056
  return { record, size, body: await driver.open(key, range ?? undefined) };
910
1057
  }
911
1058
  export async function deleteFile(tenant, workspace, rel) {
912
- const norm = assertFilePath(rel);
1059
+ const norm = assertNotReserved(assertFilePath(rel));
913
1060
  return withFileStoreLock(tenant, workspace, async () => {
914
1061
  const index = readIndex(tenant, workspace);
915
1062
  const record = index.files.find((f) => f.path === norm);
@@ -966,7 +1113,7 @@ export function previewType(rel) {
966
1113
  }
967
1114
  /** A link the browser can PUT to, plus the key it will land at. Null on fs. */
968
1115
  export async function uploadUrl(tenant, workspace, rel, sha, size) {
969
- const norm = assertFilePath(rel);
1116
+ const norm = assertNotReserved(assertFilePath(rel));
970
1117
  if (!/^[0-9a-f]{64}$/.test(sha))
971
1118
  throw new Error("expected a sha256");
972
1119
  requireWorkspace(tenant, workspace);
@@ -1102,6 +1249,9 @@ export async function materializeFiles(tenant, workspace) {
1102
1249
  const driver = driverFor(tenant, workspace);
1103
1250
  const brought = [];
1104
1251
  for (const record of readIndex(tenant, workspace).files) {
1252
+ // A run's held inputs are staged into its own step, never mirrored.
1253
+ if (isReservedPath(record.path))
1254
+ continue;
1105
1255
  const target = path.join(root, record.path);
1106
1256
  try {
1107
1257
  const stat = fs.statSync(target);
@@ -1140,7 +1290,7 @@ export async function materializeFiles(tenant, workspace) {
1140
1290
  export function storageBaseline(tenant, workspace) {
1141
1291
  if (!fileStoreEnabled())
1142
1292
  return {};
1143
- return Object.fromEntries(readIndex(tenant, workspace).files.map((f) => [f.path, f.sha]));
1293
+ return Object.fromEntries(readIndex(tenant, workspace).files.filter((f) => !isReservedPath(f.path)).map((f) => [f.path, f.sha]));
1144
1294
  }
1145
1295
  /**
1146
1296
  * Take what the run left in `storage/` back into the store, stamped with the
@@ -21,6 +21,7 @@ import { type NetworkPolicy } from "./network.ts";
21
21
  import { type SearchingAction } from "./search-egress.ts";
22
22
  import { type WireFormat, type AuthShape } from "./providers.ts";
23
23
  import type { RunContext, RunInput, ConversationRecord } from "./conversation.ts";
24
+ import type { RunInputFile } from "./storage.ts";
24
25
  /**
25
26
  * Single-workspace mode. When set, the workspace IS this directory — no
26
27
  * tenant, no projects/ nesting. That's the difference between a framework you
@@ -1405,6 +1406,11 @@ export interface StepRecord {
1405
1406
  /** What that step was given, written when it starts: which runs, how many
1406
1407
  * did not fit, and a hash of the block (conversation.ts). Never the text. */
1407
1408
  history?: ConversationRecord;
1409
+ /** FOL-163: this step is handed the run's `inputs`, staged at
1410
+ * agents/<name>/inputs/. Set when the run is made on the step the task
1411
+ * reaches; fan-out instances and an on-fail rescue inherit it; a re-run
1412
+ * sets it on the first step it runs. */
1413
+ inputsTurn?: boolean;
1408
1414
  /** On an isolated sub-agent's run: the workspace paths its sandbox's
1409
1415
  * changes were applied to — what its delegating step is told it wrote. */
1410
1416
  wrote?: string[];
@@ -1659,6 +1665,13 @@ export interface RunRecord {
1659
1665
  * an A2A message's text and data. Kept on a run with a `context`, so a
1660
1666
  * later turn reads the question, never a step's decorated instruction. */
1661
1667
  input?: RunInput;
1668
+ /** FOL-163: the files the run was handed — storage paths and the blob each
1669
+ * named when the run was made (held for it; storage.ts holdRunInputs). */
1670
+ inputs?: RunInputFile[];
1671
+ /** FOL-168: which of the partner's own users this run is for — an opaque
1672
+ * id the partner maps (customer.ts). Limits, blocks and the provider's
1673
+ * end-user id follow it. Set when the run is made, carried on a re-run. */
1674
+ customer?: string;
1662
1675
  steps: StepRecord[];
1663
1676
  }
1664
1677
  /** Merge one part (the input, on the call; the output, on its completion)
@@ -1815,6 +1828,8 @@ export interface RunSummary {
1815
1828
  };
1816
1829
  /** RunRecord.context: the conversation it belongs to (FOL-162). */
1817
1830
  context?: RunContext;
1831
+ /** RunRecord.customer (FOL-168). */
1832
+ customer?: string;
1818
1833
  steps: RunSummaryStep[];
1819
1834
  }
1820
1835
  /** One run's row. */
package/dist/src/store.js CHANGED
@@ -2984,7 +2984,14 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
2984
2984
  const file = runFilePath(tenant, workspace, runId);
2985
2985
  const dir = path.join(workspaceDir(tenant, workspace), "runs", runId);
2986
2986
  const port = records(tenant, workspace);
2987
- const had = port ? port.runGet(tenant, workspace, runId) !== null : fs.existsSync(file);
2987
+ let prior = null;
2988
+ try {
2989
+ prior = port ? port.runGet(tenant, workspace, runId) : fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null;
2990
+ }
2991
+ catch {
2992
+ prior = null; // a half-written record still goes
2993
+ }
2994
+ const had = port ? prior !== null : fs.existsSync(file);
2988
2995
  if (!had && !fs.existsSync(dir))
2989
2996
  return false;
2990
2997
  // The folder first (archived outputs, captured calls), the record last:
@@ -2998,6 +3005,12 @@ export function deleteRun(tenant, workspace, runId, opts = {}) {
2998
3005
  fs.rmSync(file, { force: true });
2999
3006
  noteRunDeleted(path.dirname(file), runId);
3000
3007
  }
3008
+ // Its held inputs go with it (FOL-163): a blob nothing else names is
3009
+ // collected. Asynchronous, and never the delete's failure — storage's own
3010
+ // sweep (sweepHeldInputs) finds any a crash left behind.
3011
+ if (prior?.inputs?.length) {
3012
+ void import("./storage.js").then((m) => m.releaseRunInputs(tenant, workspace, runId)).catch(() => { });
3013
+ }
3001
3014
  if (!had)
3002
3015
  return true;
3003
3016
  // The retention window's prune (`pruned`) is policy, not a person erasing
@@ -3268,6 +3281,7 @@ export function summarizeRun(run) {
3268
3281
  ...(run.trigger ? { trigger: run.trigger } : {}),
3269
3282
  ...(run.a2a ? { a2a: run.a2a } : {}),
3270
3283
  ...(run.context ? { context: run.context } : {}),
3284
+ ...(run.customer ? { customer: run.customer } : {}),
3271
3285
  awaitingApproval: run.steps.some((s) => s.status === "awaiting-approval" && s.waitFor !== "event"),
3272
3286
  steps: run.steps.map((s) => {
3273
3287
  // A failed step's last error — and, on a run that failed between
@@ -16,6 +16,16 @@ export declare function anthropicUsage(u: Json | undefined, wire: TranslatorWire
16
16
  * to loopback and every byte to the tenant's URL goes through the guard
17
17
  * (FOL-95). A step never gets it (translatorSpecFor returns null there). */
18
18
  export type TranslatorWire = "chat" | "responses" | "anthropic";
19
+ /** What an endpoint can be shown — images, PDFs. Unset: the format's default. */
20
+ export interface TranslatorMedia {
21
+ images?: boolean;
22
+ pdf?: boolean;
23
+ }
24
+ /** What the model reads where a file could not be shown to it. */
25
+ export declare const NOT_SHOWN: {
26
+ readonly image: "[an image was here, but this model endpoint cannot be shown images — it was not delivered]";
27
+ readonly 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]";
28
+ };
19
29
  export interface TranslatorSpec {
20
30
  /** The provider's base, e.g. https://api.openai.com/v1 — `/chat/completions`
21
31
  * or `/responses` is appended, by `wire`. */
@@ -48,6 +58,11 @@ export interface TranslatorSpec {
48
58
  /** The step's own zone, from the clock cascade — what a reset time in a
49
59
  * refusal is told in. UTC when nothing said otherwise. */
50
60
  timezone?: string;
61
+ /** What the endpoint can be shown (FOL-163), from its preset. Images:
62
+ * yes unless said. PDFs: yes on `responses` (input_file), no on `chat`
63
+ * unless the preset says the endpoint takes Chat's `file` part. What it
64
+ * cannot be shown is not sent, and the model is told so in its place. */
65
+ media?: TranslatorMedia;
51
66
  }
52
67
  export interface RunningTranslator {
53
68
  port: number;
@@ -96,6 +111,8 @@ export declare function toChatCompletions(req: Json, opts: {
96
111
  params?: Record<string, unknown>;
97
112
  /** What the provider attached to earlier tool calls, to send back. */
98
113
  extras?: ToolCallExtras;
114
+ /** What the endpoint can be shown (FOL-163). */
115
+ media?: TranslatorMedia;
99
116
  }, drop?: Dropped): Json;
100
117
  /**
101
118
  * An Anthropic Messages request as a Responses request. Pure.
@@ -112,6 +129,8 @@ export declare function toResponses(req: Json, opts: {
112
129
  stream: boolean;
113
130
  cacheKey?: string;
114
131
  params?: Record<string, unknown>;
132
+ /** What the endpoint can be shown (FOL-163); this shape takes both by default. */
133
+ media?: TranslatorMedia;
115
134
  }, drop?: Dropped): Json;
116
135
  /** A finished Chat Completion as an Anthropic message. Pure. */
117
136
  export declare function fromChatCompletion(res: Json, requestedModel: string, stopSequences?: unknown, extras?: ToolCallExtras): Json;
@@ -29,7 +29,7 @@
29
29
  // few dozen lines.
30
30
  import http from "node:http";
31
31
  import crypto from "node:crypto";
32
- import { PROTECTED_PARAMS } from "./providers.js";
32
+ import { PROTECTED_PARAMS, providerPreset } from "./providers.js";
33
33
  import { viaEgress } from "./egress.js";
34
34
  import { fetchUntrusted } from "./untrusted-fetch.js";
35
35
  import { trimSlashes } from "./paths.js";
@@ -61,6 +61,17 @@ function usageBlock(u) {
61
61
  ...(u && u.cached > 0 ? { cache_read_input_tokens: u.cached } : {}),
62
62
  };
63
63
  }
64
+ /** What the model reads where a file could not be shown to it. */
65
+ export const NOT_SHOWN = {
66
+ image: "[an image was here, but this model endpoint cannot be shown images — it was not delivered]",
67
+ 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]",
68
+ };
69
+ function pdfData(block) {
70
+ const src = block.source;
71
+ if (src?.type !== "base64" || typeof src.data !== "string")
72
+ return null;
73
+ return { filename: typeof block.title === "string" ? block.title : "document.pdf", data: src.data, mime: String(src.media_type ?? "application/pdf") };
74
+ }
64
75
  function dropped() {
65
76
  const seen = new Set();
66
77
  const notes = new Set();
@@ -129,6 +140,8 @@ function imagePart(block) {
129
140
  * first and whatever else the user said follows as a user message.
130
141
  */
131
142
  export function toChatCompletions(req, opts, drop = dropped()) {
143
+ const images = opts.media?.images !== false;
144
+ const pdfs = opts.media?.pdf === true;
132
145
  const out = { model: req.model, stream: opts.stream };
133
146
  if (opts.cacheKey)
134
147
  out.prompt_cache_key = opts.cacheKey;
@@ -136,9 +149,21 @@ export function toChatCompletions(req, opts, drop = dropped()) {
136
149
  const system = textOf(req.system);
137
150
  if (system)
138
151
  messages.push({ role: "system", content: system });
139
- for (const m of (Array.isArray(req.messages) ? req.messages : [])) {
152
+ const all = (Array.isArray(req.messages) ? req.messages : []);
153
+ // A user message's own parts (and the media lifted out of its tool
154
+ // results) wait while the next message is a user message still carrying
155
+ // tool results: Chat Completions wants every result of a turn before any
156
+ // user message (Codex review, FOL-163).
157
+ let carried = [];
158
+ const hasToolResult = (x) => x?.role === "user" && Array.isArray(x.content) && x.content.some((b) => b?.type === "tool_result");
159
+ for (let mi = 0; mi < all.length; mi++) {
160
+ const m = all[mi];
140
161
  const content = m.content;
141
162
  if (m.role === "assistant") {
163
+ if (carried.length) {
164
+ messages.push({ role: "user", content: carried.length === 1 && carried[0].type === "text" ? carried[0].text : carried });
165
+ carried = [];
166
+ }
142
167
  const text = textOf(content);
143
168
  const toolCalls = [];
144
169
  for (const b of Array.isArray(content) ? content : []) {
@@ -167,34 +192,86 @@ export function toChatCompletions(req, opts, drop = dropped()) {
167
192
  }
168
193
  // user
169
194
  if (typeof content === "string") {
170
- messages.push({ role: "user", content });
195
+ if (carried.length) {
196
+ messages.push({ role: "user", content: [...carried, { type: "text", text: content }] });
197
+ carried = [];
198
+ }
199
+ else
200
+ messages.push({ role: "user", content });
171
201
  continue;
172
202
  }
173
203
  const parts = [];
204
+ // A tool message carries text alone, so what a tool returned that is not
205
+ // text — an image the agent opened, a PDF it read — follows the tool
206
+ // messages in one user message, each labelled with the call it came
207
+ // from (FOL-163). Where the endpoint cannot be shown it, the tool's own
208
+ // message says so, so the model never answers as though it had seen it.
209
+ const lifted = [];
174
210
  for (const b of Array.isArray(content) ? content : []) {
175
211
  if (b.type === "tool_result") {
176
212
  const inner = b.content;
177
213
  const text = typeof inner === "string" ? inner : textOf(inner);
214
+ const notes = [];
215
+ const attached = [];
216
+ for (const x of Array.isArray(inner) ? inner : []) {
217
+ if (x.type === "image") {
218
+ const p = images ? imagePart(x) : null;
219
+ if (p)
220
+ attached.push(p);
221
+ else {
222
+ notes.push(NOT_SHOWN.image);
223
+ drop.add("images this endpoint cannot be shown");
224
+ }
225
+ }
226
+ else if (x.type === "document") {
227
+ const d = pdfs ? pdfData(x) : null;
228
+ if (d)
229
+ attached.push({ type: "file", file: { filename: d.filename, file_data: `data:${d.mime};base64,${d.data}` } });
230
+ else {
231
+ notes.push(NOT_SHOWN.pdf);
232
+ drop.add("PDFs (this endpoint cannot be shown them)");
233
+ }
234
+ }
235
+ }
236
+ if (attached.length) {
237
+ lifted.push({ type: "text", text: `What the tool call ${String(b.tool_use_id)} returned:` }, ...attached);
238
+ notes.push(`[${attached.length === 1 ? "the file it returned is" : `the ${attached.length} files it returned are`} attached in the next message]`);
239
+ }
240
+ const body = [text, ...notes].filter(Boolean).join("\n");
178
241
  messages.push({
179
242
  role: "tool",
180
243
  tool_call_id: String(b.tool_use_id),
181
- content: text || (b.is_error ? "error" : "ok"),
244
+ content: body || (b.is_error ? "error" : "ok"),
182
245
  });
183
- if (Array.isArray(inner) && inner.some((x) => x.type === "image"))
184
- drop.add("images inside tool results");
185
246
  }
186
247
  else if (b.type === "text") {
187
248
  parts.push({ type: "text", text: String(b.text ?? "") });
188
249
  }
189
250
  else if (b.type === "image") {
190
- const p = imagePart(b);
251
+ const p = images ? imagePart(b) : null;
191
252
  if (p)
192
253
  parts.push(p);
254
+ else {
255
+ parts.push({ type: "text", text: NOT_SHOWN.image });
256
+ drop.add("images this endpoint cannot be shown");
257
+ }
193
258
  }
194
259
  else if (b.type === "document") {
195
- drop.add("document blocks");
260
+ const d = pdfs ? pdfData(b) : null;
261
+ if (d)
262
+ parts.push({ type: "file", file: { filename: d.filename, file_data: `data:${d.mime};base64,${d.data}` } });
263
+ else {
264
+ parts.push({ type: "text", text: NOT_SHOWN.pdf });
265
+ drop.add("PDFs (this endpoint cannot be shown them)");
266
+ }
196
267
  }
197
268
  }
269
+ parts.unshift(...carried, ...lifted);
270
+ carried = [];
271
+ if (parts.length && hasToolResult(all[mi + 1])) {
272
+ carried = parts;
273
+ continue;
274
+ }
198
275
  if (parts.length) {
199
276
  // A single text part reads as a plain string on every endpoint;
200
277
  // a list is only needed when an image is among them.
@@ -302,6 +379,8 @@ export function toChatCompletions(req, opts, drop = dropped()) {
302
379
  * user said.
303
380
  */
304
381
  export function toResponses(req, opts, drop = dropped()) {
382
+ const showImages = opts.media?.images !== false;
383
+ const showPdfs = opts.media?.pdf !== false;
305
384
  const out = { model: req.model, stream: opts.stream, store: false };
306
385
  if (opts.cacheKey)
307
386
  out.prompt_cache_key = opts.cacheKey;
@@ -334,24 +413,52 @@ export function toResponses(req, opts, drop = dropped()) {
334
413
  if (b.type === "tool_result") {
335
414
  const inner = b.content;
336
415
  const text = typeof inner === "string" ? inner : textOf(inner);
337
- // A tool result that holds images (a picture the agent opened) is
338
- // sent as a list of parts, which Responses takes in a tool output.
416
+ // A tool result that holds images (a picture the agent opened) or a
417
+ // PDF it read is sent as a list of parts, which Responses takes in a
418
+ // tool output (FOL-163: PDFs too). What this endpoint cannot be shown
419
+ // is said in its place.
420
+ const notes = [];
339
421
  const images = Array.isArray(inner)
340
422
  ? inner.flatMap((x) => {
341
- const src = x.type === "image" ? x.source : undefined;
342
- if (src?.type === "base64" && typeof src.data === "string")
343
- return [{ type: "input_image", image_url: `data:${String(src.media_type ?? "image/png")};base64,${src.data}`, detail: "auto" }];
344
- if (src?.type === "url" && typeof src.url === "string")
345
- return [{ type: "input_image", image_url: src.url, detail: "auto" }];
423
+ if (x.type === "image") {
424
+ const src = x.source;
425
+ if (!showImages) {
426
+ notes.push(NOT_SHOWN.image);
427
+ drop.add("images this endpoint cannot be shown");
428
+ return [];
429
+ }
430
+ if (src?.type === "base64" && typeof src.data === "string")
431
+ return [{ type: "input_image", image_url: `data:${String(src.media_type ?? "image/png")};base64,${src.data}`, detail: "auto" }];
432
+ if (src?.type === "url" && typeof src.url === "string")
433
+ return [{ type: "input_image", image_url: src.url, detail: "auto" }];
434
+ return [];
435
+ }
436
+ if (x.type === "document") {
437
+ const d = showPdfs ? pdfData(x) : null;
438
+ if (d)
439
+ return [{ type: "input_file", filename: d.filename, file_data: `data:${d.mime};base64,${d.data}` }];
440
+ notes.push(NOT_SHOWN.pdf);
441
+ drop.add("PDFs (this endpoint cannot be shown them)");
442
+ return [];
443
+ }
346
444
  return [];
347
445
  })
348
446
  : [];
349
- const output = images.length ? [...(text ? [{ type: "input_text", text }] : []), ...images] : text || (b.is_error ? "error" : "ok");
447
+ const said = [text, ...notes].filter(Boolean).join("\n");
448
+ const output = images.length ? [...(said ? [{ type: "input_text", text: said }] : []), ...images] : said || (b.is_error ? "error" : "ok");
350
449
  input.push({ type: "function_call_output", call_id: String(b.tool_use_id), output });
351
450
  }
352
451
  else if (b.type === "text") {
353
452
  parts.push({ type: "input_text", text: String(b.text ?? "") });
354
453
  }
454
+ else if (b.type === "image" && !showImages) {
455
+ parts.push({ type: "input_text", text: NOT_SHOWN.image });
456
+ drop.add("images this endpoint cannot be shown");
457
+ }
458
+ else if (b.type === "document" && !showPdfs) {
459
+ parts.push({ type: "input_text", text: NOT_SHOWN.pdf });
460
+ drop.add("PDFs (this endpoint cannot be shown them)");
461
+ }
355
462
  else if (b.type === "image") {
356
463
  const src = b.source;
357
464
  if (src?.type === "base64" && typeof src.data === "string") {
@@ -1017,8 +1124,8 @@ export async function startTranslator(spec) {
1017
1124
  const drop = dropped();
1018
1125
  const responses = spec.wire === "responses";
1019
1126
  const outbound = responses
1020
- ? toResponses(body, { reasoningEffort: spec.reasoningEffort, params: spec.params, cacheKey: spec.cacheKey, stream }, drop)
1021
- : toChatCompletions(body, { maxTokensParam: spec.maxTokensParam, reasoningEffort: spec.reasoningEffort, params: spec.params, cacheKey: spec.cacheKey, stream, extras }, drop);
1127
+ ? toResponses(body, { reasoningEffort: spec.reasoningEffort, params: spec.params, cacheKey: spec.cacheKey, stream, media: spec.media }, drop)
1128
+ : toChatCompletions(body, { maxTokensParam: spec.maxTokensParam, reasoningEffort: spec.reasoningEffort, params: spec.params, cacheKey: spec.cacheKey, stream, extras, media: spec.media }, drop);
1022
1129
  for (const line of drop.lines())
1023
1130
  if (!log.includes(line))
1024
1131
  log.push(line);
@@ -1262,6 +1369,8 @@ export function translatorSpecFor(spec) {
1262
1369
  maxTokensParam: spec.maxTokensParam,
1263
1370
  reasoningEffort: spec.reasoningEffort,
1264
1371
  ...(spec.cacheKey ? { cacheKey: spec.cacheKey } : {}),
1372
+ // What the endpoint can be shown, from its preset (FOL-163).
1373
+ ...(spec.name && providerPreset(spec.name)?.media ? { media: providerPreset(spec.name).media } : {}),
1265
1374
  label: spec.name ? `${spec.name} (${spec.baseUrl})` : spec.baseUrl,
1266
1375
  };
1267
1376
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "18.5.0",
3
+ "version": "19.0.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",
@@ -0,0 +1,63 @@
1
+ // An end customer's id (FOL-168, 11 Nov 2026): a partner — one foldrun
2
+ // account serving thousands of people of its own — names which of its own
3
+ // users a run or a gateway call is for. foldrun then limits and blocks by
4
+ // it, so one bad end customer is held alone and the partner's account
5
+ // carries on; and the model provider is told the same, as its end-user id,
6
+ // so a provider acts on that one user, not the platform's key.
7
+ //
8
+ // Opaque by contract: the partner maps it to a person, foldrun never does,
9
+ // and it must not be personal data (an email, a name). It is not an access
10
+ // boundary either: anyone who may start runs in the account may name any
11
+ // customer.
12
+ //
13
+ // To a provider it goes hashed with the account — `fr-` and 32 hex — so two
14
+ // partners' `user-1` are never one identity there, and the partner's own id
15
+ // never leaves foldrun.
16
+
17
+ import crypto from "node:crypto";
18
+
19
+ /** A customer id as a partner writes it: printable, no spaces, 1–128. */
20
+ export const CUSTOMER_ID = /^[A-Za-z0-9._:@-]{1,128}$/;
21
+
22
+ /** Null when the id is fine; otherwise why not. */
23
+ export function customerProblem(id: unknown): string | null {
24
+ if (typeof id !== "string") return "customer must be a string";
25
+ if (!CUSTOMER_ID.test(id)) return "customer is 1–128 characters: letters, digits and . _ : @ - (an opaque id, never personal data)";
26
+ return null;
27
+ }
28
+
29
+ /** What a model provider is told for this account's customer: its end-user
30
+ * id (Anthropic metadata.user_id; OpenAI user / safety_identifier). */
31
+ export function providerUserId(tenant: string, customer: string): string {
32
+ return `fr-${crypto.createHash("sha256").update(`${tenant}\u0000${customer}`).digest("hex").slice(0, 32)}`;
33
+ }
34
+
35
+ /** A short, stable key for counters and logs — never the id itself. */
36
+ export function customerKey(tenant: string, customer: string): string {
37
+ return crypto.createHash("sha256").update(`customer\u0000${tenant}\u0000${customer}`).digest("hex").slice(0, 24);
38
+ }
39
+
40
+ /**
41
+ * Set the provider's end-user id on a model request body, in whichever shape
42
+ * it is: Anthropic Messages (`metadata.user_id`, other metadata kept),
43
+ * OpenAI Responses (`safety_identifier`), OpenAI Chat Completions (`user`).
44
+ * Returns the body unchanged when it is not JSON or not one of those.
45
+ */
46
+ export function withProviderUser(body: Buffer, userId: string, shape: "anthropic" | "responses" | "chat"): Buffer {
47
+ let parsed: Record<string, unknown>;
48
+ try {
49
+ parsed = JSON.parse(body.toString("utf8")) as Record<string, unknown>;
50
+ } catch {
51
+ return body;
52
+ }
53
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return body;
54
+ if (shape === "anthropic") {
55
+ const meta = parsed.metadata && typeof parsed.metadata === "object" && !Array.isArray(parsed.metadata) ? (parsed.metadata as Record<string, unknown>) : {};
56
+ parsed.metadata = { ...meta, user_id: userId };
57
+ } else if (shape === "responses") {
58
+ parsed.safety_identifier = userId;
59
+ } else {
60
+ parsed.user = userId;
61
+ }
62
+ return Buffer.from(JSON.stringify(parsed), "utf8");
63
+ }