@pipelex/sdk 0.71.0 → 0.72.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.
@@ -15,7 +15,7 @@ import type { CommandIO } from "./io.js";
15
15
  * update notice and npm 12's run notices off the script's stderr, which carries the command's
16
16
  * own lines, while npm's warnings and errors still print.
17
17
  */
18
- export declare const SCRIPT_RUNNER = "npx --yes --no-update-notifier --loglevel=warn @pipelex/sdk@0.71.0";
18
+ export declare const SCRIPT_RUNNER = "npx --yes --no-update-notifier --loglevel=warn @pipelex/sdk@0.72.0";
19
19
  export declare const SCRIPT_WRITER = "@pipelex/sdk";
20
20
  export declare const SCRIPT_NEEDS = "Node 22.12 or later";
21
21
  /** Run `pipelex-sdk script` and return its exit code. */
@@ -9,7 +9,7 @@
9
9
  * sends a method's tree as the SDKs do. An address travels as `method_ref` and a catalog id as
10
10
  * `method_id`, both resolved by the server.
11
11
  */
12
- import { inputFormFault, readProblemItems } from "../index.js";
12
+ import { InputsTemplateError, inputFormFault, readProblemItems, renderInputsTemplate, } from "../index.js";
13
13
  import { CommandError, EXIT_FAILED, untilInterrupted } from "./io.js";
14
14
  import { loadFailureLines, METHOD_DOES_NOT_LOAD_SENTENCE } from "./present.js";
15
15
  export function crateSelector(source) {
@@ -78,16 +78,36 @@ export async function describePipe(client, source, pipe, interrupt) {
78
78
  // names the fault. Python's closed models refuse more than this, such as a member the standard
79
79
  // does not define, which the template never reads.
80
80
  const entry = inputForm[pipeRef];
81
- if (inputFormFault(entry) !== undefined || !templateReadable(entry)) {
81
+ if (inputFormFault(entry) !== undefined ||
82
+ !templateReadable(entry) ||
83
+ !templateRenders(entry)) {
82
84
  throw new CommandError("the API's pipe I/O answer describes the pipe it selected with a malformed input form.", { exitCode: EXIT_FAILED });
83
85
  }
84
86
  return { report, pipeRef, descriptor: entry };
85
87
  }
88
+ /**
89
+ * Whether the compact inputs template renders from an entry the checks above passed. The renderer
90
+ * refuses shapes those checks do not read, such as a `JSON` input, or one whose concept refines
91
+ * `JSON`, that is not an object carrying `json_obj`, so the entry is rendered once here and its
92
+ * refusal is a malformed input form, for `script` as for `--inputs-template`.
93
+ */
94
+ function templateRenders(descriptor) {
95
+ try {
96
+ renderInputsTemplate(descriptor, { explicit: false, format: "json" });
97
+ return true;
98
+ }
99
+ catch (error) {
100
+ if (error instanceof InputsTemplateError)
101
+ return false;
102
+ throw error;
103
+ }
104
+ }
86
105
  /**
87
106
  * Whether an entry `inputFormFault` passed also holds what the inputs template reads beyond the
88
107
  * walk, in a shape it can render: every node's `concept_ref` a string, its `refines` a list of
89
- * strings, an enum's `choices` a list and a list's `item_count` a whole number of at least two,
90
- * the last three when present. Members the template only tests for truth are not checked.
108
+ * strings, an enum's `choices` a list of strings and a list's `item_count` a whole number of at
109
+ * least two, the last three when present. Members the template only tests for truth are not
110
+ * checked.
91
111
  */
92
112
  function templateReadable(entry) {
93
113
  return entry.fields.every(templateReadableNode);
@@ -116,7 +136,7 @@ function templateReadableNode(node) {
116
136
  case "object":
117
137
  return templateReadable(node);
118
138
  case "enum":
119
- return Array.isArray(node.choices);
139
+ return (Array.isArray(node.choices) && node.choices.every((choice) => typeof choice === "string"));
120
140
  case "list":
121
141
  return ((node.item_count === undefined ||
122
142
  node.item_count === null ||
@@ -1 +1 @@
1
- {"version":3,"file":"source.js","sourceRoot":"","sources":["../../src/cli/source.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAUH,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/D,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AACtE,OAAO,EAAE,gBAAgB,EAAE,6BAA6B,EAAE,MAAM,cAAc,CAAC;AAY/E,MAAM,UAAU,aAAa,CAAC,MAAoB;IAChD,QAAQ,MAAM,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,QAAQ;YACX,OAAO;gBACL,KAAK,EAA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AAU,KAAK,IAAI;gBACxB,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC,IAAK,IAAI,CAAC,UAAqB,IAAI,CAAC,CAAC,CAAC;gBAC1E,oBAAoB,CAAC,IAAI,CAAC,IAA+B,CAAC,CAC3D,CAAC;QACJ,OAAO,CAAC,CAAC,CAAC;YACR,yEAAyE;YACzE,MAAM,WAAW,GAAU,IAAI,CAAC;YAChC,OAAO,WAAW,CAAC;QACrB,CAAC;IACH,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC"}
@@ -7,7 +7,8 @@
7
7
  * the pipeline itself is identical:
8
8
  *
9
9
  * 1. local lint (`@pipelex/tools-wasm` — offline, no credentials) → BLOCK on diagnostics
10
- * 2. local format (same engine) → write back in place when changed
10
+ * 2. local format (same engine) → when changed, replace the file atomically
11
+ * (a temporary file beside it renamed over it, `format-write.ts`)
11
12
  * 3. API validate (`POST /v1/validate` via the SDK, `allow_signatures: true`)
12
13
  * → BLOCK on an invalid verdict, non-blocking nudge on pending signatures
13
14
  *
@@ -7,7 +7,8 @@
7
7
  * the pipeline itself is identical:
8
8
  *
9
9
  * 1. local lint (`@pipelex/tools-wasm` — offline, no credentials) → BLOCK on diagnostics
10
- * 2. local format (same engine) → write back in place when changed
10
+ * 2. local format (same engine) → when changed, replace the file atomically
11
+ * (a temporary file beside it renamed over it, `format-write.ts`)
11
12
  * 3. API validate (`POST /v1/validate` via the SDK, `allow_signatures: true`)
12
13
  * → BLOCK on an invalid verdict, non-blocking nudge on pending signatures
13
14
  *
@@ -53,6 +54,7 @@
53
54
  import { readFileSync, writeFileSync } from "node:fs";
54
55
  import { resolve as resolvePath } from "node:path";
55
56
  import { decideAfterLint, decideAfterValidate, encodeOutcome, extractCodexMthdsTargets, extractMthdsFilePath, extractVibeMthdsFilePath, mergeOutcomes, selectCodexTargets, uncheckedShellPatchNote, } from "./check-core.js";
57
+ import { writeBackFormatted } from "./format-write.js";
56
58
  import { runValidateStage } from "./validate-stage.js";
57
59
  async function readStdin() {
58
60
  const chunks = [];
@@ -160,12 +162,9 @@ async function checkOneFile(engine, filePath) {
160
162
  if (lintOutcome.kind !== "pass") {
161
163
  return lintOutcome;
162
164
  }
163
- // Stage 2 — local format, write back in place (mirrors `plxt fmt`)
165
+ // Stage 2 — local format (mirrors `plxt fmt`), written back atomically when it changed anything
164
166
  try {
165
- const formatted = engine.formatMthds(content);
166
- if (formatted.changed) {
167
- writeFileSync(filePath, formatted.formatted);
168
- }
167
+ writeBackFormatted(filePath, content, engine.formatMthds(content));
169
168
  }
170
169
  catch (err) {
171
170
  const message = err instanceof Error ? err.message : String(err);
@@ -1 +1 @@
1
- {"version":3,"file":"claude-mthds-check.js","sourceRoot":"","sources":["../../src/hooks/claude-mthds-check.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AAEH,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACtD,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EACL,eAAe,EACf,mBAAmB,EACnB,aAAa,EACb,wBAAwB,EACxB,oBAAoB,EACpB,wBAAwB,EACxB,aAAa,EACb,kBAAkB,EAClB,uBAAuB,GAIxB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAIvD,KAAK,UAAU,SAAS;IACtB,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;QACxC,MAAM,CAAC,IAAI,CAAC,KAAe,CAAC,CAAC;IAC/B,CAA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AAC,CAAC,CAAC;IACpD,CAAC;IACD,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAC;AAC1C,CAAC;AAED,IAAI,EAAE;KACH,KAAK,CAAC,CAAC,GAAY,EAAE,EAAE;IACtB,kEAAkE;IAClE,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACjE,IAAI,CAAC,2BAA2B,OAAO,EAAE,CAAC,CAAC;AAC7C,CAAC,CAAC;KACD,OAAO,CAAC,GAAG,EAAE;IACZ,0EAA0E;IAC1E,sEAAsE;IACtE,6BAA6B;IAC7B,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
@@ -0,0 +1,67 @@
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 * as nodeFs from "node:fs";
33
+ /** The `node:fs` calls the write-back makes, injectable so a test can fail any of them. */
34
+ export type FormatWriteFs = Pick<typeof nodeFs, "accessSync" | "chmodSync" | "closeSync" | "fchownSync" | "fstatSync" | "fsyncSync" | "openSync" | "readFileSync" | "realpathSync" | "renameSync" | "statSync" | "unlinkSync" | "writeFileSync">;
35
+ export interface FormatWriteOptions {
36
+ fs?: FormatWriteFs;
37
+ /** `process.platform` by default; the Windows rename retries apply on `win32` only. */
38
+ platform?: NodeJS.Platform;
39
+ /** The pauses between rename attempts on Windows, in milliseconds. */
40
+ renameRetryDelaysMs?: readonly number[];
41
+ /** A synchronous pause, `Atomics.wait` by default. */
42
+ sleep?: (ms: number) => void;
43
+ }
44
+ /** What the format engine answers for one file. */
45
+ export interface FormatResult {
46
+ changed: boolean;
47
+ formatted: string;
48
+ }
49
+ /** How the file was written: replaced by a rename, or written into in place. */
50
+ export type FileWriteMethod = "replaced" | "written-in-place";
51
+ export type FormatWriteOutcome = "unchanged" | FileWriteMethod;
52
+ /** About 0.6 seconds in all, far below the hook's own deadline. */
53
+ export declare const WINDOWS_RENAME_RETRY_DELAYS_MS: readonly number[];
54
+ /**
55
+ * Write the formatter's result back to `filePath` when it changed anything. `original` is the
56
+ * text the formatter was given, which the file must still hold for a Windows retry to replace it.
57
+ * Throws when the file cannot be written; the original is then left untouched and no temporary
58
+ * file remains.
59
+ */
60
+ export declare function writeBackFormatted(filePath: string, original: string, result: FormatResult, options?: FormatWriteOptions): FormatWriteOutcome;
61
+ /**
62
+ * Replace the content of the file at `filePath`, which held `original`, with `content`: through
63
+ * a temporary file and a rename, or in place when a rename would lose the file's other hard links
64
+ * or its owner and group. A symbolic link is followed, so the file it points to is written and
65
+ * the link kept.
66
+ */
67
+ export declare function replaceFileContent(filePath: string, original: string, content: string, options?: FormatWriteOptions): FileWriteMethod;
@@ -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,S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AC;QACH,CAAC;IACH,CAAC;AACH,CAAC"}
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.71.0";
6
+ export declare const SDK_VERSION = "0.72.0";
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.71.0";
6
+ export const SDK_VERSION = "0.72.0";
7
7
  //# sourceMappingURL=version.js.map
@@ -70,7 +70,7 @@ The `imports` map points into `dist/`, which is what ships, so the tools that ru
70
70
 
71
71
  ### Standard artifacts on the validate report
72
72
 
73
- `PipelexValidationReport` is a Pipelex envelope that carries artifacts the MTHDS standard owns, and it names their types by importing them: `pipe_io_contracts` is `PipeIOContracts` and `input_form` is `InputForm`, both from `mthds/protocol`, where the standard declares them as the recommended extension fields of a validation report. The SDK restates nothing about their shape, and a consumer importing from `@pipelex/sdk` reaches the node types too (`InputFormTopLevelField`, `PipeInputContract`, the `FieldKind` vocabulary) through the barrel's `export * from "mthds/protocol"`.
73
+ `PipelexValidationReport` is a Pipelex envelope that carries artifacts the MTHDS standard owns, and it names their types by importing them: `pipe_io_contracts` is `PipeIOContracts` and `input_form` is `InputForm`, both from `mthds/protocol`, where the standard declares them as the recommended extension fields of a validation report. The SDK restates nothing about their shape, and a consumer importing from `@pipelex/sdk` reaches the node types too (`InputFormTopLevelField`, `PipeInputContract`, the `FieldKind` vocabulary) through the barrel's `export * from "mthds/protocol"`. That includes the facts MTHDS `9.2.0` adds to the descriptor nodes: a `number` node's `unit` and `aggregate` (`Aggregate`), an `enum` node's `options` (`ChoiceOption`, `OptionTone`) beside its `choices`, which are strings, a `text` node's closed `format` (`ContractFormat`), and the intent-hint vocabularies (`HINT_KEYS`, `INTENT_WORDS`, `ROLE_WORDS`, `PART_WORDS` and their guards).
74
74
 
75
75
  That supersedes the earlier ruling which kept both fields opaque as `Record<string, unknown>`. The ruling was defending a real principle — this SDK does not own these types, and a second declaration here would be free to drift from the one the server emits — and the principle is unchanged. What changed is that the standard's TypeScript client now declares them, so importing enforces the same boundary the opaque typing was reaching for, and enforces it at compile time instead of leaving every consumer to cast. `bundle_blueprint` and `graph_spec` stay opaque for exactly the original reason: their canonical schemas live in the runtime's blueprint models and in `@pipelex/mthds-ui`'s `GraphSpec`, and neither has a declaration in the standard for this SDK to import. Each narrows the day the standard declares one.
76
76
 
@@ -178,7 +178,7 @@ The hosted catalog/account routes the webapp drives. All ride the same `{base}/v
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
 
package/docs/cli.md CHANGED
@@ -22,7 +22,7 @@ pipelex-sdk run --method <method> [--pipe <domain.pipe_code>] [--inputs <file> |
22
22
  - **`--method`**, required, names the method in one of the forms below, told apart by shape alone. A value starting with `mt_` is a catalog id, sent as `method_id`. A value starting with `github.com/` is a published method's address, `github.com/<owner>/<repo>[/<package>][@<tag>]`, sent as `method_ref`. Anything else is a path to a `.mthds` file or a bundle directory, which must exist and is read from disk and sent inline (see "Reading a bundle" below). A file or directory that happens to be named `mt_…` is reached as `./mt_…`, so what a value names never depends on what the current directory holds, and an address is written without its scheme. An `mt_` value holding a character no catalog id holds, anything but letters, digits, `_` and `-` (the ids are minted as `mt_` and a UUID, and the run route takes no other character), is a usage error made before any request, which says to write `./` to name a file: `mt_review.mthds` is refused, `./mt_review.mthds` is a path. A catalog id may end in a version suffix, which is sent whole: a bare `mt_…` runs the method's latest published version, `mt_…@<n>` the fixed version `n` and `mt_…@draft` its draft. A suffix that is neither a positive number without a leading zero nor `draft` (`@0`, `@03`, `@Draft`, two suffixes) is a usage error made before any request, as `parseMethodSelector` reads it.
23
23
  - **`--pipe`** names the pipe by its qualified ref, `domain.pipe_code`. It is sent as `pipe_ref` to the input preparation and as `pipe_code` to the run. A bare code, and an `alias->domain.pipe_code` ref naming a dependency's pipe, are usage errors. Without it, the run takes the method's main pipe, as the API resolves it.
24
24
  - **`--inputs`** names a JSON file holding one object, one entry per input, the shape `mthds run --inputs` and `cli-python`'s `--inputs` take; `-` reads it from stdin. The text is UTF-8, and a byte-order mark at its start is dropped, as RFC 8259 lets a JSON reader do, since Windows PowerShell 5.1 writes one (`Out-File -Encoding utf8`); a bundle's mark, by contrast, is sent as it is on disk. A relative path resolves against the current directory. A file or stdin that cannot be read is a usage error, `cannot read stdin.` with the system's reason under it (`Reason: EIO`), and a stdin closed when the command starts reads as empty, so it is not valid JSON: Node opens the null device on a standard stream a process starts without, and the Python command reads the missing stream the same way. A `process.stdin` destroyed before the command reads it is unreadable too, with the reason `ERR_STREAM_PREMATURE_CLOSE`. Without it the run gets no inputs. When the object has entries, they first go through the SDK's input preparation (`prepareInputs`, one `POST /v1/pipe-io` call): a local path or a `data:` URL at a file input is uploaded and replaced by its `pipelex-storage://` reference, each upload is reported on stderr, and a URL passes through. An empty object or no `--inputs` makes no preparation request. A value at a file input that is no file, a `data:` URL that does not decode or a value of another type such as a number, is a usage error, as is a local path that cannot be read; a method that does not load, met during the preparation, is reported as `--inputs-template` reports it ("Exit codes, errors and Ctrl-C" below). The command tells the two apart by the SDK's error classes, `InvalidLocalSourceError` and `InvalidInputValueError` for the inputs' mistakes and `MethodLoadError` for the method's ([`input-preparation.md`](input-preparation.md)).
25
- - **`--inputs-template`** prints the pipe's inputs template, the object `--inputs` takes with a placeholder for every input, and runs nothing. The template is rendered by `mthds`' `renderInputsTemplate`, in its compact JSON shape, from the input-form descriptor one `POST /v1/pipe-io` call returns, which spends no inference. It takes no `--inputs`.
25
+ - **`--inputs-template`** prints the pipe's inputs template, the object `--inputs` takes with a placeholder for every input, and runs nothing. The template is rendered by `mthds`' `renderInputsTemplate`, in its compact JSON shape, from the input-form descriptor one `POST /v1/pipe-io` call returns, which spends no inference. A `JSON` input, or one whose concept refines `JSON`, is written as the bare object it carries, `{}` to fill in, which a run reads literally. It takes no `--inputs`.
26
26
 
27
27
  The run goes through the SDK's `startAndWaitForResult`: on the hosted API a durable start, then polls until the run ends, however long it takes, and on a bare runner the blocking execute. Its `onStarted` callback prints `Run started: <id>` on stderr as soon as the run exists ([`run-results.md`](run-results.md)). The poll reads only the `main_stuff` artifact.
28
28
 
@@ -75,7 +75,7 @@ Every error goes to stderr, its first line `Error: <sentence>` and the lines und
75
75
  - **An answer the command cannot read**, a 2xx whose body the SDK could not read into what the route answers: `Error: the API's answer could not be read (status <n>).`, then `Reason: <the SDK's message>`, which names the route and what could not be read (`API POST /v1/start answered 202 with a body that is not JSON`), since such an answer carries no problem document, and `Request id: <id>` when its `X-Request-ID` header carries one.
76
76
  - **A failed run**: `Error: run <id> ended with status <STATUS>.`, then `Reason: <the report's message>` (the problem's own sentence when the run has no report) and `Next step: <the report's advised action>`.
77
77
  - **A method that does not load**: `Error: the method does not load.`, then one line per validation error that carries a string category and message, as ` - <file>: <message>`, or, when there is none, ` - <the answer's own message>`. It reads the same whichever request found it: the pipe I/O call of `--inputs-template` and `script`, or the input preparation of a run with inputs.
78
- - **A pipe I/O answer the command cannot use** for `--inputs-template` and `script`: `Error: the API's pipe I/O answer says neither that the method loads nor why it does not.` when it carries no verdict, `Error: the API's pipe I/O answer does not describe the pipe it selected.` when it names no pipe, carries no input form or describes another pipe, and `Error: the API's pipe I/O answer describes the pipe it selected with a malformed input form.` when the selected pipe's entry is malformed where input preparation or the template reads it, such as an enum with no list of `choices`, a `concept_ref` that is not a string or a fixed list counting fewer than two elements, or names a kind the SDK does not know, rather than crashing or rendering a template under made-up keys. Neither command says where the input form is malformed, since the Python client refuses it whole when it parses the answer, and the Python command refuses more, such as a member the standard does not define.
78
+ - **A pipe I/O answer the command cannot use** for `--inputs-template` and `script`: `Error: the API's pipe I/O answer says neither that the method loads nor why it does not.` when it carries no verdict, `Error: the API's pipe I/O answer does not describe the pipe it selected.` when it names no pipe, carries no input form or describes another pipe, and `Error: the API's pipe I/O answer describes the pipe it selected with a malformed input form.` when the selected pipe's entry is malformed where input preparation or the template reads it, such as an enum whose `choices` is not a list of strings, a `concept_ref` that is not a string, a fixed list counting fewer than two elements or a `JSON` input that is not an object carrying `json_obj`, or names a kind the SDK does not know, rather than crashing or rendering a template under made-up keys. Neither command says where the input form is malformed, since the Python client refuses it whole when it parses the answer, and the Python command refuses more, such as a member the standard does not define.
79
79
  - **A value at a file input that is no file**: `Error: the inputs hold a value at a file input that cannot be read as a file.`, then `Reason: <the SDK's message>` and the forms a file input takes. An unreadable local path reads `Error: Local file cannot be read: "<path>" (<reason>).`
80
80
  - **An unreachable API**: `Error: could not reach the Pipelex API at <base URL> (<code>).`
81
81
  - **A failed upload** of a file the inputs name: `Error: the upload of "<file>" failed (status <n>).`, the status left out when no answer came back, then `Reason: <the SDK's message>`, which says what the status means for an upload (a file past the size limit, a deployment without file upload, a credential refused), and `Next step:` and `Request id:` when the API's answer carries them. It covers the SDK's `RejectedAssetError`, `UploadAuthenticationError`, `UnsupportedUploadCapabilityError` and `UploadTransportError`, each of which names the file it was sending. It exits `1`, and no run starts.
@@ -4,7 +4,7 @@
4
4
 
5
5
  ## What the hook does with a file
6
6
 
7
- Each file goes through three stages: a local lint that blocks on any diagnostic, a local format that rewrites the file in place when its layout changes, and a validation by the hosted API (`POST /v1/validate`) that blocks on an invalid verdict and adds a non-blocking note about pending pipe signatures. The hook fails open: when the engine cannot load, when `PIPELEX_API_KEY` is unset or the API cannot be reached, the stage that could not run passes silently and the others stand. When several files are checked, one block among them wins and the notes are joined, and each file is read when its turn comes, so an edit made to it while an earlier file was being validated is checked rather than overwritten. The hook always exits 0, since its verdict is on stdout.
7
+ Each file goes through three stages: a local lint that blocks on any diagnostic, a local format that rewrites the file when its layout changes, and a validation by the hosted API (`POST /v1/validate`) that blocks on an invalid verdict and adds a non-blocking note about pending pipe signatures. The hook fails open: when the engine cannot load, when `PIPELEX_API_KEY` is unset or the API cannot be reached, the stage that could not run passes silently and the others stand. When several files are checked, one block among them wins and the notes are joined, and each file is read when its turn comes, so an edit made to it while an earlier file was being validated is checked rather than overwritten. The hook always exits 0, since its verdict is on stdout.
8
8
 
9
9
  An invalid verdict blocks with the server's Markdown rendering of it, which the hook always asks for, forwarded verbatim. When the server sends none, the hook words the block itself: the file that failed, the verdict's message, then one line for each fault the verdict lists in `errors[]`, each an MTHDS problem item named by its code, its sentence and where it happened, with its suggested fix, when it carries one, on a line of its own. The place and the fix are worded by the `mthds` package's `formatLocation` and `formatSuggestedFix`, as every MTHDS client words them, and a fix of a safety the hook does not know is shown as unsafe:
10
10
 
@@ -22,6 +22,18 @@ The hook reads each item member by member, with the SDK's `readProblemItems`, as
22
22
 
23
23
  The validation sends the method's tree around the file, the tree a run of the method would send: the edited file's directory listed by the `mthds` package's lister under the MTHDS standard's membership rule, so it is rooted at the nearest `METHODS.toml` at or above that directory, else at the directory itself, and holds every file the rule keeps — every bundle of the method, and every file a step reads, such as the template a `PipeDocGen` step names in `template_file`, under its tree path — while hidden entries, `node_modules`, `__pycache__`, what a `.gitignore` inside the tree keeps out and a run's inputs file never travel ([`method-trees.md`](./method-trees.md#the-four-forms-of-a-tree)), and neither does a file that looks like a secret ([below](#secrets-stay-home)). A method that fills a template thus validates as it would load from disk, its template checked by the dry run, and a step whose template file the tree does not hold makes the verdict say so, which blocks until the file is written. The client sends the tree inline when small and by hash otherwise, uploading the files the API lacks. The whole validation runs under one ten-second deadline, the version handshake, the blob route, the uploads and the validation request together, and the deadline stops whichever of them is under way when it runs out. Validation passes silently, as when the API cannot be reached, when that deadline runs out, when the tree holds a symbolic link or a directory the lister cannot read, when the edited file is not in its own tree because the rule keeps it out, when a file of the tree changes between its listing and its reading, when a file of the tree fails to upload, and past the hook's own caps: 100 files, 5 MiB for one of them or 12 MiB in all, each checked while the tree is listed, before any file is read.
24
24
 
25
+ ### How the format is written
26
+
27
+ When the format changes nothing, the file is not written at all. When it changes the layout, the hook does not write into the user's file: it writes the formatted text to a temporary file in the same directory, gives it the original's owner and group, flushes it to disk, gives it the original's permission bits, then renames it over the original (`src/hooks/format-write.ts`). A rename within one directory is atomic, so a hook stopped at any moment, by the agent's hook timeout or by the plugin wrapper's kill, leaves either the original file or the formatted one, never a truncated one. The temporary file is named after the original with a leading dot and a random suffix, such as `.main.mthds.4242.1a2b3c4d5e6f.tmp`, so the tree the validation sends, which leaves hidden entries out, never holds it, and it is removed on every failure. A symbolic link is followed, so the file it points to is replaced and the link stays a link, and a file the user cannot write is refused, as an in-place write refused it. The path is resolved to the name the directory stores, so on a case-insensitive filesystem the file keeps its name's case whatever case the agent wrote the path in.
28
+
29
+ A rename puts a new file at the original's name, so it keeps only what the hook gives the new file. Where that would change the file for the user, the hook writes the formatted text into the original in place instead, as it did before it renamed, which keeps everything the file carries at the cost of the atomicity: when the file has several hard links, since its other names would keep the old content, and on macOS and Linux when the new file cannot take the original's owner and group, because the file belongs to another user or to a group the user is not in and only root may give a file away. Running the hook as root thus formats a user's file without making it root's. The hook writes in place rather than skipping the format because these files are rare and the in-place write is the behaviour they always had.
30
+
31
+ Extended attributes and access control lists are neither copied nor looked for. Node has no interface to read them, so finding them would cost a separate program run on every format, and on macOS nearly every file carries the `com.apple.provenance` attribute, so the mere presence of one says nothing. An ACL the file inherits from its directory reaches the new file in the same way, since the new file is created in that directory; what a format loses is an attribute or an ACL entry set on the file itself, such as a Finder tag on macOS or a `setfacl` entry on Linux.
32
+
33
+ On Windows the same holds for the file's security descriptor: the renamed file keeps the one the temporary file was created with, made of the entries inherited from the directory. A file whose permissions only come from its folder, as in nearly every project tree, keeps the same permissions; a file given its own explicit entries, with `icacls` or the Security tab, loses them. Writing in place would keep them, but finding them would mean running `icacls` on every format, and the case is rare enough that the hook keeps the atomic rename there too. Windows has no POSIX owner to restore.
34
+
35
+ On Windows, a rename over an existing file also fails while another process holds that file open, as an antivirus scanner, a search indexer or an editor briefly does after a save. The hook retries such a refusal (`EPERM`, `EACCES` or `EBUSY`) a few times over about half a second. Before each retry it reads the file again, and when the file no longer holds the text the hook formatted, a newer save landed while the file was held: the hook keeps that save, removes the temporary file and prints a warning that the format was not written. When the file is still held after the last retry, or cannot be read to make that check, it removes the temporary file, prints a warning that the format could not be written, and goes on to the validation with the original file left exactly as it was.
36
+
25
37
  ## Secrets stay home
26
38
 
27
39
  When a `PIPELEX_API_KEY` is set, and before the validation sends anything, the hook reads every file of the tree once, after the format write-back, and screens it with the workshop's secret guard, the rule pipelex-mcp applies to every tree it sends, in a copy (`src/hooks/secret-guard.ts`) that is ahead of pipelex-mcp's `src/capabilities/secret-guard.ts` on the SSH key names and the PEM private key block below, until the workshop takes them up. The bytes screened are the bytes sent, never read again. The screen is needed because the listing reads only the `.gitignore` files inside the tree, so a repository's own `.gitignore` above the method's directory protects nothing in it, and the hook sends every file of the tree, not only its bundles. A `.env` never travels in any case, since the membership rule keeps out every name starting with a dot. With no key, the hook neither reads nor sends any file of the tree.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pipelex/sdk",
3
- "version": "0.71.0",
3
+ "version": "0.72.0",
4
4
  "description": "TypeScript SDK for the Pipelex hosted API — execute methods, manage runs, and call the product surface.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -80,7 +80,7 @@
80
80
  "vitest": "^4.0.18"
81
81
  },
82
82
  "dependencies": {
83
- "mthds": "^0.34.0",
83
+ "mthds": "^0.38.0",
84
84
  "smol-toml": "^1.6.0",
85
85
  "undici": "^7.29.1"
86
86
  }