@pipelex/sdk 0.67.1 → 0.69.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/dist/artifacts.js CHANGED
@@ -26,11 +26,13 @@
26
26
  * runs anywhere the global `fetch` does (the dispatcher is a Node refinement), and
27
27
  * only `downloadArtifacts` touches a filesystem.
28
28
  */
29
- import { ApiResponseError, ArtifactAuthenticationError, ArtifactFetchError, ArtifactOperationError, RunFailedError, RunStillRunningError, ScopeUnavailableError, } from "./errors.js";
29
+ import { ApiResponseError, ArtifactAuthenticationError, ArtifactFetchError, ArtifactOperationError, RunFailedError, RunStillRunningError, ScopeUnavailableError, StoredTextLoadError, } from "./errors.js";
30
30
  import { argumentInvalidProblem, responseUnreadableProblem } from "./errors.js";
31
- import { buildProblem } from "mthds/protocol";
31
+ import { ProblemError, buildProblem } from "mthds/protocol";
32
32
  import { absenceCause, loadNodeHost } from "./node-host.js";
33
33
  import { MAX_TIMER_DELAY_MS, isTimerDelay } from "./timers.js";
34
+ import { STORED_TEXT_REFERENCE_FIELDS, STORED_TEXT_VALUE_FIELD, childNode, mainStuffNode, storedTextKindOfNode, workingMemoryNode, } from "./stored-texts.js";
35
+ import { parseExactJson } from "./exact-json.js";
34
36
  // ── Constants ────────────────────────────────────────────────────────
35
37
  /** The scheme of a durable storage reference. */
36
38
  export const PIPELEX_STORAGE_SCHEME = "pipelex-storage://";
@@ -93,6 +95,22 @@ const EXTENSION_BY_CONTENT_TYPE = {
93
95
  "text/csv": ".csv",
94
96
  "application/json": ".json",
95
97
  };
98
+ /**
99
+ * The extension a saved stored text takes from the MIME type its reference states, the text types
100
+ * the runtime stores as. A stored text is named by its MIME type, never by its storage key.
101
+ */
102
+ const TEXT_EXTENSION_BY_MIME_TYPE = {
103
+ "text/plain": ".txt",
104
+ "text/markdown": ".md",
105
+ "text/html": ".html",
106
+ "application/json": ".json",
107
+ };
108
+ /** The extension a saved stored text takes when its reference states no MIME type the SDK names. */
109
+ const TEXT_EXTENSION_BY_KIND = {
110
+ text: ".txt",
111
+ html: ".html",
112
+ json: ".json",
113
+ };
96
114
  /** An object key rendered as `.key` in a path; any other key is rendered as `["…"]`. */
97
115
  const IDENTIFIER_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
98
116
  /**
@@ -108,9 +126,16 @@ const IDENTIFIER_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
108
126
  * produced image or document as content carrying its reference in `url`, so a
109
127
  * typical path ends there: `$.rooms[3].staged_photo.url`, `$.items[0].url`, or
110
128
  * `$.url` for an output that is one image. Pure — no network, no key.
129
+ *
130
+ * `node` is the descriptor node of the walked value, the standard's output-form node for a run's
131
+ * output ({@link mainStuffNode} finds it in the run's results). Given, the walk follows the
132
+ * concept at each path and skips a stored text — a `Text`, `Markdown`, `Html` or `JSON` value, or
133
+ * one refining them, which the runtime may hold by a `pipelex-storage://` reference too — since
134
+ * a stored text is a value of the run, never a file. Without it, nothing says what a value is, so
135
+ * every reference counts. A result read with its stored texts loaded, the default, holds none.
111
136
  */
112
- export function locateArtifacts(value) {
113
- return walkReferences(value).map(renderLocation);
137
+ export function locateArtifacts(value, node) {
138
+ return walkReferences(value, true, node ?? undefined).map(renderLocation);
114
139
  }
115
140
  /**
116
141
  * Every `pipelex-storage://` reference inside a JSON-shaped value, deduplicated,
@@ -121,10 +146,31 @@ export function locateArtifacts(value) {
121
146
  * heuristic: the runtime serializes a produced image or document as content
122
147
  * carrying its reference in `url`, beside an expiring `public_url` this walk
123
148
  * ignores. Pure — no network, no key — so a consumer can count or list a run's
124
- * produced files without resolving any of them.
149
+ * produced files without resolving any of them. `node` skips the stored texts by concept, as on
150
+ * {@link locateArtifacts}.
125
151
  */
126
- export function collectArtifacts(value) {
127
- return walkReferences(value, false).map((located) => located.uri);
152
+ export function collectArtifacts(value, node) {
153
+ return walkReferences(value, false, node ?? undefined).map((located) => located.uri);
154
+ }
155
+ /**
156
+ * Every `pipelex-storage://` reference inside a JSON-shaped value, told apart by concept: the
157
+ * stored files, exactly as {@link locateArtifacts} answers them, and the stored texts, each with
158
+ * what its reference states. Each list is deduplicated and in discovery order. A stored text is
159
+ * found where `node` describes a stored-text concept ({@link storedTextKindOfNode}) and the value
160
+ * there is its reference, a `pipelex-storage://` `url` with no value field. Without `node` nothing
161
+ * says what a value is, so every reference is a file: a file count one too high, never a file
162
+ * hidden. For a run's output, `node` is {@link mainStuffNode} of its results. Pure — no network.
163
+ */
164
+ export function locateStoredReferences(value, node) {
165
+ const files = [];
166
+ const texts = [];
167
+ for (const located of walkReferences(value, true, node ?? undefined, true)) {
168
+ if (located.text === undefined)
169
+ files.push(renderLocation(located));
170
+ else
171
+ texts.push(renderTextLocation(located, located.text));
172
+ }
173
+ return { files, texts };
128
174
  }
129
175
  /**
130
176
  * The walk both public functions share: depth first, keys in `Object.entries`
@@ -133,31 +179,42 @@ export function collectArtifacts(value) {
133
179
  * occurrence costs memory in proportion to occurrences times depth, where the
134
180
  * deduplicated list needs only one entry per unique reference.
135
181
  */
136
- function walkReferences(value, withPaths = true) {
182
+ function walkReferences(value, withPaths = true, described, includeTexts = false) {
137
183
  // A Map keeps insertion order, which is the order of first sighting.
138
184
  const byUri = new Map();
139
185
  const trail = [];
140
- const visit = (node) => {
141
- if (typeof node === "string") {
142
- if (!isStorageReference(node))
143
- return;
144
- const known = byUri.get(node);
145
- if (!withPaths) {
146
- if (known === undefined)
147
- byUri.set(node, { uri: node, paths: [] });
148
- return;
149
- }
150
- const path = [...trail];
186
+ const record = (uri, path, text) => {
187
+ const known = byUri.get(uri);
188
+ if (!withPaths) {
151
189
  if (known === undefined)
152
- byUri.set(node, { uri: node, paths: [path] });
153
- else
154
- known.paths.push(path);
190
+ byUri.set(uri, { uri, paths: [], ...(text ? { text } : {}) });
191
+ return;
192
+ }
193
+ if (known === undefined)
194
+ byUri.set(uri, { uri, paths: [path], ...(text ? { text } : {}) });
195
+ else
196
+ known.paths.push(path);
197
+ };
198
+ const visit = (node, nodeDescriptor) => {
199
+ // A stored text is a value of the run, never a file: its reference is recorded as a text when
200
+ // asked for, and never counts as a file.
201
+ const kind = storedTextKindOfNode(nodeDescriptor);
202
+ if (kind !== null) {
203
+ const url = includeTexts ? storedTextReferenceUrl(node, kind) : null;
204
+ if (url !== null && isStorageReference(url)) {
205
+ record(url, [...trail, "url"], { kind, reference: node });
206
+ }
207
+ return;
208
+ }
209
+ if (typeof node === "string") {
210
+ if (isStorageReference(node))
211
+ record(node, [...trail]);
155
212
  return;
156
213
  }
157
214
  if (Array.isArray(node)) {
158
215
  for (let index = 0; index < node.length; index += 1) {
159
216
  trail.push(index);
160
- visit(node[index]);
217
+ visit(node[index], childNode(nodeDescriptor, node, index));
161
218
  trail.pop();
162
219
  }
163
220
  return;
@@ -165,17 +222,27 @@ function walkReferences(value, withPaths = true) {
165
222
  if (typeof node === "object" && node !== null) {
166
223
  for (const [key, entry] of Object.entries(node)) {
167
224
  trail.push(key);
168
- visit(entry);
225
+ visit(entry, childNode(nodeDescriptor, node, key));
169
226
  trail.pop();
170
227
  }
171
228
  }
172
229
  };
173
- visit(value);
230
+ visit(value, described);
174
231
  return [...byUri.values()];
175
232
  }
176
233
  function renderLocation(located) {
177
234
  return { uri: located.uri, found_at: located.paths.map(renderPath) };
178
235
  }
236
+ function renderTextLocation(located, text) {
237
+ const { size, mime_type: mimeType, preview } = text.reference;
238
+ return {
239
+ ...renderLocation(located),
240
+ kind: text.kind,
241
+ size: typeof size === "number" ? size : null,
242
+ mime_type: typeof mimeType === "string" ? mimeType : null,
243
+ preview: typeof preview === "string" ? preview : null,
244
+ };
245
+ }
179
246
  /** Segments to the `$`-rooted notation `found_at` carries. */
180
247
  function renderPath(segments) {
181
248
  let path = "$";
@@ -230,6 +297,33 @@ function parsePath(path) {
230
297
  export function isStorageReference(value) {
231
298
  return value.startsWith(PIPELEX_STORAGE_SCHEME) && value.length > PIPELEX_STORAGE_SCHEME.length;
232
299
  }
300
+ /**
301
+ * A `url` a stored text may be loaded from: a `pipelex-storage://` reference, resolved through the
302
+ * platform's bulk route to a link it signs, or a `data:` URL, decoded where it is. A stored text at
303
+ * any other URL is never fetched, so a method cannot have the SDK read a host the caller did not
304
+ * choose: the loader refuses it as `unsupported_url`.
305
+ *
306
+ * The file walks ({@link locateStoredReferences}, `downloadArtifacts`) report the first kind
307
+ * only, since a `data:` URL holds its value inline and has nothing to resolve or save.
308
+ */
309
+ export function isLoadableStoredTextUrl(url) {
310
+ return isStorageReference(url) || url.startsWith("data:");
311
+ }
312
+ /**
313
+ * The `url` of a stored text's reference, `value` sitting where the concept is a stored text: an
314
+ * object carrying a string `url` and no value field. `null` for anything else, an inline value
315
+ * included. The one recognition the walk and the loader share, each then applying its own rule to
316
+ * the URL.
317
+ */
318
+ function storedTextReferenceUrl(value, kind) {
319
+ if (typeof value !== "object" || value === null || Array.isArray(value))
320
+ return null;
321
+ const reference = value;
322
+ const url = reference["url"];
323
+ if (typeof url !== "string" || reference[STORED_TEXT_VALUE_FIELD[kind]] != null)
324
+ return null;
325
+ return url;
326
+ }
233
327
  // ── artifactFilename ─────────────────────────────────────────────────
234
328
  /**
235
329
  * The bare filename a reference is saved under, named after the field it fills:
@@ -280,16 +374,19 @@ export function artifactFilename(location, contentType, scope) {
280
374
  throw new ArtifactOperationError(`artifactFilename needs a location whose first "found_at" entry is a path such as ` +
281
375
  `"$.items[0].url"; got ${typeof first === "string" ? JSON.stringify(first) : String(first)}.`, { problem: argumentInvalidProblem("location", "not_a_path") });
282
376
  }
283
- return filenameFor(segments, uri, contentType, scope);
377
+ const text = location;
378
+ const extension = typeof text.kind === "string" && text.kind in TEXT_EXTENSION_BY_KIND
379
+ ? textExtensionFor(text.kind, text.mime_type ?? contentType)
380
+ : extensionFor(uri, contentType);
381
+ return filenameFor(segments, extension, scope);
284
382
  }
285
383
  /** The naming rule of {@link artifactFilename}, over the walk's own segments. */
286
- function filenameFor(segments, uri, contentType, scope) {
384
+ function filenameFor(segments, extension, scope) {
287
385
  const named = segments.at(-1) === "url" ? segments.slice(0, -1) : segments;
288
386
  const words = named
289
387
  .map((segment) => typeof segment === "number" ? String(segment) : segment.replace(/[^A-Za-z0-9_]/gu, "_"))
290
388
  // Only the empty key reduces to nothing, and it says nothing about the field.
291
389
  .filter((word) => word !== "");
292
- const extension = extensionFor(uri, contentType);
293
390
  const stem = fitStem(words.length > 0 ? words : [scope], MAX_FILENAME_LENGTH - extension.length);
294
391
  // A device stem is at most four characters, so the `_` cannot overrun the cap.
295
392
  return (WINDOWS_DEVICE_STEM.test(stem) ? `${stem}_` : stem) + extension;
@@ -314,6 +411,13 @@ function extensionFor(uri, contentType) {
314
411
  return "";
315
412
  return EXTENSION_BY_CONTENT_TYPE[contentType.split(";")[0].trim().toLowerCase()] ?? "";
316
413
  }
414
+ /** `.ext` for a saved stored text — its MIME type's, else its kind's — never its storage key's. */
415
+ function textExtensionFor(kind, mimeType) {
416
+ const named = mimeType == null
417
+ ? undefined
418
+ : TEXT_EXTENSION_BY_MIME_TYPE[mimeType.split(";")[0].trim().toLowerCase()];
419
+ return named ?? TEXT_EXTENSION_BY_KIND[kind];
420
+ }
317
421
  /**
318
422
  * The extension the storage key's last segment carries, without its dot, reduced
319
423
  * to `[A-Za-z0-9]` — or `""` when it has none, or none that short. The segment is
@@ -687,6 +791,325 @@ function formatMiB(bytes) {
687
791
  const mib = bytes / (1024 * 1024);
688
792
  return `${Number.isInteger(mib) ? mib : mib.toFixed(1)} MiB`;
689
793
  }
794
+ // ── loadStoredTexts ──────────────────────────────────────────────────
795
+ /**
796
+ * The cap on one stored text's bytes: the runtime's own cap on what it reads from storage, so a
797
+ * text the runtime could read is never one the SDK refuses.
798
+ */
799
+ export const DEFAULT_STORED_TEXT_MAX_BYTES = 100 * 1024 * 1024;
800
+ /** How many stored texts one load reads at once. */
801
+ export const DEFAULT_STORED_TEXT_CONCURRENCY = 8;
802
+ /**
803
+ * A run's result with every stored text in `main_stuff` loaded: each value the runtime holds by
804
+ * reference, `{ url, size, mime_type, preview }`, replaced by its inline form, `{ text }`,
805
+ * `{ inner_html }` (its `css_class` kept) or `{ json_obj }`, which is the shape the generated
806
+ * types parse. The result readers (`getRunResult`, `waitForResult`, `startAndWaitForResult`) call
807
+ * it by default; a caller holding a result read with `loadStoredTexts: false` calls it later.
808
+ *
809
+ * Which values are stored texts is decided by concept, never by URL or MIME type: the concept at
810
+ * each path comes from the run's working memory and output form ({@link mainStuffNode}), so the
811
+ * results must carry them; a result that carries neither is returned as it is. A
812
+ * `pipelex-storage://` reference is resolved through the platform's bulk route, at most
813
+ * {@link BULK_RESOLVE_MAX_URIS} per request, and its signed link fetched under the same bounds as
814
+ * `fetchArtifact`, and a `data:` URL is decoded. A stored text under any other URL
815
+ * ({@link isLoadableStoredTextUrl}) is refused before anything is sent, since fetching it would
816
+ * read a host the method chose rather than the caller; a result read with
817
+ * `loadStoredTexts: false` keeps it as written. The bytes are UTF-8 by the standard's rule, and a
818
+ * JSON value is the object they serialize.
819
+ *
820
+ * The result passed in is never changed: a new one is returned, or the same one when there is
821
+ * nothing to load. Throws `StoredTextLoadError` naming the text that could not be loaded, where it
822
+ * sits and why, a whole-request failure of the resolve route included (`resolve_failed`, the
823
+ * route's error as its `cause`), and lets the caller's abort through.
824
+ */
825
+ export async function loadStoredTexts(client, results, options = {}) {
826
+ if (results.main_stuff == null)
827
+ return results;
828
+ const node = mainStuffNode(results);
829
+ if (node === null)
830
+ return results;
831
+ const loaded = await loadStoredTextValues(client, results.main_stuff, node, options, results.pipeline_run_id);
832
+ return loaded === results.main_stuff ? results : { ...results, main_stuff: loaded };
833
+ }
834
+ /** The result artifacts the concept at each path is read from. */
835
+ const CONCEPT_ARTIFACTS = ["working_memory", "output_form", "input_form"];
836
+ /**
837
+ * The concept facts of a run's results: the results themselves when their read carried the
838
+ * working memory and the forms (`selection` undefined reads every artifact), else those three
839
+ * read again by the run's id, beside the results. Nothing is read when nothing is missing, and a
840
+ * second read that finds no completed run leaves the results as they are.
841
+ */
842
+ export async function withConceptArtifacts(client, results, selection, signal) {
843
+ if (selection === undefined)
844
+ return results;
845
+ const missing = CONCEPT_ARTIFACTS.filter((artifact) => !selection.includes(artifact));
846
+ if (missing.length === 0)
847
+ return results;
848
+ const state = await client.getRunResult(results.pipeline_run_id, {
849
+ signal,
850
+ artifacts: missing,
851
+ loadStoredTexts: false,
852
+ });
853
+ if (state.state !== "completed")
854
+ return results;
855
+ const concepts = {};
856
+ for (const artifact of missing) {
857
+ concepts[artifact] = state.result[artifact];
858
+ }
859
+ return { ...results, ...concepts };
860
+ }
861
+ /**
862
+ * Whether a value holds anything shaped like a stored text's reference, which is what makes a read
863
+ * that left the concepts out read them again: an object carrying a string `url`, no inline value
864
+ * field, and a `size` or a `preview`, which the runtime sets on every reference it stores and an
865
+ * image or a document content never carries. So an output of images and documents alone answers
866
+ * `false`. A `true` says only that the concepts are worth reading, the concept at each path still
867
+ * deciding; a `false` says no stored text the runtime made can be there.
868
+ */
869
+ export function mayHoldStoredTexts(value) {
870
+ if (Array.isArray(value))
871
+ return value.some(mayHoldStoredTexts);
872
+ if (typeof value !== "object" || value === null)
873
+ return false;
874
+ const fields = value;
875
+ if (typeof fields["url"] === "string" &&
876
+ Object.values(STORED_TEXT_VALUE_FIELD).every((field) => fields[field] == null) &&
877
+ ("size" in fields || "preview" in fields)) {
878
+ return true;
879
+ }
880
+ return Object.values(fields).some(mayHoldStoredTexts);
881
+ }
882
+ /**
883
+ * Whether a results read narrowed to `selection` carried every artifact the concept at each path
884
+ * is read from: the working memory and both forms. `undefined`, a read of every artifact, does.
885
+ */
886
+ export function carriesConceptArtifacts(selection) {
887
+ return (selection === undefined || CONCEPT_ARTIFACTS.every((artifact) => selection.includes(artifact)));
888
+ }
889
+ /** `value` with its stored texts loaded, walked with `node`; `value` itself when it holds none. */
890
+ async function loadStoredTextValues(client, value, node, options, runId) {
891
+ const sites = findStoredTexts(value, node);
892
+ if (sites.length === 0)
893
+ return value;
894
+ const concurrency = options.concurrency ?? DEFAULT_STORED_TEXT_CONCURRENCY;
895
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
896
+ throw new ArtifactOperationError(`"concurrency" must be a positive integer, got ${String(concurrency)}.`, { problem: argumentInvalidProblem("concurrency", "not_positive") });
897
+ }
898
+ const bounds = fetchBounds({
899
+ maxBytes: options.maxBytes ?? DEFAULT_STORED_TEXT_MAX_BYTES,
900
+ timeoutMs: options.timeoutMs,
901
+ allowHttp: options.allowHttp,
902
+ signal: options.signal,
903
+ });
904
+ // One read per distinct URL, named by the first place it was found.
905
+ const firstSite = new Map();
906
+ for (const site of sites)
907
+ if (!firstSite.has(site.url))
908
+ firstSite.set(site.url, site);
909
+ const urls = [...firstSite.keys()];
910
+ const references = urls.filter(isStorageReference);
911
+ const resolved = new Map();
912
+ let items;
913
+ try {
914
+ items = await resolveArtifacts(client, references, { signal: options.signal });
915
+ }
916
+ catch (err) {
917
+ if (options.signal?.aborted === true)
918
+ throw options.signal.reason;
919
+ // A whole-request failure of the route, a bare runner's 404 among them, is the first text's.
920
+ const site = firstSite.get(references[0]);
921
+ const path = renderPath(site.segments);
922
+ const detail = err instanceof Error ? err.message : String(err);
923
+ throw new StoredTextLoadError(`The stored text at ${path} could not be loaded: the platform's bulk resolve route failed: ${detail}`, {
924
+ uri: site.url,
925
+ path,
926
+ reason: "resolve_failed",
927
+ status: err instanceof ApiResponseError ? err.status : undefined,
928
+ }, { cause: err, problem: err instanceof ProblemError ? err.problem : undefined });
929
+ }
930
+ references.forEach((uri, index) => resolved.set(uri, items[index]));
931
+ const texts = new Map();
932
+ const dispatcher = await dispatcherFor(bounds.timeoutMs);
933
+ try {
934
+ let next = 0;
935
+ const worker = async () => {
936
+ for (;;) {
937
+ const index = next;
938
+ next += 1;
939
+ if (index >= urls.length)
940
+ return;
941
+ const url = urls[index];
942
+ const site = firstSite.get(url);
943
+ const bytes = await readStoredBytes(site, resolved.get(url), bounds, dispatcher);
944
+ texts.set(url, decodeStoredValue(site, bytes, runId));
945
+ }
946
+ };
947
+ await Promise.all(Array.from({ length: Math.min(concurrency, urls.length) }, worker));
948
+ }
949
+ finally {
950
+ void dispatcher?.close().catch(() => undefined);
951
+ }
952
+ let loaded = structuredClone(value);
953
+ for (const site of sites) {
954
+ loaded = replaceAt(loaded, site.segments, loadedForm(site, texts.get(site.url)));
955
+ }
956
+ return loaded;
957
+ }
958
+ /**
959
+ * Every stored text's reference in `value`, in walk order, the concept at each path read off
960
+ * `node`. Throws `StoredTextLoadError` (`unsupported_url`) for a stored text whose `url` the
961
+ * loader never reads ({@link isLoadableStoredTextUrl}), before anything is sent.
962
+ */
963
+ function findStoredTexts(value, node) {
964
+ const sites = [];
965
+ const trail = [];
966
+ const visit = (current, described) => {
967
+ const kind = storedTextKindOfNode(described);
968
+ if (kind !== null) {
969
+ const url = storedTextReferenceUrl(current, kind);
970
+ if (url === null)
971
+ return;
972
+ if (!isLoadableStoredTextUrl(url)) {
973
+ const path = renderPath(trail);
974
+ throw new StoredTextLoadError(`The stored text at ${path} could not be loaded: its url is neither a pipelex-storage:// ` +
975
+ "reference nor a data: URL, so it is not fetched; read the result with " +
976
+ "loadStoredTexts: false to see it as written.", { uri: url, path, reason: "unsupported_url" });
977
+ }
978
+ sites.push({
979
+ segments: [...trail],
980
+ kind,
981
+ url,
982
+ reference: current,
983
+ });
984
+ return;
985
+ }
986
+ if (Array.isArray(current)) {
987
+ current.forEach((entry, index) => {
988
+ trail.push(index);
989
+ visit(entry, childNode(described, current, index));
990
+ trail.pop();
991
+ });
992
+ return;
993
+ }
994
+ if (typeof current === "object" && current !== null) {
995
+ for (const [key, entry] of Object.entries(current)) {
996
+ trail.push(key);
997
+ visit(entry, childNode(described, current, key));
998
+ trail.pop();
999
+ }
1000
+ }
1001
+ };
1002
+ visit(value, node);
1003
+ return sites;
1004
+ }
1005
+ /** The bytes of one stored text: a reference's signed link fetched, or a `data:` URL decoded. Nothing else is read. */
1006
+ async function readStoredBytes(site, resolved, bounds, dispatcher) {
1007
+ const path = renderPath(site.segments);
1008
+ const fail = (reason, detail, extra) => {
1009
+ throw new StoredTextLoadError(`The stored text at ${path} could not be loaded: ${detail}`, { uri: site.url, path, reason, status: extra?.status }, { cause: extra?.cause, problem: extra?.problem });
1010
+ };
1011
+ if (site.url.startsWith("data:")) {
1012
+ const bytes = decodeDataUrl(site.url);
1013
+ if (bytes === null)
1014
+ return fail("unsupported_url", "its data URL does not decode.");
1015
+ if (bytes.byteLength > bounds.maxBytes) {
1016
+ return fail("too_large", `it is ${formatMiB(bytes.byteLength)}, over the ${formatMiB(bounds.maxBytes)} cap.`, {
1017
+ problem: downloadLimitProblem(bounds.maxBytes),
1018
+ });
1019
+ }
1020
+ return bytes;
1021
+ }
1022
+ // Unreachable: the walk admits only a reference or a data: URL, and every reference is resolved first.
1023
+ if (resolved === undefined) {
1024
+ return fail("unsupported_url", "its url was not resolved by the platform.");
1025
+ }
1026
+ if (resolved.error !== null)
1027
+ return fail(resolved.error.code, resolved.error.detail);
1028
+ const link = resolved.url;
1029
+ try {
1030
+ const response = await fetchResolvedUrl(site.url, link, bounds, dispatcher, () => undefined);
1031
+ return new Uint8Array(await response.arrayBuffer());
1032
+ }
1033
+ catch (err) {
1034
+ if (bounds.signal?.aborted === true)
1035
+ throw bounds.signal.reason;
1036
+ if (err instanceof ArtifactFetchError) {
1037
+ return fail(err.reason, err.message, {
1038
+ cause: err,
1039
+ problem: err.problem,
1040
+ status: err.status,
1041
+ });
1042
+ }
1043
+ return fail("unknown", err instanceof Error ? err.message : String(err), { cause: err });
1044
+ }
1045
+ }
1046
+ /** A `data:` URL's bytes, base64 or percent-encoded, or `null` when it is no data URL. */
1047
+ function decodeDataUrl(url) {
1048
+ const comma = url.indexOf(",");
1049
+ if (comma < 0)
1050
+ return null;
1051
+ const header = url.slice("data:".length, comma);
1052
+ const payload = url.slice(comma + 1);
1053
+ try {
1054
+ if (/;base64$/i.test(header)) {
1055
+ const binary = atob(payload);
1056
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
1057
+ }
1058
+ return new TextEncoder().encode(decodeURIComponent(payload));
1059
+ }
1060
+ catch {
1061
+ return null;
1062
+ }
1063
+ }
1064
+ /** The value one stored text holds: its UTF-8 text, or for a JSON value the object that text serializes. */
1065
+ function decodeStoredValue(site, bytes, runId) {
1066
+ const path = renderPath(site.segments);
1067
+ const unreadable = (reason, detail, cause) => {
1068
+ throw new StoredTextLoadError(`The stored text at ${path} could not be loaded: ${detail}`, { uri: site.url, path, reason }, { cause, problem: responseUnreadableProblem(200, runId) });
1069
+ };
1070
+ let text;
1071
+ try {
1072
+ // The bytes as stored, a byte-order mark included: the value is exactly what was stored.
1073
+ text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
1074
+ }
1075
+ catch (err) {
1076
+ return unreadable("not_utf8", "its bytes are not UTF-8 text.", err);
1077
+ }
1078
+ if (site.kind !== "json")
1079
+ return text;
1080
+ let parsed;
1081
+ try {
1082
+ parsed = parseExactJson(text);
1083
+ }
1084
+ catch (err) {
1085
+ return unreadable("not_json_object", "its bytes are not JSON.", err);
1086
+ }
1087
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1088
+ return unreadable("not_json_object", "its JSON is not an object.");
1089
+ }
1090
+ return parsed;
1091
+ }
1092
+ /** The inline form of a loaded stored text: its value field first, its other inline fields kept. */
1093
+ function loadedForm(site, value) {
1094
+ const loaded = { [STORED_TEXT_VALUE_FIELD[site.kind]]: value };
1095
+ const dropped = STORED_TEXT_REFERENCE_FIELDS;
1096
+ for (const [key, entry] of Object.entries(site.reference)) {
1097
+ if (!dropped.includes(key))
1098
+ loaded[key] = entry;
1099
+ }
1100
+ return loaded;
1101
+ }
1102
+ /** `root` with the value at `segments` replaced, in place below the root; the new value itself at `$`. */
1103
+ function replaceAt(root, segments, value) {
1104
+ if (segments.length === 0)
1105
+ return value;
1106
+ let parent = root;
1107
+ for (const segment of segments.slice(0, -1)) {
1108
+ parent = parent[segment];
1109
+ }
1110
+ parent[segments.at(-1)] = value;
1111
+ return root;
1112
+ }
690
1113
  /**
691
1114
  * Write the whole chunk, looping on short writes. `FileHandle.write()` resolves
692
1115
  * with the count it managed, which can fall short of the chunk on a filesystem
@@ -740,6 +1163,7 @@ const SKIPPED_TOTAL = "Skipped: the download's total byte limit was reached by a
740
1163
  function itemError(location, contentType, code, detail) {
741
1164
  return {
742
1165
  uri: location.uri,
1166
+ kind: location.kind,
743
1167
  found_at: location.found_at,
744
1168
  path: null,
745
1169
  content_type: contentType,
@@ -760,7 +1184,12 @@ function isCredentialRefusal(err) {
760
1184
  * platform reads and re-signs nothing the download does not walk.
761
1185
  */
762
1186
  async function readCompletedResults(client, runId, scope, signal) {
763
- const state = await client.getRunResult(runId, { signal, artifacts: [scope] });
1187
+ // Files only: the stored texts are values, which the walk skips by concept rather than loads.
1188
+ const state = await client.getRunResult(runId, {
1189
+ signal,
1190
+ artifacts: [scope],
1191
+ loadStoredTexts: false,
1192
+ });
764
1193
  if (state.state === "running") {
765
1194
  throw new RunStillRunningError(`Run ${runId} is still running, so it has no artifacts to download yet` +
766
1195
  (state.retry_after_seconds != null ? ` — retry in ${state.retry_after_seconds}s.` : "."), runId, state.retry_after_seconds);
@@ -831,13 +1260,37 @@ export async function downloadArtifacts(client, request) {
831
1260
  if (walked == null) {
832
1261
  throw new ScopeUnavailableError(scope, runId);
833
1262
  }
834
- // The walk's own record names the files; `locations` is what the verdict reports.
835
- const located = walkReferences(walked);
1263
+ // The concept at each path tells a stored text, a value of the run, from a file. A run read by
1264
+ // id asked for its scope alone, so its concepts are read beside it when the walk may need them.
1265
+ const source = !hasResults && mayHoldStoredTexts(walked)
1266
+ ? await withConceptArtifacts(client, results, [scope], request.signal)
1267
+ : results;
1268
+ const node = scope === "main_stuff"
1269
+ ? mainStuffNode({ ...source, main_stuff: walked })
1270
+ : workingMemoryNode(source);
1271
+ // The walk's own record names the files; `locations` is what the verdict reports. A stored text
1272
+ // is saved too, as a text file named by its MIME type.
1273
+ const located = walkReferences(walked, true, node ?? undefined, true);
836
1274
  if (located.length === 0) {
837
1275
  return { scope, artifacts: [], saved_paths: [], all_saved: true };
838
1276
  }
839
- const locations = located.map(renderLocation);
1277
+ const locations = located.map((reference) => ({
1278
+ ...renderLocation(reference),
1279
+ kind: reference.text === undefined ? "file" : "text",
1280
+ }));
840
1281
  const uris = located.map((reference) => reference.uri);
1282
+ // A stored text's MIME type is its reference's, the platform's guess from the key otherwise.
1283
+ const contentTypeOf = (index, resolvedType) => {
1284
+ const stated = located[index].text?.reference["mime_type"];
1285
+ return typeof stated === "string" ? stated : resolvedType;
1286
+ };
1287
+ const filenameOf = (index, contentType) => {
1288
+ const reference = located[index];
1289
+ const extension = reference.text === undefined
1290
+ ? extensionFor(reference.uri, contentType)
1291
+ : textExtensionFor(reference.text.kind, contentType);
1292
+ return filenameFor(reference.paths[0], extension, scope);
1293
+ };
841
1294
  const fs = host.fs;
842
1295
  const path = host.path;
843
1296
  const dir = path.resolve(request.dir);
@@ -915,7 +1368,7 @@ export async function downloadArtifacts(client, request) {
915
1368
  const share = () => Math.max(written, reserved);
916
1369
  let target;
917
1370
  try {
918
- const filename = filenameFor(located[index].paths[0], uri, contentType, scope);
1371
+ const filename = filenameOf(index, contentType);
919
1372
  target = await openUniqueFile(fs, path, dir, filename);
920
1373
  }
921
1374
  catch (err) {
@@ -939,6 +1392,7 @@ export async function downloadArtifacts(client, request) {
939
1392
  committedBytes -= share();
940
1393
  return {
941
1394
  uri,
1395
+ kind: location.kind,
942
1396
  found_at: location.found_at,
943
1397
  path: target.path,
944
1398
  content_type: contentType,
@@ -991,6 +1445,7 @@ export async function downloadArtifacts(client, request) {
991
1445
  savedBytes += written;
992
1446
  return {
993
1447
  uri,
1448
+ kind: location.kind,
994
1449
  found_at: location.found_at,
995
1450
  path: target.path,
996
1451
  content_type: contentType,
@@ -1007,11 +1462,11 @@ export async function downloadArtifacts(client, request) {
1007
1462
  const location = locations[index];
1008
1463
  let entry = resolved[index];
1009
1464
  if (credentialFailure !== undefined || aborted()) {
1010
- outcomes[index] = itemError(location, entry.content_type, "aborted", credentialFailure ? SKIPPED_CREDENTIAL : SKIPPED_ABORTED);
1465
+ outcomes[index] = itemError(location, contentTypeOf(index, entry.content_type), "aborted", credentialFailure ? SKIPPED_CREDENTIAL : SKIPPED_ABORTED);
1011
1466
  continue;
1012
1467
  }
1013
1468
  if (limitReached) {
1014
- outcomes[index] = itemError(location, entry.content_type, "total_limit_exceeded", SKIPPED_TOTAL);
1469
+ outcomes[index] = itemError(location, contentTypeOf(index, entry.content_type), "total_limit_exceeded", SKIPPED_TOTAL);
1015
1470
  continue;
1016
1471
  }
1017
1472
  if (entry.error === null && isExpired(entry.expires_at)) {
@@ -1022,22 +1477,22 @@ export async function downloadArtifacts(client, request) {
1022
1477
  catch (err) {
1023
1478
  if (isCredentialRefusal(err)) {
1024
1479
  credentialFailure = err;
1025
- outcomes[index] = itemError(location, entry.content_type, "aborted", SKIPPED_CREDENTIAL);
1480
+ outcomes[index] = itemError(location, contentTypeOf(index, entry.content_type), "aborted", SKIPPED_CREDENTIAL);
1026
1481
  continue;
1027
1482
  }
1028
1483
  if (aborted()) {
1029
- outcomes[index] = itemError(location, entry.content_type, "aborted", SKIPPED_ABORTED);
1484
+ outcomes[index] = itemError(location, contentTypeOf(index, entry.content_type), "aborted", SKIPPED_ABORTED);
1030
1485
  continue;
1031
1486
  }
1032
- outcomes[index] = itemError(location, entry.content_type, "resolve_failed", `The expired link could not be re-resolved: ${err instanceof Error ? err.message : String(err)}.`);
1487
+ outcomes[index] = itemError(location, contentTypeOf(index, entry.content_type), "resolve_failed", `The expired link could not be re-resolved: ${err instanceof Error ? err.message : String(err)}.`);
1033
1488
  continue;
1034
1489
  }
1035
1490
  }
1036
1491
  if (entry.error !== null) {
1037
- outcomes[index] = itemError(location, null, entry.error.code, entry.error.detail);
1492
+ outcomes[index] = itemError(location, contentTypeOf(index, null), entry.error.code, entry.error.detail);
1038
1493
  continue;
1039
1494
  }
1040
- outcomes[index] = await saveOne(index, entry.url, entry.content_type);
1495
+ outcomes[index] = await saveOne(index, entry.url, contentTypeOf(index, entry.content_type));
1041
1496
  }
1042
1497
  };
1043
1498
  try {