@pipelex/sdk 0.69.5 → 0.71.1

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.
@@ -0,0 +1,175 @@
1
+ /**
2
+ * The format stage's write-back: the formatted `.mthds` replaces the user's file atomically,
3
+ * unless a replacement would lose something the file carries, in which case it is written in
4
+ * place as before.
5
+ *
6
+ * The formatted text is written to a temporary file in the target's own directory, given the
7
+ * target's owner and group, flushed to disk, given the target's permission bits, then renamed
8
+ * over the target. A rename within one directory is atomic, so a hook killed at any moment
9
+ * (Claude Code's hook timeout, the plugin wrapper's SIGKILL) leaves either the original file or
10
+ * the formatted one, never a truncated one. The temporary file's name starts with a dot, so the
11
+ * tree lister, which keeps out hidden entries, never sends it, and every failure path removes it.
12
+ *
13
+ * A rename puts a new file at the target's name, so the write-back falls back to writing into
14
+ * the file in place, the hook's behaviour before the rename, where the new file could not be the
15
+ * same as the old one in what matters to the user: when the file has several hard links, whose
16
+ * other names would keep the old content, and on POSIX when the process cannot give the new
17
+ * file the original's owner and group (a file owned by another user, or by a group the user is
18
+ * not in). Extended attributes and access control lists are not carried over and not detected:
19
+ * Node has no API to read them, macOS puts an attribute on nearly every file, and an
20
+ * inheritable ACL on the directory reaches the new file as it reached the old one
21
+ * (`docs/hook-bundle.md`, "How the format is written").
22
+ *
23
+ * On Windows a rename over an existing file fails while another process holds the target open
24
+ * without delete sharing, as an antivirus scanner, a search indexer or an editor briefly does
25
+ * after a save, with `EPERM`, `EACCES` or `EBUSY`. Those codes are retried a few times over
26
+ * well under a second, which outlasts such a hold. Before each retry the target is read again,
27
+ * and when it no longer holds the text that was formatted, a newer save landed meanwhile: the
28
+ * write-back gives up and keeps it. When the hold persists, the temporary file is removed and
29
+ * the error is raised, so the caller reports that the format could not be written and the
30
+ * user's file stays exactly as it was.
31
+ */
32
+ import { randomBytes } from "node:crypto";
33
+ import * as nodeFs from "node:fs";
34
+ import { basename, dirname, join } from "node:path";
35
+ /** About 0.6 seconds in all, far below the hook's own deadline. */
36
+ export const WINDOWS_RENAME_RETRY_DELAYS_MS = [10, 20, 40, 80, 160, 300];
37
+ const WINDOWS_TRANSIENT_RENAME_CODES = new Set(["EPERM", "EACCES", "EBUSY"]);
38
+ function sleepSync(ms) {
39
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
40
+ }
41
+ function errorCode(err) {
42
+ if (typeof err === "object" && err !== null && "code" in err) {
43
+ const code = err.code;
44
+ return typeof code === "string" ? code : undefined;
45
+ }
46
+ return undefined;
47
+ }
48
+ /**
49
+ * Write the formatter's result back to `filePath` when it changed anything. `original` is the
50
+ * text the formatter was given, which the file must still hold for a Windows retry to replace it.
51
+ * Throws when the file cannot be written; the original is then left untouched and no temporary
52
+ * file remains.
53
+ */
54
+ export function writeBackFormatted(filePath, original, result, options = {}) {
55
+ if (!result.changed) {
56
+ return "unchanged";
57
+ }
58
+ return replaceFileContent(filePath, original, result.formatted, options);
59
+ }
60
+ /**
61
+ * Replace the content of the file at `filePath`, which held `original`, with `content`: through
62
+ * a temporary file and a rename, or in place when a rename would lose the file's other hard links
63
+ * or its owner and group. A symbolic link is followed, so the file it points to is written and
64
+ * the link kept.
65
+ */
66
+ export function replaceFileContent(filePath, original, content, options = {}) {
67
+ const fs = options.fs ?? nodeFs;
68
+ const platform = options.platform ?? process.platform;
69
+ const sleep = options.sleep ?? sleepSync;
70
+ const retryDelays = platform === "win32" ? (options.renameRetryDelaysMs ?? WINDOWS_RENAME_RETRY_DELAYS_MS) : [];
71
+ // The native realpath answers the name as the directory stores it, so the rename keeps its
72
+ // case on a case-insensitive filesystem whatever case the agent wrote the path in.
73
+ const target = fs.realpathSync.native(filePath);
74
+ // An in-place write refused a file the user cannot write; a rename would not, so ask first.
75
+ fs.accessSync(target, nodeFs.constants.W_OK);
76
+ const stats = fs.statSync(target);
77
+ if (stats.nlink > 1) {
78
+ // A rename would leave the file's other names holding the old content.
79
+ fs.writeFileSync(target, content);
80
+ return "written-in-place";
81
+ }
82
+ const mode = stats.mode & 0o7777;
83
+ const temporary = join(dirname(target), `.${basename(target)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
84
+ let created = false;
85
+ let ownershipKept = false;
86
+ try {
87
+ // `wx`: never reuse a path someone else holds.
88
+ const fd = fs.openSync(temporary, "wx", mode);
89
+ created = true;
90
+ try {
91
+ ownershipKept = platform === "win32" || giveOwnership(fs, fd, stats);
92
+ if (ownershipKept) {
93
+ fs.writeFileSync(fd, content);
94
+ fs.fsyncSync(fd);
95
+ }
96
+ }
97
+ finally {
98
+ fs.closeSync(fd);
99
+ }
100
+ if (ownershipKept) {
101
+ // The mode given to `open` went through the umask, and a `chown` may clear the set-id
102
+ // bits; set the original's bits exactly.
103
+ fs.chmodSync(temporary, mode);
104
+ renameWithRetries(fs, temporary, target, original, retryDelays, sleep);
105
+ created = false;
106
+ return "replaced";
107
+ }
108
+ }
109
+ finally {
110
+ if (created) {
111
+ try {
112
+ fs.unlinkSync(temporary);
113
+ }
114
+ catch {
115
+ // Nothing more can be done; the original is intact either way.
116
+ }
117
+ }
118
+ }
119
+ // The new file could not take the original's owner and group, so write into the original.
120
+ fs.writeFileSync(target, content);
121
+ return "written-in-place";
122
+ }
123
+ /**
124
+ * Give the open temporary file the original's owner and group, which it gets from the process
125
+ * (and on BSD and macOS its group from the directory). True when the two now match.
126
+ */
127
+ function giveOwnership(fs, fd, original) {
128
+ const created = fs.fstatSync(fd);
129
+ if (created.uid === original.uid && created.gid === original.gid) {
130
+ return true;
131
+ }
132
+ try {
133
+ fs.fchownSync(fd, original.uid, original.gid);
134
+ return true;
135
+ }
136
+ catch {
137
+ // Only root gives a file away, and a user can only choose a group they are in.
138
+ return false;
139
+ }
140
+ }
141
+ function annotateStillHeld(err, attempts) {
142
+ if (err instanceof Error) {
143
+ err.message = `${err.message} (still held after ${attempts} attempts; the file was left as it was)`;
144
+ }
145
+ return err;
146
+ }
147
+ function renameWithRetries(fs, from, to, original, retryDelays, sleep) {
148
+ for (let attempt = 0;; attempt += 1) {
149
+ try {
150
+ fs.renameSync(from, to);
151
+ return;
152
+ }
153
+ catch (err) {
154
+ const code = errorCode(err);
155
+ const retried = code !== undefined && WINDOWS_TRANSIENT_RENAME_CODES.has(code);
156
+ const delay = retryDelays[attempt];
157
+ if (!retried || delay === undefined) {
158
+ throw retried && attempt > 0 ? annotateStillHeld(err, attempt + 1) : err;
159
+ }
160
+ sleep(delay);
161
+ // A newer save made while the file was held must not be overwritten with older content.
162
+ let current;
163
+ try {
164
+ current = fs.readFileSync(to, "utf-8");
165
+ }
166
+ catch {
167
+ throw annotateStillHeld(err, attempt + 1);
168
+ }
169
+ if (current !== original) {
170
+ throw new Error(`${to} changed while its formatted copy waited to replace it; the newer content was kept`);
171
+ }
172
+ }
173
+ }
174
+ }
175
+ //# sourceMappingURL=format-write.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format-write.js","sourceRoot":"","sources":["../../src/hooks/format-write.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,KAAK,MAAM,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAyCpD,mEAAmE;AACnE,MAAM,CAAC,MAAM,8BAA8B,GAAsB,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAE5F,MAAM,8BAA8B,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC;AAE7E,SAAS,SAAS,CAAC,EAAU;IAC3B,OAAO,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,iBAAiB,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,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aseDetail, MethodShowcaseDocument, MethodShowcaseFile, MethodShowcaseFreezeOutcome, MethodShowcaseFreezeResult, MethodShowcaseFrozen, MethodShowcaseInput, MethodShowcaseList, MethodShowcaseRefusalReason, MethodShowcaseRefused, MethodShowcaseSummary, MethodShowcaseUnchanged, } from "./method-showcases.js";
35
35
  export { runCodegenCheck, isStampableArtifactPath, STAMPABLE_ARTIFACT_SUFFIXES, CodegenLockError, } from "./codegen-check.js";
36
36
  export type { CodegenCheckInput, CodegenCheckReport, CodegenDrift, CodegenDriftCategory, CodegenTreeFile, } from "./codegen-check.js";
37
- export type { UserProfile, BundleStorageReference, ListMethodExamplesQuery, ListMethodsQuery, ListMethodTemplatesQuery, ListMethodVersionsQuery, MethodCategory, MethodCategoryList, MethodCopied, MethodCopiedFrom, MethodCopyInput, MethodCopyLimit, MethodCopyOutcome, MethodCopyRefusalReason, MethodCopyRefused, MethodCopyResult, MethodData, MethodDeletionAccepted, MethodDeletionState, MethodDetail, MethodDraftInput, MethodExample, MethodExampleAssistantCreated, MethodExampleAssistantKept, MethodExampleAssistantSaveInput, MethodExampleAssistantSaveOutcome, MethodExampleAssistantSaveResult, MethodExampleCreateInput, MethodExampleLatestRunInput, MethodExampleLatestRunOutcome, MethodExampleLatestRunRecorded, MethodExampleLatestRunResult, MethodExampleLatestRunStale, MethodExamplePage, MethodExampleUpdateInput, MethodPage, MethodPublished, MethodPublishInput, MethodPublishOutcome, MethodPublishRefusalReason, MethodPublishRefused, MethodPublishResult, MethodPublishUnchanged, MethodRenameInput, MethodSummary, MethodTemplate, MethodTemplatePage, MethodTemplateThumbnail, MethodThumbnail, MethodTreeInput, MethodVersion, MethodVersionPage, MethodVersionSummary, MethodVisibility, MethodWriteInput, PublicMethodDetail, SavedMethodFile, Membership, MembershipsResponse, OrgRole, BrandingColors, BrandingColorsUpdate, LogoDescriptor, OrganizationBranding, OrganizationBrandingUpdate, SubscriptionResponse, PlanView, InvoiceView, CheckoutResponse, ChangePlanResponse, BillingPortalResponse, PipelexApiKey, PipelexApiKeyCreated, PipelexApiKeyList, OnboardingRole, OnboardingCurrentTool, OnboardingInputType, OnboardingHeardFrom, OnboardingSubmission, DraftFileAdded, DraftFileBlob, DraftFileFromFileInput, DraftFileFromFileResult, FileArchive, FileArchiveFailure, FileArchiveFailureCode, FileArchiveLimit, FileArchiveRequest, FileArchiveSource, FileArchiveState, FileDetail, FileKind, FileLink, FileLinkError, FileLinksResult, FileLinkTarget, FileOrigin, FilePage, FileRecord, FileRecordList, FileRenameInput, FileRole, FileState, FileSummary, FileUse, FileUseHolderType, FileUsePage, GetFileQuery, GetFilesByUriOptions, ListFilesQuery, ListRunFilesQuery, RunFileEntry, RunFileMark, RunFilesPage, RunFilesState, RunInputLink, ResolvedStorageUrl, UploadInput, UploadedFile, UploadGrantInput, UploadGrant, UploadKind, ListRunsQuery, PipelineRun, RunDetail, RunHistoryItem, RunPage, UpdateRunInput, } from "./product-models.js";
37
+ export type { UserProfile, BundleStorageReference, ListMethodExamplesQuery, ListMethodsQuery, ListMethodTemplatesQuery, ListMethodVersionsQuery, MethodCategory, MethodCategoryList, MethodCopied, MethodCopiedFrom, MethodCopyInput, MethodCopyLimit, MethodCopyOutcome, MethodCopyRefusalReason, MethodCopyRefused, MethodCopyResult, MethodData, MethodDeletionAccepted, MethodDeletionState, MethodDetail, MethodDraftInput, MethodExample, MethodExampleAssistantCreated, MethodExampleAssistantKept, MethodExampleAssistantSaveInput, MethodExampleAssistantSaveOutcome, MethodExampleAssistantSaveResult, MethodExampleCreateInput, MethodExampleLatestRunInput, MethodExampleLatestRunOutcome, MethodExampleLatestRunRecorded, MethodExampleLatestRunResult, MethodExampleLatestRunStale, MethodExamplePage, MethodExampleUpdateInput, MethodPage, MethodPublished, MethodPublishInput, MethodPublishOutcome, MethodPublishRefusalReason, MethodPublishRefused, MethodPublishResult, MethodPublishUnchanged, MethodRenameInput, MethodSummary, MethodTemplate, MethodTemplatePage, MethodTemplateThumbnail, MethodThumbnail, MethodTreeInput, MethodVersion, MethodVersionPage, MethodVersionSummary, MethodVisibility, MethodWriteInput, PublicMethodDetail, SavedMethodFile, Membership, MembershipsResponse, OrgRole, BrandingColors, BrandingColorsUpdate, LogoDescriptor, OrganizationBranding, OrganizationBrandingUpdate, SubscriptionResponse, PlanView, InvoiceView, CheckoutResponse, ChangePlanResponse, BillingPortalResponse, PipelexApiKey, PipelexApiKeyCreated, PipelexApiKeyList, OnboardingRole, OnboardingCurrentTool, OnboardingInputType, OnboardingHeardFrom, OnboardingSubmission, DraftFileAdded, DraftFileBlob, DraftFileFromFileInput, DraftFileFromFileResult, FileArchive, FileArchiveFailure, FileArchiveFailureCode, FileArchiveLimit, FileArchiveRequest, FileArchiveSource, FileArchiveState, FileDetail, FileKind, FileLink, FileLinkError, FileLinksResult, FileLinkTarget, FileOrigin, FilePage, FilePreview, FilePreviewFailure, FilePreviewFailureCode, FilePreviewState, FileRecord, FileRecordList, FileRenameInput, FileRole, FileState, FileSummary, FileUse, FileUseHolderType, FileUsePage, GetFileQuery, GetFilesByUriOptions, ListFilesQuery, ListRunFilesQuery, RunFileEntry, RunFileMark, RunFilesPage, RunFilesState, RunInputLink, ResolvedStorageUrl, UploadInput, UploadedFile, UploadGrantInput, UploadGrant, UploadKind, ListRunsQuery, PipelineRun, RunDetail, RunHistoryItem, RunPage, UpdateRunInput, } from "./product-models.js";
38
38
  export { isFresherRunProgress, isTerminalRunStatus, isSuccessRunStatus, RUN_RESULT_ARTIFACTS, } from "./runs.js";
39
39
  export type { DegradationReason, GetRunResultOptions, ProgressAttempt, ProgressBatch, ProgressCondition, ProgressFailure, ProgressInvocation, ProgressInvocationStatus, RunDegradation, RunProgress, RunProgressStatus, RunResultArtifact, RunStatus, RunPublic, RunRead, RunResults, RunResultState, StartAndWaitForResultOptions, TokensUsageRecord, WaitForResultOptions, } from "./runs.js";
40
40
  export { verifyWebhook, isRunFinishedEvent, RUN_FINISHED_EVENT_TYPE, WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS, WebhookVerificationError, WebhookEventUnreadableError, } from "./webhooks.js";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,6FAA6F;AAC7F,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,oFAAoF;AACpF,kFAAkF;AAClF,mFAAmF;AACnF,wBAAwB;AACxB,cAAc,gBAAgB,CAAC;AAE/B,wEAAwE;AACxE,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACtF,sFAAsF;AACtF,yFAAyF;AACzF,2EAA2E;AAC3E,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAoBzF,oFAAoF;AACpF,6FAA6F;AAC7F,+FAA+F;AAC/F,kDAAkD;AAClD,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAE1D,+FAA+F;AAC/F,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAE3D,+FAA+F;AAC/F,6FAA6F;AAC7F,iGAAiG;AACjG,8FAA8F;AAC9F,iEAAiE;AACjE,OAAO,EAAE,yBAAyB,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAEhG,iGAAiG;AACjG,kFAAkF;AAClF,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAQ/E,6FAA6F;AAC7F,6FAA6F;AAC7F,4CAA4C;AAC5C,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAcpE,+FAA+F;AAC/F,0EAA0E;AAC1E,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD,uEAAuE;AACvE,wFAAwF;AACxF,0FAA0F;AAC1F,iFAAiF;AACjF,OAAO,EACL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,EAC5B,qBAAqB,EACrB,uBAAuB,EACvB,sBAAsB,EACtB,qBAAqB,EACrB,eAAe,EACf,kBAAkB,EAClB,gCAAgC,EAChC,yBAAyB,EACzB,oBAAoB,EACpB,oBAAoB,EACpB,sBAAsB,EACtB,2BAA2B,EAC3B,kBAAkB,EAClB,mBAAmB,EACnB,qBAAqB,EACrB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AAcrB,mFAAmF;AACnF,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC"}
@@ -1624,6 +1624,67 @@ export interface FileArchiveLimit {
1624
1624
  value: number;
1625
1625
  reached: number;
1626
1626
  }
1627
+ /**
1628
+ * Where the PDF preview of an Office file stands — what `getFilePreview` answers, the field a
1629
+ * caller branches on: `ready`, its `url` reads the PDF; `preparing`, a conversion is on its way,
1630
+ * so ask again shortly; `failed`, the last conversion failed and `failure` says why; `unavailable`,
1631
+ * the file gets no preview (a type that is not converted, a file over 50 MB, or an address holding
1632
+ * nothing).
1633
+ */
1634
+ export type FilePreviewState = "ready" | "preparing" | "failed" | "unavailable";
1635
+ /**
1636
+ * Why a conversion failed, as the platform names it today:
1637
+ *
1638
+ * - `file_unreadable`, the converter could not open the file, damaged or protected by a password,
1639
+ * which cannot be told apart; the file will fail the same way.
1640
+ * - `file_too_large`, the converter refused the file as over its input cap; it will fail the same
1641
+ * way.
1642
+ * - `conversion_too_slow`, the conversion ran out of the converter's two minutes; it will almost
1643
+ * certainly fail the same way.
1644
+ * - `file_gone`, the bytes were deleted between the request and the conversion.
1645
+ * - `conversion_failed`, the cause is not the file's; a later ask tries again once the failure's
1646
+ * day has passed.
1647
+ */
1648
+ export type FilePreviewFailureCode = "file_unreadable" | "file_too_large" | "conversion_too_slow" | "file_gone" | "conversion_failed";
1649
+ /** What a failed preview says about its failure. A failure stands for a day from when it failed. */
1650
+ export interface FilePreviewFailure {
1651
+ /** One of `FilePreviewFailureCode`, typed open so that a code a later platform adds still reads. */
1652
+ code: FilePreviewFailureCode | (string & {});
1653
+ /** A sentence for a person. */
1654
+ detail: string;
1655
+ }
1656
+ /**
1657
+ * The PDF preview of an Office file — what `getFilePreview`, `GET /v1/files/preview`, answers: a
1658
+ * `200` discriminated on `state`. Every arm carries all four members, the ones its state does not
1659
+ * fill `null`.
1660
+ */
1661
+ export type FilePreview = {
1662
+ state: "ready";
1663
+ /**
1664
+ * A presigned `GET` of the PDF, signed fresh on each read, valid for fifteen minutes and
1665
+ * answered `inline` under the file's name with its extension swapped to `.pdf`. A bearer
1666
+ * capability: keep it out of logs and ask again rather than store it.
1667
+ */
1668
+ url: string;
1669
+ /** ISO-8601 UTC instant `url` stops working. */
1670
+ url_expires_at: string;
1671
+ failure: null;
1672
+ } | {
1673
+ state: "preparing";
1674
+ url: null;
1675
+ url_expires_at: null;
1676
+ failure: null;
1677
+ } | {
1678
+ state: "failed";
1679
+ url: null;
1680
+ url_expires_at: null;
1681
+ failure: FilePreviewFailure;
1682
+ } | {
1683
+ state: "unavailable";
1684
+ url: null;
1685
+ url_expires_at: null;
1686
+ failure: null;
1687
+ };
1627
1688
  /**
1628
1689
  * The copy of a file into a method's draft — `copyFileIntoDraft`,
1629
1690
  * `POST /v1/methods/{id}/draft/files/from-file`, "Add to method files".
package/dist/version.d.ts CHANGED
@@ -3,4 +3,4 @@
3
3
  * `User-Agent` without importing the public barrel. Kept in sync with
4
4
  * `package.json` — enforced by `tests/index.test.ts`.
5
5
  */
6
- export declare const SDK_VERSION = "0.69.5";
6
+ export declare const SDK_VERSION = "0.71.1";
package/dist/version.js CHANGED
@@ -3,5 +3,5 @@
3
3
  * `User-Agent` without importing the public barrel. Kept in sync with
4
4
  * `package.json` — enforced by `tests/index.test.ts`.
5
5
  */
6
- export const SDK_VERSION = "0.69.5";
6
+ export const SDK_VERSION = "0.71.1";
7
7
  //# sourceMappingURL=version.js.map
@@ -125,7 +125,7 @@ Flat `src/` (mirrors `mthds-js`'s `runners/api` flatness — the SDK has one cli
125
125
  - `method-trees.ts` — a saved method's tree on the client side: `MethodTreeSource`, the shape a save reads a tree from, which the `mthds` package's `MethodTree` satisfies; the choice between sending a tree inline and by hash (`INLINE_TREE_MAX_BYTES`), the wire types of `POST /v1/blobs/missing` and the upload of a blob the platform lacks; `redactSignedLinks`, which every error built from an answer holding signed links reads its body through; the tree of an in-memory map; the tree limits a version handshake announces; the listing of a `directory`, by the `mthds` package's lister, which it gets from the Node host only when a directory is given; and the Node-only write of a saved listing to disk, with the file system it gets from the Node host when called. Outside Node, both are refused with `RequestArgumentError`. Its tree-sending half mirrors the `mthds` package's own helpers, which the `mthds/protocol` subpath does not export yet, so it holds the same rules with Web Crypto's SHA-256 and a Base64 writer of its own. See [method-trees.md](./method-trees.md).
126
126
  - `codegen-check.ts` — `runCodegenCheck`, the **pure** offline drift check over a committed codegen tree: the stamp grammar, the `codegen.lock` parser, the hash, and the drift taxonomy, ported from pipelex's `codegen/check.py` so a verdict computed here equals the one `pipelex codegen check` computes over the same bytes (the drift `detail` sentences included, verbatim). It touches no client: its runtime imports are `smol-toml`, `mthds/protocol`'s `ProblemError` and `buildProblem` for the error it raises, the plain-object guard of `records.ts` and `version.ts`'s `SDK_VERSION`, and it hashes through WebCrypto rather than `node:crypto` so it adds no Node builtin to the barrel's import graph. It raises `CodegenLockError`, a `ProblemError` outside the request family, whose problem is `client.file_unreadable` naming `codegen.lock`, `client.tool_outdated` or `client.argument_invalid` ([errors.md](./errors.md#each-classs-problem)). No filesystem, no fetch, no API key — the caller walks its own tree and hands in the text. See [crate-routes.md](./crate-routes.md#the-offline-check--runcodegencheck).
127
127
  - `upload-grant.ts` — the halves of an upload grant (`requestUploadGrant`, `POST /v1/upload/grant`) that run where the bytes are. `describeUpload` reads a file's name, type and size and computes its SHA-256 with Web Crypto, leaving the hash out, and the file unread, past a size bound of 50 MiB by default, and leaving it out where the runtime has no digest. `uploadWithGrant` sends nothing for a grant that answers `stored: true`, and otherwise sends the file as the raw body of a `PUT` to the grant's URL with its signed headers unchanged, redirects refused, a `412` read as stored for a grant that names its bytes, a `409 ConditionalRequestConflict` sent again after a short pause a few times, the whole exchange bounded by a time limit scaled by the file's size unless the caller passes `timeoutMs`, only the first 16 KiB of storage's error body read, and storage's refusals mapped onto the input-preparation errors (`RejectedAssetError` with a `code` for a `4xx` such as the `412` of a used hashless grant, the `403` of a signature mismatch or the `400 BadDigest` of bytes other than the hashed ones, `UploadTransportError` with a `code` for the time limit running out, a `5xx`, storage's `RequestTimeout`, a `409` conflict that outlasted every attempt, a redirect or no response). It is the browser-safe `@pipelex/sdk/upload` entry, so it imports the error classes, the timer bound in `timers.ts` and the wire types only, never the client. See [input-preparation.md](./input-preparation.md#uploading-with-a-grant--requestuploadgrant--uploadwithgrant).
128
- - `artifacts.ts` — the artifact stack, the download twin of `prepareInputs`, in layers: `locateArtifacts` (a pure, exported walk for `pipelex-storage://` references, each with every `$`-rooted path it sits at) and `collectArtifacts` (the same walk's bare references), `resolveArtifacts` (the bulk resolve route over a whole list, chunked at its bound), `fetchArtifact` (one reference as a bounded `Response`) and `downloadArtifacts` (Node-only, a run's produced files saved under a directory as a produced verdict), plus `artifactFilename`, the rule that names a saved file after the field it fills. The three network operations are client methods over a small structural seam (`ArtifactCapableClient`: the raw `resolveStorageUrls` call and `getRunResult`); the module's graph, static and dynamic, stays free of Node builtins, because `node:fs/promises`, `node:path` and `undici` come from the Node host. `undici` is a runtime dependency for one reason: the fetch runs on an `Agent` carrying `headersTimeout` and `bodyTimeout`, the per-stall bounds an `AbortSignal` budget does not give, and Node exposes its bundled undici's `fetch` but not its `Agent`. See [artifact-download.md](./artifact-download.md).
128
+ - `artifacts.ts` — the artifact stack, the download twin of `prepareInputs`, in layers: `locateArtifacts` (a pure, exported walk for `pipelex-storage://` references, each with every `$`-rooted path it sits at) and `collectArtifacts` (the same walk's bare references), `resolveArtifacts` (the bulk resolve route over a whole list, chunked at its bound), `fetchArtifact` (one reference as a bounded `Response`) and `downloadArtifacts` (Node-only, a run's produced files saved under a directory as a produced verdict), plus `artifactFilename`, the rule that names a saved file after the field it fills. The three network operations are client methods over a small structural seam (`ArtifactCapableClient`: the raw `resolveStorageUrls` call, `getRunResult` and the `originUrl` a plain-http link is checked against); the module's graph, static and dynamic, stays free of Node builtins, because `node:fs/promises`, `node:path` and `undici` come from the Node host. `undici` is a runtime dependency for one reason: the fetch runs on an `Agent` carrying `headersTimeout` and `bodyTimeout`, the per-stall bounds an `AbortSignal` budget does not give, and Node exposes its bundled undici's `fetch` but not its `Agent`. See [artifact-download.md](./artifact-download.md).
129
129
  - `runs.ts` — the run-lifecycle types (`RunStatus`, `RunRead`, `RunResults`, `RunResultState`) and the single poll loop (`pollUntilResult`). `RunResults.main_stuff` (the resolved main output content) is always present for a completed run: on the hosted path it is the `main_stuff.json` S3 artifact; on the bare-runner blocking path the SDK resolves it from the returned working memory via the response's `main_stuff_name`, so both paths deliver the same shape. Consumers read `main_stuff` directly. `working_memory` — every named stuff of the run, `{ root, aliases }`, typed `DictWorkingMemory` from `models.ts` — reads the same on both paths: the hosted path relays the `working_memory.json` artifact, and the blocking path lifts it off `pipe_output`, which still rides whole (blocking path only). `graph_spec` — the executed graph — also reaches the client on both paths: the hosted path relays the `graphspec.json` artifact, and the blocking path lifts it off `pipe_output` beside `graph_assembly_error`, the graph's twin of `usage_assembly_error`. That error field is declared ahead of the wire on the hosted side, where the platform's results body relays no such key and the field is therefore absent, reading `undefined` rather than `null`. A completed run that cannot deliver a main stuff throws `MissingMainStuffError` when the read asked for it. `runs.ts` also declares `RUN_RESULT_ARTIFACTS` / `RunResultArtifact`, the artifacts a results read can be narrowed to with `getRunResult`'s `artifacts` option; with a selection an unselected artifact is absent while a selected unwritten one is `null`. `runs.ts` also owns `TokensUsageRecord` — one client-facing usage record per inference call, carried by `RunResults.tokens_usages` on both paths. That is a mirror of a wire contract this SDK does not own (inference accounting is a Pipelex runtime extension rather than part of the MTHDS standard): every field is optional and the interface carries an index signature so pre-contract artifacts (relayed verbatim, never migrated) still type-check. See [`run-usage.md`](./run-usage.md) for the field reference, the cost/null semantics, and the old-artifact rules, and [`run-results.md`](./run-results.md) for the field-by-field account of `RunResults` — the durable handle, the output and how to read it, the run's working memory, the executed graph and how to render or keep it, and the produced files with their short-lived links.
130
130
  - `usage.ts` — `summarizeUsage`, the **pure** fold of a run's usage pair (`tokens_usages` / `usage_assembly_error`) into one `UsageSummary`: a `state` (`records`, `no_inference` or `unavailable`), the null-aware total cost with its `cost_partial` flag, the `input` and `output` token totals, the call count, the relayed assembly error, and a `by_pipe` rollup sorted by cost with the unattributed calls grouped under a `null` `pipe_code`. It applies the rules [`run-usage.md`](./run-usage.md#summarizing-a-run--summarizeusage) states, so that every consumer reads one computation rather than re-deriving those rules by hand. It imports types from `runs.ts` and nothing else: no client, no fetch, no `mthds/protocol`.
131
131
  - `execute-result.ts` — `PipelexExecuteResult`, a `DictRunResultExecute` subtype that adds a resolved `.main_stuff` accessor (dug out of `pipe_output`'s working memory via the response's `main_stuff_name`, throwing `MissingMainStuffError` if unlocatable). `execute()` returns it, giving blocking and durable results the **same output accessor** — `result.main_stuff` — so callers never branch on which path ran. The neutral `mthds` wire model leaves `main_stuff_name` in its extension index signature; this Pipelex-branded subtype declares it as a typed field (Pipelex owns that concept). `resultsFromExecute` (the public lift from that result onto `RunResults`, in the same module) reads that accessor too, keeping the resolution single-sourced; the `executeBlocking` fallback is its only caller inside the SDK, and a consumer driving `execute()` directly calls it by name.
@@ -174,11 +174,11 @@ The hosted catalog/account routes the webapp drives. All ride the same `{base}/v
174
174
  - **Onboarding:** `submitOnboarding`.
175
175
  - **Storage:** `resolveStorageUrl`, `resolveStorageUrls` (`POST /v1/resolve-storage-url/bulk` — the single route applied to a list of at most 100 references, one verdict per reference in request order, a refused reference a value on its item; a deployment without the route answers a `404` `ApiResponseError`), `upload` (JSON base64 — the multipart hop is browser→BFF only — answering the file's `uri`, its `filename` and the `file_id` of its record), `requestUploadGrant` (`POST /v1/upload/grant` — for a file described by its name, size and, from `describeUpload`, its SHA-256: either `stored: true`, the organization already holding those bytes, or a presigned, create-only `PUT` for the object, which the holder of the bytes sends with the standalone `uploadWithGrant`; both helpers are also exported from the browser-safe `@pipelex/sdk/upload` entry; a declared size over the cap is a `413` `ApiResponseError`). The higher-level `uploadFile` / `prepareInputs` preparation surface is built on top of `upload`; `prepareInputs` additionally composes one `pipeIo` call, which selects the pipe and answers with the input-form descriptor it walks, and takes the method as its tree, a `method_ref` or a `method_id` like every other method-taking operation — see [input-preparation.md](./input-preparation.md). The download twin — `locateArtifacts`, `collectArtifacts`, `resolveArtifacts`, `fetchArtifact`, `downloadArtifacts` — is built on top of `resolveStorageUrls` and `getRunResult`, never on the embedded `public_url`, and is documented on [artifact-download.md](./artifact-download.md); downloading is a separate explicit gesture, and no run call takes a `download` option.
176
176
  - **Runs list/detail/update:** `listRuns(query?)` returns **one page**, not the whole history — a `RunPage` (`{items, nextCursor}`) served from a time-ordered index, so its cost is the page size rather than the size of the history. The method is one filter among the others: `methodId`, sent as `method_id`, lists that method's runs, and without it the page holds the organization's runs of every method, newest first, the other filters applying exactly as with a method. A cursor is bound to the list that issued it, so the cursor of one method's runs is refused on the organization's and the other way round; pass it back with the same `methodId`. A query that is not an object, such as the method id a call written for the former `listRuns(methodId, query)` passes first, is a `RequestArgumentError` before any request, and `iterateRuns` throws it at the call, since spread into a page's query a string would become an object of its characters naming no filter. Its rows are `RunHistoryItem`, **not** `PipelineRun`: the id, `method_id`, the bare catalog id of the method the run ran, `created_by_user_id`, the canonical user id of the member who started it, both always present so that a list across methods can name each row's method from the catalog and its author from the organization's members, `status`, `created_at`, `finished_at`, `pipe_code`, for a failed run `error`, and `method_version` and `source_digest`, which version of the method the run ran (a number, `"draft"`, or `null` for an inline source) and the SHA-256 of the sources it sent as text, 64 hex digits with no prefix and `null` for a run whose `files` held bytes as Base64 or by hash — what a history row shows. A row also carries `results_stored`, which says whether `getRunResult` can read the run's results: `true` exactly when the run is `COMPLETED` with its results stored, and `false` on every other row. Only while the run is still queued or running (`PENDING`, `STARTED`, `RUNNING`) does `false` mean "not yet". On a run that ended any other way than `COMPLETED` it is `false` for good, there being no results to read, and on a `COMPLETED` run it is `false` for good when the result went inline to the caller that started it, as a blocking `execute` run's does, and the results read of such a run answers `404 run.results_not_stored`, so a history asks for no results on that row. The field is optional, since a platform that predates it leaves it out, which says nothing either way: an absent field does not mean `false`. `getRunDetail` also carries the run's `tree_digest` and `crate_fingerprint`, each `null` for a run that recorded none. The history lists the runs of every version and of the draft together, by the bare id. `method_version` and `source_digest` are optional on every run record (`RunPublic`, `RunRead`, `PipelineRun`, `RunDetail`, `RunHistoryItem`), since a run recorded before the platform recorded them carries neither. The run's organization, workflow id and result location are not on the list; `getRunDetail` returns them. `iterateRuns` is the async iterator that follows the cursor for callers who genuinely want everything (`for await (const run of client.iterateRuns({ methodId }))`, or `client.iterateRuns()` for every method), sending its query with every page; it is deliberately not a `listAllRuns(): Promise<RunHistoryItem[]>`, because an all-at-once helper needs a page cap and a cap means silently returning a truncated list. Both accept `createdFrom` / `createdTo`, applied server-side as index key conditions — these are **instants, not days** (ISO-8601 with a UTC offset; a naive timestamp is refused as `request.invalid`), because only the caller knows which timezone's day it means. Both also accept `createdBy: "me"`, sent as `created_by=me`, which keeps the runs the caller started (the platform resolves "me" from the authenticated identity and takes no other value), and `status`, a list of `RunStatus` sent as one repeated `status=` parameter per status, deduplicated into the platform's order, which keeps the runs in any of them: the caller's own latest unfinished run is `{ createdBy: "me", status: ["PENDING", "STARTED", "RUNNING"], limit: 1 }`. An empty `status` list would be sent as no parameter at all, which lists every status, so it is a `RequestArgumentError` before any request, as is a name that is no `RunStatus`. The platform may apply these two after its index read, so **a filtered page can hold fewer runs than `limit`, or none, and still carry a `nextCursor`**: an empty page is not the end of the history, a `null` cursor is, and `iterateRuns` keeps following the cursor through one. It runs the same loop as `iterateMethods`, so it also stops on a cursor the server failed to advance and throws `PagingNotTerminatingError` past the same page ceiling. `getRunDetail` (`GET /v1/runs/{id}`) is the only call returning `mthds_contents` — what the run actually executed — and `inputs`; it is kept off the status read that pollers hit every few seconds and off the list, where the bundle would be multiplied by the page size. `updateRun` is the admin/manual status patch. The status/results/start lifecycle routes live in the run-lifecycle section above.
177
- - **An organization's files:** `listFiles` (`GET /v1/files`) returns **one page** of the organization's listed files, newest first, a `FilePage` (`{items, nextCursor}`) of `FileSummary` rows, each with the `uri` a run's inputs take as any address, its name, type, size, `kind` (`uploaded`, `attachment`, `generated` or `test`) and `origin`. Its `ListFilesQuery` follows `ListRunsQuery`'s camelCase and is sent under the API's names: `methodId`, `runId` and `createdBy` choose the method's, the run's (in the order of its addresses), one member's or the organization's list, and `q`, `kind`, `format`, `mediaType`, `createdFrom` and `createdTo` filter it, `format` and `mediaType` as one repeated parameter per value, an empty list of either refused with `RequestArgumentError` before any request since it would be sent as no filter at all. The filters apply after the index read, so a filtered page can be short or empty and still carry a `nextCursor`, which is bound to the list and filters that issued it; `iterateFiles` follows it through the loop the other iterators share. An upload is recorded as a method's test file by `kind: "test"` with its `method_id`, the pair `UploadInput`, `uploadFile`'s options and `prepareInputs`' nested `upload` all take, checked before any file is read; the upload route's refusals of a test file, for the caller's role or for its method, are a `TestFileRefusedError`. The rest of the files surface reads and acts on one file or a selection: `getFile` answers a `FileDetail`, the whole `FileRecord` with its `method_ids` and one page of its uses, whose cursor stays inside the answer as `uses.next_cursor`; `getFilesByUri` the records holding one address, the one a surface shows first; `renameFile` the record under the name the platform's one rule saved; and `linkFiles` one `FileLink` per requested file, in order, each a link or an `error`, a `200` either way, read through `withLinks` so an answer the SDK cannot read hides every link. A zip is two calls, `requestFileArchive` (answered `202`, `queued`) and `getFileArchive`, read until `ready` or `failed`, with no waiting helper; a selection past a cap is a `422` refusal whose problem carries a `limit` member. `listRunFiles` (`GET /v1/runs/{id}/files`) answers a `RunFilesPage` of a run's inputs, outputs, intermediate files and web links, its `next_cursor` read as `nextCursor` and its `state` `listing` until every record is written. `copyFileIntoDraft` copies a file into a method's draft and answers a `200` discriminated on `blob`, `copied` or `already_held`, with the new draft token on its `method`. Each answer is checked on the member a caller branches on before it is handed back. See [files.md](./files.md).
177
+ - **An organization's files:** `listFiles` (`GET /v1/files`) returns **one page** of the organization's listed files, newest first, a `FilePage` (`{items, nextCursor}`) of `FileSummary` rows, each with the `uri` a run's inputs take as any address, its name, type, size, `kind` (`uploaded`, `attachment`, `generated` or `test`) and `origin`. Its `ListFilesQuery` follows `ListRunsQuery`'s camelCase and is sent under the API's names: `methodId`, `runId` and `createdBy` choose the method's, the run's (in the order of its addresses), one member's or the organization's list, and `q`, `kind`, `format`, `mediaType`, `createdFrom` and `createdTo` filter it, `format` and `mediaType` as one repeated parameter per value, an empty list of either refused with `RequestArgumentError` before any request since it would be sent as no filter at all. The filters apply after the index read, so a filtered page can be short or empty and still carry a `nextCursor`, which is bound to the list and filters that issued it; `iterateFiles` follows it through the loop the other iterators share. An upload is recorded as a method's test file by `kind: "test"` with its `method_id`, the pair `UploadInput`, `uploadFile`'s options and `prepareInputs`' nested `upload` all take, checked before any file is read; the upload route's refusals of a test file, for the caller's role or for its method, are a `TestFileRefusedError`. The rest of the files surface reads and acts on one file or a selection: `getFile` answers a `FileDetail`, the whole `FileRecord` with its `method_ids` and one page of its uses, whose cursor stays inside the answer as `uses.next_cursor`; `getFilesByUri` the records holding one address, the one a surface shows first; `renameFile` the record under the name the platform's one rule saved; and `linkFiles` one `FileLink` per requested file, in order, each a link or an `error`, a `200` either way, read through `withLinks` so an answer the SDK cannot read hides every link. A zip is two calls, `requestFileArchive` (answered `202`, `queued`) and `getFileArchive`, read until `ready` or `failed`, with no waiting helper; a selection past a cap is a `422` refusal whose problem carries a `limit` member. `getFilePreview` (`GET /v1/files/preview`) answers the PDF preview of an Office file as a `FilePreview`, a `200` discriminated on `state` (`ready` with its link, `preparing`, `failed` with its `failure`, `unavailable`), read through `withLinks` and narrowed to the members its state fills, with no waiting helper either. `listRunFiles` (`GET /v1/runs/{id}/files`) answers a `RunFilesPage` of a run's inputs, outputs, intermediate files and web links, its `next_cursor` read as `nextCursor` and its `state` `listing` until every record is written. `copyFileIntoDraft` copies a file into a method's draft and answers a `200` discriminated on `blob`, `copied` or `already_held`, with the new draft token on its `method`. Each answer is checked on the member a caller branches on before it is handed back. See [files.md](./files.md).
178
178
 
179
179
  ## Hook bundle (`dist-hooks/check.mjs`)
180
180
 
181
- `src/hooks/` holds the post-edit `.mthds` hook pipeline (local lint/format via `@pipelex/tools-wasm`, then a `POST /v1/validate` verdict through this SDK), bundled into a single dependency-free ESM file by `npm run build:hook`. Its validate client is built by `src/hooks/validate-client.ts` with `appInfo: { name: "pipelex-mthds-check", version: SDK_VERSION }`, the `hook` surface's registry token, so the platform attributes its calls to the hook rather than to a plain SDK caller. The one specifier left external is `undici`, reached only by the artifact fetch path through the Node host's dynamic import, which the hook never executes, so the bundle does not inline an HTTP client it cannot use; the hook runs in Node, so the build resolves `#node-host` to the source of the Node host. **Distribution is source-checkout vendoring, not npm:** `pipelex-plugins` runs `make vendor-hook`, which builds `dist-hooks/check.mjs` in a sibling checkout of this repo and copies it in as a static hook asset — the published `@pipelex/sdk` tarball deliberately does not ship the bundle (it inlines the ~4 MB WASM engine, and no npm consumer of the SDK's library API uses it). `dist-hooks/` is gitignored; the consumer repo's own checks gate a stale vendored copy. `@pipelex/tools-wasm` is pinned to an exact version in `package.json`, because the engine carries the MTHDS schema the hook lints against: a newer schema reaches the hook only by a deliberate bump followed by a rebuild and a re-vendor, and the bundle's provenance line (`@pipelex/sdk <version> (<commit>) + @pipelex/tools-wasm <version> (npm)`) names the engine it embeds. Its tree gatherer (`src/hooks/bundle-gather.ts`) lists the edited file's directory with the `mthds` package's lister, which the bundle inlines, under the hook's own caps, and the validation sends that tree, the template files its `PipeDocGen` steps name included. The networked stage is `src/hooks/validate-stage.ts`: it holds the whole stage, the version handshake, the blob route, the uploads and the validation, to one deadline (`VALIDATE_TIMEOUT_MS`, ten seconds) whose signal it hands to `validate`, so the request or upload under way stops when it runs out and the stage reads as `unavailable`. Which file the hook checks on each platform, what it sends with it, and how it finds the file a Codex patch run through the shell wrote, is in [`hook-bundle.md`](./hook-bundle.md).
181
+ `src/hooks/` holds the post-edit `.mthds` hook pipeline (local lint/format via `@pipelex/tools-wasm`, then a `POST /v1/validate` verdict through this SDK), bundled into a single dependency-free ESM file by `npm run build:hook`. Its validate client is built by `src/hooks/validate-client.ts` with `appInfo: { name: "pipelex-mthds-check", version: SDK_VERSION }`, the `hook` surface's registry token, so the platform attributes its calls to the hook rather than to a plain SDK caller. The one specifier left external is `undici`, reached only by the artifact fetch path through the Node host's dynamic import, which the hook never executes, so the bundle does not inline an HTTP client it cannot use; the hook runs in Node, so the build resolves `#node-host` to the source of the Node host. **Distribution is source-checkout vendoring, not npm:** `pipelex-plugins` runs `make vendor-hook`, which builds `dist-hooks/check.mjs` in a sibling checkout of this repo and copies it in as a static hook asset — the published `@pipelex/sdk` tarball deliberately does not ship the bundle (it inlines the ~4 MB WASM engine, and no npm consumer of the SDK's library API uses it). `dist-hooks/` is gitignored; the consumer repo's own checks gate a stale vendored copy. `@pipelex/tools-wasm` is pinned to an exact version in `package.json`, because the engine carries the MTHDS schema the hook lints against: a newer schema reaches the hook only by a deliberate bump followed by a rebuild and a re-vendor, and the bundle's provenance line (`@pipelex/sdk <version> (<commit>) + @pipelex/tools-wasm <version> (npm)`) names the engine it embeds. Its tree gatherer (`src/hooks/bundle-gather.ts`) lists the edited file's directory with the `mthds` package's lister, which the bundle inlines, under the hook's own caps, and the validation sends that tree, the template files its `PipeDocGen` steps name included. The format stage's write-back, `src/hooks/format-write.ts`, replaces the edited file atomically, through a temporary file beside it given the original's owner, group and permission bits and renamed over it, so a killed hook never leaves the file truncated, and writes in place instead when a rename would break a hard link or change the file's owner ([`hook-bundle.md`](./hook-bundle.md#how-the-format-is-written)). The networked stage is `src/hooks/validate-stage.ts`: it holds the whole stage, the version handshake, the blob route, the uploads and the validation, to one deadline (`VALIDATE_TIMEOUT_MS`, ten seconds) whose signal it hands to `validate`, so the request or upload under way stops when it runs out and the stage reads as `unavailable`. Which file the hook checks on each platform, what it sends with it, and how it finds the file a Codex patch run through the shell wrote, is in [`hook-bundle.md`](./hook-bundle.md).
182
182
 
183
183
  Before the validation sends anything, the gatherer reads every file of the tree once and screens it with `src/hooks/secret-guard.ts`, the workshop's secret guard (pipelex-mcp's `src/capabilities/secret-guard.ts`), ahead of the workshop's copy on its SSH key names and its PEM private key block, because the lister reads no `.gitignore` above the tree's root. A file named like a known secret file, or holding a well-known key format, stays home and is named in the note the verdict carries, placed after the verdict's text and named once for one tree, never quoted, and no note is shown when no verdict comes back; one that is a bundle or the manifest, which every validation reads, keeps the whole tree home, and the stage reads as `refused`. The tree sent serves the bytes screened, never read again ([`hook-bundle.md`](./hook-bundle.md#secrets-stay-home)).
184
184
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  > **Status: implemented** (`src/artifacts.ts`). This is the download twin of [input preparation](./input-preparation.md): where `prepareInputs` turns local files into `pipelex-storage://` references before a run, these operations turn the references a run produced back into bytes on disk, or into a bounded stream, afterwards. They are layered so that each is usable without the next.
4
4
  >
5
- > **They need a platform that serves the bulk resolve route.** Everything below the pure walk mints its links through `POST /v1/resolve-storage-url/bulk`, a hosted-platform route. The public bare runner (`pipelex-api`) has no resolve route at all, single or bulk, and a hosted deployment that predates the route answers a `404`; in both cases the operation throws the existing `ApiResponseError` and nothing is downloaded. `resolveStorageUrl`, the single-reference primitive, stays for the callers that have one link to mint.
5
+ > **They need a server that serves the bulk resolve route.** Everything below the pure walk mints its links through `POST /v1/resolve-storage-url/bulk`. The hosted platform serves it and, from pipelex-api 0.118.0, so does a self-hosted runner, which resolves the references under the caller's own scope to links on its own signed download route. A runner from pipelex-api 0.118.0 serves only the bulk route, never the single `POST /v1/resolve-storage-url`, and an older runner serves neither. Against an older runner, or a hosted deployment that predates the bulk route and answers a `404`, the operation throws the existing `ApiResponseError` and nothing is downloaded. `resolveStorageUrl`, the single-reference primitive, reaches the hosted platform only: a self-hosted caller with one link to mint calls `resolveArtifacts` with a one-item list.
6
6
 
7
7
  ## Why this exists
8
8
 
@@ -10,7 +10,7 @@ A run that produces an image, a PDF or a document does not embed the bytes in it
10
10
 
11
11
  Downloading is **explicit and separate from running**, the input-preparation rule in reverse: `execute` / `start` never silently upload, and `startAndWaitForResult` never silently downloads. There is no `download` option on any run call. A download is its own gesture, inspectable and repeatable — by run id, days after the run.
12
12
 
13
- Nothing here reads the embedded `public_url`. Every link is minted fresh by the platform, which is what makes a download work long after the embedded link died, and what keeps the tenant boundary where the platform enforces it.
13
+ Nothing here reads the embedded `public_url`. Every link is minted fresh by the server's bulk resolve route, the hosted platform's presigned link or a self-hosted runner's own signed link, which is what makes a download work long after the embedded link died, and what keeps the tenant boundary where the server enforces it.
14
14
 
15
15
  ## The operations
16
16
 
@@ -50,9 +50,9 @@ for (const item of resolved) {
50
50
  }
51
51
  ```
52
52
 
53
- One call to the platform's bulk route for the whole list, chunked at the route's bound of 100 references per request (`BULK_RESOLVE_MAX_URIS`), answering one `ResolvedArtifact` per reference **in request order, duplicates included**. A resolved item carries `url`, `expires_at` (UTC, ISO 8601) and `content_type` (`string | null` — the platform's guess from the reference's extension, null when it has none) with `error: null`; a refused item carries `error` as `{ code, detail }` with the three link fields null. The codes are the route's, from the platform's registry: `pipelex.storage.uri_invalid` for a malformed reference and `pipelex.org.mismatch` for one belonging to another organization. A consumer branches on `error`, never on an HTTP status, because the request is a `200` whenever every reference got a verdict.
53
+ One call to the server's bulk route for the whole list, chunked at the route's bound of 100 references per request (`BULK_RESOLVE_MAX_URIS`), answering one `ResolvedArtifact` per reference **in request order, duplicates included**. A resolved item carries `url`, `expires_at` (UTC, ISO 8601) and `content_type` (`string | null` — the server's guess from the reference's extension, null when it has none) with `error: null`; a refused item carries `error` as `{ code, detail, params }` with the three link fields null, `params` being the parameters the code declares when the route sends them. The codes are the route's, from the registry: `pipelex.storage.uri_invalid` for a malformed reference, `pipelex.org.mismatch` on the platform for one belonging to another organization, and `auth.forbidden` whose `params.requirement` is `read_scope_under_caller` on a self-hosted runner for one outside the caller's scope. A consumer branches on `error`, never on an HTTP status, because the request is a `200` whenever every reference got a verdict.
54
54
 
55
- Only what is not about a reference throws: the route's whole-request refusals (a caller with no organization, a request over the bound or with an unknown field, a signing failure, a deployment without the route) as `ApiResponseError`, and an unreachable host as `ApiUnreachableError`. An empty list resolves to an empty list with no request made. A link lives about fifteen minutes; resolve close to the moment of use.
55
+ Only what is not about a reference throws: the route's whole-request refusals (a caller with no organization, a request over the bound or with an unknown field, a signing failure, a deployment without the route) as `ApiResponseError`, and an unreachable host as `ApiUnreachableError`. An empty list resolves to an empty list with no request made. A link lives as long as the server signs it for, about fifteen minutes on the hosted platform and `STORAGE_LINK_TTL_SECONDS` on a self-hosted runner; resolve close to the moment of use.
56
56
 
57
57
  This is where every browser-side or server-rendering consumer stops: it mints links on the server and hands each one to a client that uses it immediately. `resolveStorageUrls` is the raw wire call underneath it (one request, at most the bound), the way `upload` sits under `uploadFile`.
58
58
 
@@ -77,14 +77,14 @@ export async function GET(request: Request, { params }: { params: { uri: string
77
77
  Resolves the reference fresh and returns the object store's response as a bounded `Response`. The bounds:
78
78
 
79
79
  - **A timeout** covering the connection, the headers and the whole body (`timeoutMs`, default 120 s). On Node the fetch also runs on an `undici` dispatcher carrying `headersTimeout` and `bodyTimeout` at the same value, the per-stall bounds an `AbortSignal` alone does not give. It must be a positive number no larger than 2147483647, the longest delay a timer honours, or the call throws an `ArtifactOperationError` before anything is resolved.
80
- - **Redirects refused** (`redirect: "manual"`): a presigned link has no reason to redirect, and one that does is refused rather than followed.
80
+ - **Redirects refused** (`redirect: "manual"`): a signed link has no reason to redirect, and one that does is refused rather than followed.
81
81
  - **The byte cap enforced mid-stream** (`maxBytes`, default 1 GiB): a declared `Content-Length` over the cap is refused before a byte is read, and a body that crosses the cap while streaming errors the returned stream — never buffered.
82
82
  - **No credentials forwarded**: the request carries no headers of ours. The link's authorization is in its query string, and nothing else may ride along to the store.
83
- - **Plain `http:` refused** unless `allowHttp: true`. A general-purpose library does not fetch over plain http silently; the local compose stack's object store hands out such links, and that is what the option opts into.
83
+ - **Plain `http:` refused off the client's own origin** unless `allowHttp: true`. A plain `http:` link whose origin (scheme, host and port, a default port and a trailing slash making no difference) is the origin of the client's configured base URL is fetched as is: the client already sends its API key to that origin, so a link to it reveals nothing the client does not already trust that server with, and that is how a self-hosted runner listening on plain http hands back what it stores. Hosts are compared in the WHATWG URL parser's form, which lowercases them, encodes an internationalized name as IDNA and writes an IP address canonically (`127.1` is `127.0.0.1`), but a name is never resolved, so a client configured with `http://localhost:8091` refuses a link on `http://127.0.0.1:8091`. Any other plain `http:` link is refused, since a general-purpose library does not fetch over plain http silently; the local compose stack's object store hands out such links on its own origin, and that is what the option opts into. The client states its origin through `ArtifactCapableClient.originUrl`, which `PipelexApiClient` derives from its base URL.
84
84
 
85
85
  It is **header-neutral**: the status, status text and headers are the store's own. The one change is that a `Content-Encoding` the fetch already decoded is dropped with the encoded `Content-Length`, since the body handed on is the decoded bytes. A proxy relaying it therefore owns the response hygiene — `X-Content-Type-Options: nosniff`, a sandboxing CSP on the asset response, a controlled `Content-Disposition`, private caching — and must set them itself, as the example does.
86
86
 
87
- Only a `2xx` is returned. Anything else throws an `ArtifactFetchError` whose `reason` says why, beside its problem ([errors.md](./errors.md#each-classs-problem)), in the same closed vocabulary the download verdict uses per item: the route's `pipelex.storage.uri_invalid` / `pipelex.org.mismatch`, both read as `input.reference_not_found`, then `unsupported_url` (not a URL, not http(s), or carrying credentials), `plain_http_refused`, `redirect_refused`, `store_refused` (a 401/403 from the store — the link is freshly minted, so this is the store refusing a fresh signature, not an expired link), `not_found` (404/410), `store_error` (any other non-2xx, with `status`), `too_large`, `timeout` and `network`. Its problem follows its `reason` and `status`: a `store_error` or a `store_refused` is `runtime.unavailable`, `retry` `yes`, when its `status` is a `408`, a `429` or a `5xx` other than `501`, `runtime.unsupported` for a `501`, and `client.response_unreadable` naming the status, `retry` `no`, for any other status, so a `400`, a `405`, a `401` or a `403` is not worth asking again; `timeout` and `network` are `runtime.unavailable`, `retry` `yes`. The caller's abort propagates as-is, and the body reader is cancelled with it. `downloadArtifacts` and a proxy share this boundary: the download is the same fetch followed by a write.
87
+ Only a `2xx` is returned. Anything else throws an `ArtifactFetchError` whose `reason` says why, beside its problem ([errors.md](./errors.md#each-classs-problem)), in the same closed vocabulary the download verdict uses per item: the route's `pipelex.storage.uri_invalid`, `pipelex.org.mismatch` and a self-hosted runner's `auth.forbidden` naming `read_scope_under_caller`, all three read as `input.reference_not_found` (an `auth.forbidden` naming any other requirement is `runtime.unexpected`), then `unsupported_url` (not a URL, not http(s), or carrying credentials), `plain_http_refused`, `redirect_refused`, `store_refused` (a 401/403 from the store — the link is freshly minted, so this is the store refusing a fresh signature, not an expired link; a self-hosted runner's download route answers its `403` `auth.forbidden` for a signature that does not hold or has expired, read the same way), `not_found` (404/410, a self-hosted runner's `404` `pipelex.storage.object_missing` included, since only the status is read), `store_error` (any other non-2xx, with `status`), `too_large`, `timeout` and `network`. Its problem follows its `reason` and `status`: a `store_error` or a `store_refused` is `runtime.unavailable`, `retry` `yes`, when its `status` is a `408`, a `429` or a `5xx` other than `501`, `runtime.unsupported` for a `501`, and `client.response_unreadable` naming the status, `retry` `no`, for any other status, so a `400`, a `405`, a `401` or a `403` is not worth asking again; `timeout` and `network` are `runtime.unavailable`, `retry` `yes`. The caller's abort propagates as-is, and the body reader is cancelled with it. `downloadArtifacts` and a proxy share this boundary: the download is the same fetch followed by a write.
88
88
 
89
89
  ### `downloadArtifacts({ run_id | results, dir, … })` — the files on disk
90
90
 
@@ -150,7 +150,7 @@ Files are **never overwritten**: a name already on disk gets a numeric suffix (`
150
150
  scope: "main_stuff" | "working_memory",
151
151
  artifacts: [
152
152
  { uri, found_at, path, content_type, size, error: null }, // saved — path is absolute
153
- { uri, found_at, path: null, content_type, size: null, error: { code, detail } }, // not saved
153
+ { uri, found_at, path: null, content_type, size: null, error: { code, detail, params? } }, // not saved
154
154
  ],
155
155
  saved_paths: [ /* the absolute paths of the saved ones, same order */ ],
156
156
  all_saved: boolean, // every reference saved; vacuously true for an empty walk
@@ -158,7 +158,7 @@ Files are **never overwritten**: a name already on disk gets a numeric suffix (`
158
158
  }
159
159
  ```
160
160
 
161
- `artifacts.length` is the count of references walked, errors included. An empty walk over a present scope — an output that references no stored file — is a verdict with empty lists and `all_saved: true`, not an error, and it touches neither the network nor the disk. `found_at` is the reference's paths in the walked scope, exactly as `locateArtifacts` reports them, and `content_type` is the platform's guess from the reference, known before the fetch; both are on both arms, so an item that was not saved still says which field it would have filled.
161
+ `artifacts.length` is the count of references walked, errors included. An empty walk over a present scope — an output that references no stored file — is a verdict with empty lists and `all_saved: true`, not an error, and it touches neither the network nor the disk. `found_at` is the reference's paths in the walked scope, exactly as `locateArtifacts` reports them, and `content_type` is the server's guess from the reference, known before the fetch; both are on both arms, so an item that was not saved still says which field it would have filled. An item the resolve route refused keeps the refusal's `params` on its `error` when the route sent them, so a self-hosted runner's `auth.forbidden` still names its `requirement`.
162
162
 
163
163
  Per-item `error.code` is the fetch vocabulary above plus the download's own: `resolve_failed` (an expired link could not be re-resolved, for a reason that is not the credential), `total_limit_exceeded` (the item that would take the call past `maxTotalBytes`, and, once the files already saved leave no room, every item not yet started, whose `detail` says it was skipped; an item refused only because files still in flight hold the room stops nothing else, since one of them may yet fail and give it back), `write_failed` (the file could not be created, written or closed), `aborted` (in flight or not yet started when the signal fired) and `unknown` (a failure the SDK cannot place, never one a retry can pass).
164
164
 
@@ -181,7 +181,7 @@ Everything else that can go wrong with one reference is that reference's `error`
181
181
  | `maxBytes` | 1 GiB | one file, from `Content-Length` and again mid-stream |
182
182
  | `timeoutMs` | 120 s | one file's whole exchange, plus the dispatcher's per-stall timeouts |
183
183
  | `maxTotalBytes` | 4 GiB | the bytes the whole call saves, a file in flight counting its declared length |
184
- | `allowHttp` | `false` | whether a plain `http:` link is fetched |
184
+ | `allowHttp` | `false` | whether a plain `http:` link off the client's own origin is fetched |
185
185
  | `signal` | — | cancels the call: in-flight fetches are cancelled and their partial files unlinked, the rest are marked, and the verdict comes back with `aborted: true` |
186
186
 
187
187
  The per-file defaults are the MCP server's, which this replaces; the caps are accident guards against filling a disk from a runaway output, not judgments about artifact size.
package/docs/errors.md CHANGED
@@ -126,8 +126,8 @@ The classes remain, so a `catch` can still tell an argument refusal from a refus
126
126
  | `MethodFileTransferError` | By `reason`: `unreachable` and `storage_error` are `runtime.unavailable`; `refused` reads storage's status, as above, `runtime.unexpected` with none; `mismatch`, downloaded bytes that are not the file listed, is `client.response_unreadable`. It carries `operation`, `reason`, `sha256`, `path` and `status`, and neither the link, nor storage's error body, nor a cause ([method-trees.md](./method-trees.md#when-a-transfer-fails)). |
127
127
  | `ArtifactOperationError` | `runtime.unexpected` when built without a problem; the SDK gives `client.argument_invalid` where it refuses an argument (a `scope`, a bound, a location), `runtime.unsupported` for a runtime with no filesystem, `client.write_failed` for a directory that cannot be created, and `client.response_unreadable` for a resolution that answered the wrong count of items. |
128
128
  | `ScopeUnavailableError` | `client.response_unreadable`: the run's results carry no artifact in the scope asked for. |
129
- | `ArtifactFetchError` | The SDK gives `client.download_limit_exceeded` naming the cap for a file over it (`too_large`), `client.timeout` naming the budget for a download that ran out of time, and `client.unreachable` naming the store's origin for one that failed on the network. Otherwise by `reason` and `status`: `input.reference_not_found` naming the reference for the bulk resolve route's `pipelex.storage.uri_invalid` and `pipelex.org.mismatch` and for `not_found`; `client.link_refused` for `unsupported_url`, `plain_http_refused` and `redirect_refused`; for `store_error` and `store_refused`, the reading of the store's status as for any storage answer (`runtime.unavailable` for a `408`, a `429` or a `5xx` other than `501`, `runtime.unsupported` for a `501`, `client.response_unreadable` naming any other status, a `401` or a `403` included), and `runtime.unavailable` when no status is known; `runtime.unavailable` for `timeout` and `network`; and `runtime.unexpected` otherwise. |
130
- | `StoredTextLoadError` | The fetch failure's own problem, as `ArtifactFetchError` gives it, when a stored text's bytes could not be read, a refusal of the resolve route included; the resolve route's own problem for `resolve_failed`, the route failing as a whole; `client.link_refused` for `unsupported_url`, a stored text whose `url` is neither a `pipelex-storage://` reference nor a `data:` URL, which is never fetched; and `client.response_unreadable` naming the run for `not_utf8` and `not_json_object`, bytes read that are not the value. `uri`, `path` and `reason` name the text; `wireResults` carries the completed result as it was answered on the blocking fallback alone, where there is no run to read again, and is `undefined` elsewhere, where reading it again with `loadStoredTexts: false` gives it. |
129
+ | `ArtifactFetchError` | The SDK gives `client.download_limit_exceeded` naming the cap for a file over it (`too_large`), `client.timeout` naming the budget for a download that ran out of time, and `client.unreachable` naming the store's origin for one that failed on the network. Otherwise by `reason` and `status`: `input.reference_not_found` naming the reference for the bulk resolve route's `pipelex.storage.uri_invalid` and `pipelex.org.mismatch`, for a self-hosted runner's `auth.forbidden` whose `params.requirement` is `read_scope_under_caller`, and for `not_found`; `client.link_refused` for `unsupported_url`, `plain_http_refused` and `redirect_refused`; for `store_error` and `store_refused`, the reading of the store's status as for any storage answer (`runtime.unavailable` for a `408`, a `429` or a `5xx` other than `501`, `runtime.unsupported` for a `501`, `client.response_unreadable` naming any other status, a `401` or a `403` included), and `runtime.unavailable` when no status is known; `runtime.unavailable` for `timeout` and `network`; and `runtime.unexpected` otherwise. `uri` and `reason` name the reference and the failure, `status` the store's HTTP status when one was received, and `requirement` the `requirement` the resolve route's refusal names in its `params`, when it names one, which tells a self-hosted runner's scope refusal from any other `auth.forbidden`. |
130
+ | `StoredTextLoadError` | The fetch failure's own problem, as `ArtifactFetchError` gives it, when a stored text's bytes could not be read, a refusal of the resolve route included; the resolve route's own problem for `resolve_failed`, the route failing as a whole; `client.link_refused` for `unsupported_url`, a stored text whose `url` is neither a `pipelex-storage://` reference nor a `data:` URL, which is never fetched; and `client.response_unreadable` naming the run for `not_utf8` and `not_json_object`, bytes read that are not the value. `uri`, `path` and `reason` name the text, `status` the HTTP status received when one was, and `requirement` the `requirement` the resolve route's refusal of the reference names in its `params`, when it names one, which tells a self-hosted runner's scope refusal from any other `auth.forbidden`; `wireResults` carries the completed result as it was answered on the blocking fallback alone, where there is no run to read again, and is `undefined` elsewhere, where reading it again with `loadStoredTexts: false` gives it. |
131
131
  | `CodegenLockError` | `client.file_unreadable` naming `codegen.lock` for a lock that is malformed or tracks an unsafe path, `client.tool_outdated` naming this SDK for a lock newer than it reads, and `client.argument_invalid` naming `files` for a supplied tree holding an unsafe or duplicate path. It extends `ProblemError` rather than `PipelexRequestError`, since nothing was requested. |
132
132
  | `ExactJsonUnsupportedError` | `client.tool_outdated`, naming the JavaScript runtime: `parseExactJson` met a number past `Number.MAX_SAFE_INTEGER` on a runtime whose `JSON.parse` hands a reviver no source text ([exact-integers.md](./exact-integers.md)). It extends `ProblemError`; the client reports it as the `ApiResponseError` of an answer it cannot read, with this error as `cause`. |
133
133
 
package/docs/files.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # An organization's files
2
2
 
3
- A **file** is the record the hosted platform keeps of a stored object: a member's upload, a test file made for a method, or a file a run made that reached its result. The bytes stay where they were written, and a run, a form or an example still points at them by their `pipelex-storage://` address; the record adds what the bytes lack, the name a person sees, a kind, a type, a size and where the file came from. A file belongs to the organization: every role of it reads every file of it, as every role reads every run. The client reaches them on the hosted API's `/v1/files` routes, a run's files on `GET /v1/runs/{run_id}/files` and the copy into a method's draft on `POST /v1/methods/{method_id}/draft/files/from-file`, and the types are in `src/product-models.ts`. The platform's own contract is `platform/docs/files.md` in `pipelex-server`.
3
+ A **file** is the record the hosted platform keeps of a stored object: a member's upload, a test file made for a method, or a file a run made that reached its result. The bytes stay where they were written, and a run, a form or an example still points at them by their `pipelex-storage://` address; the record adds what the bytes lack, the name a person sees, a kind, a type, a size and where the file came from. A file belongs to the organization: every role of it reads every file of it, as every role reads every run. The client reaches them on the hosted API's `/v1/files` routes, the PDF preview of an Office file on `GET /v1/files/preview`, a run's files on `GET /v1/runs/{run_id}/files` and the copy into a method's draft on `POST /v1/methods/{method_id}/draft/files/from-file`, and the types are in `src/product-models.ts`. The platform's own contract is `platform/docs/files.md` in `pipelex-server`.
4
4
 
5
5
  The point of the list for a program is the `uri` on every row: a run's inputs take it as they take any address, so an agent or an app can find "the invoice uploaded this morning" and run a method on it without uploading it again.
6
6
 
@@ -45,6 +45,7 @@ A file read by its id or its address, renamed, or listed among a run's files is
45
45
  | `linkFiles(files)` | `POST /v1/files/links` | A `FileLinksResult`, `{ items }`: one `FileLink` per requested file, in order, each a link or an error. |
46
46
  | `requestFileArchive(request)` | `POST /v1/files/archives` | The `FileArchive`, `queued`. |
47
47
  | `getFileArchive(archiveId)` | `GET /v1/files/archives/{archive_id}` | The `FileArchive` as it stands, with a link to the zip once it is `ready`. |
48
+ | `getFilePreview(uri)` | `GET /v1/files/preview` | A `FilePreview`, discriminated on `state`: the PDF preview of an Office file, with a link to it once it is `ready`. |
48
49
  | `listRunFiles(runId, { limit?, cursor? })` | `GET /v1/runs/{run_id}/files` | One `RunFilesPage`: the run's inputs, outputs, intermediate files and web links, with `nextCursor`. |
49
50
  | `copyFileIntoDraft(methodId, { file_id, path, expected_updated_at? })` | `POST /v1/methods/{method_id}/draft/files/from-file` | A `DraftFileFromFileResult`, discriminated on `blob`. |
50
51
 
@@ -198,6 +199,45 @@ try {
198
199
 
199
200
  The other refusals of a request: `422` `request.invalid` for more than 1,000 ids listed or an id longer than one can be; `404` `pipelex.storage.not_found` for a file that is not the organization's, the `detail` naming up to five of them, or a run whose files hold nothing stored to zip; `404` `run.not_found` for a run that is not the organization's; `409` `run.not_finished`, `retry` `yes`, for a run whose files are not all recorded yet, which the same request clears a few seconds after the run ends, and a `409` with `retry` `no` for a selected file whose upload has not finished; and `503` `runtime.unavailable`, `retry` `yes`, when the archive could not be queued. Each is an `ApiResponseError` whose problem's `domain` and `retry` say what to do ([errors.md](./errors.md)).
200
201
 
202
+ ## The PDF preview of an Office file
203
+
204
+ A browser cannot draw a Word, Excel or PowerPoint file, so the platform keeps a PDF of it. `getFilePreview` asks where that PDF stands, naming the file by its `pipelex-storage://` address. The platform converts the files whose address ends in `docx`, `xlsx`, `pptx`, `doc`, `xls`, `ppt`, `odt`, `ods` or `odp`.
205
+
206
+ **The answer is always a `200`: branch on `state`.** The platform never waits on a conversion: the first ask queues one and answers `preparing` at once, and asking again queues nothing more, so polling is safe; the app polls for up to three minutes. The SDK has no waiting helper, since how long to wait and how to show it is the caller's.
207
+
208
+ ```ts
209
+ let preview = await client.getFilePreview(output.uri);
210
+ while (preview.state === "preparing") {
211
+ await new Promise((resolve) => setTimeout(resolve, 2000));
212
+ preview = await client.getFilePreview(output.uri);
213
+ }
214
+ if (preview.state === "ready") frame.src = preview.url;
215
+ else if (preview.state === "failed") console.warn(preview.failure.code, preview.failure.detail);
216
+ ```
217
+
218
+ A `FilePreview` carries all four members in every state, those its state does not fill `null`, and the type narrows on `state`, so a `ready` preview's `url` is a `string` and a `failed` one's `failure` is never `null`.
219
+
220
+ | `state` | What it means | The other members |
221
+ |---|---|---|
222
+ | `ready` | The PDF is there. | `url`, a presigned `GET` of the PDF signed fresh on each read, valid for fifteen minutes and answered `inline` under the file's name with its extension swapped to `.pdf`, and `url_expires_at`, the UTC instant it lapses. |
223
+ | `preparing` | A conversion is on its way: ask again shortly. | All `null`. |
224
+ | `failed` | The last conversion failed. | `failure`, a `FilePreviewFailure` `{ code, detail }`, `detail` being a sentence for a person. |
225
+ | `unavailable` | The file gets no preview: a type that is not converted, a file over 50 MB, or an address holding nothing. | All `null`. |
226
+
227
+ **A failure stands for a day** from the moment it failed: asking again within that day answers the same failure and queues nothing, and after it the next ask starts a new conversion. `FilePreviewFailureCode` names the codes the platform answers today, and `code` is typed open, so a code a later platform adds still reads.
228
+
229
+ | `failure.code` | Why | What happens next |
230
+ |---|---|---|
231
+ | `file_unreadable` | The converter could not open the file. A damaged file and one protected by a password cannot be told apart reliably, so the sentence names both. | The file will fail the same way. |
232
+ | `file_too_large` | The converter refused the file as over its input cap. | The file will fail the same way. |
233
+ | `conversion_too_slow` | The conversion ran out of the converter's two minutes, as a hostile or very large file does. | The file will almost certainly fail the same way. |
234
+ | `file_gone` | The bytes were deleted between the request and the conversion. | Nothing to retry. |
235
+ | `conversion_failed` | The worker's last attempt failed, or the job was not done within the hour it has; the cause is not the file's. | A later ask tries again once the failure's day has passed. |
236
+
237
+ **The link is a bearer capability.** Keep it out of logs and ask again for a fresh one rather than storing it. The SDK keeps it out of its own errors: an answer it cannot read, one whose `state` it does not know, a `ready` one without a non-empty `url` and a string `url_expires_at`, or a `failed` one whose `failure` is not a `code` and a `detail`, is an `ApiResponseError` of `client.response_unreadable` whose `responseBody` replaces every `url` member and every link's query with `[redacted]`, and which carries no `cause` ([errors.md](./errors.md)). The answer it hands back holds the four members and nothing else the platform may add.
238
+
239
+ A `uri` that is not a non-empty string is refused before any request with a `RequestArgumentError`. The platform answers `422` `pipelex.storage.uri_invalid` for a malformed address, `403` `pipelex.org.mismatch` for another organization's, `422` `request.invalid` for an address over 512 characters, and `503` `runtime.unavailable`, `retry` `yes`, when the conversion could not be queued, so the same request can be sent again. Each is an `ApiResponseError` whose problem's `domain` and `retry` say what to do.
240
+
201
241
  ## A run's files
202
242
 
203
243
  `listRunFiles` answers a `RunFilesPage` of what went in, what came out and what was made along the way, sorted by where each file sits in the run. Each `RunFileEntry` carries its `mark` (`input`, `final` or `intermediate`), the `input_name` of the run's input that held an input given by its address (`null` for an inline input and for every file the run made), its `uri` and the `FileRecord` a surface shows for it, `null` for an input no record holds.