@foldrun/core 18.0.1 → 18.2.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.
@@ -1,9 +1,13 @@
1
1
  import { type WireFormat } from "./providers.ts";
2
- export type SupplyProviderName = "anthropic" | "openai" | "gemini" | "deepseek" | "moonshot";
2
+ export type SupplyProviderName = "anthropic" | "openai" | "gemini" | "deepseek" | "moonshot" | "zai" | "qwen" | "minimax" | "mimo";
3
3
  export interface SupplyProvider {
4
4
  name: SupplyProviderName;
5
- /** The preset the step's provider block is built from (providers.ts). */
5
+ /** The preset the step's provider block is built from (providers.ts);
6
+ * "" when the runtime has none for this provider. */
6
7
  preset: string;
8
+ /** The endpoint, where the preset has none (a per-account address) or
9
+ * there is no preset: the one place the platform's key is used. */
10
+ baseUrl?: string;
7
11
  format: WireFormat;
8
12
  /** The one host the key is granted to. */
9
13
  host: string;
@@ -33,6 +37,10 @@ export interface SendShape {
33
37
  drop?: string[];
34
38
  /** The keys of `thinking` that are sent; null drops `thinking` whole. */
35
39
  thinking?: string[] | null;
40
+ /** `thinking.type` as this provider spells it (Claude Code sends
41
+ * `adaptive` to newer models; an endpoint that documents enabled |
42
+ * disabled alone gets `enabled`). A type not listed is sent as it is. */
43
+ thinkingType?: Record<string, string>;
36
44
  /** `output_config.effort`, as this provider spells it. */
37
45
  effort?: Record<string, string>;
38
46
  /** A `system` message inside `messages` (Anthropic's mid-conversation
@@ -87,6 +87,77 @@ export const SUPPLY_PROVIDERS = {
87
87
  dropDeferredTools: true,
88
88
  },
89
89
  },
90
+ // Four more open-weight coding families (owner, 10 Nov 2026), each on its
91
+ // own Anthropic-format endpoint, pay-as-you-go keys (a coding-plan key is
92
+ // a different product). What each documents was read from its own docs on
93
+ // 10 Nov 2026; `service_tier` is dropped everywhere — MiniMax bills its
94
+ // priority tier at 1.5x, and the others do not say what it does.
95
+ zai: {
96
+ name: "zai",
97
+ preset: "zai",
98
+ format: "anthropic",
99
+ host: "api.z.ai",
100
+ auth: "bearer",
101
+ metered: ["/api/anthropic/v1/messages"],
102
+ free: [],
103
+ // docs.z.ai documents no request schema for its Anthropic endpoint, only
104
+ // that Claude Code runs on it; its OpenAI one takes thinking.type
105
+ // enabled | disabled (GLM-5.3 refuses disabled). Context editing and
106
+ // tool search are Claude's alone.
107
+ send: { drop: ["context_management", "service_tier"], thinking: ["type", "budget_tokens"], thinkingType: { adaptive: "enabled" }, mergeSystemMessages: true, dropDeferredTools: true },
108
+ },
109
+ qwen: {
110
+ name: "qwen",
111
+ preset: "qwen",
112
+ // The preset's address is per account and per plan; the platform's
113
+ // pay-as-you-go key is used on the region-wide Singapore host.
114
+ baseUrl: "https://dashscope-intl.aliyuncs.com/apps/anthropic",
115
+ format: "anthropic",
116
+ // Alibaba Model Studio, Singapore: the region-wide host (still fully
117
+ // supported; the per-workspace host differs per account).
118
+ host: "dashscope-intl.aliyuncs.com",
119
+ auth: "x-api-key",
120
+ metered: ["/apps/anthropic/v1/messages"],
121
+ free: [],
122
+ // alibabacloud.com/help/en/model-studio/anthropic-api-messages (5 Nov
123
+ // 2026): thinking.type enabled | disabled, budget_tokens; effort xhigh |
124
+ // medium | low (max and high run as xhigh); user and assistant roles
125
+ // only. Web search is a typed tool, refused like Anthropic's.
126
+ send: { drop: ["context_management", "service_tier"], thinking: ["type", "budget_tokens"], thinkingType: { adaptive: "enabled" }, mergeSystemMessages: true, dropDeferredTools: true },
127
+ },
128
+ minimax: {
129
+ name: "minimax",
130
+ preset: "minimax",
131
+ format: "anthropic",
132
+ host: "api.minimax.io",
133
+ auth: "bearer",
134
+ metered: ["/anthropic/v1/messages"],
135
+ free: [{ method: "GET", path: "/anthropic/v1/models" }],
136
+ // platform.minimax.io/docs/api-reference/text-chat-anthropic (10 Nov
137
+ // 2026): thinking.type disabled | adaptive (no budget); effort takes
138
+ // every word ours does; no system role in messages (roles alternate);
139
+ // context_management, stop_sequences and top_k ignored.
140
+ send: { drop: ["context_management", "service_tier"], thinking: ["type"], thinkingType: { enabled: "adaptive" }, mergeSystemMessages: true, dropDeferredTools: true },
141
+ },
142
+ mimo: {
143
+ name: "mimo",
144
+ preset: "",
145
+ baseUrl: "https://api.xiaomimimo.com/anthropic",
146
+ format: "anthropic",
147
+ host: "api.xiaomimimo.com",
148
+ auth: "bearer",
149
+ metered: ["/anthropic/v1/messages"],
150
+ free: [],
151
+ // mimo.mi.com/static/docs/api/chat/anthropic-api-post (10 Nov 2026):
152
+ // the request schema is these fields alone; thinking.type enabled |
153
+ // disabled; a system role in messages is accepted; no effort.
154
+ send: {
155
+ fields: ["model", "messages", "max_tokens", "system", "stream", "stop_sequences", "temperature", "top_p", "tools", "tool_choice", "thinking"],
156
+ thinking: ["type"],
157
+ thinkingType: { adaptive: "enabled" },
158
+ dropDeferredTools: true,
159
+ },
160
+ },
90
161
  };
91
162
  export const SUPPLY_PROVIDER_NAMES = Object.keys(SUPPLY_PROVIDERS);
92
163
  /** How each reads to a person: on a step's credential line, in Settings. */
@@ -96,6 +167,10 @@ export const SUPPLY_TITLES = {
96
167
  gemini: "Google Gemini",
97
168
  deepseek: "DeepSeek",
98
169
  moonshot: "Moonshot Kimi",
170
+ zai: "Z.ai GLM",
171
+ qwen: "Alibaba Qwen",
172
+ minimax: "MiniMax",
173
+ mimo: "Xiaomi MiMo",
99
174
  };
100
175
  export function isSupplyProvider(name) {
101
176
  return typeof name === "string" && Object.hasOwn(SUPPLY_PROVIDERS, name);
@@ -119,13 +194,17 @@ export function supplyProviderOfToken(value) {
119
194
  * placeholder only. */
120
195
  export function supplyProviderBlock(provider, tiers) {
121
196
  const p = SUPPLY_PROVIDERS[provider];
122
- const preset = providerPreset(p.preset);
123
- if (!preset?.baseUrl)
124
- throw new Error(`model supply: no preset endpoint for ${provider}`);
197
+ const preset = p.preset ? providerPreset(p.preset) : undefined;
198
+ const baseUrl = p.baseUrl ?? preset?.baseUrl;
199
+ if (!baseUrl)
200
+ throw new Error(`model supply: no endpoint for ${provider}`);
125
201
  return {
126
- name: p.preset,
127
- base_url: preset.baseUrl,
202
+ // A provider the runtime has no preset for is spelled out whole: its
203
+ // address, format and auth, no name to look up.
204
+ ...(preset ? { name: p.preset } : {}),
205
+ base_url: baseUrl,
128
206
  format: p.format,
207
+ auth: p.auth,
129
208
  token: supplyToken(provider),
130
209
  ...(Object.keys(tiers).length ? { models: tiers } : {}),
131
210
  };
@@ -161,6 +240,14 @@ export function shapeRequest(p, json) {
161
240
  (delete t[k], (changed = true));
162
241
  }
163
242
  }
243
+ if (shape.thinkingType && json.thinking && typeof json.thinking === "object") {
244
+ const t = json.thinking;
245
+ const to = typeof t.type === "string" ? shape.thinkingType[t.type] : undefined;
246
+ if (to !== undefined && to !== t.type) {
247
+ t.type = to;
248
+ changed = true;
249
+ }
250
+ }
164
251
  if (shape.dropDeferredTools && Array.isArray(json.tools)) {
165
252
  const kept = json.tools.filter((t) => !(t && typeof t === "object" && t.defer_loading === true));
166
253
  if (kept.length !== json.tools.length) {
@@ -207,6 +294,10 @@ export function shapeRequest(p, json) {
207
294
  /** DeepSeek takes every foldrun word but runs three levels (its docs:
208
295
  * "medium and xhigh both map to high"). Said, not rewritten. */
209
296
  const DEEPSEEK_RUNS = { low: "low", medium: "high", high: "high", xhigh: "high", max: "max" };
297
+ /** Qwen 3.8 runs xhigh, medium and low ("max and high map to xhigh",
298
+ * Alibaba's Anthropic API page, 5 Nov 2026). Its other models' levels are
299
+ * not documented: said as written. */
300
+ const QWEN38_RUNS = { low: "low", medium: "medium", high: "xhigh", xhigh: "xhigh", max: "xhigh" };
210
301
  /**
211
302
  * The effort a foldrun level actually runs at on one of foldrun's models:
212
303
  * the provider's own aliases (DeepSeek), its reshaping (Kimi), the model's
@@ -222,6 +313,8 @@ export function effortRunsAs(provider, model, word) {
222
313
  return p.send.effort[word] ?? null;
223
314
  if (provider === "deepseek")
224
315
  return DEEPSEEK_RUNS[word] ?? null;
316
+ if (provider === "qwen" && /^qwen3\.8/i.test(model))
317
+ return QWEN38_RUNS[word] ?? null;
225
318
  if (p.format === "anthropic")
226
319
  return word;
227
320
  return fitEffort(model, word);
package/dist/src/otel.js CHANGED
@@ -92,7 +92,7 @@ const lastError = (s) => {
92
92
  * says whose model it was: the platform's own Claude credential, or one of
93
93
  * foldrun's models. An account's own provider: block could be anyone's, so
94
94
  * it says nothing rather than guess. */
95
- const PROVIDER = { anthropic: "anthropic", openai: "openai", gemini: "gcp.gemini", deepseek: "deepseek", moonshot: "moonshot_ai" };
95
+ const PROVIDER = { anthropic: "anthropic", openai: "openai", gemini: "gcp.gemini", deepseek: "deepseek", moonshot: "moonshot_ai", zai: "z_ai", qwen: "alibaba_qwen", minimax: "minimax", mimo: "xiaomi_mimo" };
96
96
  function providerOf(step) {
97
97
  if (!step)
98
98
  return null;
@@ -93,6 +93,23 @@ export declare function untrustedTextFindings(text: string): {
93
93
  line: number;
94
94
  message: string;
95
95
  }[];
96
+ /**
97
+ * Secrets in files about to LEAVE this machine (a snapshot upload, Part B3,
98
+ * 10 Nov 2026): every file, with nothing the files themselves can turn off —
99
+ * no foldrun-ignore, no vendored-path skip (Codex: a repo comment must not
100
+ * silence a key on its way out). A file that is not text (a NUL in its
101
+ * first 8 KB) cannot be read for secrets and is returned as unscanned, for
102
+ * the caller to say so rather than pass it quietly.
103
+ */
104
+ export declare function uploadSecretFindings(files: ScanFile[]): {
105
+ findings: {
106
+ rule: string;
107
+ file: string;
108
+ line?: number;
109
+ message: string;
110
+ }[];
111
+ unscanned: string[];
112
+ };
96
113
  /** The known field a key was probably meant to be, or null. */
97
114
  export declare function nearestField(key: string, known: readonly string[]): string | null;
98
115
  /** What a run leaves in an agent's folder — the Claude CLI's `.cache/` logs,
package/dist/src/scan.js CHANGED
@@ -598,6 +598,33 @@ export function untrustedTextFindings(text) {
598
598
  scanContent({ path: "untrusted", content: text }, text.split(/\r?\n/), (rule, _file, line, _text, message) => out.push({ rule, line: line ?? 0, message }), true);
599
599
  return out;
600
600
  }
601
+ /**
602
+ * Secrets in files about to LEAVE this machine (a snapshot upload, Part B3,
603
+ * 10 Nov 2026): every file, with nothing the files themselves can turn off —
604
+ * no foldrun-ignore, no vendored-path skip (Codex: a repo comment must not
605
+ * silence a key on its way out). A file that is not text (a NUL in its
606
+ * first 8 KB) cannot be read for secrets and is returned as unscanned, for
607
+ * the caller to say so rather than pass it quietly.
608
+ */
609
+ export function uploadSecretFindings(files) {
610
+ const findings = [];
611
+ const unscanned = [];
612
+ const seen = new Set();
613
+ for (const f of files) {
614
+ if (f.content.slice(0, 8000).includes("\u0000")) {
615
+ unscanned.push(f.path);
616
+ continue;
617
+ }
618
+ scanSecrets(f, f.content.split(/\r?\n/), (rule, file, line, _text, message) => {
619
+ const key = `${rule}\0${file}\0${line ?? ""}`;
620
+ if (seen.has(key))
621
+ return;
622
+ seen.add(key);
623
+ findings.push({ rule, file, ...(line ? { line } : {}), message });
624
+ });
625
+ }
626
+ return { findings, unscanned };
627
+ }
601
628
  /** The text hidden in tag characters: each is U+E0000 + an ASCII code. */
602
629
  function decodeTags(s) {
603
630
  let out = "";
@@ -0,0 +1,37 @@
1
+ export interface SnapshotEntry {
2
+ /** Relative, `/`-separated. */
3
+ path: string;
4
+ /** 0o644 or 0o755. */
5
+ mode: number;
6
+ content: Buffer;
7
+ }
8
+ export interface SnapshotLimits {
9
+ maxFiles: number;
10
+ maxFileBytes: number;
11
+ maxTotalBytes: number;
12
+ maxCompressedBytes: number;
13
+ }
14
+ export declare const SNAPSHOT_LIMITS: SnapshotLimits;
15
+ /** Why an archive was refused, in words a person can act on. */
16
+ export declare class SnapshotRefused extends Error {
17
+ constructor(message: string);
18
+ }
19
+ /** The path rules, for the packer to check before it packs, and the reader after. */
20
+ export declare function snapshotPathProblem(p: string): string | null;
21
+ /** A deterministic gzipped tar of these files (directories are implied). */
22
+ export declare function packSnapshot(entries: SnapshotEntry[], limits?: SnapshotLimits): {
23
+ archive: Buffer;
24
+ sha256: string;
25
+ files: number;
26
+ bytes: number;
27
+ };
28
+ /**
29
+ * Unpack an archive a stranger sent, under every rule above. Throws
30
+ * SnapshotRefused naming the first thing wrong; nothing is written anywhere —
31
+ * the caller gets the entries to store.
32
+ */
33
+ export declare function unpackSnapshot(archive: Buffer, limits?: SnapshotLimits): {
34
+ entries: SnapshotEntry[];
35
+ sha256: string;
36
+ bytes: number;
37
+ };
@@ -0,0 +1,255 @@
1
+ // Snapshot archives (Part B3, 10 Nov 2026): a folder from the user's machine,
2
+ // as one gzipped tar, for an agent on foldrun to work on.
3
+ //
4
+ // One writer and one strict reader, here, so the CLI (which packs) and the
5
+ // platform (which unpacks what a stranger sent) hold the same rules:
6
+ //
7
+ // - only regular files and directories — no links, devices, FIFOs, sparse
8
+ // files, PAX or GNU long-name headers (each a way to make a path mean
9
+ // something other than it says);
10
+ // - every path relative, `/`-separated, no `.`/`..`/empty segment, no
11
+ // backslash, NUL or control character, ≤ 255 bytes and ≤ 32 levels;
12
+ // - no path twice, also when only its case differs, and no file where a
13
+ // directory is (`a` and `a/b`);
14
+ // - limits on file count, one file's size and the whole, enforced while
15
+ // reading — before a byte past them is held;
16
+ // - header checksums verified; nothing after the end-of-archive blocks;
17
+ // - modes are 0644 or 0755 (the owner's exec bit), nothing else kept.
18
+ //
19
+ // The writer is deterministic: entries sorted, mtime 0, uid/gid 0, no names
20
+ // — the same folder is the same bytes, so a snapshot is known by its hash.
21
+ import crypto from "node:crypto";
22
+ import zlib from "node:zlib";
23
+ export const SNAPSHOT_LIMITS = {
24
+ maxFiles: 20_000,
25
+ maxFileBytes: 10 * 1024 * 1024,
26
+ maxTotalBytes: 200 * 1024 * 1024,
27
+ maxCompressedBytes: 50 * 1024 * 1024,
28
+ };
29
+ const MAX_PATH = 255;
30
+ const MAX_DEPTH = 32;
31
+ /** Why an archive was refused, in words a person can act on. */
32
+ export class SnapshotRefused extends Error {
33
+ constructor(message) {
34
+ super(message);
35
+ this.name = "SnapshotRefused";
36
+ }
37
+ }
38
+ /** The path rules, for the packer to check before it packs, and the reader after. */
39
+ export function snapshotPathProblem(p) {
40
+ if (!p)
41
+ return "an empty path";
42
+ if (Buffer.byteLength(p) > MAX_PATH)
43
+ return `a path longer than ${MAX_PATH} bytes`;
44
+ if (p.startsWith("/"))
45
+ return "an absolute path";
46
+ if (/[\u0000-\u001f\u007f\\]/.test(p))
47
+ return "a backslash or control character in a path";
48
+ const parts = p.split("/");
49
+ if (parts.length > MAX_DEPTH)
50
+ return `a path deeper than ${MAX_DEPTH} folders`;
51
+ if (parts.some((s) => s === "" || s === "." || s === ".."))
52
+ return "an empty, `.` or `..` segment";
53
+ return null;
54
+ }
55
+ /**
56
+ * The set of paths in one archive, with every clash rule in one place for the
57
+ * writer and the reader alike (Codex: the writer packed what the reader then
58
+ * refused). Case-insensitive throughout: `A` and `a/b` cannot both exist on
59
+ * a case-insensitive filesystem, so neither may be here.
60
+ */
61
+ class PathSet {
62
+ kinds = new Map();
63
+ parents = new Set();
64
+ add(p, isDir) {
65
+ const key = p.toLowerCase();
66
+ if (this.kinds.has(key))
67
+ throw new SnapshotRefused(`${p}: there twice (paths may not differ only by case)`);
68
+ const segs = key.split("/");
69
+ for (let i = 1; i < segs.length; i++) {
70
+ const parent = segs.slice(0, i).join("/");
71
+ if (this.kinds.get(parent) === "file")
72
+ throw new SnapshotRefused(`${p}: inside ${p.split("/").slice(0, i).join("/")}, which is a file`);
73
+ }
74
+ if (!isDir && this.parents.has(key))
75
+ throw new SnapshotRefused(`${p}: a file where another entry makes it a folder`);
76
+ this.kinds.set(key, isDir ? "dir" : "file");
77
+ for (let i = 1; i < segs.length; i++)
78
+ this.parents.add(segs.slice(0, i).join("/"));
79
+ }
80
+ }
81
+ // ------------------------------------------------------------------ writer
82
+ function octal(n, width) {
83
+ return n.toString(8).padStart(width - 1, "0") + "\0";
84
+ }
85
+ function header(path, size, mode, type) {
86
+ const h = Buffer.alloc(512, 0);
87
+ // ustar: name (100) and prefix (155); split at a "/" when it is long.
88
+ let name = path;
89
+ let prefix = "";
90
+ if (Buffer.byteLength(name) > 100) {
91
+ const cut = path.lastIndexOf("/", path.length - 1);
92
+ let at = -1;
93
+ for (let i = cut; i > 0; i = path.lastIndexOf("/", i - 1)) {
94
+ if (Buffer.byteLength(path.slice(i + 1)) <= 100 && Buffer.byteLength(path.slice(0, i)) <= 155) {
95
+ at = i;
96
+ break;
97
+ }
98
+ }
99
+ if (at < 0)
100
+ throw new SnapshotRefused(`${path}: too long to store`);
101
+ prefix = path.slice(0, at);
102
+ name = path.slice(at + 1);
103
+ }
104
+ h.write(name, 0, 100, "utf8");
105
+ h.write(octal(mode, 8), 100, 8, "ascii");
106
+ h.write(octal(0, 8), 108, 8, "ascii"); // uid
107
+ h.write(octal(0, 8), 116, 8, "ascii"); // gid
108
+ h.write(octal(size, 12), 124, 12, "ascii");
109
+ h.write(octal(0, 12), 136, 12, "ascii"); // mtime
110
+ h.write(" ", 148, 8, "ascii"); // checksum placeholder
111
+ h.write(type, 156, 1, "ascii");
112
+ h.write("ustar\u000000", 257, 8, "ascii");
113
+ h.write(prefix, 345, 155, "utf8");
114
+ let sum = 0;
115
+ for (const b of h)
116
+ sum += b;
117
+ h.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, 8, "ascii");
118
+ return h;
119
+ }
120
+ /** A deterministic gzipped tar of these files (directories are implied). */
121
+ export function packSnapshot(entries, limits = SNAPSHOT_LIMITS) {
122
+ if (entries.length > limits.maxFiles)
123
+ throw new SnapshotRefused(`${entries.length} files — the most is ${limits.maxFiles}`);
124
+ const sorted = [...entries].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
125
+ const parts = [];
126
+ let total = 0;
127
+ const paths = new PathSet();
128
+ for (const e of sorted) {
129
+ const problem = snapshotPathProblem(e.path);
130
+ if (problem)
131
+ throw new SnapshotRefused(`${e.path}: ${problem}`);
132
+ paths.add(e.path, false);
133
+ if (e.content.length > limits.maxFileBytes)
134
+ throw new SnapshotRefused(`${e.path}: ${e.content.length} bytes — the most for one file is ${limits.maxFileBytes}`);
135
+ total += e.content.length;
136
+ if (total > limits.maxTotalBytes)
137
+ throw new SnapshotRefused(`more than ${limits.maxTotalBytes} bytes in all`);
138
+ parts.push(header(e.path, e.content.length, e.mode === 0o755 ? 0o755 : 0o644, "0"));
139
+ parts.push(e.content);
140
+ const pad = (512 - (e.content.length % 512)) % 512;
141
+ if (pad)
142
+ parts.push(Buffer.alloc(pad, 0));
143
+ }
144
+ parts.push(Buffer.alloc(1024, 0));
145
+ const archive = zlib.gzipSync(Buffer.concat(parts), { level: 9, mtime: 0 });
146
+ // gzip's header carries an mtime and an OS byte; both fixed, so the bytes are the folder's alone.
147
+ archive.writeUInt32LE(0, 4);
148
+ archive[9] = 255;
149
+ if (archive.length > limits.maxCompressedBytes)
150
+ throw new SnapshotRefused(`${archive.length} bytes compressed — the most is ${limits.maxCompressedBytes}`);
151
+ return { archive, sha256: crypto.createHash("sha256").update(archive).digest("hex"), files: sorted.length, bytes: total };
152
+ }
153
+ // ------------------------------------------------------------------ reader
154
+ function readString(b, start, len) {
155
+ const s = b.subarray(start, start + len);
156
+ const nul = s.indexOf(0);
157
+ return s.subarray(0, nul < 0 ? len : nul).toString("utf8");
158
+ }
159
+ function readOctal(b, start, len, what) {
160
+ const raw = readString(b, start, len).trim();
161
+ if (raw === "")
162
+ return 0;
163
+ if (!/^[0-7]+$/.test(raw))
164
+ throw new SnapshotRefused(`a header's ${what} is not a number`);
165
+ const n = parseInt(raw, 8);
166
+ if (!Number.isSafeInteger(n))
167
+ throw new SnapshotRefused(`a header's ${what} is out of range`);
168
+ return n;
169
+ }
170
+ /**
171
+ * Unpack an archive a stranger sent, under every rule above. Throws
172
+ * SnapshotRefused naming the first thing wrong; nothing is written anywhere —
173
+ * the caller gets the entries to store.
174
+ */
175
+ export function unpackSnapshot(archive, limits = SNAPSHOT_LIMITS) {
176
+ if (archive.length > limits.maxCompressedBytes)
177
+ throw new SnapshotRefused(`${archive.length} bytes compressed — the most is ${limits.maxCompressedBytes}`);
178
+ let tar;
179
+ try {
180
+ // The tar is at most the files, their headers and padding: past that, a bomb.
181
+ const ceiling = limits.maxTotalBytes + (limits.maxFiles + 2) * 1024 + 1024;
182
+ tar = zlib.gunzipSync(archive, { maxOutputLength: ceiling });
183
+ }
184
+ catch (err) {
185
+ const code = err.code;
186
+ throw new SnapshotRefused(code === "ERR_BUFFER_TOO_LARGE" || /larger than/i.test(String(err.message)) ? `it unpacks past ${limits.maxTotalBytes} bytes` : "it is not a gzip archive");
187
+ }
188
+ const entries = [];
189
+ const paths = new PathSet();
190
+ // Every entry counts against maxFiles, folders too, before its path is
191
+ // recorded: an archive of folders alone would otherwise pass every limit
192
+ // and fill memory with paths (Codex). Our writer emits no folder entries.
193
+ let count = 0;
194
+ let total = 0;
195
+ let off = 0;
196
+ let ended = false;
197
+ while (off + 512 <= tar.length) {
198
+ const h = tar.subarray(off, off + 512);
199
+ if (h.every((x) => x === 0)) {
200
+ const next = tar.subarray(off + 512, off + 1024);
201
+ if (next.length === 512 && next.every((x) => x === 0)) {
202
+ ended = true;
203
+ off += 1024;
204
+ break;
205
+ }
206
+ throw new SnapshotRefused("a lone empty block before the end");
207
+ }
208
+ let sum = 0;
209
+ for (let i = 0; i < 512; i++)
210
+ sum += i >= 148 && i < 156 ? 32 : h[i];
211
+ if (readOctal(h, 148, 8, "checksum") !== sum)
212
+ throw new SnapshotRefused("a header's checksum is wrong");
213
+ if (readString(h, 257, 6) !== "ustar")
214
+ throw new SnapshotRefused("not a ustar archive");
215
+ const type = String.fromCharCode(h[156]);
216
+ const name = readString(h, 0, 100);
217
+ const prefix = readString(h, 345, 155);
218
+ const p0 = prefix ? `${prefix}/${name}` : name;
219
+ const isDir = type === "5";
220
+ const p = isDir ? p0.replace(/\/+$/, "") : p0;
221
+ if (type !== "0" && type !== "\0" && !isDir) {
222
+ const what = { "1": "a hard link", "2": "a symbolic link", "3": "a character device", "4": "a block device", "6": "a FIFO", x: "an extended (PAX) header", g: "a global PAX header", L: "a GNU long name", K: "a GNU long link", S: "a sparse file" }[type] ?? `an entry of type ${JSON.stringify(type)}`;
223
+ throw new SnapshotRefused(`${p || "(unnamed)"}: ${what} — only plain files and folders`);
224
+ }
225
+ const problem = snapshotPathProblem(p);
226
+ if (problem)
227
+ throw new SnapshotRefused(`${p}: ${problem}`);
228
+ const size = readOctal(h, 124, 12, "size");
229
+ if (isDir && size !== 0)
230
+ throw new SnapshotRefused(`${p}: a folder with a size`);
231
+ if (size > limits.maxFileBytes)
232
+ throw new SnapshotRefused(`${p}: ${size} bytes — the most for one file is ${limits.maxFileBytes}`);
233
+ if (++count > limits.maxFiles)
234
+ throw new SnapshotRefused(`more than ${limits.maxFiles} entries`);
235
+ paths.add(p, isDir);
236
+ off += 512;
237
+ if (!isDir) {
238
+ if (off + size > tar.length)
239
+ throw new SnapshotRefused(`${p}: cut short`);
240
+ total += size;
241
+ if (total > limits.maxTotalBytes)
242
+ throw new SnapshotRefused(`more than ${limits.maxTotalBytes} bytes in all`);
243
+ if (entries.length + 1 > limits.maxFiles)
244
+ throw new SnapshotRefused(`more than ${limits.maxFiles} files`);
245
+ const mode = readOctal(h, 100, 8, "mode");
246
+ entries.push({ path: p, mode: mode & 0o100 ? 0o755 : 0o644, content: Buffer.from(tar.subarray(off, off + size)) });
247
+ off += size + ((512 - (size % 512)) % 512);
248
+ }
249
+ }
250
+ if (!ended)
251
+ throw new SnapshotRefused("no end-of-archive marker");
252
+ if (tar.subarray(off).some((x) => x !== 0))
253
+ throw new SnapshotRefused("data after the end of the archive");
254
+ return { entries, sha256: crypto.createHash("sha256").update(archive).digest("hex"), bytes: total };
255
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "18.0.1",
3
+ "version": "18.2.0",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
@@ -33,7 +33,8 @@
33
33
  "./providers",
34
34
  "./subagents",
35
35
  "./tool-names",
36
- "./scan"
36
+ "./scan",
37
+ "./snapshot-archive"
37
38
  ]
38
39
  },
39
40
  "main": "./dist/index.js",
@@ -16,12 +16,16 @@
16
16
  import { providerPreset, type WireFormat } from "./providers.ts";
17
17
  import { fitEffort, EFFORT_ORDER } from "./effort-fit.ts";
18
18
 
19
- export type SupplyProviderName = "anthropic" | "openai" | "gemini" | "deepseek" | "moonshot";
19
+ export type SupplyProviderName = "anthropic" | "openai" | "gemini" | "deepseek" | "moonshot" | "zai" | "qwen" | "minimax" | "mimo";
20
20
 
21
21
  export interface SupplyProvider {
22
22
  name: SupplyProviderName;
23
- /** The preset the step's provider block is built from (providers.ts). */
23
+ /** The preset the step's provider block is built from (providers.ts);
24
+ * "" when the runtime has none for this provider. */
24
25
  preset: string;
26
+ /** The endpoint, where the preset has none (a per-account address) or
27
+ * there is no preset: the one place the platform's key is used. */
28
+ baseUrl?: string;
25
29
  format: WireFormat;
26
30
  /** The one host the key is granted to. */
27
31
  host: string;
@@ -49,6 +53,10 @@ export interface SendShape {
49
53
  drop?: string[];
50
54
  /** The keys of `thinking` that are sent; null drops `thinking` whole. */
51
55
  thinking?: string[] | null;
56
+ /** `thinking.type` as this provider spells it (Claude Code sends
57
+ * `adaptive` to newer models; an endpoint that documents enabled |
58
+ * disabled alone gets `enabled`). A type not listed is sent as it is. */
59
+ thinkingType?: Record<string, string>;
52
60
  /** `output_config.effort`, as this provider spells it. */
53
61
  effort?: Record<string, string>;
54
62
  /** A `system` message inside `messages` (Anthropic's mid-conversation
@@ -133,6 +141,77 @@ export const SUPPLY_PROVIDERS: Record<SupplyProviderName, SupplyProvider> = {
133
141
  dropDeferredTools: true,
134
142
  },
135
143
  },
144
+ // Four more open-weight coding families (owner, 10 Nov 2026), each on its
145
+ // own Anthropic-format endpoint, pay-as-you-go keys (a coding-plan key is
146
+ // a different product). What each documents was read from its own docs on
147
+ // 10 Nov 2026; `service_tier` is dropped everywhere — MiniMax bills its
148
+ // priority tier at 1.5x, and the others do not say what it does.
149
+ zai: {
150
+ name: "zai",
151
+ preset: "zai",
152
+ format: "anthropic",
153
+ host: "api.z.ai",
154
+ auth: "bearer",
155
+ metered: ["/api/anthropic/v1/messages"],
156
+ free: [],
157
+ // docs.z.ai documents no request schema for its Anthropic endpoint, only
158
+ // that Claude Code runs on it; its OpenAI one takes thinking.type
159
+ // enabled | disabled (GLM-5.3 refuses disabled). Context editing and
160
+ // tool search are Claude's alone.
161
+ send: { drop: ["context_management", "service_tier"], thinking: ["type", "budget_tokens"], thinkingType: { adaptive: "enabled" }, mergeSystemMessages: true, dropDeferredTools: true },
162
+ },
163
+ qwen: {
164
+ name: "qwen",
165
+ preset: "qwen",
166
+ // The preset's address is per account and per plan; the platform's
167
+ // pay-as-you-go key is used on the region-wide Singapore host.
168
+ baseUrl: "https://dashscope-intl.aliyuncs.com/apps/anthropic",
169
+ format: "anthropic",
170
+ // Alibaba Model Studio, Singapore: the region-wide host (still fully
171
+ // supported; the per-workspace host differs per account).
172
+ host: "dashscope-intl.aliyuncs.com",
173
+ auth: "x-api-key",
174
+ metered: ["/apps/anthropic/v1/messages"],
175
+ free: [],
176
+ // alibabacloud.com/help/en/model-studio/anthropic-api-messages (5 Nov
177
+ // 2026): thinking.type enabled | disabled, budget_tokens; effort xhigh |
178
+ // medium | low (max and high run as xhigh); user and assistant roles
179
+ // only. Web search is a typed tool, refused like Anthropic's.
180
+ send: { drop: ["context_management", "service_tier"], thinking: ["type", "budget_tokens"], thinkingType: { adaptive: "enabled" }, mergeSystemMessages: true, dropDeferredTools: true },
181
+ },
182
+ minimax: {
183
+ name: "minimax",
184
+ preset: "minimax",
185
+ format: "anthropic",
186
+ host: "api.minimax.io",
187
+ auth: "bearer",
188
+ metered: ["/anthropic/v1/messages"],
189
+ free: [{ method: "GET", path: "/anthropic/v1/models" }],
190
+ // platform.minimax.io/docs/api-reference/text-chat-anthropic (10 Nov
191
+ // 2026): thinking.type disabled | adaptive (no budget); effort takes
192
+ // every word ours does; no system role in messages (roles alternate);
193
+ // context_management, stop_sequences and top_k ignored.
194
+ send: { drop: ["context_management", "service_tier"], thinking: ["type"], thinkingType: { enabled: "adaptive" }, mergeSystemMessages: true, dropDeferredTools: true },
195
+ },
196
+ mimo: {
197
+ name: "mimo",
198
+ preset: "",
199
+ baseUrl: "https://api.xiaomimimo.com/anthropic",
200
+ format: "anthropic",
201
+ host: "api.xiaomimimo.com",
202
+ auth: "bearer",
203
+ metered: ["/anthropic/v1/messages"],
204
+ free: [],
205
+ // mimo.mi.com/static/docs/api/chat/anthropic-api-post (10 Nov 2026):
206
+ // the request schema is these fields alone; thinking.type enabled |
207
+ // disabled; a system role in messages is accepted; no effort.
208
+ send: {
209
+ fields: ["model", "messages", "max_tokens", "system", "stream", "stop_sequences", "temperature", "top_p", "tools", "tool_choice", "thinking"],
210
+ thinking: ["type"],
211
+ thinkingType: { adaptive: "enabled" },
212
+ dropDeferredTools: true,
213
+ },
214
+ },
136
215
  };
137
216
 
138
217
  export const SUPPLY_PROVIDER_NAMES = Object.keys(SUPPLY_PROVIDERS) as SupplyProviderName[];
@@ -144,6 +223,10 @@ export const SUPPLY_TITLES: Record<SupplyProviderName, string> = {
144
223
  gemini: "Google Gemini",
145
224
  deepseek: "DeepSeek",
146
225
  moonshot: "Moonshot Kimi",
226
+ zai: "Z.ai GLM",
227
+ qwen: "Alibaba Qwen",
228
+ minimax: "MiniMax",
229
+ mimo: "Xiaomi MiMo",
147
230
  };
148
231
 
149
232
  export function isSupplyProvider(name: unknown): name is SupplyProviderName {
@@ -192,12 +275,16 @@ export function supplyProviderOfToken(value: string | null | undefined): SupplyP
192
275
  * placeholder only. */
193
276
  export function supplyProviderBlock(provider: SupplyProviderName, tiers: Partial<Record<"fast" | "default" | "max", string>>): Record<string, unknown> {
194
277
  const p = SUPPLY_PROVIDERS[provider];
195
- const preset = providerPreset(p.preset);
196
- if (!preset?.baseUrl) throw new Error(`model supply: no preset endpoint for ${provider}`);
278
+ const preset = p.preset ? providerPreset(p.preset) : undefined;
279
+ const baseUrl = p.baseUrl ?? preset?.baseUrl;
280
+ if (!baseUrl) throw new Error(`model supply: no endpoint for ${provider}`);
197
281
  return {
198
- name: p.preset,
199
- base_url: preset.baseUrl,
282
+ // A provider the runtime has no preset for is spelled out whole: its
283
+ // address, format and auth, no name to look up.
284
+ ...(preset ? { name: p.preset } : {}),
285
+ base_url: baseUrl,
200
286
  format: p.format,
287
+ auth: p.auth,
201
288
  token: supplyToken(provider),
202
289
  ...(Object.keys(tiers).length ? { models: tiers } : {}),
203
290
  };
@@ -226,6 +313,14 @@ export function shapeRequest(p: SupplyProvider, json: Record<string, unknown>):
226
313
  for (const k of Object.keys(t)) if (!shape.thinking.includes(k)) (delete t[k], (changed = true));
227
314
  }
228
315
  }
316
+ if (shape.thinkingType && json.thinking && typeof json.thinking === "object") {
317
+ const t = json.thinking as Record<string, unknown>;
318
+ const to = typeof t.type === "string" ? shape.thinkingType[t.type] : undefined;
319
+ if (to !== undefined && to !== t.type) {
320
+ t.type = to;
321
+ changed = true;
322
+ }
323
+ }
229
324
  if (shape.dropDeferredTools && Array.isArray(json.tools)) {
230
325
  const kept = (json.tools as unknown[]).filter((t) => !(t && typeof t === "object" && (t as Record<string, unknown>).defer_loading === true));
231
326
  if (kept.length !== json.tools.length) {
@@ -271,6 +366,11 @@ export function shapeRequest(p: SupplyProvider, json: Record<string, unknown>):
271
366
  * "medium and xhigh both map to high"). Said, not rewritten. */
272
367
  const DEEPSEEK_RUNS: Record<string, string> = { low: "low", medium: "high", high: "high", xhigh: "high", max: "max" };
273
368
 
369
+ /** Qwen 3.8 runs xhigh, medium and low ("max and high map to xhigh",
370
+ * Alibaba's Anthropic API page, 5 Nov 2026). Its other models' levels are
371
+ * not documented: said as written. */
372
+ const QWEN38_RUNS: Record<string, string> = { low: "low", medium: "medium", high: "xhigh", xhigh: "xhigh", max: "xhigh" };
373
+
274
374
  /**
275
375
  * The effort a foldrun level actually runs at on one of foldrun's models:
276
376
  * the provider's own aliases (DeepSeek), its reshaping (Kimi), the model's
@@ -283,6 +383,7 @@ export function effortRunsAs(provider: SupplyProviderName, model: string, word:
283
383
  const p = SUPPLY_PROVIDERS[provider];
284
384
  if (p.send?.effort) return p.send.effort[word] ?? null;
285
385
  if (provider === "deepseek") return DEEPSEEK_RUNS[word] ?? null;
386
+ if (provider === "qwen" && /^qwen3\.8/i.test(model)) return QWEN38_RUNS[word] ?? null;
286
387
  if (p.format === "anthropic") return word;
287
388
  return fitEffort(model, word);
288
389
  }
package/src/otel.ts CHANGED
@@ -99,7 +99,7 @@ const lastError = (s: StepRecord | undefined) => {
99
99
  * says whose model it was: the platform's own Claude credential, or one of
100
100
  * foldrun's models. An account's own provider: block could be anyone's, so
101
101
  * it says nothing rather than guess. */
102
- const PROVIDER: Record<string, string> = { anthropic: "anthropic", openai: "openai", gemini: "gcp.gemini", deepseek: "deepseek", moonshot: "moonshot_ai" };
102
+ const PROVIDER: Record<string, string> = { anthropic: "anthropic", openai: "openai", gemini: "gcp.gemini", deepseek: "deepseek", moonshot: "moonshot_ai", zai: "z_ai", qwen: "alibaba_qwen", minimax: "minimax", mimo: "xiaomi_mimo" };
103
103
  function providerOf(step: StepRecord | undefined): string | null {
104
104
  if (!step) return null;
105
105
  // A refusal retried on the fallback supply (runner.ts) runs calls the
package/src/scan.ts CHANGED
@@ -679,6 +679,33 @@ export function untrustedTextFindings(text: string): { rule: string; line: numbe
679
679
  return out;
680
680
  }
681
681
 
682
+ /**
683
+ * Secrets in files about to LEAVE this machine (a snapshot upload, Part B3,
684
+ * 10 Nov 2026): every file, with nothing the files themselves can turn off —
685
+ * no foldrun-ignore, no vendored-path skip (Codex: a repo comment must not
686
+ * silence a key on its way out). A file that is not text (a NUL in its
687
+ * first 8 KB) cannot be read for secrets and is returned as unscanned, for
688
+ * the caller to say so rather than pass it quietly.
689
+ */
690
+ export function uploadSecretFindings(files: ScanFile[]): { findings: { rule: string; file: string; line?: number; message: string }[]; unscanned: string[] } {
691
+ const findings: { rule: string; file: string; line?: number; message: string }[] = [];
692
+ const unscanned: string[] = [];
693
+ const seen = new Set<string>();
694
+ for (const f of files) {
695
+ if (f.content.slice(0, 8000).includes("\u0000")) {
696
+ unscanned.push(f.path);
697
+ continue;
698
+ }
699
+ scanSecrets(f, f.content.split(/\r?\n/), (rule, file, line, _text, message) => {
700
+ const key = `${rule}\0${file}\0${line ?? ""}`;
701
+ if (seen.has(key)) return;
702
+ seen.add(key);
703
+ findings.push({ rule, file, ...(line ? { line } : {}), message });
704
+ });
705
+ }
706
+ return { findings, unscanned };
707
+ }
708
+
682
709
  /** The text hidden in tag characters: each is U+E0000 + an ASCII code. */
683
710
  function decodeTags(s: string): string {
684
711
  let out = "";
@@ -0,0 +1,249 @@
1
+ // Snapshot archives (Part B3, 10 Nov 2026): a folder from the user's machine,
2
+ // as one gzipped tar, for an agent on foldrun to work on.
3
+ //
4
+ // One writer and one strict reader, here, so the CLI (which packs) and the
5
+ // platform (which unpacks what a stranger sent) hold the same rules:
6
+ //
7
+ // - only regular files and directories — no links, devices, FIFOs, sparse
8
+ // files, PAX or GNU long-name headers (each a way to make a path mean
9
+ // something other than it says);
10
+ // - every path relative, `/`-separated, no `.`/`..`/empty segment, no
11
+ // backslash, NUL or control character, ≤ 255 bytes and ≤ 32 levels;
12
+ // - no path twice, also when only its case differs, and no file where a
13
+ // directory is (`a` and `a/b`);
14
+ // - limits on file count, one file's size and the whole, enforced while
15
+ // reading — before a byte past them is held;
16
+ // - header checksums verified; nothing after the end-of-archive blocks;
17
+ // - modes are 0644 or 0755 (the owner's exec bit), nothing else kept.
18
+ //
19
+ // The writer is deterministic: entries sorted, mtime 0, uid/gid 0, no names
20
+ // — the same folder is the same bytes, so a snapshot is known by its hash.
21
+
22
+ import crypto from "node:crypto";
23
+ import zlib from "node:zlib";
24
+
25
+ export interface SnapshotEntry {
26
+ /** Relative, `/`-separated. */
27
+ path: string;
28
+ /** 0o644 or 0o755. */
29
+ mode: number;
30
+ content: Buffer;
31
+ }
32
+
33
+ export interface SnapshotLimits {
34
+ maxFiles: number;
35
+ maxFileBytes: number;
36
+ maxTotalBytes: number;
37
+ maxCompressedBytes: number;
38
+ }
39
+
40
+ export const SNAPSHOT_LIMITS: SnapshotLimits = {
41
+ maxFiles: 20_000,
42
+ maxFileBytes: 10 * 1024 * 1024,
43
+ maxTotalBytes: 200 * 1024 * 1024,
44
+ maxCompressedBytes: 50 * 1024 * 1024,
45
+ };
46
+
47
+ const MAX_PATH = 255;
48
+ const MAX_DEPTH = 32;
49
+
50
+ /** Why an archive was refused, in words a person can act on. */
51
+ export class SnapshotRefused extends Error {
52
+ constructor(message: string) {
53
+ super(message);
54
+ this.name = "SnapshotRefused";
55
+ }
56
+ }
57
+
58
+ /** The path rules, for the packer to check before it packs, and the reader after. */
59
+ export function snapshotPathProblem(p: string): string | null {
60
+ if (!p) return "an empty path";
61
+ if (Buffer.byteLength(p) > MAX_PATH) return `a path longer than ${MAX_PATH} bytes`;
62
+ if (p.startsWith("/")) return "an absolute path";
63
+ if (/[\u0000-\u001f\u007f\\]/.test(p)) return "a backslash or control character in a path";
64
+ const parts = p.split("/");
65
+ if (parts.length > MAX_DEPTH) return `a path deeper than ${MAX_DEPTH} folders`;
66
+ if (parts.some((s) => s === "" || s === "." || s === "..")) return "an empty, `.` or `..` segment";
67
+ return null;
68
+ }
69
+
70
+ /**
71
+ * The set of paths in one archive, with every clash rule in one place for the
72
+ * writer and the reader alike (Codex: the writer packed what the reader then
73
+ * refused). Case-insensitive throughout: `A` and `a/b` cannot both exist on
74
+ * a case-insensitive filesystem, so neither may be here.
75
+ */
76
+ class PathSet {
77
+ private kinds = new Map<string, "file" | "dir">();
78
+ private parents = new Set<string>();
79
+ add(p: string, isDir: boolean): void {
80
+ const key = p.toLowerCase();
81
+ if (this.kinds.has(key)) throw new SnapshotRefused(`${p}: there twice (paths may not differ only by case)`);
82
+ const segs = key.split("/");
83
+ for (let i = 1; i < segs.length; i++) {
84
+ const parent = segs.slice(0, i).join("/");
85
+ if (this.kinds.get(parent) === "file") throw new SnapshotRefused(`${p}: inside ${p.split("/").slice(0, i).join("/")}, which is a file`);
86
+ }
87
+ if (!isDir && this.parents.has(key)) throw new SnapshotRefused(`${p}: a file where another entry makes it a folder`);
88
+ this.kinds.set(key, isDir ? "dir" : "file");
89
+ for (let i = 1; i < segs.length; i++) this.parents.add(segs.slice(0, i).join("/"));
90
+ }
91
+ }
92
+
93
+ // ------------------------------------------------------------------ writer
94
+
95
+ function octal(n: number, width: number): string {
96
+ return n.toString(8).padStart(width - 1, "0") + "\0";
97
+ }
98
+
99
+ function header(path: string, size: number, mode: number, type: "0" | "5"): Buffer {
100
+ const h = Buffer.alloc(512, 0);
101
+ // ustar: name (100) and prefix (155); split at a "/" when it is long.
102
+ let name = path;
103
+ let prefix = "";
104
+ if (Buffer.byteLength(name) > 100) {
105
+ const cut = path.lastIndexOf("/", path.length - 1);
106
+ let at = -1;
107
+ for (let i = cut; i > 0; i = path.lastIndexOf("/", i - 1)) {
108
+ if (Buffer.byteLength(path.slice(i + 1)) <= 100 && Buffer.byteLength(path.slice(0, i)) <= 155) {
109
+ at = i;
110
+ break;
111
+ }
112
+ }
113
+ if (at < 0) throw new SnapshotRefused(`${path}: too long to store`);
114
+ prefix = path.slice(0, at);
115
+ name = path.slice(at + 1);
116
+ }
117
+ h.write(name, 0, 100, "utf8");
118
+ h.write(octal(mode, 8), 100, 8, "ascii");
119
+ h.write(octal(0, 8), 108, 8, "ascii"); // uid
120
+ h.write(octal(0, 8), 116, 8, "ascii"); // gid
121
+ h.write(octal(size, 12), 124, 12, "ascii");
122
+ h.write(octal(0, 12), 136, 12, "ascii"); // mtime
123
+ h.write(" ", 148, 8, "ascii"); // checksum placeholder
124
+ h.write(type, 156, 1, "ascii");
125
+ h.write("ustar\u000000", 257, 8, "ascii");
126
+ h.write(prefix, 345, 155, "utf8");
127
+ let sum = 0;
128
+ for (const b of h) sum += b;
129
+ h.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, 8, "ascii");
130
+ return h;
131
+ }
132
+
133
+ /** A deterministic gzipped tar of these files (directories are implied). */
134
+ export function packSnapshot(entries: SnapshotEntry[], limits: SnapshotLimits = SNAPSHOT_LIMITS): { archive: Buffer; sha256: string; files: number; bytes: number } {
135
+ if (entries.length > limits.maxFiles) throw new SnapshotRefused(`${entries.length} files — the most is ${limits.maxFiles}`);
136
+ const sorted = [...entries].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
137
+ const parts: Buffer[] = [];
138
+ let total = 0;
139
+ const paths = new PathSet();
140
+ for (const e of sorted) {
141
+ const problem = snapshotPathProblem(e.path);
142
+ if (problem) throw new SnapshotRefused(`${e.path}: ${problem}`);
143
+ paths.add(e.path, false);
144
+ if (e.content.length > limits.maxFileBytes) throw new SnapshotRefused(`${e.path}: ${e.content.length} bytes — the most for one file is ${limits.maxFileBytes}`);
145
+ total += e.content.length;
146
+ if (total > limits.maxTotalBytes) throw new SnapshotRefused(`more than ${limits.maxTotalBytes} bytes in all`);
147
+ parts.push(header(e.path, e.content.length, e.mode === 0o755 ? 0o755 : 0o644, "0"));
148
+ parts.push(e.content);
149
+ const pad = (512 - (e.content.length % 512)) % 512;
150
+ if (pad) parts.push(Buffer.alloc(pad, 0));
151
+ }
152
+ parts.push(Buffer.alloc(1024, 0));
153
+ const archive = zlib.gzipSync(Buffer.concat(parts), { level: 9, mtime: 0 } as zlib.ZlibOptions);
154
+ // gzip's header carries an mtime and an OS byte; both fixed, so the bytes are the folder's alone.
155
+ archive.writeUInt32LE(0, 4);
156
+ archive[9] = 255;
157
+ if (archive.length > limits.maxCompressedBytes) throw new SnapshotRefused(`${archive.length} bytes compressed — the most is ${limits.maxCompressedBytes}`);
158
+ return { archive, sha256: crypto.createHash("sha256").update(archive).digest("hex"), files: sorted.length, bytes: total };
159
+ }
160
+
161
+ // ------------------------------------------------------------------ reader
162
+
163
+ function readString(b: Buffer, start: number, len: number): string {
164
+ const s = b.subarray(start, start + len);
165
+ const nul = s.indexOf(0);
166
+ return s.subarray(0, nul < 0 ? len : nul).toString("utf8");
167
+ }
168
+
169
+ function readOctal(b: Buffer, start: number, len: number, what: string): number {
170
+ const raw = readString(b, start, len).trim();
171
+ if (raw === "") return 0;
172
+ if (!/^[0-7]+$/.test(raw)) throw new SnapshotRefused(`a header's ${what} is not a number`);
173
+ const n = parseInt(raw, 8);
174
+ if (!Number.isSafeInteger(n)) throw new SnapshotRefused(`a header's ${what} is out of range`);
175
+ return n;
176
+ }
177
+
178
+ /**
179
+ * Unpack an archive a stranger sent, under every rule above. Throws
180
+ * SnapshotRefused naming the first thing wrong; nothing is written anywhere —
181
+ * the caller gets the entries to store.
182
+ */
183
+ export function unpackSnapshot(archive: Buffer, limits: SnapshotLimits = SNAPSHOT_LIMITS): { entries: SnapshotEntry[]; sha256: string; bytes: number } {
184
+ if (archive.length > limits.maxCompressedBytes) throw new SnapshotRefused(`${archive.length} bytes compressed — the most is ${limits.maxCompressedBytes}`);
185
+ let tar: Buffer;
186
+ try {
187
+ // The tar is at most the files, their headers and padding: past that, a bomb.
188
+ const ceiling = limits.maxTotalBytes + (limits.maxFiles + 2) * 1024 + 1024;
189
+ tar = zlib.gunzipSync(archive, { maxOutputLength: ceiling });
190
+ } catch (err) {
191
+ const code = (err as { code?: string }).code;
192
+ throw new SnapshotRefused(code === "ERR_BUFFER_TOO_LARGE" || /larger than/i.test(String((err as Error).message)) ? `it unpacks past ${limits.maxTotalBytes} bytes` : "it is not a gzip archive");
193
+ }
194
+ const entries: SnapshotEntry[] = [];
195
+ const paths = new PathSet();
196
+ // Every entry counts against maxFiles, folders too, before its path is
197
+ // recorded: an archive of folders alone would otherwise pass every limit
198
+ // and fill memory with paths (Codex). Our writer emits no folder entries.
199
+ let count = 0;
200
+ let total = 0;
201
+ let off = 0;
202
+ let ended = false;
203
+ while (off + 512 <= tar.length) {
204
+ const h = tar.subarray(off, off + 512);
205
+ if (h.every((x) => x === 0)) {
206
+ const next = tar.subarray(off + 512, off + 1024);
207
+ if (next.length === 512 && next.every((x) => x === 0)) {
208
+ ended = true;
209
+ off += 1024;
210
+ break;
211
+ }
212
+ throw new SnapshotRefused("a lone empty block before the end");
213
+ }
214
+ let sum = 0;
215
+ for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : h[i]!;
216
+ if (readOctal(h, 148, 8, "checksum") !== sum) throw new SnapshotRefused("a header's checksum is wrong");
217
+ if (readString(h, 257, 6) !== "ustar") throw new SnapshotRefused("not a ustar archive");
218
+ const type = String.fromCharCode(h[156]!);
219
+ const name = readString(h, 0, 100);
220
+ const prefix = readString(h, 345, 155);
221
+ const p0 = prefix ? `${prefix}/${name}` : name;
222
+ const isDir = type === "5";
223
+ const p = isDir ? p0.replace(/\/+$/, "") : p0;
224
+ if (type !== "0" && type !== "\0" && !isDir) {
225
+ const what = { "1": "a hard link", "2": "a symbolic link", "3": "a character device", "4": "a block device", "6": "a FIFO", x: "an extended (PAX) header", g: "a global PAX header", L: "a GNU long name", K: "a GNU long link", S: "a sparse file" }[type] ?? `an entry of type ${JSON.stringify(type)}`;
226
+ throw new SnapshotRefused(`${p || "(unnamed)"}: ${what} — only plain files and folders`);
227
+ }
228
+ const problem = snapshotPathProblem(p);
229
+ if (problem) throw new SnapshotRefused(`${p}: ${problem}`);
230
+ const size = readOctal(h, 124, 12, "size");
231
+ if (isDir && size !== 0) throw new SnapshotRefused(`${p}: a folder with a size`);
232
+ if (size > limits.maxFileBytes) throw new SnapshotRefused(`${p}: ${size} bytes — the most for one file is ${limits.maxFileBytes}`);
233
+ if (++count > limits.maxFiles) throw new SnapshotRefused(`more than ${limits.maxFiles} entries`);
234
+ paths.add(p, isDir);
235
+ off += 512;
236
+ if (!isDir) {
237
+ if (off + size > tar.length) throw new SnapshotRefused(`${p}: cut short`);
238
+ total += size;
239
+ if (total > limits.maxTotalBytes) throw new SnapshotRefused(`more than ${limits.maxTotalBytes} bytes in all`);
240
+ if (entries.length + 1 > limits.maxFiles) throw new SnapshotRefused(`more than ${limits.maxFiles} files`);
241
+ const mode = readOctal(h, 100, 8, "mode");
242
+ entries.push({ path: p, mode: mode & 0o100 ? 0o755 : 0o644, content: Buffer.from(tar.subarray(off, off + size)) });
243
+ off += size + ((512 - (size % 512)) % 512);
244
+ }
245
+ }
246
+ if (!ended) throw new SnapshotRefused("no end-of-archive marker");
247
+ if (tar.subarray(off).some((x) => x !== 0)) throw new SnapshotRefused("data after the end of the archive");
248
+ return { entries, sha256: crypto.createHash("sha256").update(archive).digest("hex"), bytes: total };
249
+ }