@lambdacurry/arbor 0.24.15 → 0.24.16

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.
Files changed (2) hide show
  1. package/dist/arbor.js +2278 -2104
  2. package/package.json +1 -1
package/dist/arbor.js CHANGED
@@ -1,2041 +1,1348 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // src/config.ts
4
- import {
5
- chmodSync,
6
- existsSync,
7
- lstatSync,
8
- mkdirSync,
9
- readFileSync,
10
- readdirSync,
11
- rmSync,
12
- statSync,
13
- writeFileSync
14
- } from "node:fs";
15
- import { homedir } from "node:os";
16
- import { dirname, join } from "node:path";
17
-
18
- // src/errors.ts
19
- var ERROR_CODES = new Set([
20
- "UNAUTHORIZED",
21
- "FORBIDDEN",
22
- "NOT_FOUND",
23
- "VALIDATION",
24
- "CONFLICT",
25
- "RATE_LIMITED",
26
- "NETWORK",
27
- "INTERNAL"
28
- ]);
29
- function isErrorCode(value) {
30
- return typeof value === "string" && ERROR_CODES.has(value);
31
- }
32
- function codeForStatus(status) {
33
- switch (status) {
34
- case 0:
35
- return "NETWORK";
36
- case 400:
37
- case 422:
38
- return "VALIDATION";
39
- case 401:
40
- return "UNAUTHORIZED";
41
- case 403:
42
- return "FORBIDDEN";
43
- case 404:
44
- case 410:
45
- return "NOT_FOUND";
46
- case 409:
47
- return "CONFLICT";
48
- case 429:
49
- return "RATE_LIMITED";
50
- default:
51
- return "INTERNAL";
52
- }
3
+ // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/util.js
4
+ function getEnumValues(entries) {
5
+ const numericValues = Object.values(entries).filter((v) => typeof v === "number");
6
+ const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
7
+ return values;
53
8
  }
54
- function exitCodeForError(code) {
55
- switch (code) {
56
- case "VALIDATION":
57
- return 2;
58
- case "UNAUTHORIZED":
59
- return 22;
60
- default:
61
- return 1;
62
- }
9
+ function joinValues(array, separator = "|") {
10
+ return array.map((val) => stringifyPrimitive(val)).join(separator);
63
11
  }
64
- function codeForError(err) {
65
- if (err && typeof err === "object" && "code" in err && isErrorCode(err.code)) {
66
- return err.code;
67
- }
68
- return "INTERNAL";
12
+ function jsonStringifyReplacer(_, value) {
13
+ if (typeof value === "bigint")
14
+ return value.toString();
15
+ return value;
69
16
  }
70
- function parseErrorDetails(value) {
71
- if (!value || typeof value !== "object")
72
- return;
73
- const raw = value;
74
- if (typeof raw.reason !== "string" || raw.reason === "")
75
- return;
76
- const details = { reason: raw.reason };
77
- if (typeof raw.field === "string")
78
- details.field = raw.field;
79
- if (typeof raw.limit === "number")
80
- details.limit = raw.limit;
81
- if (typeof raw.retryable === "boolean")
82
- details.retryable = raw.retryable;
83
- if (typeof raw.phase === "string")
84
- details.phase = raw.phase;
85
- if (raw.provider && typeof raw.provider === "object" && !Array.isArray(raw.provider)) {
86
- const provider = raw.provider;
87
- if (typeof provider.stage === "string" && provider.stage !== "") {
88
- details.provider = {
89
- stage: provider.stage,
90
- ...typeof provider.exitCode === "number" ? { exitCode: provider.exitCode } : {},
91
- ...typeof provider.stdout === "string" ? { stdout: provider.stdout } : {},
92
- ...typeof provider.stderr === "string" ? { stderr: provider.stderr } : {},
93
- ...typeof provider.containerStarted === "boolean" ? { containerStarted: provider.containerStarted } : {},
94
- ...typeof provider.repositoryMaterialized === "boolean" ? { repositoryMaterialized: provider.repositoryMaterialized } : {}
95
- };
96
- }
97
- }
98
- if (typeof raw.runId === "string")
99
- details.runId = raw.runId;
100
- if (typeof raw.operationId === "string")
101
- details.operationId = raw.operationId;
102
- if (typeof raw.processId === "string")
103
- details.processId = raw.processId;
104
- if (raw.outputRetention && typeof raw.outputRetention === "object") {
105
- const retention = raw.outputRetention;
106
- if (retention.state === "expired" && typeof retention.expiresAt === "string") {
107
- details.outputRetention = { state: "expired", expiresAt: retention.expiresAt };
17
+ function cached(getter) {
18
+ const set = false;
19
+ return {
20
+ get value() {
21
+ if (!set) {
22
+ const value = getter();
23
+ Object.defineProperty(this, "value", { value });
24
+ return value;
25
+ }
26
+ throw new Error("cached value already set");
108
27
  }
109
- }
110
- if (raw.commandExecution === "not-routed" || raw.commandExecution === "unknown") {
111
- details.commandExecution = raw.commandExecution;
112
- }
113
- if (raw.mutationRetrySafety === "safe" || raw.mutationRetrySafety === "unsafe" || raw.mutationRetrySafety === "unknown") {
114
- details.mutationRetrySafety = raw.mutationRetrySafety;
115
- }
116
- if (typeof raw.compatibilityState === "string") {
117
- details.compatibilityState = raw.compatibilityState;
118
- }
119
- if (typeof raw.compatibilityReason === "string") {
120
- details.compatibilityReason = raw.compatibilityReason;
121
- }
122
- if (typeof raw.suggestedAction === "string")
123
- details.suggestedAction = raw.suggestedAction;
124
- if (typeof raw.catalogRevision === "string")
125
- details.catalogRevision = raw.catalogRevision;
126
- if (typeof raw.clientCatalogRevision === "string") {
127
- details.clientCatalogRevision = raw.clientCatalogRevision;
128
- }
129
- if (typeof raw.catalogNextStep === "string")
130
- details.catalogNextStep = raw.catalogNextStep;
131
- return details;
28
+ };
132
29
  }
133
- function detailsForError(err) {
134
- if (!err || typeof err !== "object" || !("details" in err))
135
- return;
136
- return parseErrorDetails(err.details);
30
+ function nullish(input) {
31
+ return input === null || input === undefined;
137
32
  }
138
-
139
- class ApiError extends Error {
140
- status;
141
- details;
142
- code;
143
- constructor(message, status, details) {
144
- super(message);
145
- this.status = status;
146
- this.details = details;
147
- this.name = "ApiError";
148
- this.code = codeForStatus(status);
149
- }
33
+ function cleanRegex(source) {
34
+ const start = source.startsWith("^") ? 1 : 0;
35
+ const end = source.endsWith("$") ? source.length - 1 : source.length;
36
+ return source.slice(start, end);
150
37
  }
151
-
152
- class UsageError extends Error {
153
- code = "VALIDATION";
154
- details;
155
- constructor(message, details) {
156
- super(message);
157
- this.name = "UsageError";
158
- this.details = details ?? { reason: "validation.invalid_value" };
159
- }
38
+ function floatSafeRemainder(val, step) {
39
+ const ratio = val / step;
40
+ const roundedRatio = Math.round(ratio);
41
+ const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);
42
+ if (Math.abs(ratio - roundedRatio) < tolerance)
43
+ return 0;
44
+ return ratio - roundedRatio;
160
45
  }
161
-
162
- class PartialUploadError extends Error {
163
- partialResult;
164
- code;
165
- details;
166
- constructor(message, cause, partialResult) {
167
- super(message);
168
- this.partialResult = partialResult;
169
- this.name = "PartialUploadError";
170
- this.code = codeForError(cause);
171
- this.details = detailsForError(cause);
172
- }
46
+ var EVALUATING = /* @__PURE__ */ Symbol("evaluating");
47
+ function defineLazy(object, key, getter) {
48
+ let value = undefined;
49
+ Object.defineProperty(object, key, {
50
+ get() {
51
+ if (value === EVALUATING) {
52
+ return;
53
+ }
54
+ if (value === undefined) {
55
+ value = EVALUATING;
56
+ value = getter();
57
+ }
58
+ return value;
59
+ },
60
+ set(v) {
61
+ Object.defineProperty(object, key, {
62
+ value: v
63
+ });
64
+ },
65
+ configurable: true
66
+ });
173
67
  }
174
-
175
- // src/config.ts
176
- var PROD_API_URL = "https://arborthreads.com";
177
- var PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
178
- function arborDir() {
179
- return join(homedir(), ".arbor");
68
+ function assignProp(target, prop, value) {
69
+ Object.defineProperty(target, prop, {
70
+ value,
71
+ writable: true,
72
+ enumerable: true,
73
+ configurable: true
74
+ });
180
75
  }
181
- function defaultConfigPath() {
182
- return join(arborDir(), "config.json");
76
+ function mergeDefs(...defs) {
77
+ const mergedDescriptors = {};
78
+ for (const def of defs) {
79
+ const descriptors = Object.getOwnPropertyDescriptors(def);
80
+ Object.assign(mergedDescriptors, descriptors);
81
+ }
82
+ return Object.defineProperties({}, mergedDescriptors);
183
83
  }
184
- function profilesDir() {
185
- return join(arborDir(), "profiles");
84
+ function esc(str) {
85
+ return JSON.stringify(str);
186
86
  }
187
- function registryPath() {
188
- return join(arborDir(), "profiles.json");
87
+ function slugify(input) {
88
+ return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
189
89
  }
190
- function namedConfigPath(name) {
191
- return join(profilesDir(), `${name}.json`);
90
+ var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
91
+ function isObject(data) {
92
+ return typeof data === "object" && data !== null && !Array.isArray(data);
192
93
  }
193
- var CONFIG_PATH = process.env.ARBOR_CONFIG ?? join(homedir(), ".arbor", "config.json");
194
- var DEFAULT_TOKEN_OVERWRITE_REFUSAL = "refusing to overwrite ~/.arbor/config.json — a token already exists. Set ARBOR_CONFIG to an isolated path (e.g. ~/.arbor/<agent>.config.json) and retry.";
195
- var LOCK_TIMEOUT_MS = 5000;
196
- var LOCK_STALE_MS = 30000;
197
- var LOCK_POLL_MS = 20;
198
- var activeTarget;
199
- function sleepSync(ms) {
200
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
201
- }
202
- function acquireConfigLock(configPath) {
203
- const lockPath = `${configPath}.lock`;
204
- const deadline = Date.now() + LOCK_TIMEOUT_MS;
205
- for (;; ) {
206
- try {
207
- mkdirSync(lockPath);
208
- return () => {
209
- try {
210
- rmSync(lockPath, { recursive: true, force: true });
211
- } catch {}
212
- };
213
- } catch (err) {
214
- if (err?.code !== "EEXIST")
215
- throw err;
216
- try {
217
- if (Date.now() - statSync(lockPath).mtimeMs > LOCK_STALE_MS) {
218
- rmSync(lockPath, { recursive: true, force: true });
219
- continue;
220
- }
221
- } catch {
222
- continue;
223
- }
224
- if (Date.now() >= deadline) {
225
- throw new Error(`timed out waiting for another arbor process to finish writing ${configPath}. If none is running, remove ${lockPath}.`);
226
- }
227
- sleepSync(LOCK_POLL_MS);
228
- }
94
+ var allowsEval = /* @__PURE__ */ cached(() => {
95
+ if (globalConfig.jitless) {
96
+ return false;
229
97
  }
230
- }
231
- function validateProfileName(name, field = "profile") {
232
- if (!PROFILE_NAME.test(name)) {
233
- throw new UsageError(`invalid profile name: ${JSON.stringify(name)}`, {
234
- reason: "validation.invalid_value",
235
- field
236
- });
98
+ if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
99
+ return false;
237
100
  }
101
+ try {
102
+ const F = Function;
103
+ new F("");
104
+ return true;
105
+ } catch (_) {
106
+ return false;
107
+ }
108
+ });
109
+ function isPlainObject(o) {
110
+ if (isObject(o) === false)
111
+ return false;
112
+ const ctor = o.constructor;
113
+ if (ctor === undefined)
114
+ return true;
115
+ if (typeof ctor !== "function")
116
+ return true;
117
+ const prot = ctor.prototype;
118
+ if (isObject(prot) === false)
119
+ return false;
120
+ if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
121
+ return false;
122
+ }
123
+ return true;
238
124
  }
239
- function fsType(entry, predicate) {
240
- const value = entry[predicate];
241
- return typeof value === "function" ? Boolean(value.call(entry)) : value === true;
242
- }
243
- function rejectSymlink(path, label) {
244
- if (!existsSync(path))
245
- return;
246
- if (fsType(lstatSync(path), "isSymbolicLink"))
247
- throw new Error(`${label} must not be a symbolic link: ${path}`);
125
+ function shallowClone(o) {
126
+ if (isPlainObject(o))
127
+ return { ...o };
128
+ if (Array.isArray(o))
129
+ return [...o];
130
+ if (o instanceof Map)
131
+ return new Map(o);
132
+ if (o instanceof Set)
133
+ return new Set(o);
134
+ return o;
248
135
  }
249
- function ensureArborDir() {
250
- const dir = arborDir();
251
- rejectSymlink(dir, "Arbor config directory");
252
- mkdirSync(dir, { recursive: true, mode: 448 });
253
- chmodSync(dir, 448);
136
+ var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
137
+ function escapeRegex(str) {
138
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
254
139
  }
255
- function ensureProfilesDir() {
256
- ensureArborDir();
257
- const dir = profilesDir();
258
- rejectSymlink(dir, "Arbor profiles directory");
259
- mkdirSync(dir, { recursive: true, mode: 448 });
260
- chmodSync(dir, 448);
140
+ function clone(inst, def, params) {
141
+ const cl = new inst._zod.constr(def ?? inst._zod.def);
142
+ if (!def || params?.parent)
143
+ cl._zod.parent = inst;
144
+ return cl;
261
145
  }
262
- function readRegistry() {
263
- const path = registryPath();
264
- if (!existsSync(path))
146
+ function normalizeParams(_params) {
147
+ const params = _params;
148
+ if (!params)
265
149
  return {};
266
- rejectSymlink(path, "Arbor profile registry");
267
- try {
268
- const parsed = JSON.parse(readFileSync(path, "utf8"));
269
- if (parsed.defaultProfile !== undefined)
270
- validateProfileName(parsed.defaultProfile);
271
- return { defaultProfile: parsed.defaultProfile };
272
- } catch (err) {
273
- if (err instanceof UsageError)
274
- throw err;
275
- throw new Error(`could not read Arbor profile registry ${path}`);
276
- }
277
- }
278
- function writeRegistry(registry) {
279
- ensureArborDir();
280
- const path = registryPath();
281
- rejectSymlink(path, "Arbor profile registry");
282
- const release = acquireConfigLock(path);
283
- try {
284
- const safe = registry.defaultProfile ? { defaultProfile: registry.defaultProfile } : {};
285
- writeFileSync(path, `${JSON.stringify(safe, null, 2)}
286
- `, { mode: 384 });
287
- chmodSync(path, 384);
288
- } finally {
289
- release();
150
+ if (typeof params === "string")
151
+ return { error: () => params };
152
+ if (params?.message !== undefined) {
153
+ if (params?.error !== undefined)
154
+ throw new Error("Cannot specify both `message` and `error` params");
155
+ params.error = params.message;
290
156
  }
157
+ delete params.message;
158
+ if (typeof params.error === "string")
159
+ return { ...params, error: () => params.error };
160
+ return params;
291
161
  }
292
- function profileExists(name, field = "profile") {
293
- validateProfileName(name, field);
294
- const path = namedConfigPath(name);
295
- if (!existsSync(path))
296
- return false;
297
- rejectSymlink(path, `Arbor profile ${name}`);
298
- return fsType(lstatSync(path), "isFile");
162
+ function stringifyPrimitive(value) {
163
+ if (typeof value === "bigint")
164
+ return value.toString() + "n";
165
+ if (typeof value === "string")
166
+ return `"${value}"`;
167
+ return `${value}`;
299
168
  }
300
- function legacyTarget() {
301
- const defaultPath = defaultConfigPath();
302
- const envPath = process.env.ARBOR_CONFIG;
303
- return {
304
- path: envPath ?? defaultPath,
305
- defaultPath,
306
- isolated: Boolean(envPath),
307
- named: false,
308
- explicitProfile: false
309
- };
169
+ function optionalKeys(shape) {
170
+ return Object.keys(shape).filter((k) => {
171
+ return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional";
172
+ });
310
173
  }
311
- function resolveTarget(opts) {
312
- const profileFlag = opts?.profileFlag;
313
- const envProfile = process.env.ARBOR_PROFILE;
314
- if (process.env.ARBOR_CONFIG && profileFlag !== undefined) {
315
- throw new UsageError("ARBOR_CONFIG and --profile are ambiguous; choose one credential selector", {
316
- reason: "validation.invalid_value",
317
- field: "profile"
318
- });
174
+ var NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({
175
+ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
176
+ int32: [-2147483648, 2147483647],
177
+ uint32: [0, 4294967295],
178
+ float32: [-340282346638528860000000000000000000000, 340282346638528860000000000000000000000],
179
+ float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
180
+ }))();
181
+ function pick(schema, mask) {
182
+ const currDef = schema._zod.def;
183
+ const checks = currDef.checks;
184
+ const hasChecks = checks && checks.length > 0;
185
+ if (hasChecks) {
186
+ throw new Error(".pick() cannot be used on object schemas containing refinements");
319
187
  }
320
- if (process.env.ARBOR_CONFIG && envProfile !== undefined) {
321
- throw new UsageError("ARBOR_CONFIG and ARBOR_PROFILE are ambiguous; choose one credential selector", { reason: "validation.invalid_value", field: "ARBOR_PROFILE" });
188
+ const def = mergeDefs(schema._zod.def, {
189
+ get shape() {
190
+ const newShape = {};
191
+ for (const key of Reflect.ownKeys(mask)) {
192
+ if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) {
193
+ throw new Error(`Unrecognized key: "${String(key)}"`);
194
+ }
195
+ if (!mask[key])
196
+ continue;
197
+ assignProp(newShape, key, currDef.shape[key]);
198
+ }
199
+ assignProp(this, "shape", newShape);
200
+ return newShape;
201
+ },
202
+ checks: []
203
+ });
204
+ return clone(schema, def);
205
+ }
206
+ function omit(schema, mask) {
207
+ const currDef = schema._zod.def;
208
+ const checks = currDef.checks;
209
+ const hasChecks = checks && checks.length > 0;
210
+ if (hasChecks) {
211
+ throw new Error(".omit() cannot be used on object schemas containing refinements");
322
212
  }
323
- if (process.env.ARBOR_CONFIG)
324
- return legacyTarget();
325
- const registryDefault = readRegistry().defaultProfile;
326
- const selected = profileFlag ?? envProfile ?? registryDefault;
327
- if (selected === undefined)
328
- return legacyTarget();
329
- const field = profileFlag !== undefined ? "profile" : envProfile !== undefined ? "ARBOR_PROFILE" : "profile";
330
- validateProfileName(selected, field);
331
- if (!opts?.allowMissingProfile && !profileExists(selected, field)) {
332
- throw new UsageError(`unknown profile: ${selected}`, {
333
- reason: "validation.invalid_value",
334
- field
335
- });
213
+ const def = mergeDefs(schema._zod.def, {
214
+ get shape() {
215
+ const newShape = { ...schema._zod.def.shape };
216
+ for (const key of Reflect.ownKeys(mask)) {
217
+ if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) {
218
+ throw new Error(`Unrecognized key: "${String(key)}"`);
219
+ }
220
+ if (!mask[key])
221
+ continue;
222
+ delete newShape[key];
223
+ }
224
+ assignProp(this, "shape", newShape);
225
+ return newShape;
226
+ },
227
+ checks: []
228
+ });
229
+ return clone(schema, def);
230
+ }
231
+ function extend(schema, shape) {
232
+ if (!isPlainObject(shape)) {
233
+ throw new Error("Invalid input to extend: expected a plain object");
336
234
  }
337
- return {
338
- path: namedConfigPath(selected),
339
- defaultPath: defaultConfigPath(),
340
- isolated: true,
341
- profile: selected,
342
- named: true,
343
- explicitProfile: profileFlag !== undefined
344
- };
345
- }
346
- function configureConfigTarget(opts) {
347
- activeTarget = resolveTarget(opts);
348
- }
349
- function currentTarget() {
350
- return activeTarget ?? resolveTarget();
351
- }
352
- function getConfigPath() {
353
- return currentTarget().path;
354
- }
355
- function listProfiles() {
356
- const registry = readRegistry();
357
- const dir = profilesDir();
358
- if (!existsSync(dir))
359
- return { defaultProfile: registry.defaultProfile, profiles: [] };
360
- rejectSymlink(dir, "Arbor profiles directory");
361
- const profiles = readdirSync(dir).filter((entry) => entry.endsWith(".json")).map((entry) => {
362
- const name = entry.slice(0, -5);
363
- validateProfileName(name);
364
- const path = join(dir, entry);
365
- const stats = lstatSync(path);
366
- if (fsType(stats, "isSymbolicLink"))
367
- throw new Error(`Arbor profile ${name} must not be a symbolic link: ${path}`);
368
- if (!fsType(stats, "isFile"))
369
- throw new Error(`Arbor profile ${name} is not a regular file: ${path}`);
370
- return { name, default: registry.defaultProfile === name };
371
- }).sort((a, b) => a.name.localeCompare(b.name));
372
- return { defaultProfile: registry.defaultProfile, profiles };
373
- }
374
- function profileShow(name) {
375
- validateProfileName(name);
376
- if (!profileExists(name)) {
377
- throw new UsageError(`unknown profile: ${name}`, {
378
- reason: "validation.invalid_value",
379
- field: "profile"
380
- });
381
- }
382
- const registry = readRegistry();
383
- const cfg = JSON.parse(readFileSync(namedConfigPath(name), "utf8"));
384
- return {
385
- name,
386
- default: registry.defaultProfile === name,
387
- apiUrl: cfg.apiUrl || PROD_API_URL
388
- };
389
- }
390
- function setDefaultProfile(name) {
391
- if (name !== null) {
392
- validateProfileName(name);
393
- if (!profileExists(name)) {
394
- throw new UsageError(`unknown profile: ${name}`, {
395
- reason: "validation.invalid_value",
396
- field: "profile"
397
- });
235
+ const checks = schema._zod.def.checks;
236
+ const hasChecks = checks && checks.length > 0;
237
+ if (hasChecks) {
238
+ const existingShape = schema._zod.def.shape;
239
+ for (const key of Reflect.ownKeys(shape)) {
240
+ if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {
241
+ throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
242
+ }
398
243
  }
399
244
  }
400
- writeRegistry(name ? { defaultProfile: name } : {});
245
+ const def = mergeDefs(schema._zod.def, {
246
+ get shape() {
247
+ const _shape = { ...schema._zod.def.shape, ...shape };
248
+ assignProp(this, "shape", _shape);
249
+ return _shape;
250
+ }
251
+ });
252
+ return clone(schema, def);
401
253
  }
402
- function clearDefaultProfile() {
403
- setDefaultProfile(null);
254
+ function safeExtend(schema, shape) {
255
+ if (!isPlainObject(shape)) {
256
+ throw new Error("Invalid input to safeExtend: expected a plain object");
257
+ }
258
+ const def = mergeDefs(schema._zod.def, {
259
+ get shape() {
260
+ const _shape = { ...schema._zod.def.shape, ...shape };
261
+ assignProp(this, "shape", _shape);
262
+ return _shape;
263
+ }
264
+ });
265
+ return clone(schema, def);
404
266
  }
405
- function deleteProfile(name) {
406
- validateProfileName(name);
407
- const registry = readRegistry();
408
- if (registry.defaultProfile === name) {
409
- throw new UsageError(`cannot delete default profile ${name}; select another default or run profile clear-default first`, { reason: "validation.invalid_value", field: "profile" });
267
+ function merge(a, b) {
268
+ if (!b?._zod?.def) {
269
+ throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");
410
270
  }
411
- if (!profileExists(name)) {
412
- throw new UsageError(`unknown profile: ${name}`, {
413
- reason: "validation.invalid_value",
414
- field: "profile"
415
- });
271
+ if (a._zod.def.checks?.length) {
272
+ throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
416
273
  }
417
- const path = namedConfigPath(name);
418
- rejectSymlink(path, `Arbor profile ${name}`);
419
- rmSync(path);
274
+ const def = mergeDefs(a._zod.def, {
275
+ get shape() {
276
+ const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
277
+ assignProp(this, "shape", _shape);
278
+ return _shape;
279
+ },
280
+ get catchall() {
281
+ return b._zod.def.catchall;
282
+ },
283
+ checks: b._zod.def.checks ?? []
284
+ });
285
+ return clone(a, def);
420
286
  }
421
- function defaultConfigOverwriteBlocked(opts) {
422
- const target = currentTarget();
423
- const isolated = opts?.isolated ?? target.isolated;
424
- const path = opts?.path ?? target.defaultPath;
425
- if (isolated)
426
- return false;
427
- if (!existsSync(path))
428
- return false;
429
- try {
430
- const cfg = JSON.parse(readFileSync(path, "utf8"));
431
- return Boolean(cfg.token);
432
- } catch {
433
- return false;
287
+ function partial(Class, schema, mask, name = "partial") {
288
+ const currDef = schema._zod.def;
289
+ const checks = currDef.checks;
290
+ const hasChecks = checks && checks.length > 0;
291
+ if (hasChecks) {
292
+ throw new Error(`.${name}() cannot be used on object schemas containing refinements`);
434
293
  }
294
+ const def = mergeDefs(schema._zod.def, {
295
+ get shape() {
296
+ const oldShape = schema._zod.def.shape;
297
+ const shape = { ...oldShape };
298
+ if (mask) {
299
+ for (const key of Reflect.ownKeys(mask)) {
300
+ if (!Object.prototype.hasOwnProperty.call(oldShape, key)) {
301
+ throw new Error(`Unrecognized key: "${String(key)}"`);
302
+ }
303
+ if (!mask[key])
304
+ continue;
305
+ shape[key] = Class ? new Class({
306
+ type: "optional",
307
+ innerType: oldShape[key]
308
+ }) : oldShape[key];
309
+ }
310
+ } else {
311
+ for (const key of Reflect.ownKeys(oldShape)) {
312
+ shape[key] = Class ? new Class({
313
+ type: "optional",
314
+ innerType: oldShape[key]
315
+ }) : oldShape[key];
316
+ }
317
+ }
318
+ assignProp(this, "shape", shape);
319
+ return shape;
320
+ },
321
+ checks: []
322
+ });
323
+ return clone(schema, def);
435
324
  }
436
- function loadConfig() {
437
- const target = currentTarget();
438
- const envToken = target.explicitProfile ? undefined : process.env.ARBOR_TOKEN || undefined;
439
- const envUrl = process.env.ARBOR_API_URL || undefined;
440
- if (target.named)
441
- rejectSymlink(target.path, `Arbor profile ${target.profile}`);
442
- if (existsSync(target.path)) {
443
- try {
444
- const cfg = JSON.parse(readFileSync(target.path, "utf8"));
445
- return { apiUrl: envUrl ?? (cfg.apiUrl || PROD_API_URL), token: envToken ?? cfg.token };
446
- } catch (err) {
447
- if (err instanceof Error && /symbolic link/i.test(err.message))
448
- throw err;
325
+ function required(Class, schema, mask) {
326
+ const def = mergeDefs(schema._zod.def, {
327
+ get shape() {
328
+ const oldShape = schema._zod.def.shape;
329
+ const shape = { ...oldShape };
330
+ if (mask) {
331
+ for (const key of Reflect.ownKeys(mask)) {
332
+ if (!Object.prototype.hasOwnProperty.call(shape, key)) {
333
+ throw new Error(`Unrecognized key: "${String(key)}"`);
334
+ }
335
+ if (!mask[key])
336
+ continue;
337
+ shape[key] = new Class({
338
+ type: "nonoptional",
339
+ innerType: oldShape[key]
340
+ });
341
+ }
342
+ } else {
343
+ for (const key of Reflect.ownKeys(oldShape)) {
344
+ shape[key] = new Class({
345
+ type: "nonoptional",
346
+ innerType: oldShape[key]
347
+ });
348
+ }
349
+ }
350
+ assignProp(this, "shape", shape);
351
+ return shape;
449
352
  }
450
- }
451
- return { apiUrl: envUrl ?? PROD_API_URL, token: envToken };
353
+ });
354
+ return clone(schema, def);
452
355
  }
453
- function writeConfigGuarded(opts) {
454
- mkdirSync(dirname(opts.configPath), { recursive: true });
455
- const release = acquireConfigLock(opts.configPath);
456
- try {
457
- if (!opts.allowDefaultTokenOverwrite && defaultConfigOverwriteBlocked({ isolated: opts.isolated, path: opts.defaultPath })) {
458
- throw new Error(DEFAULT_TOKEN_OVERWRITE_REFUSAL);
356
+ function aborted(x, startIndex = 0) {
357
+ if (x.aborted === true)
358
+ return true;
359
+ for (let i = startIndex;i < x.issues.length; i++) {
360
+ if (x.issues[i]?.continue !== true) {
361
+ return true;
459
362
  }
460
- writeFileSync(opts.configPath, `${JSON.stringify(opts.cfg, null, 2)}
461
- `, { mode: 384 });
462
- chmodSync(opts.configPath, 384);
463
- } finally {
464
- release();
465
363
  }
364
+ return false;
466
365
  }
467
- function saveConfig(cfg, opts) {
468
- const target = currentTarget();
469
- if (target.named) {
470
- ensureProfilesDir();
471
- rejectSymlink(target.path, `Arbor profile ${target.profile}`);
366
+ function explicitlyAborted(x, startIndex = 0) {
367
+ if (x.aborted === true)
368
+ return true;
369
+ for (let i = startIndex;i < x.issues.length; i++) {
370
+ if (x.issues[i]?.continue === false) {
371
+ return true;
372
+ }
472
373
  }
473
- writeConfigGuarded({
474
- cfg,
475
- configPath: target.path,
476
- defaultPath: target.defaultPath,
477
- isolated: target.isolated,
478
- allowDefaultTokenOverwrite: opts?.allowDefaultTokenOverwrite
479
- });
480
- }
481
- function clearToken() {
482
- const cfg = loadConfig();
483
- saveConfig({ apiUrl: cfg.apiUrl }, { allowDefaultTokenOverwrite: true });
374
+ return false;
484
375
  }
485
-
486
- // src/source.ts
487
- var SNIFF = [
488
- ["CLAUDECODE", "Claude Code"],
489
- ["CLAUDE_CODE_ENTRYPOINT", "Claude Code"],
490
- ["OPENCLAW_HOME", "openclaw"],
491
- ["CODEX_SANDBOX", "Codex"],
492
- ["CURSOR_TRACE_ID", "Cursor"]
493
- ];
494
- function detectSource(env = process.env) {
495
- const explicit = env.ARBOR_SOURCE?.trim();
496
- if (explicit)
497
- return explicit;
498
- for (const [envVar, tool] of SNIFF) {
499
- if (env[envVar]?.trim())
500
- return tool;
501
- }
502
- return;
376
+ function prefixIssues(path, issues) {
377
+ return issues.map((iss) => {
378
+ var _a;
379
+ (_a = iss).path ?? (_a.path = []);
380
+ iss.path.unshift(path);
381
+ return iss;
382
+ });
503
383
  }
504
-
505
- // src/client.ts
506
- class NotLoggedInError extends Error {
507
- code = "UNAUTHORIZED";
508
- details = { reason: "authorization.denied" };
509
- constructor() {
510
- super("Not logged in. Run: arbor login");
511
- this.name = "NotLoggedInError";
384
+ function unwrapMessage(message) {
385
+ return typeof message === "string" ? message : message?.message;
386
+ }
387
+ function attachSchema(issues, start, inst) {
388
+ var _a;
389
+ for (let i = start;i < issues.length; i++) {
390
+ (_a = issues[i]).schema ?? (_a.schema = inst);
512
391
  }
513
392
  }
514
- function authHeader() {
515
- const cfg = loadConfig();
516
- if (!cfg.token)
517
- throw new NotLoggedInError;
518
- return { authorization: `Bearer ${cfg.token}`, apiUrl: cfg.apiUrl };
393
+ function finalizeIssue(iss, ctx, config) {
394
+ var _a;
395
+ const traits = iss.inst?._zod?.traits;
396
+ if (traits?.has("$ZodType")) {
397
+ if (traits.has("$ZodCheck"))
398
+ (_a = iss).schema ?? (_a.schema = iss.inst);
399
+ else
400
+ iss.schema = iss.inst;
401
+ }
402
+ const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;
403
+ const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
404
+ const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss;
405
+ rest.path ?? (rest.path = []);
406
+ rest.message = message;
407
+ if (ctx?.reportInput) {
408
+ rest.input = _input;
409
+ }
410
+ return rest;
519
411
  }
520
- var source = detectSource();
521
- var httpExecutor = {
522
- async call(name, input) {
523
- const { authorization, apiUrl } = authHeader();
524
- const dot = name.indexOf(".");
525
- const object = dot === -1 ? name : name.slice(0, dot);
526
- const verb = dot === -1 ? "" : name.slice(dot + 1);
527
- let res;
528
- try {
529
- res = await fetch(`${apiUrl}/api`, {
530
- method: "POST",
531
- headers: {
532
- "content-type": "application/json",
533
- authorization,
534
- ...source ? { "x-arbor-source": source } : {}
535
- },
536
- body: JSON.stringify({ object, verb, input })
537
- });
538
- } catch (cause) {
539
- throw new ApiError(`could not reach ${apiUrl} (${cause instanceof Error ? cause.message : String(cause)})`, 0);
412
+ var highSurrogate = /[\uD800-\uDBFF]/;
413
+ function codePointLength(str) {
414
+ const units = str.length;
415
+ if (!highSurrogate.test(str))
416
+ return units;
417
+ let count = units;
418
+ for (let i = 0;i < units - 1; i++) {
419
+ if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) {
420
+ count--;
421
+ i++;
540
422
  }
541
- const body = await res.json().catch(() => ({}));
542
- if (!res.ok || !body.success)
543
- throw new ApiError(body.error ?? `request failed (${res.status})`, res.status, parseErrorDetails(body.errorDetails));
544
- return body.data;
545
- }
546
- };
547
- async function binaryGet(path, authenticated = true) {
548
- const { authorization, apiUrl } = authHeader();
549
- let response;
550
- const url = new URL(path, apiUrl);
551
- if (url.origin !== new URL(apiUrl).origin || !authenticated && !url.pathname.startsWith("/api/attachment-read/"))
552
- throw new Error("Invalid download target");
553
- try {
554
- response = await fetch(url.toString(), {
555
- headers: authenticated ? { authorization } : {},
556
- redirect: "error"
557
- });
558
- } catch {
559
- throw new ApiError("Binary download request failed", 0);
560
423
  }
561
- if (!response.ok)
562
- throw new ApiError(`Download failed (${response.status})`, response.status);
563
- return response;
424
+ return count;
564
425
  }
565
-
566
- // src/attachment-download.ts
567
- async function downloadAttachment(id, output, signed = false, force = false) {
568
- const { createHash, randomUUID } = await import("node:crypto");
569
- const { open, rename, unlink, link } = await import("node:fs/promises");
570
- const { basename, resolve } = await import("node:path");
571
- if (!/^(att_|art_)[a-zA-Z0-9_-]+$/.test(id))
572
- throw new Error("Expected an Attachment or Artifact id");
573
- const artifact = id.startsWith("art_");
574
- const metadata = artifact && !signed ? null : await httpExecutor.call("attachment.get", {
575
- attachmentId: id,
576
- ...signed ? { signed: true } : {}
577
- });
578
- if (signed && !metadata?.signedRead)
579
- throw new Error("Signed download is unavailable");
580
- const response = await binaryGet(signed ? metadata.signedRead.url : `/api/download/${artifact ? "artifact/" : ""}${encodeURIComponent(id)}`, !signed);
581
- const size = metadata?.size ?? Number(response.headers.get("x-arbor-size") ?? response.headers.get("content-length") ?? "NaN");
582
- if (!Number.isSafeInteger(size) || size < 0 || !response.body)
583
- throw new Error("Download has no valid size or body");
584
- const suggested = basename(metadata?.filename ?? dispositionFilename(response.headers.get("content-disposition")) ?? id);
585
- const destination = resolve(output ?? (suggested.startsWith(".") ? id : suggested));
586
- const temporary = `${destination}.${randomUUID()}.part`;
587
- const file = await open(temporary, "wx", 384);
588
- const reader = response.body.getReader();
589
- const hash = createHash("sha256");
590
- let received = 0;
591
- try {
592
- for (;; ) {
593
- const { done, value } = await reader.read();
594
- if (done)
595
- break;
596
- received += value.byteLength;
597
- if (received > size)
598
- throw new Error("Download size mismatch");
599
- hash.update(value);
600
- let offset = 0;
601
- while (offset < value.length) {
602
- const written = await file.write(value, offset, value.length - offset);
603
- offset += written.bytesWritten;
604
- }
426
+ function getLengthableOrigin(input) {
427
+ if (Array.isArray(input))
428
+ return "array";
429
+ if (typeof input === "string")
430
+ return "string";
431
+ return "unknown";
432
+ }
433
+ function parsedType(data) {
434
+ const t = typeof data;
435
+ switch (t) {
436
+ case "number": {
437
+ return Number.isNaN(data) ? "nan" : "number";
605
438
  }
606
- const sha256 = hash.digest("hex");
607
- const expectedHash = metadata?.sha256 ?? response.headers.get("x-arbor-sha256");
608
- if (received !== size || expectedHash && expectedHash !== sha256)
609
- throw new Error("Download integrity mismatch");
610
- await file.close();
611
- if (force)
612
- await rename(temporary, destination);
613
- else {
614
- try {
615
- await link(temporary, destination);
616
- } catch (error) {
617
- if (error.code === "EEXIST")
618
- throw new Error("Destination exists; use --force to replace it");
619
- if (["EPERM", "ENOTSUP"].includes(error.code ?? ""))
620
- throw new Error("Filesystem does not support safe no-replace downloads; choose another destination or use --force to allow replacement");
621
- throw error;
439
+ case "object": {
440
+ if (data === null) {
441
+ return "null";
442
+ }
443
+ if (Array.isArray(data)) {
444
+ return "array";
445
+ }
446
+ const obj = data;
447
+ if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) {
448
+ return obj.constructor.name;
622
449
  }
623
- await unlink(temporary);
624
450
  }
625
- return { path: destination, size: received, sha256 };
626
- } catch (error) {
627
- await reader.cancel().catch(() => {});
628
- await file.close().catch(() => {});
629
- await unlink(temporary).catch(() => {});
630
- throw error;
631
- } finally {
632
- reader.releaseLock();
633
451
  }
452
+ return t;
634
453
  }
635
- function dispositionFilename(value) {
636
- if (!value)
637
- return;
638
- const encoded = /filename\*=UTF-8''([^;]+)/i.exec(value)?.[1];
639
- if (encoded) {
640
- try {
641
- return decodeURIComponent(encoded);
642
- } catch {}
454
+ function issue(...args) {
455
+ const [iss, input, inst] = args;
456
+ if (typeof iss === "string") {
457
+ return {
458
+ message: iss,
459
+ code: "custom",
460
+ input,
461
+ inst
462
+ };
643
463
  }
644
- return /filename="([^"]*)"/i.exec(value)?.[1] ?? /filename=([^;\s]+)/i.exec(value)?.[1];
464
+ return { ...iss };
645
465
  }
646
- // package.json
647
- var package_default = {
648
- name: "@lambdacurry/arbor",
649
- version: "0.24.15",
650
- description: "The Arbor CLI — a shared workspace for people and agents. The human + headless-agent write path over Arbor's guarded operation surface.",
651
- keywords: [
652
- "agents",
653
- "arbor",
654
- "cli",
655
- "collaboration",
656
- "mcp"
657
- ],
658
- license: "MIT",
659
- repository: {
660
- type: "git",
661
- url: "git+https://github.com/lambda-curry/arbor.git",
662
- directory: "packages/cli"
663
- },
664
- bin: {
665
- arbor: "./dist/arbor.js"
666
- },
667
- files: [
668
- "dist",
669
- "README.md"
670
- ],
671
- type: "module",
672
- publishConfig: {
673
- access: "public"
674
- },
675
- scripts: {
676
- arbor: "vpx src/bin.ts",
677
- build: "bun build ./src/bin.ts --target=node --outfile=dist/arbor.js",
678
- test: "vp test run --passWithNoTests",
679
- typecheck: "tsc -b",
680
- prepublishOnly: "bun run build"
681
- },
682
- devDependencies: {
683
- "@arbor/actions": "workspace:*",
684
- "@arbor/core": "workspace:*",
685
- "@types/node": "^26.2.0",
686
- "just-bash": "3.4.2",
687
- typescript: "^5.8.0",
688
- "vite-plus": "catalog:",
689
- zod: "^4.4.3"
690
- },
691
- engines: {
692
- node: ">=18"
693
- }
694
- };
695
-
696
- // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/util.js
697
- function getEnumValues(entries) {
698
- const numericValues = Object.values(entries).filter((v) => typeof v === "number");
699
- const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
700
- return values;
701
- }
702
- function joinValues(array, separator = "|") {
703
- return array.map((val) => stringifyPrimitive(val)).join(separator);
466
+ function members(proto, table) {
467
+ for (const key in table) {
468
+ const desc = Object.getOwnPropertyDescriptor(table, key);
469
+ if (desc.get)
470
+ Object.defineProperty(proto, key, { ...desc, enumerable: false });
471
+ else
472
+ defineBound(proto, key, desc.value);
473
+ }
704
474
  }
705
- function jsonStringifyReplacer(_, value) {
706
- if (typeof value === "bigint")
707
- return value.toString();
475
+ function own(inst, key, value, enumerable = true) {
476
+ Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });
708
477
  return value;
709
478
  }
710
- function cached(getter) {
711
- const set = false;
712
- return {
713
- get value() {
714
- if (!set) {
715
- const value = getter();
716
- Object.defineProperty(this, "value", { value });
717
- return value;
718
- }
719
- throw new Error("cached value already set");
720
- }
721
- };
722
- }
723
- function nullish(input) {
724
- return input === null || input === undefined;
479
+ function hide(inst, key, value) {
480
+ return own(inst, key, value, false);
725
481
  }
726
- function cleanRegex(source) {
727
- const start = source.startsWith("^") ? 1 : 0;
728
- const end = source.endsWith("$") ? source.length - 1 : source.length;
729
- return source.slice(start, end);
482
+ function defineBound(proto, key, fn) {
483
+ Object.defineProperty(proto, key, {
484
+ configurable: true,
485
+ get() {
486
+ return this == null ? fn : own(this, key, fn.bind(this));
487
+ },
488
+ set(value) {
489
+ own(this, key, value);
490
+ }
491
+ });
730
492
  }
731
- function floatSafeRemainder(val, step) {
732
- const ratio = val / step;
733
- const roundedRatio = Math.round(ratio);
734
- const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);
735
- if (Math.abs(ratio - roundedRatio) < tolerance)
736
- return 0;
737
- return ratio - roundedRatio;
493
+ function claim(inst, sentinel) {
494
+ const proto = Object.getPrototypeOf(inst);
495
+ return sentinel in proto ? undefined : proto;
738
496
  }
739
- var EVALUATING = /* @__PURE__ */ Symbol("evaluating");
740
- function defineLazy(object, key, getter) {
741
- let value = undefined;
742
- Object.defineProperty(object, key, {
497
+ var installing;
498
+ var broke = false;
499
+ var breaker = {
500
+ configurable: true,
501
+ get() {
502
+ broke = true;
503
+ return;
504
+ }
505
+ };
506
+ function defineLazyInternal(inst, key, compute) {
507
+ const proto = Object.getPrototypeOf(inst._zod);
508
+ if (key in proto && installing !== inst._zod) {
509
+ installing = undefined;
510
+ return;
511
+ }
512
+ installing = inst._zod;
513
+ Object.defineProperty(proto, key, {
514
+ configurable: true,
743
515
  get() {
744
- if (value === EVALUATING) {
745
- return;
746
- }
747
- if (value === undefined) {
748
- value = EVALUATING;
749
- value = getter();
516
+ Object.defineProperty(this, key, breaker);
517
+ const outer = broke;
518
+ broke = false;
519
+ try {
520
+ const value = compute(this);
521
+ if (broke)
522
+ delete this[key];
523
+ else
524
+ Object.defineProperty(this, key, { configurable: true, writable: true, value });
525
+ broke = broke || outer;
526
+ return value;
527
+ } catch (err) {
528
+ delete this[key];
529
+ broke = broke || outer;
530
+ throw err;
750
531
  }
751
- return value;
752
- },
753
- set(v) {
754
- Object.defineProperty(object, key, {
755
- value: v
756
- });
757
532
  },
758
- configurable: true
533
+ set(value) {
534
+ Object.defineProperty(this, key, { configurable: true, writable: true, value });
535
+ }
759
536
  });
760
537
  }
761
- function assignProp(target, prop, value) {
762
- Object.defineProperty(target, prop, {
763
- value,
764
- writable: true,
765
- enumerable: true,
766
- configurable: true
538
+ function installLazyProp(inst, key, make, enumerable) {
539
+ const proto = claim(inst, key);
540
+ if (!proto)
541
+ return;
542
+ Object.defineProperty(proto, key, {
543
+ configurable: true,
544
+ get() {
545
+ const desc = { configurable: true, writable: true, enumerable, value: undefined };
546
+ Object.defineProperty(this, key, desc);
547
+ desc.value = make(this);
548
+ Object.defineProperty(this, key, desc);
549
+ return desc.value;
550
+ },
551
+ set(value) {
552
+ Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });
553
+ }
767
554
  });
768
555
  }
769
- function mergeDefs(...defs) {
770
- const mergedDescriptors = {};
771
- for (const def of defs) {
772
- const descriptors = Object.getOwnPropertyDescriptors(def);
773
- Object.assign(mergedDescriptors, descriptors);
774
- }
775
- return Object.defineProperties({}, mergedDescriptors);
776
- }
777
- function esc(str) {
778
- return JSON.stringify(str);
779
- }
780
- function slugify(input) {
781
- return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
782
- }
783
- var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
784
- function isObject(data) {
785
- return typeof data === "object" && data !== null && !Array.isArray(data);
556
+ var CONSTANT_CATCH = "~constantCatch";
557
+ function constantCatch(value) {
558
+ const fn = () => value;
559
+ fn[CONSTANT_CATCH] = true;
560
+ return fn;
786
561
  }
787
- var allowsEval = /* @__PURE__ */ cached(() => {
788
- if (globalConfig.jitless) {
789
- return false;
562
+
563
+ // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/core.js
564
+ var _a;
565
+ var _zodDesc = { value: undefined, enumerable: false };
566
+ var _E = "captureStackTrace" in Error ? Error : null;
567
+ function newError(Definition) {
568
+ const E = _E;
569
+ if (E) {
570
+ const saved = E.stackTraceLimit;
571
+ if (typeof saved === "number") {
572
+ try {
573
+ E.stackTraceLimit = 0;
574
+ } catch {
575
+ _E = null;
576
+ return new Definition;
577
+ }
578
+ try {
579
+ return new Definition;
580
+ } finally {
581
+ E.stackTraceLimit = saved;
582
+ }
583
+ }
790
584
  }
791
- if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
792
- return false;
585
+ return new Definition;
586
+ }
587
+ function $constructor(name, initializer, proto, params) {
588
+ const zodProto = {};
589
+ function Internals(def) {
590
+ this.def = def;
591
+ this.constr = _;
592
+ this.traits = new Set;
793
593
  }
794
- try {
795
- const F = Function;
796
- new F("");
797
- return true;
798
- } catch (_) {
799
- return false;
594
+ Internals.prototype = zodProto;
595
+ const protoMembers = proto;
596
+ const initialized = protoMembers && new WeakSet;
597
+ function init(inst, def) {
598
+ if (!inst._zod) {
599
+ _zodDesc.value = new Internals(def);
600
+ try {
601
+ Object.defineProperty(inst, "_zod", _zodDesc);
602
+ } finally {
603
+ _zodDesc.value = undefined;
604
+ }
605
+ }
606
+ if (inst._zod.traits.has(name)) {
607
+ return;
608
+ }
609
+ inst._zod.traits.add(name);
610
+ initializer(inst, def);
611
+ if (initialized) {
612
+ const own = Object.getPrototypeOf(inst);
613
+ const ctorProto = inst._zod.constr.prototype;
614
+ let up = own;
615
+ while (up && up !== ctorProto)
616
+ up = Object.getPrototypeOf(up);
617
+ const target = up ?? own;
618
+ if (!initialized.has(target)) {
619
+ initialized.add(target);
620
+ members(target, protoMembers);
621
+ }
622
+ }
623
+ const proto = _.prototype;
624
+ for (const k in proto) {
625
+ if (!Object.prototype.hasOwnProperty.call(proto, k))
626
+ continue;
627
+ if (!(k in inst)) {
628
+ inst[k] = proto[k].bind(inst);
629
+ }
630
+ }
800
631
  }
801
- });
802
- function isPlainObject(o) {
803
- if (isObject(o) === false)
804
- return false;
805
- const ctor = o.constructor;
806
- if (ctor === undefined)
807
- return true;
808
- if (typeof ctor !== "function")
809
- return true;
810
- const prot = ctor.prototype;
811
- if (isObject(prot) === false)
812
- return false;
813
- if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
814
- return false;
632
+ const Parent = params?.Parent ?? Object;
633
+
634
+ class Definition extends Parent {
815
635
  }
816
- return true;
817
- }
818
- function shallowClone(o) {
819
- if (isPlainObject(o))
820
- return { ...o };
821
- if (Array.isArray(o))
822
- return [...o];
823
- if (o instanceof Map)
824
- return new Map(o);
825
- if (o instanceof Set)
826
- return new Set(o);
827
- return o;
828
- }
829
- var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
830
- function escapeRegex(str) {
831
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
636
+ Object.defineProperty(Definition, "name", { value: name });
637
+ function _(def) {
638
+ const inst = params?.Parent ? newError(Definition) : this;
639
+ init(inst, def);
640
+ const deferred = inst._zod.deferred;
641
+ if (deferred) {
642
+ for (const fn of deferred) {
643
+ fn();
644
+ }
645
+ inst._zod.deferred = undefined;
646
+ }
647
+ const pp = globalThis.__zod_globalConfig?.postProcessor;
648
+ if (pp)
649
+ pp(inst);
650
+ return inst;
651
+ }
652
+ Object.defineProperty(_, "init", { value: init });
653
+ Object.defineProperty(_, Symbol.hasInstance, {
654
+ value: (inst) => {
655
+ if (params?.Parent && inst instanceof params.Parent)
656
+ return true;
657
+ return inst?._zod?.traits?.has(name);
658
+ }
659
+ });
660
+ Object.defineProperty(_, "name", { value: name });
661
+ return _;
832
662
  }
833
- function clone(inst, def, params) {
834
- const cl = new inst._zod.constr(def ?? inst._zod.def);
835
- if (!def || params?.parent)
836
- cl._zod.parent = inst;
837
- return cl;
663
+ class $ZodAsyncError extends Error {
664
+ constructor() {
665
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
666
+ }
838
667
  }
839
- function normalizeParams(_params) {
840
- const params = _params;
841
- if (!params)
842
- return {};
843
- if (typeof params === "string")
844
- return { error: () => params };
845
- if (params?.message !== undefined) {
846
- if (params?.error !== undefined)
847
- throw new Error("Cannot specify both `message` and `error` params");
848
- params.error = params.message;
668
+
669
+ class $ZodEncodeError extends Error {
670
+ constructor(name) {
671
+ super(`Encountered unidirectional transform during encode: ${name}`);
672
+ this.name = "ZodEncodeError";
849
673
  }
850
- delete params.message;
851
- if (typeof params.error === "string")
852
- return { ...params, error: () => params.error };
853
- return params;
854
674
  }
855
- function stringifyPrimitive(value) {
856
- if (typeof value === "bigint")
857
- return value.toString() + "n";
858
- if (typeof value === "string")
859
- return `"${value}"`;
860
- return `${value}`;
675
+ (_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
676
+ var globalConfig = globalThis.__zod_globalConfig;
677
+ function config(newConfig) {
678
+ if (newConfig)
679
+ Object.assign(globalConfig, newConfig);
680
+ return globalConfig;
861
681
  }
862
- function optionalKeys(shape) {
863
- return Object.keys(shape).filter((k) => {
864
- return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional";
865
- });
682
+ // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/errors.js
683
+ function _getMessage() {
684
+ const internals = this._zod;
685
+ internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2));
686
+ return internals.message;
866
687
  }
867
- var NUMBER_FORMAT_RANGES = /* @__PURE__ */ (() => ({
868
- safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
869
- int32: [-2147483648, 2147483647],
870
- uint32: [0, 4294967295],
871
- float32: [-340282346638528860000000000000000000000, 340282346638528860000000000000000000000],
872
- float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
873
- }))();
874
- function pick(schema, mask) {
875
- const currDef = schema._zod.def;
876
- const checks = currDef.checks;
877
- const hasChecks = checks && checks.length > 0;
878
- if (hasChecks) {
879
- throw new Error(".pick() cannot be used on object schemas containing refinements");
880
- }
881
- const def = mergeDefs(schema._zod.def, {
882
- get shape() {
883
- const newShape = {};
884
- for (const key of Reflect.ownKeys(mask)) {
885
- if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) {
886
- throw new Error(`Unrecognized key: "${String(key)}"`);
887
- }
888
- if (!mask[key])
889
- continue;
890
- assignProp(newShape, key, currDef.shape[key]);
891
- }
892
- assignProp(this, "shape", newShape);
893
- return newShape;
894
- },
895
- checks: []
896
- });
897
- return clone(schema, def);
688
+ function _setMessage(value) {
689
+ this._zod.message = value;
898
690
  }
899
- function omit(schema, mask) {
900
- const currDef = schema._zod.def;
901
- const checks = currDef.checks;
902
- const hasChecks = checks && checks.length > 0;
903
- if (hasChecks) {
904
- throw new Error(".omit() cannot be used on object schemas containing refinements");
905
- }
906
- const def = mergeDefs(schema._zod.def, {
907
- get shape() {
908
- const newShape = { ...schema._zod.def.shape };
909
- for (const key of Reflect.ownKeys(mask)) {
910
- if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) {
911
- throw new Error(`Unrecognized key: "${String(key)}"`);
912
- }
913
- if (!mask[key])
914
- continue;
915
- delete newShape[key];
691
+ var _messageDesc = {
692
+ get: _getMessage,
693
+ set: _setMessage,
694
+ enumerable: true,
695
+ configurable: true
696
+ };
697
+ var _zodDesc2 = { value: undefined, enumerable: false };
698
+ var _issuesDesc = { value: undefined, enumerable: false };
699
+ var _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
700
+ var initializer = (inst, def) => {
701
+ inst.name = "$ZodError";
702
+ _zodDesc2.value = inst._zod;
703
+ Object.defineProperty(inst, "_zod", _zodDesc2);
704
+ _issuesDesc.value = def;
705
+ Object.defineProperty(inst, "issues", _issuesDesc);
706
+ _zodDesc2.value = undefined;
707
+ _issuesDesc.value = undefined;
708
+ Object.defineProperty(inst, "message", _messageDesc);
709
+ const proto = Object.getPrototypeOf(inst);
710
+ if (!_installedToString.has(proto)) {
711
+ _installedToString.add(proto);
712
+ Object.defineProperty(proto, "toString", {
713
+ configurable: true,
714
+ enumerable: false,
715
+ get() {
716
+ const value = () => this.message;
717
+ Object.defineProperty(this, "toString", { value, configurable: true, writable: true });
718
+ return value;
719
+ },
720
+ set(value) {
721
+ Object.defineProperty(this, "toString", { value, configurable: true, writable: true });
916
722
  }
917
- assignProp(this, "shape", newShape);
918
- return newShape;
919
- },
920
- checks: []
921
- });
922
- return clone(schema, def);
923
- }
924
- function extend(schema, shape) {
925
- if (!isPlainObject(shape)) {
926
- throw new Error("Invalid input to extend: expected a plain object");
723
+ });
927
724
  }
928
- const checks = schema._zod.def.checks;
929
- const hasChecks = checks && checks.length > 0;
930
- if (hasChecks) {
931
- const existingShape = schema._zod.def.shape;
932
- for (const key of Reflect.ownKeys(shape)) {
933
- if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {
934
- throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
935
- }
725
+ };
726
+ var $ZodError = $constructor("$ZodError", initializer);
727
+ var $ZodRealError = $constructor("$ZodError", initializer, undefined, {
728
+ Parent: Error
729
+ });
730
+ function node(obj, key, make) {
731
+ if (!Object.prototype.hasOwnProperty.call(obj, key)) {
732
+ if (key === "__proto__") {
733
+ Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });
734
+ } else {
735
+ obj[key] = make();
936
736
  }
937
737
  }
938
- const def = mergeDefs(schema._zod.def, {
939
- get shape() {
940
- const _shape = { ...schema._zod.def.shape, ...shape };
941
- assignProp(this, "shape", _shape);
942
- return _shape;
943
- }
944
- });
945
- return clone(schema, def);
738
+ return obj[key];
946
739
  }
947
- function safeExtend(schema, shape) {
948
- if (!isPlainObject(shape)) {
949
- throw new Error("Invalid input to safeExtend: expected a plain object");
950
- }
951
- const def = mergeDefs(schema._zod.def, {
952
- get shape() {
953
- const _shape = { ...schema._zod.def.shape, ...shape };
954
- assignProp(this, "shape", _shape);
955
- return _shape;
740
+ function flattenError(error, mapper = (issue) => issue.message) {
741
+ const fieldErrors = {};
742
+ const formErrors = [];
743
+ for (const sub of error.issues) {
744
+ if (sub.path.length > 0) {
745
+ node(fieldErrors, sub.path[0], () => []).push(mapper(sub));
746
+ } else {
747
+ formErrors.push(mapper(sub));
956
748
  }
957
- });
958
- return clone(schema, def);
959
- }
960
- function merge(a, b) {
961
- if (!b?._zod?.def) {
962
- throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");
963
- }
964
- if (a._zod.def.checks?.length) {
965
- throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
966
749
  }
967
- const def = mergeDefs(a._zod.def, {
968
- get shape() {
969
- const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
970
- assignProp(this, "shape", _shape);
971
- return _shape;
972
- },
973
- get catchall() {
974
- return b._zod.def.catchall;
975
- },
976
- checks: b._zod.def.checks ?? []
977
- });
978
- return clone(a, def);
750
+ return { formErrors, fieldErrors };
979
751
  }
980
- function partial(Class, schema, mask, name = "partial") {
981
- const currDef = schema._zod.def;
982
- const checks = currDef.checks;
983
- const hasChecks = checks && checks.length > 0;
984
- if (hasChecks) {
985
- throw new Error(`.${name}() cannot be used on object schemas containing refinements`);
986
- }
987
- const def = mergeDefs(schema._zod.def, {
988
- get shape() {
989
- const oldShape = schema._zod.def.shape;
990
- const shape = { ...oldShape };
991
- if (mask) {
992
- for (const key of Reflect.ownKeys(mask)) {
993
- if (!Object.prototype.hasOwnProperty.call(oldShape, key)) {
994
- throw new Error(`Unrecognized key: "${String(key)}"`);
995
- }
996
- if (!mask[key])
997
- continue;
998
- shape[key] = Class ? new Class({
999
- type: "optional",
1000
- innerType: oldShape[key]
1001
- }) : oldShape[key];
1002
- }
752
+ function formatError(error, mapper = (issue) => issue.message) {
753
+ const fieldErrors = { _errors: [] };
754
+ const processError = (error, path = []) => {
755
+ for (const issue of error.issues) {
756
+ if (issue.code === "invalid_union" && issue.errors.length) {
757
+ issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
758
+ } else if (issue.code === "invalid_key") {
759
+ processError({ issues: issue.issues }, [...path, ...issue.path]);
760
+ } else if (issue.code === "invalid_element") {
761
+ processError({ issues: issue.issues }, [...path, ...issue.path]);
1003
762
  } else {
1004
- for (const key of Reflect.ownKeys(oldShape)) {
1005
- shape[key] = Class ? new Class({
1006
- type: "optional",
1007
- innerType: oldShape[key]
1008
- }) : oldShape[key];
1009
- }
1010
- }
1011
- assignProp(this, "shape", shape);
1012
- return shape;
1013
- },
1014
- checks: []
1015
- });
1016
- return clone(schema, def);
1017
- }
1018
- function required(Class, schema, mask) {
1019
- const def = mergeDefs(schema._zod.def, {
1020
- get shape() {
1021
- const oldShape = schema._zod.def.shape;
1022
- const shape = { ...oldShape };
1023
- if (mask) {
1024
- for (const key of Reflect.ownKeys(mask)) {
1025
- if (!Object.prototype.hasOwnProperty.call(shape, key)) {
1026
- throw new Error(`Unrecognized key: "${String(key)}"`);
763
+ const fullpath = [...path, ...issue.path];
764
+ if (fullpath.length === 0) {
765
+ fieldErrors._errors.push(mapper(issue));
766
+ } else {
767
+ let curr = fieldErrors;
768
+ let i = 0;
769
+ while (i < fullpath.length) {
770
+ const el = fullpath[i];
771
+ const terminal = i === fullpath.length - 1;
772
+ if (el === "_errors") {
773
+ if (terminal)
774
+ curr._errors.push(mapper(issue));
775
+ i++;
776
+ continue;
777
+ }
778
+ if (!Object.prototype.hasOwnProperty.call(curr, el)) {
779
+ Object.defineProperty(curr, el, {
780
+ value: { _errors: [] },
781
+ enumerable: true,
782
+ writable: true,
783
+ configurable: true
784
+ });
785
+ }
786
+ const node = curr[el];
787
+ if (terminal) {
788
+ node._errors.push(mapper(issue));
789
+ }
790
+ curr = node;
791
+ i++;
1027
792
  }
1028
- if (!mask[key])
1029
- continue;
1030
- shape[key] = new Class({
1031
- type: "nonoptional",
1032
- innerType: oldShape[key]
1033
- });
1034
- }
1035
- } else {
1036
- for (const key of Reflect.ownKeys(oldShape)) {
1037
- shape[key] = new Class({
1038
- type: "nonoptional",
1039
- innerType: oldShape[key]
1040
- });
1041
793
  }
1042
794
  }
1043
- assignProp(this, "shape", shape);
1044
- return shape;
1045
795
  }
1046
- });
1047
- return clone(schema, def);
796
+ };
797
+ processError(error);
798
+ return fieldErrors;
1048
799
  }
1049
- function aborted(x, startIndex = 0) {
1050
- if (x.aborted === true)
1051
- return true;
1052
- for (let i = startIndex;i < x.issues.length; i++) {
1053
- if (x.issues[i]?.continue !== true) {
1054
- return true;
1055
- }
1056
- }
1057
- return false;
800
+
801
+ // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/parse.js
802
+ function finalizeParams(callee, params) {
803
+ return { callee: params?.callee ?? callee, Err: params?.Err };
1058
804
  }
1059
- function explicitlyAborted(x, startIndex = 0) {
1060
- if (x.aborted === true)
1061
- return true;
1062
- for (let i = startIndex;i < x.issues.length; i++) {
1063
- if (x.issues[i]?.continue === false) {
1064
- return true;
805
+ var _parse = (_Err) => {
806
+ const fn = (schema, value, _ctx, _params) => {
807
+ const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
808
+ const result = schema._zod.run({ value, issues: [] }, ctx);
809
+ if (result instanceof Promise) {
810
+ throw new $ZodAsyncError;
811
+ }
812
+ if (result.issues.length) {
813
+ const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
814
+ captureStackTrace(e, _params?.callee ?? fn);
815
+ throw e;
816
+ }
817
+ return result.value;
818
+ };
819
+ return fn;
820
+ };
821
+ var _parseAsync = (_Err) => {
822
+ const fn = async (schema, value, _ctx, params) => {
823
+ const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
824
+ let result = schema._zod.run({ value, issues: [] }, ctx);
825
+ if (result instanceof Promise)
826
+ result = await result;
827
+ if (result.issues.length) {
828
+ const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
829
+ captureStackTrace(e, params?.callee ?? fn);
830
+ throw e;
1065
831
  }
832
+ return result.value;
833
+ };
834
+ return fn;
835
+ };
836
+ var _safeParse = (_Err) => (schema, value, _ctx) => {
837
+ const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
838
+ const result = schema._zod.run({ value, issues: [] }, ctx);
839
+ if (result instanceof Promise) {
840
+ throw new $ZodAsyncError;
1066
841
  }
1067
- return false;
1068
- }
1069
- function prefixIssues(path, issues) {
1070
- return issues.map((iss) => {
1071
- var _a;
1072
- (_a = iss).path ?? (_a.path = []);
1073
- iss.path.unshift(path);
1074
- return iss;
1075
- });
842
+ return result.issues.length ? {
843
+ success: false,
844
+ error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
845
+ } : { success: true, data: result.value };
846
+ };
847
+ var safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
848
+ var _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
849
+ const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
850
+ let result = schema._zod.run({ value, issues: [] }, ctx);
851
+ if (result instanceof Promise)
852
+ result = await result;
853
+ return result.issues.length ? {
854
+ success: false,
855
+ error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
856
+ } : { success: true, data: result.value };
857
+ };
858
+ var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
859
+ var _encode = (_Err) => {
860
+ const parse = _parse(_Err);
861
+ const fn = (schema, value, _ctx, _params) => {
862
+ const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
863
+ return parse(schema, value, ctx, finalizeParams(fn, _params));
864
+ };
865
+ return fn;
866
+ };
867
+ var _decode = (_Err) => {
868
+ const parse = _parse(_Err);
869
+ const fn = (schema, value, _ctx, _params) => {
870
+ return parse(schema, value, _ctx, finalizeParams(fn, _params));
871
+ };
872
+ return fn;
873
+ };
874
+ var _encodeAsync = (_Err) => {
875
+ const parseAsync = _parseAsync(_Err);
876
+ const fn = async (schema, value, _ctx, _params) => {
877
+ const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
878
+ return await parseAsync(schema, value, ctx, finalizeParams(fn, _params));
879
+ };
880
+ return fn;
881
+ };
882
+ var _decodeAsync = (_Err) => {
883
+ const parseAsync = _parseAsync(_Err);
884
+ const fn = async (schema, value, _ctx, _params) => {
885
+ return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));
886
+ };
887
+ return fn;
888
+ };
889
+ var _safeEncode = (_Err) => (schema, value, _ctx) => {
890
+ const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
891
+ return _safeParse(_Err)(schema, value, ctx);
892
+ };
893
+ var _safeDecode = (_Err) => (schema, value, _ctx) => {
894
+ return _safeParse(_Err)(schema, value, _ctx);
895
+ };
896
+ var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
897
+ const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
898
+ return _safeParseAsync(_Err)(schema, value, ctx);
899
+ };
900
+ var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
901
+ return _safeParseAsync(_Err)(schema, value, _ctx);
902
+ };
903
+ // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/regexes.js
904
+ var cuid = /^[cC][0-9a-z]{6,}$/;
905
+ var cuid2 = /^[0-9a-z]+$/;
906
+ var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;
907
+ var xid = /^[0-9a-vA-V]{20}$/;
908
+ var ksuid = /^[A-Za-z0-9]{27}$/;
909
+ var nanoid = /^[a-zA-Z0-9_-]{21}$/;
910
+ function nanoidOfLength(length) {
911
+ return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);
1076
912
  }
1077
- function unwrapMessage(message) {
1078
- return typeof message === "string" ? message : message?.message;
913
+ var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
914
+ var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
915
+ var uuid = (version) => {
916
+ if (!version)
917
+ return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
918
+ return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
919
+ };
920
+ var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
921
+ var _emoji = `^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;
922
+ function emoji() {
923
+ return new RegExp(_emoji, "u");
1079
924
  }
1080
- function attachSchema(issues, start, inst) {
1081
- var _a;
1082
- for (let i = start;i < issues.length; i++) {
1083
- (_a = issues[i]).schema ?? (_a.schema = inst);
1084
- }
925
+ var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
926
+ var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
927
+ var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
928
+ var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
929
+ var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
930
+ var base64url = /^[A-Za-z0-9_-]*$/;
931
+ var httpProtocol = /^https?$/;
932
+ var e164 = /^\+[1-9]\d{6,14}$/;
933
+ var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
934
+ function anchor(source) {
935
+ return new RegExp(`^${source}$`);
1085
936
  }
1086
- function finalizeIssue(iss, ctx, config) {
1087
- var _a;
1088
- const traits = iss.inst?._zod?.traits;
1089
- if (traits?.has("$ZodType")) {
1090
- if (traits.has("$ZodCheck"))
1091
- (_a = iss).schema ?? (_a.schema = iss.inst);
1092
- else
1093
- iss.schema = iss.inst;
1094
- }
1095
- const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;
1096
- const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
1097
- const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss;
1098
- rest.path ?? (rest.path = []);
1099
- rest.message = message;
1100
- if (ctx?.reportInput) {
1101
- rest.input = _input;
1102
- }
1103
- return rest;
1104
- }
1105
- var highSurrogate = /[\uD800-\uDBFF]/;
1106
- function codePointLength(str) {
1107
- const units = str.length;
1108
- if (!highSurrogate.test(str))
1109
- return units;
1110
- let count = units;
1111
- for (let i = 0;i < units - 1; i++) {
1112
- if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) {
1113
- count--;
1114
- i++;
1115
- }
1116
- }
1117
- return count;
1118
- }
1119
- function getLengthableOrigin(input) {
1120
- if (Array.isArray(input))
1121
- return "array";
1122
- if (typeof input === "string")
1123
- return "string";
1124
- return "unknown";
1125
- }
1126
- function parsedType(data) {
1127
- const t = typeof data;
1128
- switch (t) {
1129
- case "number": {
1130
- return Number.isNaN(data) ? "nan" : "number";
1131
- }
1132
- case "object": {
1133
- if (data === null) {
1134
- return "null";
1135
- }
1136
- if (Array.isArray(data)) {
1137
- return "array";
1138
- }
1139
- const obj = data;
1140
- if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) {
1141
- return obj.constructor.name;
1142
- }
1143
- }
1144
- }
1145
- return t;
1146
- }
1147
- function issue(...args) {
1148
- const [iss, input, inst] = args;
1149
- if (typeof iss === "string") {
1150
- return {
1151
- message: iss,
1152
- code: "custom",
1153
- input,
1154
- inst
1155
- };
1156
- }
1157
- return { ...iss };
1158
- }
1159
- function members(proto, table) {
1160
- for (const key in table) {
1161
- const desc = Object.getOwnPropertyDescriptor(table, key);
1162
- if (desc.get)
1163
- Object.defineProperty(proto, key, { ...desc, enumerable: false });
1164
- else
1165
- defineBound(proto, key, desc.value);
1166
- }
937
+ var date = /* @__PURE__ */ anchor(dateSource);
938
+ function timeSource(args) {
939
+ const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
940
+ const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
941
+ return regex;
1167
942
  }
1168
- function own(inst, key, value, enumerable = true) {
1169
- Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });
1170
- return value;
943
+ function time(args) {
944
+ return new RegExp(`^${timeSource(args)}$`);
1171
945
  }
1172
- function hide(inst, key, value) {
1173
- return own(inst, key, value, false);
946
+ function datetime(args) {
947
+ const opts = ["Z"];
948
+ if (args.offset)
949
+ opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
950
+ const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`;
951
+ const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;
952
+ return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
1174
953
  }
1175
- function defineBound(proto, key, fn) {
1176
- Object.defineProperty(proto, key, {
1177
- configurable: true,
1178
- get() {
1179
- return this == null ? fn : own(this, key, fn.bind(this));
1180
- },
1181
- set(value) {
1182
- own(this, key, value);
954
+ var string = (params) => {
955
+ const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
956
+ return new RegExp(`^${regex}$`);
957
+ };
958
+ var integer = /^-?\d+$/;
959
+ var number = /^-?\d+(?:\.\d+)?$/;
960
+ var boolean = /^(?:true|false)$/i;
961
+ var _null = /^null$/i;
962
+ var lowercase = /^[^A-Z]*$/;
963
+ var uppercase = /^[^a-z]*$/;
964
+
965
+ // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/checks.js
966
+ var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
967
+ var _a;
968
+ inst._zod ?? (inst._zod = {});
969
+ inst._zod.def = def;
970
+ (_a = inst._zod).onattach ?? (_a.onattach = []);
971
+ });
972
+ var _whenHasLength = (payload) => {
973
+ const val = payload.value;
974
+ return !nullish(val) && val.length !== undefined;
975
+ };
976
+ var numericOriginMap = {
977
+ number: "number",
978
+ bigint: "bigint",
979
+ object: "date"
980
+ };
981
+ var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
982
+ $ZodCheck.init(inst, def);
983
+ const origin = numericOriginMap[typeof def.value];
984
+ inst._zod.onattach.push((inst) => {
985
+ const bag = inst._zod.bag;
986
+ const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
987
+ if (def.value < curr) {
988
+ if (def.inclusive)
989
+ bag.maximum = def.value;
990
+ else
991
+ bag.exclusiveMaximum = def.value;
1183
992
  }
1184
993
  });
1185
- }
1186
- function claim(inst, sentinel) {
1187
- const proto = Object.getPrototypeOf(inst);
1188
- return sentinel in proto ? undefined : proto;
1189
- }
1190
- var installing;
1191
- var broke = false;
1192
- var breaker = {
1193
- configurable: true,
1194
- get() {
1195
- broke = true;
1196
- return;
1197
- }
1198
- };
1199
- function defineLazyInternal(inst, key, compute) {
1200
- const proto = Object.getPrototypeOf(inst._zod);
1201
- if (key in proto && installing !== inst._zod) {
1202
- installing = undefined;
1203
- return;
1204
- }
1205
- installing = inst._zod;
1206
- Object.defineProperty(proto, key, {
1207
- configurable: true,
1208
- get() {
1209
- Object.defineProperty(this, key, breaker);
1210
- const outer = broke;
1211
- broke = false;
1212
- try {
1213
- const value = compute(this);
1214
- if (broke)
1215
- delete this[key];
1216
- else
1217
- Object.defineProperty(this, key, { configurable: true, writable: true, value });
1218
- broke = broke || outer;
1219
- return value;
1220
- } catch (err) {
1221
- delete this[key];
1222
- broke = broke || outer;
1223
- throw err;
1224
- }
1225
- },
1226
- set(value) {
1227
- Object.defineProperty(this, key, { configurable: true, writable: true, value });
994
+ inst._zod.check = (payload) => {
995
+ if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
996
+ return;
997
+ }
998
+ payload.issues.push({
999
+ origin: numericOriginMap[typeof payload.value] ?? origin,
1000
+ code: "too_big",
1001
+ maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
1002
+ input: payload.value,
1003
+ inclusive: def.inclusive,
1004
+ inst,
1005
+ continue: !def.abort
1006
+ });
1007
+ };
1008
+ });
1009
+ var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
1010
+ $ZodCheck.init(inst, def);
1011
+ const origin = numericOriginMap[typeof def.value];
1012
+ inst._zod.onattach.push((inst) => {
1013
+ const bag = inst._zod.bag;
1014
+ const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
1015
+ if (def.value > curr) {
1016
+ if (def.inclusive)
1017
+ bag.minimum = def.value;
1018
+ else
1019
+ bag.exclusiveMinimum = def.value;
1228
1020
  }
1229
1021
  });
1230
- }
1231
- function installLazyProp(inst, key, make, enumerable) {
1232
- const proto = claim(inst, key);
1233
- if (!proto)
1234
- return;
1235
- Object.defineProperty(proto, key, {
1236
- configurable: true,
1237
- get() {
1238
- const desc = { configurable: true, writable: true, enumerable, value: undefined };
1239
- Object.defineProperty(this, key, desc);
1240
- desc.value = make(this);
1241
- Object.defineProperty(this, key, desc);
1242
- return desc.value;
1243
- },
1244
- set(value) {
1245
- Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });
1022
+ inst._zod.check = (payload) => {
1023
+ if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
1024
+ return;
1246
1025
  }
1026
+ payload.issues.push({
1027
+ origin: numericOriginMap[typeof payload.value] ?? origin,
1028
+ code: "too_small",
1029
+ minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
1030
+ input: payload.value,
1031
+ inclusive: def.inclusive,
1032
+ inst,
1033
+ continue: !def.abort
1034
+ });
1035
+ };
1036
+ });
1037
+ var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
1038
+ $ZodCheck.init(inst, def);
1039
+ inst._zod.onattach.push((inst) => {
1040
+ var _a;
1041
+ (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
1247
1042
  });
1248
- }
1249
- var CONSTANT_CATCH = "~constantCatch";
1250
- function constantCatch(value) {
1251
- const fn = () => value;
1252
- fn[CONSTANT_CATCH] = true;
1253
- return fn;
1254
- }
1255
-
1256
- // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/core.js
1257
- var _a;
1258
- var _zodDesc = { value: undefined, enumerable: false };
1259
- var _E = "captureStackTrace" in Error ? Error : null;
1260
- function newError(Definition) {
1261
- const E = _E;
1262
- if (E) {
1263
- const saved = E.stackTraceLimit;
1264
- if (typeof saved === "number") {
1265
- try {
1266
- E.stackTraceLimit = 0;
1267
- } catch {
1268
- _E = null;
1269
- return new Definition;
1270
- }
1271
- try {
1272
- return new Definition;
1273
- } finally {
1274
- E.stackTraceLimit = saved;
1275
- }
1276
- }
1277
- }
1278
- return new Definition;
1279
- }
1280
- function $constructor(name, initializer, proto, params) {
1281
- const zodProto = {};
1282
- function Internals(def) {
1283
- this.def = def;
1284
- this.constr = _;
1285
- this.traits = new Set;
1286
- }
1287
- Internals.prototype = zodProto;
1288
- const protoMembers = proto;
1289
- const initialized = protoMembers && new WeakSet;
1290
- function init(inst, def) {
1291
- if (!inst._zod) {
1292
- _zodDesc.value = new Internals(def);
1293
- try {
1294
- Object.defineProperty(inst, "_zod", _zodDesc);
1295
- } finally {
1296
- _zodDesc.value = undefined;
1297
- }
1298
- }
1299
- if (inst._zod.traits.has(name)) {
1043
+ inst._zod.check = (payload) => {
1044
+ if (typeof payload.value !== typeof def.value)
1045
+ throw new Error("Cannot mix number and bigint in multiple_of check.");
1046
+ const isMultiple = typeof payload.value === "bigint" ? def.value !== BigInt(0) && payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0;
1047
+ if (isMultiple)
1300
1048
  return;
1301
- }
1302
- inst._zod.traits.add(name);
1303
- initializer(inst, def);
1304
- if (initialized) {
1305
- const own = Object.getPrototypeOf(inst);
1306
- const ctorProto = inst._zod.constr.prototype;
1307
- let up = own;
1308
- while (up && up !== ctorProto)
1309
- up = Object.getPrototypeOf(up);
1310
- const target = up ?? own;
1311
- if (!initialized.has(target)) {
1312
- initialized.add(target);
1313
- members(target, protoMembers);
1049
+ payload.issues.push({
1050
+ origin: typeof payload.value,
1051
+ code: "not_multiple_of",
1052
+ divisor: def.value,
1053
+ input: payload.value,
1054
+ inst,
1055
+ continue: !def.abort
1056
+ });
1057
+ };
1058
+ });
1059
+ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
1060
+ $ZodCheck.init(inst, def);
1061
+ def.format = def.format || "float64";
1062
+ const isInt = def.format?.includes("int");
1063
+ const origin = isInt ? "int" : "number";
1064
+ const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
1065
+ inst._zod.onattach.push((inst) => {
1066
+ const bag = inst._zod.bag;
1067
+ bag.format = def.format;
1068
+ bag.minimum = minimum;
1069
+ bag.maximum = maximum;
1070
+ if (isInt)
1071
+ bag.pattern = integer;
1072
+ });
1073
+ inst._zod.check = (payload) => {
1074
+ const input = payload.value;
1075
+ if (isInt) {
1076
+ if (!Number.isInteger(input)) {
1077
+ payload.issues.push({
1078
+ expected: origin,
1079
+ format: def.format,
1080
+ code: "invalid_type",
1081
+ continue: false,
1082
+ input,
1083
+ inst
1084
+ });
1085
+ return;
1314
1086
  }
1315
- }
1316
- const proto = _.prototype;
1317
- for (const k in proto) {
1318
- if (!Object.prototype.hasOwnProperty.call(proto, k))
1319
- continue;
1320
- if (!(k in inst)) {
1321
- inst[k] = proto[k].bind(inst);
1087
+ if (!Number.isSafeInteger(input)) {
1088
+ if (input > 0) {
1089
+ payload.issues.push({
1090
+ input,
1091
+ code: "too_big",
1092
+ maximum: Number.MAX_SAFE_INTEGER,
1093
+ note: "Integers must be within the safe integer range.",
1094
+ inst,
1095
+ origin,
1096
+ inclusive: true,
1097
+ continue: !def.abort
1098
+ });
1099
+ } else {
1100
+ payload.issues.push({
1101
+ input,
1102
+ code: "too_small",
1103
+ minimum: Number.MIN_SAFE_INTEGER,
1104
+ note: "Integers must be within the safe integer range.",
1105
+ inst,
1106
+ origin,
1107
+ inclusive: true,
1108
+ continue: !def.abort
1109
+ });
1110
+ }
1111
+ return;
1322
1112
  }
1323
1113
  }
1324
- }
1325
- const Parent = params?.Parent ?? Object;
1326
-
1327
- class Definition extends Parent {
1328
- }
1329
- Object.defineProperty(Definition, "name", { value: name });
1330
- function _(def) {
1331
- const inst = params?.Parent ? newError(Definition) : this;
1332
- init(inst, def);
1333
- const deferred = inst._zod.deferred;
1334
- if (deferred) {
1335
- for (const fn of deferred) {
1336
- fn();
1337
- }
1338
- inst._zod.deferred = undefined;
1114
+ if (input < minimum) {
1115
+ payload.issues.push({
1116
+ origin: "number",
1117
+ input,
1118
+ code: "too_small",
1119
+ minimum,
1120
+ inclusive: true,
1121
+ inst,
1122
+ continue: !def.abort
1123
+ });
1339
1124
  }
1340
- const pp = globalThis.__zod_globalConfig?.postProcessor;
1341
- if (pp)
1342
- pp(inst);
1343
- return inst;
1344
- }
1345
- Object.defineProperty(_, "init", { value: init });
1346
- Object.defineProperty(_, Symbol.hasInstance, {
1347
- value: (inst) => {
1348
- if (params?.Parent && inst instanceof params.Parent)
1349
- return true;
1350
- return inst?._zod?.traits?.has(name);
1125
+ if (input > maximum) {
1126
+ payload.issues.push({
1127
+ origin: "number",
1128
+ input,
1129
+ code: "too_big",
1130
+ maximum,
1131
+ inclusive: true,
1132
+ inst,
1133
+ continue: !def.abort
1134
+ });
1351
1135
  }
1352
- });
1353
- Object.defineProperty(_, "name", { value: name });
1354
- return _;
1355
- }
1356
- class $ZodAsyncError extends Error {
1357
- constructor() {
1358
- super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
1359
- }
1360
- }
1361
-
1362
- class $ZodEncodeError extends Error {
1363
- constructor(name) {
1364
- super(`Encountered unidirectional transform during encode: ${name}`);
1365
- this.name = "ZodEncodeError";
1366
- }
1367
- }
1368
- (_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
1369
- var globalConfig = globalThis.__zod_globalConfig;
1370
- function config(newConfig) {
1371
- if (newConfig)
1372
- Object.assign(globalConfig, newConfig);
1373
- return globalConfig;
1374
- }
1375
- // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/errors.js
1376
- function _getMessage() {
1377
- const internals = this._zod;
1378
- internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2));
1379
- return internals.message;
1380
- }
1381
- function _setMessage(value) {
1382
- this._zod.message = value;
1383
- }
1384
- var _messageDesc = {
1385
- get: _getMessage,
1386
- set: _setMessage,
1387
- enumerable: true,
1388
- configurable: true
1389
- };
1390
- var _zodDesc2 = { value: undefined, enumerable: false };
1391
- var _issuesDesc = { value: undefined, enumerable: false };
1392
- var _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
1393
- var initializer = (inst, def) => {
1394
- inst.name = "$ZodError";
1395
- _zodDesc2.value = inst._zod;
1396
- Object.defineProperty(inst, "_zod", _zodDesc2);
1397
- _issuesDesc.value = def;
1398
- Object.defineProperty(inst, "issues", _issuesDesc);
1399
- _zodDesc2.value = undefined;
1400
- _issuesDesc.value = undefined;
1401
- Object.defineProperty(inst, "message", _messageDesc);
1402
- const proto = Object.getPrototypeOf(inst);
1403
- if (!_installedToString.has(proto)) {
1404
- _installedToString.add(proto);
1405
- Object.defineProperty(proto, "toString", {
1406
- configurable: true,
1407
- enumerable: false,
1408
- get() {
1409
- const value = () => this.message;
1410
- Object.defineProperty(this, "toString", { value, configurable: true, writable: true });
1411
- return value;
1412
- },
1413
- set(value) {
1414
- Object.defineProperty(this, "toString", { value, configurable: true, writable: true });
1415
- }
1416
- });
1417
- }
1418
- };
1419
- var $ZodError = $constructor("$ZodError", initializer);
1420
- var $ZodRealError = $constructor("$ZodError", initializer, undefined, {
1421
- Parent: Error
1136
+ };
1422
1137
  });
1423
- function node(obj, key, make) {
1424
- if (!Object.prototype.hasOwnProperty.call(obj, key)) {
1425
- if (key === "__proto__") {
1426
- Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });
1427
- } else {
1428
- obj[key] = make();
1429
- }
1430
- }
1431
- return obj[key];
1432
- }
1433
- function flattenError(error, mapper = (issue) => issue.message) {
1434
- const fieldErrors = {};
1435
- const formErrors = [];
1436
- for (const sub of error.issues) {
1437
- if (sub.path.length > 0) {
1438
- node(fieldErrors, sub.path[0], () => []).push(mapper(sub));
1439
- } else {
1440
- formErrors.push(mapper(sub));
1441
- }
1442
- }
1443
- return { formErrors, fieldErrors };
1444
- }
1445
- function formatError(error, mapper = (issue) => issue.message) {
1446
- const fieldErrors = { _errors: [] };
1447
- const processError = (error, path = []) => {
1448
- for (const issue of error.issues) {
1449
- if (issue.code === "invalid_union" && issue.errors.length) {
1450
- issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
1451
- } else if (issue.code === "invalid_key") {
1452
- processError({ issues: issue.issues }, [...path, ...issue.path]);
1453
- } else if (issue.code === "invalid_element") {
1454
- processError({ issues: issue.issues }, [...path, ...issue.path]);
1455
- } else {
1456
- const fullpath = [...path, ...issue.path];
1457
- if (fullpath.length === 0) {
1458
- fieldErrors._errors.push(mapper(issue));
1459
- } else {
1460
- let curr = fieldErrors;
1461
- let i = 0;
1462
- while (i < fullpath.length) {
1463
- const el = fullpath[i];
1464
- const terminal = i === fullpath.length - 1;
1465
- if (el === "_errors") {
1466
- if (terminal)
1467
- curr._errors.push(mapper(issue));
1468
- i++;
1469
- continue;
1470
- }
1471
- if (!Object.prototype.hasOwnProperty.call(curr, el)) {
1472
- Object.defineProperty(curr, el, {
1473
- value: { _errors: [] },
1474
- enumerable: true,
1475
- writable: true,
1476
- configurable: true
1477
- });
1478
- }
1479
- const node = curr[el];
1480
- if (terminal) {
1481
- node._errors.push(mapper(issue));
1482
- }
1483
- curr = node;
1484
- i++;
1485
- }
1486
- }
1487
- }
1488
- }
1489
- };
1490
- processError(error);
1491
- return fieldErrors;
1492
- }
1493
-
1494
- // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/parse.js
1495
- function finalizeParams(callee, params) {
1496
- return { callee: params?.callee ?? callee, Err: params?.Err };
1497
- }
1498
- var _parse = (_Err) => {
1499
- const fn = (schema, value, _ctx, _params) => {
1500
- const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
1501
- const result = schema._zod.run({ value, issues: [] }, ctx);
1502
- if (result instanceof Promise) {
1503
- throw new $ZodAsyncError;
1504
- }
1505
- if (result.issues.length) {
1506
- const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
1507
- captureStackTrace(e, _params?.callee ?? fn);
1508
- throw e;
1509
- }
1510
- return result.value;
1138
+ var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
1139
+ var _a;
1140
+ $ZodCheck.init(inst, def);
1141
+ (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
1142
+ inst._zod.onattach.push((inst) => {
1143
+ const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
1144
+ if (def.maximum < curr)
1145
+ inst._zod.bag.maximum = def.maximum;
1146
+ });
1147
+ inst._zod.check = (payload) => {
1148
+ const input = payload.value;
1149
+ const units = input.length;
1150
+ const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units;
1151
+ if (length <= def.maximum)
1152
+ return;
1153
+ const origin = getLengthableOrigin(input);
1154
+ payload.issues.push({
1155
+ origin,
1156
+ code: "too_big",
1157
+ maximum: def.maximum,
1158
+ inclusive: true,
1159
+ input,
1160
+ inst,
1161
+ continue: !def.abort
1162
+ });
1511
1163
  };
1512
- return fn;
1513
- };
1514
- var _parseAsync = (_Err) => {
1515
- const fn = async (schema, value, _ctx, params) => {
1516
- const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
1517
- let result = schema._zod.run({ value, issues: [] }, ctx);
1518
- if (result instanceof Promise)
1519
- result = await result;
1520
- if (result.issues.length) {
1521
- const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
1522
- captureStackTrace(e, params?.callee ?? fn);
1523
- throw e;
1524
- }
1525
- return result.value;
1164
+ });
1165
+ var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
1166
+ var _a;
1167
+ $ZodCheck.init(inst, def);
1168
+ (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
1169
+ inst._zod.onattach.push((inst) => {
1170
+ const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
1171
+ if (def.minimum > curr)
1172
+ inst._zod.bag.minimum = def.minimum;
1173
+ });
1174
+ inst._zod.check = (payload) => {
1175
+ const input = payload.value;
1176
+ const units = input.length;
1177
+ const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input) : units;
1178
+ if (length >= def.minimum)
1179
+ return;
1180
+ const origin = getLengthableOrigin(input);
1181
+ payload.issues.push({
1182
+ origin,
1183
+ code: "too_small",
1184
+ minimum: def.minimum,
1185
+ inclusive: true,
1186
+ input,
1187
+ inst,
1188
+ continue: !def.abort
1189
+ });
1526
1190
  };
1527
- return fn;
1528
- };
1529
- var _safeParse = (_Err) => (schema, value, _ctx) => {
1530
- const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
1531
- const result = schema._zod.run({ value, issues: [] }, ctx);
1532
- if (result instanceof Promise) {
1533
- throw new $ZodAsyncError;
1534
- }
1535
- return result.issues.length ? {
1536
- success: false,
1537
- error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
1538
- } : { success: true, data: result.value };
1539
- };
1540
- var safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
1541
- var _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
1542
- const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
1543
- let result = schema._zod.run({ value, issues: [] }, ctx);
1544
- if (result instanceof Promise)
1545
- result = await result;
1546
- return result.issues.length ? {
1547
- success: false,
1548
- error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
1549
- } : { success: true, data: result.value };
1550
- };
1551
- var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
1552
- var _encode = (_Err) => {
1553
- const parse = _parse(_Err);
1554
- const fn = (schema, value, _ctx, _params) => {
1555
- const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
1556
- return parse(schema, value, ctx, finalizeParams(fn, _params));
1191
+ });
1192
+ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
1193
+ var _a;
1194
+ $ZodCheck.init(inst, def);
1195
+ (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
1196
+ inst._zod.onattach.push((inst) => {
1197
+ const bag = inst._zod.bag;
1198
+ bag.minimum = def.length;
1199
+ bag.maximum = def.length;
1200
+ bag.length = def.length;
1201
+ });
1202
+ inst._zod.check = (payload) => {
1203
+ const input = payload.value;
1204
+ const units = input.length;
1205
+ const length = typeof input === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input) : units;
1206
+ if (length === def.length)
1207
+ return;
1208
+ const origin = getLengthableOrigin(input);
1209
+ const tooBig = length > def.length;
1210
+ payload.issues.push({
1211
+ origin,
1212
+ ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length },
1213
+ inclusive: true,
1214
+ exact: true,
1215
+ input: payload.value,
1216
+ inst,
1217
+ continue: !def.abort
1218
+ });
1557
1219
  };
1558
- return fn;
1559
- };
1560
- var _decode = (_Err) => {
1561
- const parse = _parse(_Err);
1562
- const fn = (schema, value, _ctx, _params) => {
1563
- return parse(schema, value, _ctx, finalizeParams(fn, _params));
1220
+ });
1221
+ var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
1222
+ var _a, _b;
1223
+ $ZodCheck.init(inst, def);
1224
+ inst._zod.onattach.push((inst) => {
1225
+ const bag = inst._zod.bag;
1226
+ bag.format = def.format;
1227
+ if (def.pattern) {
1228
+ bag.patterns ?? (bag.patterns = new Set);
1229
+ bag.patterns.add(def.pattern);
1230
+ }
1231
+ });
1232
+ if (def.pattern)
1233
+ (_a = inst._zod).check ?? (_a.check = (payload) => {
1234
+ def.pattern.lastIndex = 0;
1235
+ if (def.pattern.test(payload.value))
1236
+ return;
1237
+ payload.issues.push({
1238
+ origin: "string",
1239
+ code: "invalid_format",
1240
+ format: def.format,
1241
+ input: payload.value,
1242
+ ...def.pattern ? { pattern: def.pattern.toString() } : {},
1243
+ inst,
1244
+ continue: !def.abort
1245
+ });
1246
+ });
1247
+ else
1248
+ (_b = inst._zod).check ?? (_b.check = () => {});
1249
+ });
1250
+ var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
1251
+ $ZodCheckStringFormat.init(inst, def);
1252
+ inst._zod.check = (payload) => {
1253
+ def.pattern.lastIndex = 0;
1254
+ if (def.pattern.test(payload.value))
1255
+ return;
1256
+ payload.issues.push({
1257
+ origin: "string",
1258
+ code: "invalid_format",
1259
+ format: "regex",
1260
+ input: payload.value,
1261
+ pattern: def.pattern.toString(),
1262
+ inst,
1263
+ continue: !def.abort
1264
+ });
1564
1265
  };
1565
- return fn;
1566
- };
1567
- var _encodeAsync = (_Err) => {
1568
- const parseAsync = _parseAsync(_Err);
1569
- const fn = async (schema, value, _ctx, _params) => {
1570
- const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
1571
- return await parseAsync(schema, value, ctx, finalizeParams(fn, _params));
1572
- };
1573
- return fn;
1574
- };
1575
- var _decodeAsync = (_Err) => {
1576
- const parseAsync = _parseAsync(_Err);
1577
- const fn = async (schema, value, _ctx, _params) => {
1578
- return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));
1579
- };
1580
- return fn;
1581
- };
1582
- var _safeEncode = (_Err) => (schema, value, _ctx) => {
1583
- const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
1584
- return _safeParse(_Err)(schema, value, ctx);
1585
- };
1586
- var _safeDecode = (_Err) => (schema, value, _ctx) => {
1587
- return _safeParse(_Err)(schema, value, _ctx);
1588
- };
1589
- var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
1590
- const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
1591
- return _safeParseAsync(_Err)(schema, value, ctx);
1592
- };
1593
- var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
1594
- return _safeParseAsync(_Err)(schema, value, _ctx);
1595
- };
1596
- // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/regexes.js
1597
- var cuid = /^[cC][0-9a-z]{6,}$/;
1598
- var cuid2 = /^[0-9a-z]+$/;
1599
- var ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;
1600
- var xid = /^[0-9a-vA-V]{20}$/;
1601
- var ksuid = /^[A-Za-z0-9]{27}$/;
1602
- var nanoid = /^[a-zA-Z0-9_-]{21}$/;
1603
- function nanoidOfLength(length) {
1604
- return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);
1605
- }
1606
- var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
1607
- var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
1608
- var uuid = (version) => {
1609
- if (!version)
1610
- return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
1611
- return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
1612
- };
1613
- var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
1614
- var _emoji = `^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;
1615
- function emoji() {
1616
- return new RegExp(_emoji, "u");
1617
- }
1618
- var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
1619
- var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
1620
- var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
1621
- var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
1622
- var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
1623
- var base64url = /^[A-Za-z0-9_-]*$/;
1624
- var httpProtocol = /^https?$/;
1625
- var e164 = /^\+[1-9]\d{6,14}$/;
1626
- var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
1627
- function anchor(source) {
1628
- return new RegExp(`^${source}$`);
1629
- }
1630
- var date = /* @__PURE__ */ anchor(dateSource);
1631
- function timeSource(args) {
1632
- const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
1633
- const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
1634
- return regex;
1635
- }
1636
- function time(args) {
1637
- return new RegExp(`^${timeSource(args)}$`);
1638
- }
1639
- function datetime(args) {
1640
- const opts = ["Z"];
1641
- if (args.offset)
1642
- opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
1643
- const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`;
1644
- const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;
1645
- return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
1646
- }
1647
- var string = (params) => {
1648
- const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
1649
- return new RegExp(`^${regex}$`);
1650
- };
1651
- var integer = /^-?\d+$/;
1652
- var number = /^-?\d+(?:\.\d+)?$/;
1653
- var boolean = /^(?:true|false)$/i;
1654
- var _null = /^null$/i;
1655
- var lowercase = /^[^A-Z]*$/;
1656
- var uppercase = /^[^a-z]*$/;
1657
-
1658
- // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/checks.js
1659
- var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
1660
- var _a;
1661
- inst._zod ?? (inst._zod = {});
1662
- inst._zod.def = def;
1663
- (_a = inst._zod).onattach ?? (_a.onattach = []);
1664
1266
  });
1665
- var _whenHasLength = (payload) => {
1666
- const val = payload.value;
1667
- return !nullish(val) && val.length !== undefined;
1668
- };
1669
- var numericOriginMap = {
1670
- number: "number",
1671
- bigint: "bigint",
1672
- object: "date"
1673
- };
1674
- var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
1267
+ var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
1268
+ def.pattern ?? (def.pattern = lowercase);
1269
+ $ZodCheckStringFormat.init(inst, def);
1270
+ });
1271
+ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
1272
+ def.pattern ?? (def.pattern = uppercase);
1273
+ $ZodCheckStringFormat.init(inst, def);
1274
+ });
1275
+ var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
1675
1276
  $ZodCheck.init(inst, def);
1676
- const origin = numericOriginMap[typeof def.value];
1277
+ const escapedRegex = escapeRegex(def.includes);
1278
+ const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);
1279
+ def.pattern = pattern;
1677
1280
  inst._zod.onattach.push((inst) => {
1678
1281
  const bag = inst._zod.bag;
1679
- const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
1680
- if (def.value < curr) {
1681
- if (def.inclusive)
1682
- bag.maximum = def.value;
1683
- else
1684
- bag.exclusiveMaximum = def.value;
1685
- }
1282
+ bag.patterns ?? (bag.patterns = new Set);
1283
+ bag.patterns.add(pattern);
1686
1284
  });
1687
1285
  inst._zod.check = (payload) => {
1688
- if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
1286
+ if (payload.value.includes(def.includes, def.position))
1689
1287
  return;
1690
- }
1691
1288
  payload.issues.push({
1692
- origin: numericOriginMap[typeof payload.value] ?? origin,
1693
- code: "too_big",
1694
- maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
1289
+ origin: "string",
1290
+ code: "invalid_format",
1291
+ format: "includes",
1292
+ includes: def.includes,
1695
1293
  input: payload.value,
1696
- inclusive: def.inclusive,
1697
1294
  inst,
1698
1295
  continue: !def.abort
1699
1296
  });
1700
1297
  };
1701
1298
  });
1702
- var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
1299
+ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
1703
1300
  $ZodCheck.init(inst, def);
1704
- const origin = numericOriginMap[typeof def.value];
1301
+ const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
1302
+ def.pattern ?? (def.pattern = pattern);
1705
1303
  inst._zod.onattach.push((inst) => {
1706
1304
  const bag = inst._zod.bag;
1707
- const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
1708
- if (def.value > curr) {
1709
- if (def.inclusive)
1710
- bag.minimum = def.value;
1711
- else
1712
- bag.exclusiveMinimum = def.value;
1713
- }
1305
+ bag.patterns ?? (bag.patterns = new Set);
1306
+ bag.patterns.add(pattern);
1714
1307
  });
1715
1308
  inst._zod.check = (payload) => {
1716
- if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
1309
+ if (payload.value.startsWith(def.prefix))
1717
1310
  return;
1718
- }
1719
1311
  payload.issues.push({
1720
- origin: numericOriginMap[typeof payload.value] ?? origin,
1721
- code: "too_small",
1722
- minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
1312
+ origin: "string",
1313
+ code: "invalid_format",
1314
+ format: "starts_with",
1315
+ prefix: def.prefix,
1723
1316
  input: payload.value,
1724
- inclusive: def.inclusive,
1725
1317
  inst,
1726
1318
  continue: !def.abort
1727
1319
  });
1728
1320
  };
1729
1321
  });
1730
- var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
1322
+ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
1731
1323
  $ZodCheck.init(inst, def);
1324
+ const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
1325
+ def.pattern ?? (def.pattern = pattern);
1732
1326
  inst._zod.onattach.push((inst) => {
1733
- var _a;
1734
- (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
1327
+ const bag = inst._zod.bag;
1328
+ bag.patterns ?? (bag.patterns = new Set);
1329
+ bag.patterns.add(pattern);
1735
1330
  });
1736
1331
  inst._zod.check = (payload) => {
1737
- if (typeof payload.value !== typeof def.value)
1738
- throw new Error("Cannot mix number and bigint in multiple_of check.");
1739
- const isMultiple = typeof payload.value === "bigint" ? def.value !== BigInt(0) && payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0;
1740
- if (isMultiple)
1332
+ if (payload.value.endsWith(def.suffix))
1741
1333
  return;
1742
1334
  payload.issues.push({
1743
- origin: typeof payload.value,
1744
- code: "not_multiple_of",
1745
- divisor: def.value,
1335
+ origin: "string",
1336
+ code: "invalid_format",
1337
+ format: "ends_with",
1338
+ suffix: def.suffix,
1746
1339
  input: payload.value,
1747
1340
  inst,
1748
1341
  continue: !def.abort
1749
1342
  });
1750
1343
  };
1751
1344
  });
1752
- var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
1753
- $ZodCheck.init(inst, def);
1754
- def.format = def.format || "float64";
1755
- const isInt = def.format?.includes("int");
1756
- const origin = isInt ? "int" : "number";
1757
- const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
1758
- inst._zod.onattach.push((inst) => {
1759
- const bag = inst._zod.bag;
1760
- bag.format = def.format;
1761
- bag.minimum = minimum;
1762
- bag.maximum = maximum;
1763
- if (isInt)
1764
- bag.pattern = integer;
1765
- });
1766
- inst._zod.check = (payload) => {
1767
- const input = payload.value;
1768
- if (isInt) {
1769
- if (!Number.isInteger(input)) {
1770
- payload.issues.push({
1771
- expected: origin,
1772
- format: def.format,
1773
- code: "invalid_type",
1774
- continue: false,
1775
- input,
1776
- inst
1777
- });
1778
- return;
1779
- }
1780
- if (!Number.isSafeInteger(input)) {
1781
- if (input > 0) {
1782
- payload.issues.push({
1783
- input,
1784
- code: "too_big",
1785
- maximum: Number.MAX_SAFE_INTEGER,
1786
- note: "Integers must be within the safe integer range.",
1787
- inst,
1788
- origin,
1789
- inclusive: true,
1790
- continue: !def.abort
1791
- });
1792
- } else {
1793
- payload.issues.push({
1794
- input,
1795
- code: "too_small",
1796
- minimum: Number.MIN_SAFE_INTEGER,
1797
- note: "Integers must be within the safe integer range.",
1798
- inst,
1799
- origin,
1800
- inclusive: true,
1801
- continue: !def.abort
1802
- });
1803
- }
1804
- return;
1805
- }
1806
- }
1807
- if (input < minimum) {
1808
- payload.issues.push({
1809
- origin: "number",
1810
- input,
1811
- code: "too_small",
1812
- minimum,
1813
- inclusive: true,
1814
- inst,
1815
- continue: !def.abort
1816
- });
1817
- }
1818
- if (input > maximum) {
1819
- payload.issues.push({
1820
- origin: "number",
1821
- input,
1822
- code: "too_big",
1823
- maximum,
1824
- inclusive: true,
1825
- inst,
1826
- continue: !def.abort
1827
- });
1828
- }
1829
- };
1830
- });
1831
- var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
1832
- var _a;
1833
- $ZodCheck.init(inst, def);
1834
- (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
1835
- inst._zod.onattach.push((inst) => {
1836
- const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
1837
- if (def.maximum < curr)
1838
- inst._zod.bag.maximum = def.maximum;
1839
- });
1840
- inst._zod.check = (payload) => {
1841
- const input = payload.value;
1842
- const units = input.length;
1843
- const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units;
1844
- if (length <= def.maximum)
1845
- return;
1846
- const origin = getLengthableOrigin(input);
1847
- payload.issues.push({
1848
- origin,
1849
- code: "too_big",
1850
- maximum: def.maximum,
1851
- inclusive: true,
1852
- input,
1853
- inst,
1854
- continue: !def.abort
1855
- });
1856
- };
1857
- });
1858
- var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
1859
- var _a;
1860
- $ZodCheck.init(inst, def);
1861
- (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
1862
- inst._zod.onattach.push((inst) => {
1863
- const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
1864
- if (def.minimum > curr)
1865
- inst._zod.bag.minimum = def.minimum;
1866
- });
1867
- inst._zod.check = (payload) => {
1868
- const input = payload.value;
1869
- const units = input.length;
1870
- const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input) : units;
1871
- if (length >= def.minimum)
1872
- return;
1873
- const origin = getLengthableOrigin(input);
1874
- payload.issues.push({
1875
- origin,
1876
- code: "too_small",
1877
- minimum: def.minimum,
1878
- inclusive: true,
1879
- input,
1880
- inst,
1881
- continue: !def.abort
1882
- });
1883
- };
1884
- });
1885
- var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
1886
- var _a;
1887
- $ZodCheck.init(inst, def);
1888
- (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
1889
- inst._zod.onattach.push((inst) => {
1890
- const bag = inst._zod.bag;
1891
- bag.minimum = def.length;
1892
- bag.maximum = def.length;
1893
- bag.length = def.length;
1894
- });
1895
- inst._zod.check = (payload) => {
1896
- const input = payload.value;
1897
- const units = input.length;
1898
- const length = typeof input === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input) : units;
1899
- if (length === def.length)
1900
- return;
1901
- const origin = getLengthableOrigin(input);
1902
- const tooBig = length > def.length;
1903
- payload.issues.push({
1904
- origin,
1905
- ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length },
1906
- inclusive: true,
1907
- exact: true,
1908
- input: payload.value,
1909
- inst,
1910
- continue: !def.abort
1911
- });
1912
- };
1913
- });
1914
- var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
1915
- var _a, _b;
1916
- $ZodCheck.init(inst, def);
1917
- inst._zod.onattach.push((inst) => {
1918
- const bag = inst._zod.bag;
1919
- bag.format = def.format;
1920
- if (def.pattern) {
1921
- bag.patterns ?? (bag.patterns = new Set);
1922
- bag.patterns.add(def.pattern);
1923
- }
1924
- });
1925
- if (def.pattern)
1926
- (_a = inst._zod).check ?? (_a.check = (payload) => {
1927
- def.pattern.lastIndex = 0;
1928
- if (def.pattern.test(payload.value))
1929
- return;
1930
- payload.issues.push({
1931
- origin: "string",
1932
- code: "invalid_format",
1933
- format: def.format,
1934
- input: payload.value,
1935
- ...def.pattern ? { pattern: def.pattern.toString() } : {},
1936
- inst,
1937
- continue: !def.abort
1938
- });
1939
- });
1940
- else
1941
- (_b = inst._zod).check ?? (_b.check = () => {});
1942
- });
1943
- var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
1944
- $ZodCheckStringFormat.init(inst, def);
1945
- inst._zod.check = (payload) => {
1946
- def.pattern.lastIndex = 0;
1947
- if (def.pattern.test(payload.value))
1948
- return;
1949
- payload.issues.push({
1950
- origin: "string",
1951
- code: "invalid_format",
1952
- format: "regex",
1953
- input: payload.value,
1954
- pattern: def.pattern.toString(),
1955
- inst,
1956
- continue: !def.abort
1957
- });
1958
- };
1959
- });
1960
- var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
1961
- def.pattern ?? (def.pattern = lowercase);
1962
- $ZodCheckStringFormat.init(inst, def);
1963
- });
1964
- var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
1965
- def.pattern ?? (def.pattern = uppercase);
1966
- $ZodCheckStringFormat.init(inst, def);
1967
- });
1968
- var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
1969
- $ZodCheck.init(inst, def);
1970
- const escapedRegex = escapeRegex(def.includes);
1971
- const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);
1972
- def.pattern = pattern;
1973
- inst._zod.onattach.push((inst) => {
1974
- const bag = inst._zod.bag;
1975
- bag.patterns ?? (bag.patterns = new Set);
1976
- bag.patterns.add(pattern);
1977
- });
1978
- inst._zod.check = (payload) => {
1979
- if (payload.value.includes(def.includes, def.position))
1980
- return;
1981
- payload.issues.push({
1982
- origin: "string",
1983
- code: "invalid_format",
1984
- format: "includes",
1985
- includes: def.includes,
1986
- input: payload.value,
1987
- inst,
1988
- continue: !def.abort
1989
- });
1990
- };
1991
- });
1992
- var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
1993
- $ZodCheck.init(inst, def);
1994
- const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
1995
- def.pattern ?? (def.pattern = pattern);
1996
- inst._zod.onattach.push((inst) => {
1997
- const bag = inst._zod.bag;
1998
- bag.patterns ?? (bag.patterns = new Set);
1999
- bag.patterns.add(pattern);
2000
- });
2001
- inst._zod.check = (payload) => {
2002
- if (payload.value.startsWith(def.prefix))
2003
- return;
2004
- payload.issues.push({
2005
- origin: "string",
2006
- code: "invalid_format",
2007
- format: "starts_with",
2008
- prefix: def.prefix,
2009
- input: payload.value,
2010
- inst,
2011
- continue: !def.abort
2012
- });
2013
- };
2014
- });
2015
- var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
2016
- $ZodCheck.init(inst, def);
2017
- const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
2018
- def.pattern ?? (def.pattern = pattern);
2019
- inst._zod.onattach.push((inst) => {
2020
- const bag = inst._zod.bag;
2021
- bag.patterns ?? (bag.patterns = new Set);
2022
- bag.patterns.add(pattern);
2023
- });
2024
- inst._zod.check = (payload) => {
2025
- if (payload.value.endsWith(def.suffix))
2026
- return;
2027
- payload.issues.push({
2028
- origin: "string",
2029
- code: "invalid_format",
2030
- format: "ends_with",
2031
- suffix: def.suffix,
2032
- input: payload.value,
2033
- inst,
2034
- continue: !def.abort
2035
- });
2036
- };
2037
- });
2038
- var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
1345
+ var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
2039
1346
  $ZodCheck.init(inst, def);
2040
1347
  inst._zod.check = (payload) => {
2041
1348
  payload.value = def.tx(payload.value);
@@ -6338,6 +5645,14 @@ function object(shape, params) {
6338
5645
  };
6339
5646
  return new ZodObject(def);
6340
5647
  }
5648
+ function strictObject(shape, params) {
5649
+ return new ZodObject({
5650
+ type: "object",
5651
+ shape,
5652
+ catchall: never(),
5653
+ ...normalizeParams(params)
5654
+ });
5655
+ }
6341
5656
  function looseObject(shape, params) {
6342
5657
  return new ZodObject({
6343
5658
  type: "object",
@@ -8937,6 +8252,7 @@ var contributions = sqliteTable("contributions", {
8937
8252
  createdAt: ts("created_at").notNull()
8938
8253
  }, (t) => ({
8939
8254
  threadIdx: index("contributions_thread_idx").on(t.threadId),
8255
+ threadCreatedIdx: index("contributions_thread_created_idx").on(t.threadId, t.createdAt),
8940
8256
  aboutIdx: index("contributions_about_idx").on(t.aboutType, t.aboutId),
8941
8257
  authorIdempotencyIdx: uniqueIndex("contributions_author_idempotency_idx").on(t.authorProfileId, t.idempotencyKey)
8942
8258
  }));
@@ -9612,6 +8928,14 @@ var notificationCursors = sqliteTable("notification_cursors", {
9612
8928
  profileId: text("profile_id").primaryKey().references(() => profiles.id),
9613
8929
  lastSeenAt: ts("last_seen_at").notNull()
9614
8930
  });
8931
+ var spaceVisits = sqliteTable("space_visits", {
8932
+ profileId: text("profile_id").notNull().references(() => profiles.id),
8933
+ spaceId: text("space_id").notNull().references(() => spaces.id),
8934
+ lastVisitedAt: ts("last_visited_at").notNull()
8935
+ }, (t) => ({
8936
+ pk: primaryKey({ columns: [t.profileId, t.spaceId] }),
8937
+ spaceIdx: index("space_visits_space_idx").on(t.spaceId, t.lastVisitedAt)
8938
+ }));
9615
8939
  var recallIndex = sqliteTable("recall_index", {
9616
8940
  objectId: text("object_id").primaryKey(),
9617
8941
  indexedAt: ts("indexed_at").notNull(),
@@ -9994,6 +9318,8 @@ var EMOJI_RE = new RegExp("^\\p{RGI_Emoji}$", "v");
9994
9318
  var BASE_MS = Date.parse("2026-07-20T15:00:00.000Z");
9995
9319
  // ../core/src/ops/agent-pairing.ts
9996
9320
  var PAIRING_TTL_MS = 15 * 60 * 1000;
9321
+ // ../core/src/ops/space-visit.ts
9322
+ var VISIT_THROTTLE_MS = 5 * 60 * 1000;
9997
9323
  // ../core/src/ops/package-cache.ts
9998
9324
  var PACKAGE_CACHE_PENDING_TTL_MS = 15 * 60 * 1000;
9999
9325
  var PACKAGE_CACHE_FINAL_TTL_MS = 30 * 24 * 60 * 60 * 1000;
@@ -10139,6 +9465,13 @@ function recordExternalReadDefaults(operation, defaults) {
10139
9465
  }
10140
9466
 
10141
9467
  // ../actions/src/output-schemas.ts
9468
+ var adminCloseOutputSchema = strictObject({
9469
+ finishMode: literal("admin_close"),
9470
+ runId: string2(),
9471
+ status: literal("cancelled"),
9472
+ reasonCode: literal("run.admin_closed_abandoned"),
9473
+ actorProfileId: string2()
9474
+ });
10142
9475
  function buildOutputSchemas() {
10143
9476
  const id = string2();
10144
9477
  const timestamp = string2();
@@ -11740,6 +11073,7 @@ function buildOutputSchemas() {
11740
11073
  computer_run_finish: looseObject({
11741
11074
  runId: id,
11742
11075
  status: string2(),
11076
+ finishMode: literal("owner").optional(),
11743
11077
  replayed: boolean2(),
11744
11078
  durability: computerRunDurability,
11745
11079
  finishAssessment: computerRunFinishAssessment.nullable(),
@@ -12142,6 +11476,78 @@ function outputSchemaFor(actionName) {
12142
11476
  return outputSchemas[actionName];
12143
11477
  }
12144
11478
 
11479
+ // ../actions/src/action-projection.ts
11480
+ var templates = new WeakMap;
11481
+ var origins = new WeakMap;
11482
+ var advertisements = new WeakMap;
11483
+ function variantShape(action, variant) {
11484
+ return Object.fromEntries(Object.entries({ ...action.inputSchema, ...variant.inputSchema }).filter(([key]) => !variant.omitInputs?.includes(key)));
11485
+ }
11486
+ function objectUnion(schemas) {
11487
+ const shape = {};
11488
+ const keys = new Set(schemas.flatMap((schema) => Object.keys(schema.shape)));
11489
+ for (const key of keys) {
11490
+ const fields = schemas.map((schema) => schema.shape[key]);
11491
+ const present = fields.filter((field) => field !== undefined);
11492
+ const field = present.length === 1 ? present[0] : union(present);
11493
+ shape[key] = fields.some((field) => field === undefined || field.isOptional()) ? field.optional() : field;
11494
+ }
11495
+ const union2 = union(schemas);
11496
+ return looseObject(shape).superRefine((value, ctx) => {
11497
+ const parsed = union2.safeParse(value);
11498
+ if (!parsed.success)
11499
+ for (const issue of parsed.error.issues)
11500
+ ctx.addIssue({ code: "custom", path: issue.path, message: issue.message });
11501
+ });
11502
+ }
11503
+ function prepare(action) {
11504
+ action = origins.get(action) ?? action;
11505
+ const cached = templates.get(action);
11506
+ if (cached)
11507
+ return cached;
11508
+ const inputs = [strictObject(action.inputSchema)];
11509
+ const outputs = action.outputSchema ? [action.outputSchema] : [];
11510
+ const combined = { ...action.inputSchema };
11511
+ const extensions = action.privilegedVariants ?? [];
11512
+ for (const variant of extensions) {
11513
+ inputs.push(strictObject(variantShape(action, variant)));
11514
+ outputs.push(variant.outputSchema);
11515
+ for (const [key, field] of Object.entries(variant.inputSchema)) {
11516
+ const base = combined[key];
11517
+ const extension = field;
11518
+ combined[key] = (base ? union([base, extension]).optional() : extension.optional()).describe(extension.description ?? "");
11519
+ }
11520
+ }
11521
+ Object.freeze(action.inputSchema);
11522
+ const advertisedOutput = objectUnion(outputs);
11523
+ Object.freeze(advertisedOutput.shape);
11524
+ const result = {
11525
+ tags: Object.freeze(extensions.map((variant) => variant.tag)),
11526
+ advertised: Object.freeze({
11527
+ ...action,
11528
+ description: extensions.map((variant) => variant.description).join(" "),
11529
+ inputSchema: Object.freeze(combined),
11530
+ outputSchema: advertisedOutput
11531
+ }),
11532
+ executionInput: inputs.length === 1 ? inputs[0] : discriminatedUnion(action.variantDiscriminator, [inputs[0], ...inputs.slice(1)]),
11533
+ executionOutput: outputs.length > 1 ? union(outputs) : outputs[0],
11534
+ executionShape: combined
11535
+ };
11536
+ origins.set(result.advertised, action);
11537
+ templates.set(action, result);
11538
+ return result;
11539
+ }
11540
+ function projectActionVariants(action, tags) {
11541
+ action = origins.get(action) ?? action;
11542
+ if (!action.privilegedVariants?.length || tags.length === 0)
11543
+ return action;
11544
+ const template = prepare(action);
11545
+ return tags.length === template.tags.length && template.tags.every((tag) => tags.includes(tag)) ? template.advertised : action;
11546
+ }
11547
+ function canonicalInputShape(action) {
11548
+ return action.privilegedVariants?.length ? prepare(action).executionShape : action.inputSchema;
11549
+ }
11550
+ var manifests = new WeakMap;
12145
11551
  // ../actions/src/agent-guides.ts
12146
11552
  var AGENT_GUIDE_URLS = {
12147
11553
  tldraw: "https://arborthreads.com/docs/agents/tldraw",
@@ -12380,6 +11786,9 @@ var OUTPUT_SHAPERS = {
12380
11786
  ]);
12381
11787
  },
12382
11788
  computer_run_finish: (result) => {
11789
+ if (result.finishMode === "admin_close") {
11790
+ return selected(result, ["finishMode", "runId", "status", "reasonCode", "actorProfileId"]);
11791
+ }
12383
11792
  const run = record2(result.run) ?? {};
12384
11793
  return defined([
12385
11794
  ["runId", run.runId],
@@ -12444,7 +11853,7 @@ function shapeActionOutput(actionName, value, input = {}) {
12444
11853
  if (!shaper)
12445
11854
  return value;
12446
11855
  const publicValue = shaper(record2(value) ?? {}, input);
12447
- const schema = outputSchemaFor(actionName);
11856
+ const schema = actionName === "computer_run_finish" && record2(publicValue)?.finishMode === "admin_close" ? adminCloseOutputSchema : outputSchemaFor(actionName);
12448
11857
  if (!schema)
12449
11858
  throw new Error(`${actionName}: compact action is missing an output schema`);
12450
11859
  const parsed = schema.safeParse(publicValue);
@@ -12618,7 +12027,7 @@ var MCP_TOOL_ANNOTATIONS = {
12618
12027
  computer_run_suspend: idempotent,
12619
12028
  computer_run_promote: idempotent,
12620
12029
  computer_repo_work_status: readOnly,
12621
- computer_run_finish: idempotent,
12030
+ computer_run_finish: destructive,
12622
12031
  computer_run_receipt: readOnly,
12623
12032
  computer_run_retention: readOnly,
12624
12033
  computer_run_keep: idempotent,
@@ -13854,16 +13263,30 @@ var ACTION_DEFINITIONS = [
13854
13263
  {
13855
13264
  name: "computer_run_finish",
13856
13265
  title: "Finish a run",
13857
- description: "End this Run with an accomplishments summary when done with its workspace; suspend if you expect to return. Git publication not required (isolated finish drops unpublished work); shared finish checkpoints/stops last shared Run; shared discard closes only record; isolated discard abandons after quiescence; May stay pending for quiescence, checkpoint, release; discard=true requires failed/cancelled.",
13266
+ description: "End your Run with a reason; suspend if you expect to return; shared finish checkpoints/stops the last Run, isolated finish needs no Git publication and may stay pending for quiescence, checkpoint, release. Owner discard=true requires failed/cancelled; shared closes only the record, isolated abandons after quiescence.",
13858
13267
  inputSchema: {
13859
13268
  runId: string2().describe("the runId returned by computer_run_start, run_…"),
13860
- outcome: _enum(["finished", "failed", "cancelled"]).optional().describe("terminal outcome; defaults to finished"),
13861
- reason: string2().trim().max(500).optional().describe("required for a new finish intent: accomplishments and useful outcomes or limits; exact accepted legacy retries reuse their original text or omission"),
13862
- discard: boolean2().optional().describe("explicitly abandon this Run's workspace only after provider quiescence; requires outcome failed or cancelled and never overrides active or unknown execution"),
13863
- save: boolean2().optional().describe("false closes without the final checkpoint and deletes nothing: receipt records reasonCode run.closed_without_save and save.lastDurableSnapshotId; shared or suspended Runs only; not with discard")
13269
+ finishMode: literal("owner").optional().describe("owner finish; omission preserves existing behavior"),
13270
+ outcome: _enum(["finished", "failed", "cancelled"]).optional().describe("owner mode only: terminal outcome; defaults to finished"),
13271
+ reason: string2().trim().max(500).optional().describe("owner mode only, required for a new finish intent: accomplishments and useful outcomes or limits; exact accepted legacy retries reuse their original text or omission"),
13272
+ discard: boolean2().optional().describe("owner mode only: discard=true requires failed/cancelled; shared closes only the record, isolated abandons after quiescence; never overrides active or unknown execution"),
13273
+ save: boolean2().optional().describe("owner mode only: false closes without the final checkpoint and deletes nothing: receipt records reasonCode run.closed_without_save and save.lastDurableSnapshotId; shared or suspended Runs only; not with discard")
13864
13274
  },
13865
13275
  surfaces: ["computer-mcp", "computer-cli"],
13866
13276
  toolset: "loop",
13277
+ variantDiscriminator: "finishMode",
13278
+ privilegedVariants: [
13279
+ {
13280
+ tag: "admin_close",
13281
+ requires: "active-org-admin",
13282
+ inputSchema: {
13283
+ finishMode: literal("admin_close").describe("active same-org owner/admin only: admin_close is record-only cancelled/run.admin_closed_abandoned for an abandoned shared Run; omit outcome/reason/discard/save; refuses unsettled processes, pending finish or isolated execution")
13284
+ },
13285
+ omitInputs: ["outcome", "reason", "discard", "save"],
13286
+ description: "End your Run with a reason; owner finish checkpoints/stops the last shared Run or releases isolated execution. Organization owner/admin only: finishMode=admin_close cancels only an abandoned shared record with fixed audit code and no runtime work; omit outcome/reason/discard/save.",
13287
+ outputSchema: adminCloseOutputSchema
13288
+ }
13289
+ ],
13867
13290
  run: forward("computer_runtime.run_finish")
13868
13291
  },
13869
13292
  {
@@ -16077,224 +15500,962 @@ var ACTION_DEFINITIONS = [
16077
15500
  })
16078
15501
  }
16079
15502
  ];
16080
- var ACTIONS = ACTION_DEFINITIONS.map((action) => {
16081
- if (action.requiresCapability && !action.surfaces.includes("mcp")) {
16082
- throw new Error(`${action.name}: requiresCapability is an MCP catalog gate`);
15503
+ var ACTIONS = ACTION_DEFINITIONS.map((action) => {
15504
+ if (action.requiresCapability && !action.surfaces.includes("mcp")) {
15505
+ throw new Error(`${action.name}: requiresCapability is an MCP catalog gate`);
15506
+ }
15507
+ const externalReadDefaults = action.inputSchema.limit === PAGINATION_INPUT.limit ? { ...action.externalReadDefaults, limit: EXTERNAL_DEFAULT_PAGE_SIZE } : action.externalReadDefaults;
15508
+ for (const operation of forwardedOperations(action.run)) {
15509
+ recordExternalReadDefaults(operation, externalReadDefaults);
15510
+ }
15511
+ if (!action.surfaces.some((surface) => surface === "mcp" || surface === "computer-mcp")) {
15512
+ return externalReadDefaults ? { ...action, externalReadDefaults } : action;
15513
+ }
15514
+ const annotations = mcpAnnotationsFor(action.name);
15515
+ return {
15516
+ ...action,
15517
+ externalReadDefaults,
15518
+ get outputSchema() {
15519
+ const schema = outputSchemaFor(action.name);
15520
+ if (!schema)
15521
+ throw new Error(`${action.name}: MCP action is missing an output schema`);
15522
+ return schema;
15523
+ },
15524
+ annotations
15525
+ };
15526
+ });
15527
+
15528
+ // ../actions/src/retention-entry.ts
15529
+ var ARBOR_VERSION = "0.24.16";
15530
+ var historyPolicySchema = _enum(["full", "checkpoint"]).optional().describe("text Artifacts: future history retention policy; full retains every source snapshot, checkpoint keeps metadata for every revision and source only when explicitly retained");
15531
+ var retainSourceSchema = boolean2().optional().describe("edit: in checkpoint mode, retain this newly minted content revision's source");
15532
+ var checkpointSchema = boolean2().optional().describe("edit: retain the exact current version source without incrementing content version");
15533
+ var ARTIFACT_GET_PUBLIC_DESCRIPTION = "Read one Artifact as a compact card without loading its body; editable text supports its outline plus bounded startLine+limit or heading windows and explicit all=true; File Artifacts remain files and report whether bounded UTF-8 text projection is available. For text-like files use startLine+limit and nextLine; all=true and heading stay unavailable for files, binary/unsupported files use the Artifact URL/download/media surface, and editable historical reads retain exact artifactVersionId.";
15534
+ function artifactEditInput(input) {
15535
+ const patches = Array.isArray(input.patches);
15536
+ const hasSource = typeof input.source === "string";
15537
+ const checkpoint = input.checkpoint === true;
15538
+ const historyPolicy = input.historyPolicy === "full" || input.historyPolicy === "checkpoint";
15539
+ if (checkpoint && (patches || hasSource || historyPolicy)) {
15540
+ throw new Error("artifact edit checkpoint cannot be combined with source, patches, or historyPolicy");
15541
+ }
15542
+ if (historyPolicy && (patches || hasSource)) {
15543
+ throw new Error("artifact historyPolicy change cannot be combined with a content edit");
15544
+ }
15545
+ if (checkpoint)
15546
+ return { ...input, verb: "checkpoint" };
15547
+ if (historyPolicy)
15548
+ return { ...input, verb: "set_history_policy" };
15549
+ return { ...input, verb: patches ? "patch" : "replace" };
15550
+ }
15551
+ function runArtifact(ex, input) {
15552
+ const { verb, ...rest } = input;
15553
+ if (verb === "create")
15554
+ return ex.call("artifact.create", rest);
15555
+ if (verb === "edit")
15556
+ return ex.call("artifact.edit", artifactEditInput(rest));
15557
+ if (verb === "set_live_preview")
15558
+ return ex.call("artifact.setLivePreview", rest);
15559
+ if (verb === "set_snapshot")
15560
+ return ex.call("artifact.setSnapshot", rest);
15561
+ if (verb === "promote_attachment")
15562
+ return ex.call("attachment.promote", rest);
15563
+ return Promise.reject(new Error(`unknown artifact verb "${verb ?? ""}"`));
15564
+ }
15565
+ function overrideAction(action, overrides) {
15566
+ return Object.assign(Object.defineProperties({}, Object.getOwnPropertyDescriptors(action)), overrides);
15567
+ }
15568
+ function retentionAction(action) {
15569
+ if (action.name === "create_artifact") {
15570
+ return overrideAction(action, {
15571
+ description: "Create a durable Artifact; text kinds may choose historyPolicy=full (default) or checkpoint. Checkpoint mode still keeps metadata/provenance for every revision while source snapshots are retained only when explicitly checkpointed.",
15572
+ inputSchema: { ...action.inputSchema, historyPolicy: historyPolicySchema }
15573
+ });
15574
+ }
15575
+ if (action.name === "edit_artifact") {
15576
+ return overrideAction(action, {
15577
+ description: "Edit a text Artifact from the baseVersion you read, or change its future historyPolicy/checkpoint the exact current source without minting a content version. Content edits return the exact artifactVersionId; byte-identical results are idempotent no-ops that reuse the current version identity, while stale divergent edits remain structured conflicts.",
15578
+ inputSchema: {
15579
+ ...action.inputSchema,
15580
+ historyPolicy: historyPolicySchema,
15581
+ checkpoint: checkpointSchema,
15582
+ retainSource: retainSourceSchema
15583
+ },
15584
+ run: (ex, input) => ex.call("artifact.edit", artifactEditInput(input))
15585
+ });
15586
+ }
15587
+ if (action.name === "get_artifact" || action.name === "artifact_get") {
15588
+ return overrideAction(action, { description: ARTIFACT_GET_PUBLIC_DESCRIPTION });
15589
+ }
15590
+ if (action.name === "artifact") {
15591
+ return overrideAction(action, {
15592
+ description: "Create/edit a durable Artifact with full|checkpoint retention or manage Live Preview, snapshots, and attachments. Git edits derive retry keys (omitted edits derive one); keyless creates mint per-invocation keys; stable idempotencyKey supports caller retries; never blindly repeat ambiguous creates. promote_attachment creates a file Artifact from a Contribution; exported reports use the Attachment downloadUrl; policy changes do not mint content versions.",
15593
+ inputSchema: {
15594
+ ...action.inputSchema,
15595
+ historyPolicy: historyPolicySchema,
15596
+ checkpoint: checkpointSchema,
15597
+ retainSource: retainSourceSchema
15598
+ },
15599
+ run: runArtifact
15600
+ });
15601
+ }
15602
+ return action;
15603
+ }
15604
+ var ACTIONS2 = ACTIONS.map(retentionAction);
15605
+
15606
+ // ../actions/src/recovery-entry.ts
15607
+ var grantOutput = object({
15608
+ grant: object({
15609
+ grantId: string2(),
15610
+ requestId: string2(),
15611
+ threadId: string2(),
15612
+ runId: string2(),
15613
+ computerId: string2(),
15614
+ granteeProfileId: string2(),
15615
+ grantedByProfileId: string2(),
15616
+ expiresAt: string2(),
15617
+ createdAt: string2(),
15618
+ revokedAt: string2().nullable(),
15619
+ revokedByProfileId: string2().nullable()
15620
+ }),
15621
+ replayed: boolean2()
15622
+ });
15623
+ var diagnosticOutput = object({
15624
+ grant: object({
15625
+ grantId: string2(),
15626
+ requestId: string2(),
15627
+ expiresAt: string2()
15628
+ }),
15629
+ diagnostic: object({
15630
+ runId: string2(),
15631
+ computerId: string2(),
15632
+ computerGeneration: number2().int().positive(),
15633
+ status: _enum(["active", "finished", "failed", "cancelled"]),
15634
+ outcome: _enum(["finished", "failed", "cancelled"]).nullable(),
15635
+ reasonCode: string2().nullable(),
15636
+ runtimeState: _enum(["shared", "live", "suspended", "releasing", "released"]),
15637
+ snapshotLineage: object({
15638
+ baseSnapshotId: string2().nullable(),
15639
+ currentSnapshotId: string2().nullable()
15640
+ }),
15641
+ providerState: object({
15642
+ generation: number2().int().min(0).nullable(),
15643
+ lastPhase: string2().nullable(),
15644
+ lastReasonCode: string2().nullable()
15645
+ }),
15646
+ operations: array(object({
15647
+ operationId: string2(),
15648
+ execution: _enum(["foreground", "background"]),
15649
+ state: _enum([
15650
+ "starting",
15651
+ "running",
15652
+ "completed",
15653
+ "failed",
15654
+ "cancelled",
15655
+ "not-routed",
15656
+ "provider-lost",
15657
+ "unknown"
15658
+ ]),
15659
+ mutationRetrySafety: _enum(["not-needed", "safe", "unsafe", "unknown"]),
15660
+ reasonCode: string2()
15661
+ }))
15662
+ }),
15663
+ auditEventId: string2()
15664
+ });
15665
+ var additive2 = {
15666
+ readOnlyHint: false,
15667
+ destructiveHint: false,
15668
+ idempotentHint: true,
15669
+ openWorldHint: false
15670
+ };
15671
+ var auditedRead = {
15672
+ readOnlyHint: false,
15673
+ destructiveHint: false,
15674
+ idempotentHint: false,
15675
+ openWorldHint: false
15676
+ };
15677
+ var RECOVERY_ACTIONS = [
15678
+ {
15679
+ name: "computer_recovery_grant",
15680
+ title: "Grant delegated Computer recovery",
15681
+ description: "Issue one short-lived diagnostic grant for a profile explicitly targeted by the same open Request and exact Run. This grants no execution, file, environment, Secret, Git, checkpoint, or lifecycle capability.",
15682
+ inputSchema: {
15683
+ requestId: string2().describe("the targeted open Request authorizing this recovery scope, req_…"),
15684
+ runId: string2().describe("the exact Run whose diagnostic state may be inspected, run_…"),
15685
+ granteeProfileId: string2().describe("the exact targeted profile receiving diagnostic visibility"),
15686
+ expiresAt: string2().describe("future ISO timestamp, at most 24 hours and never after Request expiry"),
15687
+ idempotencyKey: string2().min(1).max(200).describe("stable key for this one logical grant")
15688
+ },
15689
+ outputSchema: grantOutput,
15690
+ annotations: additive2,
15691
+ surfaces: ["computer-cli"],
15692
+ toolset: "loop",
15693
+ run: (ex, input) => ex.call("computer_recovery.grant", input)
15694
+ },
15695
+ {
15696
+ name: "computer_recovery_revoke",
15697
+ title: "Revoke delegated Computer recovery",
15698
+ description: "Revoke one previously issued delegated diagnostic grant without touching the Computer or provider. Repeating the same revoke is an idempotent no-op.",
15699
+ inputSchema: {
15700
+ grantId: string2().describe("the delegated recovery grant, crg_…")
15701
+ },
15702
+ outputSchema: grantOutput,
15703
+ annotations: additive2,
15704
+ surfaces: ["computer-cli"],
15705
+ toolset: "loop",
15706
+ run: (ex, input) => ex.call("computer_recovery.revoke", input)
15707
+ },
15708
+ {
15709
+ name: "computer_recovery_inspect",
15710
+ title: "Inspect delegated Computer recovery state",
15711
+ description: "Read only the sanitized diagnostic projection authorized by one live delegated grant; every successful read records an attributed Arbor audit Event. It never calls the provider or exposes repository paths/heads, command output, environment, Secrets, sessions, or mutation controls.",
15712
+ inputSchema: {
15713
+ grantId: string2().describe("the delegated recovery grant, crg_…")
15714
+ },
15715
+ outputSchema: diagnosticOutput,
15716
+ annotations: auditedRead,
15717
+ surfaces: ["computer-mcp", "computer-cli"],
15718
+ toolset: "loop",
15719
+ run: (ex, input) => ex.call("computer_recovery.inspect", input)
15720
+ }
15721
+ ];
15722
+ var ACTIONS3 = [...ACTIONS2, ...RECOVERY_ACTIONS];
15723
+
15724
+ // src/config.ts
15725
+ import {
15726
+ chmodSync,
15727
+ existsSync,
15728
+ lstatSync,
15729
+ mkdirSync,
15730
+ readFileSync,
15731
+ readdirSync,
15732
+ rmSync,
15733
+ statSync,
15734
+ writeFileSync
15735
+ } from "node:fs";
15736
+ import { homedir } from "node:os";
15737
+ import { dirname, join } from "node:path";
15738
+
15739
+ // src/errors.ts
15740
+ var ERROR_CODES = new Set([
15741
+ "UNAUTHORIZED",
15742
+ "FORBIDDEN",
15743
+ "NOT_FOUND",
15744
+ "VALIDATION",
15745
+ "CONFLICT",
15746
+ "RATE_LIMITED",
15747
+ "NETWORK",
15748
+ "INTERNAL"
15749
+ ]);
15750
+ function isErrorCode(value) {
15751
+ return typeof value === "string" && ERROR_CODES.has(value);
15752
+ }
15753
+ function codeForStatus(status) {
15754
+ switch (status) {
15755
+ case 0:
15756
+ return "NETWORK";
15757
+ case 400:
15758
+ case 422:
15759
+ return "VALIDATION";
15760
+ case 401:
15761
+ return "UNAUTHORIZED";
15762
+ case 403:
15763
+ return "FORBIDDEN";
15764
+ case 404:
15765
+ case 410:
15766
+ return "NOT_FOUND";
15767
+ case 409:
15768
+ return "CONFLICT";
15769
+ case 429:
15770
+ return "RATE_LIMITED";
15771
+ default:
15772
+ return "INTERNAL";
15773
+ }
15774
+ }
15775
+ function exitCodeForError(code) {
15776
+ switch (code) {
15777
+ case "VALIDATION":
15778
+ return 2;
15779
+ case "UNAUTHORIZED":
15780
+ return 22;
15781
+ default:
15782
+ return 1;
15783
+ }
15784
+ }
15785
+ function codeForError(err) {
15786
+ if (err && typeof err === "object" && "code" in err && isErrorCode(err.code)) {
15787
+ return err.code;
15788
+ }
15789
+ return "INTERNAL";
15790
+ }
15791
+ function parseErrorDetails(value) {
15792
+ if (!value || typeof value !== "object")
15793
+ return;
15794
+ const raw = value;
15795
+ if (typeof raw.reason !== "string" || raw.reason === "")
15796
+ return;
15797
+ const details = { reason: raw.reason };
15798
+ if (typeof raw.field === "string")
15799
+ details.field = raw.field;
15800
+ if (typeof raw.limit === "number")
15801
+ details.limit = raw.limit;
15802
+ if (typeof raw.retryable === "boolean")
15803
+ details.retryable = raw.retryable;
15804
+ if (typeof raw.phase === "string")
15805
+ details.phase = raw.phase;
15806
+ if (raw.provider && typeof raw.provider === "object" && !Array.isArray(raw.provider)) {
15807
+ const provider = raw.provider;
15808
+ if (typeof provider.stage === "string" && provider.stage !== "") {
15809
+ details.provider = {
15810
+ stage: provider.stage,
15811
+ ...typeof provider.exitCode === "number" ? { exitCode: provider.exitCode } : {},
15812
+ ...typeof provider.stdout === "string" ? { stdout: provider.stdout } : {},
15813
+ ...typeof provider.stderr === "string" ? { stderr: provider.stderr } : {},
15814
+ ...typeof provider.containerStarted === "boolean" ? { containerStarted: provider.containerStarted } : {},
15815
+ ...typeof provider.repositoryMaterialized === "boolean" ? { repositoryMaterialized: provider.repositoryMaterialized } : {}
15816
+ };
15817
+ }
15818
+ }
15819
+ if (typeof raw.runId === "string")
15820
+ details.runId = raw.runId;
15821
+ if (typeof raw.operationId === "string")
15822
+ details.operationId = raw.operationId;
15823
+ if (typeof raw.processId === "string")
15824
+ details.processId = raw.processId;
15825
+ if (raw.outputRetention && typeof raw.outputRetention === "object") {
15826
+ const retention = raw.outputRetention;
15827
+ if (retention.state === "expired" && typeof retention.expiresAt === "string") {
15828
+ details.outputRetention = { state: "expired", expiresAt: retention.expiresAt };
15829
+ }
15830
+ }
15831
+ if (raw.commandExecution === "not-routed" || raw.commandExecution === "unknown") {
15832
+ details.commandExecution = raw.commandExecution;
15833
+ }
15834
+ if (raw.mutationRetrySafety === "safe" || raw.mutationRetrySafety === "unsafe" || raw.mutationRetrySafety === "unknown") {
15835
+ details.mutationRetrySafety = raw.mutationRetrySafety;
15836
+ }
15837
+ if (typeof raw.compatibilityState === "string") {
15838
+ details.compatibilityState = raw.compatibilityState;
15839
+ }
15840
+ if (typeof raw.compatibilityReason === "string") {
15841
+ details.compatibilityReason = raw.compatibilityReason;
15842
+ }
15843
+ if (typeof raw.suggestedAction === "string")
15844
+ details.suggestedAction = raw.suggestedAction;
15845
+ if (typeof raw.catalogRevision === "string")
15846
+ details.catalogRevision = raw.catalogRevision;
15847
+ if (typeof raw.clientCatalogRevision === "string") {
15848
+ details.clientCatalogRevision = raw.clientCatalogRevision;
15849
+ }
15850
+ if (typeof raw.catalogNextStep === "string")
15851
+ details.catalogNextStep = raw.catalogNextStep;
15852
+ return details;
15853
+ }
15854
+ function detailsForError(err) {
15855
+ if (!err || typeof err !== "object" || !("details" in err))
15856
+ return;
15857
+ return parseErrorDetails(err.details);
15858
+ }
15859
+
15860
+ class ApiError extends Error {
15861
+ status;
15862
+ details;
15863
+ code;
15864
+ constructor(message, status, details) {
15865
+ super(message);
15866
+ this.status = status;
15867
+ this.details = details;
15868
+ this.name = "ApiError";
15869
+ this.code = codeForStatus(status);
15870
+ }
15871
+ }
15872
+
15873
+ class UsageError extends Error {
15874
+ code = "VALIDATION";
15875
+ details;
15876
+ constructor(message, details) {
15877
+ super(message);
15878
+ this.name = "UsageError";
15879
+ this.details = details ?? { reason: "validation.invalid_value" };
15880
+ }
15881
+ }
15882
+
15883
+ class PartialUploadError extends Error {
15884
+ partialResult;
15885
+ code;
15886
+ details;
15887
+ constructor(message, cause, partialResult) {
15888
+ super(message);
15889
+ this.partialResult = partialResult;
15890
+ this.name = "PartialUploadError";
15891
+ this.code = codeForError(cause);
15892
+ this.details = detailsForError(cause);
15893
+ }
15894
+ }
15895
+
15896
+ // src/config.ts
15897
+ var PROD_API_URL = "https://arborthreads.com";
15898
+ var PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
15899
+ function arborDir() {
15900
+ return join(homedir(), ".arbor");
15901
+ }
15902
+ function defaultConfigPath() {
15903
+ return join(arborDir(), "config.json");
15904
+ }
15905
+ function profilesDir() {
15906
+ return join(arborDir(), "profiles");
15907
+ }
15908
+ function registryPath() {
15909
+ return join(arborDir(), "profiles.json");
15910
+ }
15911
+ function namedConfigPath(name) {
15912
+ return join(profilesDir(), `${name}.json`);
15913
+ }
15914
+ var CONFIG_PATH = process.env.ARBOR_CONFIG ?? join(homedir(), ".arbor", "config.json");
15915
+ var DEFAULT_TOKEN_OVERWRITE_REFUSAL = "refusing to overwrite ~/.arbor/config.json — a token already exists. Set ARBOR_CONFIG to an isolated path (e.g. ~/.arbor/<agent>.config.json) and retry.";
15916
+ var LOCK_TIMEOUT_MS = 5000;
15917
+ var LOCK_STALE_MS = 30000;
15918
+ var LOCK_POLL_MS = 20;
15919
+ var activeTarget;
15920
+ function sleepSync(ms) {
15921
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
15922
+ }
15923
+ function acquireConfigLock(configPath) {
15924
+ const lockPath = `${configPath}.lock`;
15925
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
15926
+ for (;; ) {
15927
+ try {
15928
+ mkdirSync(lockPath);
15929
+ return () => {
15930
+ try {
15931
+ rmSync(lockPath, { recursive: true, force: true });
15932
+ } catch {}
15933
+ };
15934
+ } catch (err) {
15935
+ if (err?.code !== "EEXIST")
15936
+ throw err;
15937
+ try {
15938
+ if (Date.now() - statSync(lockPath).mtimeMs > LOCK_STALE_MS) {
15939
+ rmSync(lockPath, { recursive: true, force: true });
15940
+ continue;
15941
+ }
15942
+ } catch {
15943
+ continue;
15944
+ }
15945
+ if (Date.now() >= deadline) {
15946
+ throw new Error(`timed out waiting for another arbor process to finish writing ${configPath}. If none is running, remove ${lockPath}.`);
15947
+ }
15948
+ sleepSync(LOCK_POLL_MS);
15949
+ }
15950
+ }
15951
+ }
15952
+ function validateProfileName(name, field = "profile") {
15953
+ if (!PROFILE_NAME.test(name)) {
15954
+ throw new UsageError(`invalid profile name: ${JSON.stringify(name)}`, {
15955
+ reason: "validation.invalid_value",
15956
+ field
15957
+ });
15958
+ }
15959
+ }
15960
+ function fsType(entry, predicate) {
15961
+ const value = entry[predicate];
15962
+ return typeof value === "function" ? Boolean(value.call(entry)) : value === true;
15963
+ }
15964
+ function rejectSymlink(path, label) {
15965
+ if (!existsSync(path))
15966
+ return;
15967
+ if (fsType(lstatSync(path), "isSymbolicLink"))
15968
+ throw new Error(`${label} must not be a symbolic link: ${path}`);
15969
+ }
15970
+ function ensureArborDir() {
15971
+ const dir = arborDir();
15972
+ rejectSymlink(dir, "Arbor config directory");
15973
+ mkdirSync(dir, { recursive: true, mode: 448 });
15974
+ chmodSync(dir, 448);
15975
+ }
15976
+ function ensureProfilesDir() {
15977
+ ensureArborDir();
15978
+ const dir = profilesDir();
15979
+ rejectSymlink(dir, "Arbor profiles directory");
15980
+ mkdirSync(dir, { recursive: true, mode: 448 });
15981
+ chmodSync(dir, 448);
15982
+ }
15983
+ function readRegistry() {
15984
+ const path = registryPath();
15985
+ if (!existsSync(path))
15986
+ return {};
15987
+ rejectSymlink(path, "Arbor profile registry");
15988
+ try {
15989
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
15990
+ if (parsed.defaultProfile !== undefined)
15991
+ validateProfileName(parsed.defaultProfile);
15992
+ return { defaultProfile: parsed.defaultProfile };
15993
+ } catch (err) {
15994
+ if (err instanceof UsageError)
15995
+ throw err;
15996
+ throw new Error(`could not read Arbor profile registry ${path}`);
15997
+ }
15998
+ }
15999
+ function writeRegistry(registry) {
16000
+ ensureArborDir();
16001
+ const path = registryPath();
16002
+ rejectSymlink(path, "Arbor profile registry");
16003
+ const release = acquireConfigLock(path);
16004
+ try {
16005
+ const safe = registry.defaultProfile ? { defaultProfile: registry.defaultProfile } : {};
16006
+ writeFileSync(path, `${JSON.stringify(safe, null, 2)}
16007
+ `, { mode: 384 });
16008
+ chmodSync(path, 384);
16009
+ } finally {
16010
+ release();
16011
+ }
16012
+ }
16013
+ function profileExists(name, field = "profile") {
16014
+ validateProfileName(name, field);
16015
+ const path = namedConfigPath(name);
16016
+ if (!existsSync(path))
16017
+ return false;
16018
+ rejectSymlink(path, `Arbor profile ${name}`);
16019
+ return fsType(lstatSync(path), "isFile");
16020
+ }
16021
+ function legacyTarget() {
16022
+ const defaultPath = defaultConfigPath();
16023
+ const envPath = process.env.ARBOR_CONFIG;
16024
+ return {
16025
+ path: envPath ?? defaultPath,
16026
+ defaultPath,
16027
+ isolated: Boolean(envPath),
16028
+ named: false,
16029
+ explicitProfile: false
16030
+ };
16031
+ }
16032
+ function resolveTarget(opts) {
16033
+ const profileFlag = opts?.profileFlag;
16034
+ const envProfile = process.env.ARBOR_PROFILE;
16035
+ if (process.env.ARBOR_CONFIG && profileFlag !== undefined) {
16036
+ throw new UsageError("ARBOR_CONFIG and --profile are ambiguous; choose one credential selector", {
16037
+ reason: "validation.invalid_value",
16038
+ field: "profile"
16039
+ });
16040
+ }
16041
+ if (process.env.ARBOR_CONFIG && envProfile !== undefined) {
16042
+ throw new UsageError("ARBOR_CONFIG and ARBOR_PROFILE are ambiguous; choose one credential selector", { reason: "validation.invalid_value", field: "ARBOR_PROFILE" });
16043
+ }
16044
+ if (process.env.ARBOR_CONFIG)
16045
+ return legacyTarget();
16046
+ const registryDefault = readRegistry().defaultProfile;
16047
+ const selected = profileFlag ?? envProfile ?? registryDefault;
16048
+ if (selected === undefined)
16049
+ return legacyTarget();
16050
+ const field = profileFlag !== undefined ? "profile" : envProfile !== undefined ? "ARBOR_PROFILE" : "profile";
16051
+ validateProfileName(selected, field);
16052
+ if (!opts?.allowMissingProfile && !profileExists(selected, field)) {
16053
+ throw new UsageError(`unknown profile: ${selected}`, {
16054
+ reason: "validation.invalid_value",
16055
+ field
16056
+ });
16057
+ }
16058
+ return {
16059
+ path: namedConfigPath(selected),
16060
+ defaultPath: defaultConfigPath(),
16061
+ isolated: true,
16062
+ profile: selected,
16063
+ named: true,
16064
+ explicitProfile: profileFlag !== undefined
16065
+ };
16066
+ }
16067
+ function configureConfigTarget(opts) {
16068
+ activeTarget = resolveTarget(opts);
16069
+ }
16070
+ function currentTarget() {
16071
+ return activeTarget ?? resolveTarget();
16072
+ }
16073
+ function getConfigPath() {
16074
+ return currentTarget().path;
16075
+ }
16076
+ function listProfiles() {
16077
+ const registry = readRegistry();
16078
+ const dir = profilesDir();
16079
+ if (!existsSync(dir))
16080
+ return { defaultProfile: registry.defaultProfile, profiles: [] };
16081
+ rejectSymlink(dir, "Arbor profiles directory");
16082
+ const profiles = readdirSync(dir).filter((entry) => entry.endsWith(".json")).map((entry) => {
16083
+ const name = entry.slice(0, -5);
16084
+ validateProfileName(name);
16085
+ const path = join(dir, entry);
16086
+ const stats = lstatSync(path);
16087
+ if (fsType(stats, "isSymbolicLink"))
16088
+ throw new Error(`Arbor profile ${name} must not be a symbolic link: ${path}`);
16089
+ if (!fsType(stats, "isFile"))
16090
+ throw new Error(`Arbor profile ${name} is not a regular file: ${path}`);
16091
+ return { name, default: registry.defaultProfile === name };
16092
+ }).sort((a, b) => a.name.localeCompare(b.name));
16093
+ return { defaultProfile: registry.defaultProfile, profiles };
16094
+ }
16095
+ function profileShow(name) {
16096
+ validateProfileName(name);
16097
+ if (!profileExists(name)) {
16098
+ throw new UsageError(`unknown profile: ${name}`, {
16099
+ reason: "validation.invalid_value",
16100
+ field: "profile"
16101
+ });
16102
+ }
16103
+ const registry = readRegistry();
16104
+ const cfg = JSON.parse(readFileSync(namedConfigPath(name), "utf8"));
16105
+ return {
16106
+ name,
16107
+ default: registry.defaultProfile === name,
16108
+ apiUrl: cfg.apiUrl || PROD_API_URL
16109
+ };
16110
+ }
16111
+ function setDefaultProfile(name) {
16112
+ if (name !== null) {
16113
+ validateProfileName(name);
16114
+ if (!profileExists(name)) {
16115
+ throw new UsageError(`unknown profile: ${name}`, {
16116
+ reason: "validation.invalid_value",
16117
+ field: "profile"
16118
+ });
16119
+ }
16120
+ }
16121
+ writeRegistry(name ? { defaultProfile: name } : {});
16122
+ }
16123
+ function clearDefaultProfile() {
16124
+ setDefaultProfile(null);
16125
+ }
16126
+ function deleteProfile(name) {
16127
+ validateProfileName(name);
16128
+ const registry = readRegistry();
16129
+ if (registry.defaultProfile === name) {
16130
+ throw new UsageError(`cannot delete default profile ${name}; select another default or run profile clear-default first`, { reason: "validation.invalid_value", field: "profile" });
16131
+ }
16132
+ if (!profileExists(name)) {
16133
+ throw new UsageError(`unknown profile: ${name}`, {
16134
+ reason: "validation.invalid_value",
16135
+ field: "profile"
16136
+ });
16137
+ }
16138
+ const path = namedConfigPath(name);
16139
+ rejectSymlink(path, `Arbor profile ${name}`);
16140
+ rmSync(path);
16141
+ }
16142
+ function defaultConfigOverwriteBlocked(opts) {
16143
+ const target = currentTarget();
16144
+ const isolated = opts?.isolated ?? target.isolated;
16145
+ const path = opts?.path ?? target.defaultPath;
16146
+ if (isolated)
16147
+ return false;
16148
+ if (!existsSync(path))
16149
+ return false;
16150
+ try {
16151
+ const cfg = JSON.parse(readFileSync(path, "utf8"));
16152
+ return Boolean(cfg.token);
16153
+ } catch {
16154
+ return false;
16155
+ }
16156
+ }
16157
+ function loadConfig() {
16158
+ const target = currentTarget();
16159
+ const envToken = target.explicitProfile ? undefined : process.env.ARBOR_TOKEN || undefined;
16160
+ const envUrl = process.env.ARBOR_API_URL || undefined;
16161
+ if (target.named)
16162
+ rejectSymlink(target.path, `Arbor profile ${target.profile}`);
16163
+ if (existsSync(target.path)) {
16164
+ try {
16165
+ const cfg = JSON.parse(readFileSync(target.path, "utf8"));
16166
+ return { apiUrl: envUrl ?? (cfg.apiUrl || PROD_API_URL), token: envToken ?? cfg.token };
16167
+ } catch (err) {
16168
+ if (err instanceof Error && /symbolic link/i.test(err.message))
16169
+ throw err;
16170
+ }
16171
+ }
16172
+ return { apiUrl: envUrl ?? PROD_API_URL, token: envToken };
16173
+ }
16174
+ function writeConfigGuarded(opts) {
16175
+ mkdirSync(dirname(opts.configPath), { recursive: true });
16176
+ const release = acquireConfigLock(opts.configPath);
16177
+ try {
16178
+ if (!opts.allowDefaultTokenOverwrite && defaultConfigOverwriteBlocked({ isolated: opts.isolated, path: opts.defaultPath })) {
16179
+ throw new Error(DEFAULT_TOKEN_OVERWRITE_REFUSAL);
16180
+ }
16181
+ writeFileSync(opts.configPath, `${JSON.stringify(opts.cfg, null, 2)}
16182
+ `, { mode: 384 });
16183
+ chmodSync(opts.configPath, 384);
16184
+ } finally {
16185
+ release();
16186
+ }
16187
+ }
16188
+ function saveConfig(cfg, opts) {
16189
+ const target = currentTarget();
16190
+ if (target.named) {
16191
+ ensureProfilesDir();
16192
+ rejectSymlink(target.path, `Arbor profile ${target.profile}`);
16193
+ }
16194
+ writeConfigGuarded({
16195
+ cfg,
16196
+ configPath: target.path,
16197
+ defaultPath: target.defaultPath,
16198
+ isolated: target.isolated,
16199
+ allowDefaultTokenOverwrite: opts?.allowDefaultTokenOverwrite
16200
+ });
16201
+ }
16202
+ function clearToken() {
16203
+ const cfg = loadConfig();
16204
+ saveConfig({ apiUrl: cfg.apiUrl }, { allowDefaultTokenOverwrite: true });
16205
+ }
16206
+
16207
+ // src/source.ts
16208
+ var SNIFF = [
16209
+ ["CLAUDECODE", "Claude Code"],
16210
+ ["CLAUDE_CODE_ENTRYPOINT", "Claude Code"],
16211
+ ["OPENCLAW_HOME", "openclaw"],
16212
+ ["CODEX_SANDBOX", "Codex"],
16213
+ ["CURSOR_TRACE_ID", "Cursor"]
16214
+ ];
16215
+ function detectSource(env = process.env) {
16216
+ const explicit = env.ARBOR_SOURCE?.trim();
16217
+ if (explicit)
16218
+ return explicit;
16219
+ for (const [envVar, tool] of SNIFF) {
16220
+ if (env[envVar]?.trim())
16221
+ return tool;
16083
16222
  }
16084
- const externalReadDefaults = action.inputSchema.limit === PAGINATION_INPUT.limit ? { ...action.externalReadDefaults, limit: EXTERNAL_DEFAULT_PAGE_SIZE } : action.externalReadDefaults;
16085
- for (const operation of forwardedOperations(action.run)) {
16086
- recordExternalReadDefaults(operation, externalReadDefaults);
16223
+ return;
16224
+ }
16225
+
16226
+ // src/client.ts
16227
+ class NotLoggedInError extends Error {
16228
+ code = "UNAUTHORIZED";
16229
+ details = { reason: "authorization.denied" };
16230
+ constructor() {
16231
+ super("Not logged in. Run: arbor login");
16232
+ this.name = "NotLoggedInError";
16087
16233
  }
16088
- if (!action.surfaces.some((surface) => surface === "mcp" || surface === "computer-mcp")) {
16089
- return externalReadDefaults ? { ...action, externalReadDefaults } : action;
16234
+ }
16235
+ function authHeader() {
16236
+ const cfg = loadConfig();
16237
+ if (!cfg.token)
16238
+ throw new NotLoggedInError;
16239
+ return { authorization: `Bearer ${cfg.token}`, apiUrl: cfg.apiUrl };
16240
+ }
16241
+ var source = detectSource();
16242
+ async function callApi(name, input, signal) {
16243
+ const { authorization, apiUrl } = authHeader();
16244
+ const dot = name.indexOf(".");
16245
+ const object = dot === -1 ? name : name.slice(0, dot);
16246
+ const verb = dot === -1 ? "" : name.slice(dot + 1);
16247
+ let res;
16248
+ try {
16249
+ res = await fetch(`${apiUrl}/api`, {
16250
+ method: "POST",
16251
+ signal,
16252
+ headers: {
16253
+ "content-type": "application/json",
16254
+ authorization,
16255
+ ...source ? { "x-arbor-source": source } : {}
16256
+ },
16257
+ body: JSON.stringify({ object, verb, input })
16258
+ });
16259
+ } catch (cause) {
16260
+ throw new ApiError(`could not reach ${apiUrl} (${cause instanceof Error ? cause.message : String(cause)})`, 0);
16090
16261
  }
16091
- const annotations = mcpAnnotationsFor(action.name);
16092
- return {
16093
- ...action,
16094
- externalReadDefaults,
16095
- get outputSchema() {
16096
- const schema = outputSchemaFor(action.name);
16097
- if (!schema)
16098
- throw new Error(`${action.name}: MCP action is missing an output schema`);
16099
- return schema;
16100
- },
16101
- annotations
16102
- };
16103
- });
16104
- // ../actions/src/retention-entry.ts
16105
- var historyPolicySchema = _enum(["full", "checkpoint"]).optional().describe("text Artifacts: future history retention policy; full retains every source snapshot, checkpoint keeps metadata for every revision and source only when explicitly retained");
16106
- var retainSourceSchema = boolean2().optional().describe("edit: in checkpoint mode, retain this newly minted content revision's source");
16107
- var checkpointSchema = boolean2().optional().describe("edit: retain the exact current version source without incrementing content version");
16108
- var ARTIFACT_GET_PUBLIC_DESCRIPTION = "Read one Artifact as a compact card without loading its body; editable text supports its outline plus bounded startLine+limit or heading windows and explicit all=true; File Artifacts remain files and report whether bounded UTF-8 text projection is available. For text-like files use startLine+limit and nextLine; all=true and heading stay unavailable for files, binary/unsupported files use the Artifact URL/download/media surface, and editable historical reads retain exact artifactVersionId.";
16109
- function artifactEditInput(input) {
16110
- const patches = Array.isArray(input.patches);
16111
- const hasSource = typeof input.source === "string";
16112
- const checkpoint = input.checkpoint === true;
16113
- const historyPolicy = input.historyPolicy === "full" || input.historyPolicy === "checkpoint";
16114
- if (checkpoint && (patches || hasSource || historyPolicy)) {
16115
- throw new Error("artifact edit checkpoint cannot be combined with source, patches, or historyPolicy");
16262
+ const body = await res.json().catch(() => ({}));
16263
+ if (!res.ok || !body.success)
16264
+ throw new ApiError(body.error ?? `request failed (${res.status})`, res.status, parseErrorDetails(body.errorDetails));
16265
+ return body.data;
16266
+ }
16267
+ var httpExecutor = { call: callApi };
16268
+ async function binaryGet(path, authenticated = true) {
16269
+ const { authorization, apiUrl } = authHeader();
16270
+ let response;
16271
+ const url = new URL(path, apiUrl);
16272
+ if (url.origin !== new URL(apiUrl).origin || !authenticated && !url.pathname.startsWith("/api/attachment-read/"))
16273
+ throw new Error("Invalid download target");
16274
+ try {
16275
+ response = await fetch(url.toString(), {
16276
+ headers: authenticated ? { authorization } : {},
16277
+ redirect: "error"
16278
+ });
16279
+ } catch {
16280
+ throw new ApiError("Binary download request failed", 0);
16116
16281
  }
16117
- if (historyPolicy && (patches || hasSource)) {
16118
- throw new Error("artifact historyPolicy change cannot be combined with a content edit");
16282
+ if (!response.ok)
16283
+ throw new ApiError(`Download failed (${response.status})`, response.status);
16284
+ return response;
16285
+ }
16286
+
16287
+ // src/discovery.ts
16288
+ var HELP_DISCOVERY_TIMEOUT_MS = 1000;
16289
+ var baseActions = ACTIONS3.filter((action) => action.surfaces.some((surface) => surface === "cli" || surface === "computer-cli"));
16290
+ var BASE_HELP_NOTE = "Base help only: authenticated catalog unavailable.";
16291
+ async function discoverHelpActions(timeoutMs = HELP_DISCOVERY_TIMEOUT_MS) {
16292
+ const base = () => ({ actions: baseActions, note: BASE_HELP_NOTE });
16293
+ if (!loadConfig().token)
16294
+ return base();
16295
+ if (typeof AbortController !== "function" || typeof setTimeout !== "function")
16296
+ return base();
16297
+ const controller = new AbortController;
16298
+ let timer;
16299
+ try {
16300
+ const value = await Promise.race([
16301
+ callApi("tooling.catalog", {}, controller.signal),
16302
+ new Promise((_, reject) => {
16303
+ timer = setTimeout(() => {
16304
+ controller.abort();
16305
+ reject(new Error("catalog deadline"));
16306
+ }, timeoutMs);
16307
+ })
16308
+ ]);
16309
+ const catalog = value;
16310
+ if (catalog?.serverVersion !== ARBOR_VERSION || !Array.isArray(catalog.actions))
16311
+ return base();
16312
+ const selectors = new Map;
16313
+ for (const item of catalog.actions) {
16314
+ if (!item || typeof item.name !== "string" || !Array.isArray(item.variants) || !item.variants.every((tag) => typeof tag === "string"))
16315
+ return base();
16316
+ selectors.set(item.name, item.variants);
16317
+ }
16318
+ return {
16319
+ actions: baseActions.map((action) => projectActionVariants(action, selectors.get(action.name) ?? []))
16320
+ };
16321
+ } catch {
16322
+ return base();
16323
+ } finally {
16324
+ if (timer !== undefined)
16325
+ clearTimeout(timer);
16326
+ controller.abort();
16327
+ }
16328
+ }
16329
+
16330
+ // src/attachment-download.ts
16331
+ async function downloadAttachment(id, output, signed = false, force = false) {
16332
+ const { createHash, randomUUID } = await import("node:crypto");
16333
+ const { open, rename, unlink, link } = await import("node:fs/promises");
16334
+ const { basename, resolve } = await import("node:path");
16335
+ if (!/^(att_|art_)[a-zA-Z0-9_-]+$/.test(id))
16336
+ throw new Error("Expected an Attachment or Artifact id");
16337
+ const artifact = id.startsWith("art_");
16338
+ const metadata = artifact && !signed ? null : await httpExecutor.call("attachment.get", {
16339
+ attachmentId: id,
16340
+ ...signed ? { signed: true } : {}
16341
+ });
16342
+ if (signed && !metadata?.signedRead)
16343
+ throw new Error("Signed download is unavailable");
16344
+ const response = await binaryGet(signed ? metadata.signedRead.url : `/api/download/${artifact ? "artifact/" : ""}${encodeURIComponent(id)}`, !signed);
16345
+ const size = metadata?.size ?? Number(response.headers.get("x-arbor-size") ?? response.headers.get("content-length") ?? "NaN");
16346
+ if (!Number.isSafeInteger(size) || size < 0 || !response.body)
16347
+ throw new Error("Download has no valid size or body");
16348
+ const suggested = basename(metadata?.filename ?? dispositionFilename(response.headers.get("content-disposition")) ?? id);
16349
+ const destination = resolve(output ?? (suggested.startsWith(".") ? id : suggested));
16350
+ const temporary = `${destination}.${randomUUID()}.part`;
16351
+ const file = await open(temporary, "wx", 384);
16352
+ const reader = response.body.getReader();
16353
+ const hash = createHash("sha256");
16354
+ let received = 0;
16355
+ try {
16356
+ for (;; ) {
16357
+ const { done, value } = await reader.read();
16358
+ if (done)
16359
+ break;
16360
+ received += value.byteLength;
16361
+ if (received > size)
16362
+ throw new Error("Download size mismatch");
16363
+ hash.update(value);
16364
+ let offset = 0;
16365
+ while (offset < value.length) {
16366
+ const written = await file.write(value, offset, value.length - offset);
16367
+ offset += written.bytesWritten;
16368
+ }
16369
+ }
16370
+ const sha256 = hash.digest("hex");
16371
+ const expectedHash = metadata?.sha256 ?? response.headers.get("x-arbor-sha256");
16372
+ if (received !== size || expectedHash && expectedHash !== sha256)
16373
+ throw new Error("Download integrity mismatch");
16374
+ await file.close();
16375
+ if (force)
16376
+ await rename(temporary, destination);
16377
+ else {
16378
+ try {
16379
+ await link(temporary, destination);
16380
+ } catch (error) {
16381
+ if (error.code === "EEXIST")
16382
+ throw new Error("Destination exists; use --force to replace it");
16383
+ if (["EPERM", "ENOTSUP"].includes(error.code ?? ""))
16384
+ throw new Error("Filesystem does not support safe no-replace downloads; choose another destination or use --force to allow replacement");
16385
+ throw error;
16386
+ }
16387
+ await unlink(temporary);
16388
+ }
16389
+ return { path: destination, size: received, sha256 };
16390
+ } catch (error) {
16391
+ await reader.cancel().catch(() => {});
16392
+ await file.close().catch(() => {});
16393
+ await unlink(temporary).catch(() => {});
16394
+ throw error;
16395
+ } finally {
16396
+ reader.releaseLock();
16119
16397
  }
16120
- if (checkpoint)
16121
- return { ...input, verb: "checkpoint" };
16122
- if (historyPolicy)
16123
- return { ...input, verb: "set_history_policy" };
16124
- return { ...input, verb: patches ? "patch" : "replace" };
16125
- }
16126
- function runArtifact(ex, input) {
16127
- const { verb, ...rest } = input;
16128
- if (verb === "create")
16129
- return ex.call("artifact.create", rest);
16130
- if (verb === "edit")
16131
- return ex.call("artifact.edit", artifactEditInput(rest));
16132
- if (verb === "set_live_preview")
16133
- return ex.call("artifact.setLivePreview", rest);
16134
- if (verb === "set_snapshot")
16135
- return ex.call("artifact.setSnapshot", rest);
16136
- if (verb === "promote_attachment")
16137
- return ex.call("attachment.promote", rest);
16138
- return Promise.reject(new Error(`unknown artifact verb "${verb ?? ""}"`));
16139
- }
16140
- function overrideAction(action, overrides) {
16141
- return Object.assign(Object.defineProperties({}, Object.getOwnPropertyDescriptors(action)), overrides);
16142
16398
  }
16143
- function retentionAction(action) {
16144
- if (action.name === "create_artifact") {
16145
- return overrideAction(action, {
16146
- description: "Create a durable Artifact; text kinds may choose historyPolicy=full (default) or checkpoint. Checkpoint mode still keeps metadata/provenance for every revision while source snapshots are retained only when explicitly checkpointed.",
16147
- inputSchema: { ...action.inputSchema, historyPolicy: historyPolicySchema }
16148
- });
16149
- }
16150
- if (action.name === "edit_artifact") {
16151
- return overrideAction(action, {
16152
- description: "Edit a text Artifact from the baseVersion you read, or change its future historyPolicy/checkpoint the exact current source without minting a content version. Content edits return the exact artifactVersionId; byte-identical results are idempotent no-ops that reuse the current version identity, while stale divergent edits remain structured conflicts.",
16153
- inputSchema: {
16154
- ...action.inputSchema,
16155
- historyPolicy: historyPolicySchema,
16156
- checkpoint: checkpointSchema,
16157
- retainSource: retainSourceSchema
16158
- },
16159
- run: (ex, input) => ex.call("artifact.edit", artifactEditInput(input))
16160
- });
16161
- }
16162
- if (action.name === "get_artifact" || action.name === "artifact_get") {
16163
- return overrideAction(action, { description: ARTIFACT_GET_PUBLIC_DESCRIPTION });
16164
- }
16165
- if (action.name === "artifact") {
16166
- return overrideAction(action, {
16167
- description: "Create/edit a durable Artifact with full|checkpoint retention or manage Live Preview, snapshots, and attachments. Git edits derive retry keys (omitted edits derive one); keyless creates mint per-invocation keys; stable idempotencyKey supports caller retries; never blindly repeat ambiguous creates. promote_attachment creates a file Artifact from a Contribution; exported reports use the Attachment downloadUrl; policy changes do not mint content versions.",
16168
- inputSchema: {
16169
- ...action.inputSchema,
16170
- historyPolicy: historyPolicySchema,
16171
- checkpoint: checkpointSchema,
16172
- retainSource: retainSourceSchema
16173
- },
16174
- run: runArtifact
16175
- });
16399
+ function dispositionFilename(value) {
16400
+ if (!value)
16401
+ return;
16402
+ const encoded = /filename\*=UTF-8''([^;]+)/i.exec(value)?.[1];
16403
+ if (encoded) {
16404
+ try {
16405
+ return decodeURIComponent(encoded);
16406
+ } catch {}
16176
16407
  }
16177
- return action;
16408
+ return /filename="([^"]*)"/i.exec(value)?.[1] ?? /filename=([^;\s]+)/i.exec(value)?.[1];
16178
16409
  }
16179
- var ACTIONS2 = ACTIONS.map(retentionAction);
16180
-
16181
- // ../actions/src/recovery-entry.ts
16182
- var grantOutput = object({
16183
- grant: object({
16184
- grantId: string2(),
16185
- requestId: string2(),
16186
- threadId: string2(),
16187
- runId: string2(),
16188
- computerId: string2(),
16189
- granteeProfileId: string2(),
16190
- grantedByProfileId: string2(),
16191
- expiresAt: string2(),
16192
- createdAt: string2(),
16193
- revokedAt: string2().nullable(),
16194
- revokedByProfileId: string2().nullable()
16195
- }),
16196
- replayed: boolean2()
16197
- });
16198
- var diagnosticOutput = object({
16199
- grant: object({
16200
- grantId: string2(),
16201
- requestId: string2(),
16202
- expiresAt: string2()
16203
- }),
16204
- diagnostic: object({
16205
- runId: string2(),
16206
- computerId: string2(),
16207
- computerGeneration: number2().int().positive(),
16208
- status: _enum(["active", "finished", "failed", "cancelled"]),
16209
- outcome: _enum(["finished", "failed", "cancelled"]).nullable(),
16210
- reasonCode: string2().nullable(),
16211
- runtimeState: _enum(["shared", "live", "suspended", "releasing", "released"]),
16212
- snapshotLineage: object({
16213
- baseSnapshotId: string2().nullable(),
16214
- currentSnapshotId: string2().nullable()
16215
- }),
16216
- providerState: object({
16217
- generation: number2().int().min(0).nullable(),
16218
- lastPhase: string2().nullable(),
16219
- lastReasonCode: string2().nullable()
16220
- }),
16221
- operations: array(object({
16222
- operationId: string2(),
16223
- execution: _enum(["foreground", "background"]),
16224
- state: _enum([
16225
- "starting",
16226
- "running",
16227
- "completed",
16228
- "failed",
16229
- "cancelled",
16230
- "not-routed",
16231
- "provider-lost",
16232
- "unknown"
16233
- ]),
16234
- mutationRetrySafety: _enum(["not-needed", "safe", "unsafe", "unknown"]),
16235
- reasonCode: string2()
16236
- }))
16237
- }),
16238
- auditEventId: string2()
16239
- });
16240
- var additive2 = {
16241
- readOnlyHint: false,
16242
- destructiveHint: false,
16243
- idempotentHint: true,
16244
- openWorldHint: false
16245
- };
16246
- var auditedRead = {
16247
- readOnlyHint: false,
16248
- destructiveHint: false,
16249
- idempotentHint: false,
16250
- openWorldHint: false
16251
- };
16252
- var RECOVERY_ACTIONS = [
16253
- {
16254
- name: "computer_recovery_grant",
16255
- title: "Grant delegated Computer recovery",
16256
- description: "Issue one short-lived diagnostic grant for a profile explicitly targeted by the same open Request and exact Run. This grants no execution, file, environment, Secret, Git, checkpoint, or lifecycle capability.",
16257
- inputSchema: {
16258
- requestId: string2().describe("the targeted open Request authorizing this recovery scope, req_…"),
16259
- runId: string2().describe("the exact Run whose diagnostic state may be inspected, run_…"),
16260
- granteeProfileId: string2().describe("the exact targeted profile receiving diagnostic visibility"),
16261
- expiresAt: string2().describe("future ISO timestamp, at most 24 hours and never after Request expiry"),
16262
- idempotencyKey: string2().min(1).max(200).describe("stable key for this one logical grant")
16263
- },
16264
- outputSchema: grantOutput,
16265
- annotations: additive2,
16266
- surfaces: ["computer-cli"],
16267
- toolset: "loop",
16268
- run: (ex, input) => ex.call("computer_recovery.grant", input)
16410
+ // package.json
16411
+ var package_default = {
16412
+ name: "@lambdacurry/arbor",
16413
+ version: "0.24.16",
16414
+ description: "The Arbor CLI — a shared workspace for people and agents. The human + headless-agent write path over Arbor's guarded operation surface.",
16415
+ keywords: [
16416
+ "agents",
16417
+ "arbor",
16418
+ "cli",
16419
+ "collaboration",
16420
+ "mcp"
16421
+ ],
16422
+ license: "MIT",
16423
+ repository: {
16424
+ type: "git",
16425
+ url: "git+https://github.com/lambda-curry/arbor.git",
16426
+ directory: "packages/cli"
16269
16427
  },
16270
- {
16271
- name: "computer_recovery_revoke",
16272
- title: "Revoke delegated Computer recovery",
16273
- description: "Revoke one previously issued delegated diagnostic grant without touching the Computer or provider. Repeating the same revoke is an idempotent no-op.",
16274
- inputSchema: {
16275
- grantId: string2().describe("the delegated recovery grant, crg_…")
16276
- },
16277
- outputSchema: grantOutput,
16278
- annotations: additive2,
16279
- surfaces: ["computer-cli"],
16280
- toolset: "loop",
16281
- run: (ex, input) => ex.call("computer_recovery.revoke", input)
16428
+ bin: {
16429
+ arbor: "./dist/arbor.js"
16282
16430
  },
16283
- {
16284
- name: "computer_recovery_inspect",
16285
- title: "Inspect delegated Computer recovery state",
16286
- description: "Read only the sanitized diagnostic projection authorized by one live delegated grant; every successful read records an attributed Arbor audit Event. It never calls the provider or exposes repository paths/heads, command output, environment, Secrets, sessions, or mutation controls.",
16287
- inputSchema: {
16288
- grantId: string2().describe("the delegated recovery grant, crg_…")
16289
- },
16290
- outputSchema: diagnosticOutput,
16291
- annotations: auditedRead,
16292
- surfaces: ["computer-mcp", "computer-cli"],
16293
- toolset: "loop",
16294
- run: (ex, input) => ex.call("computer_recovery.inspect", input)
16431
+ files: [
16432
+ "dist",
16433
+ "README.md"
16434
+ ],
16435
+ type: "module",
16436
+ publishConfig: {
16437
+ access: "public"
16438
+ },
16439
+ scripts: {
16440
+ arbor: "vpx src/bin.ts",
16441
+ build: "bun build ./src/bin.ts --target=node --outfile=dist/arbor.js",
16442
+ test: "vp test run --passWithNoTests",
16443
+ typecheck: "tsc -b",
16444
+ prepublishOnly: "bun run build"
16445
+ },
16446
+ devDependencies: {
16447
+ "@arbor/actions": "workspace:*",
16448
+ "@arbor/core": "workspace:*",
16449
+ "@types/node": "^26.2.0",
16450
+ "just-bash": "3.4.2",
16451
+ typescript: "^5.8.0",
16452
+ "vite-plus": "catalog:",
16453
+ zod: "^4.4.3"
16454
+ },
16455
+ engines: {
16456
+ node: ">=18"
16295
16457
  }
16296
- ];
16297
- var ACTIONS3 = [...ACTIONS2, ...RECOVERY_ACTIONS];
16458
+ };
16298
16459
 
16299
16460
  // src/attachment-upload.ts
16300
16461
  import { basename, resolve } from "node:path";
@@ -17130,11 +17291,11 @@ var KNOWN_MISREACHES = [
17130
17291
  why: "this command is noun-verb"
17131
17292
  }
17132
17293
  ];
17133
- function familyHelp(positionals) {
17294
+ function familyHelp(positionals, actions = CLI_ACTIONS) {
17134
17295
  if (positionals.length !== 1)
17135
17296
  return;
17136
17297
  const word = positionals[0].toLowerCase().replace(/_/g, " ");
17137
- const members = CLI_ACTIONS.filter((a) => commandWords(a).split(" ").includes(word)).sort((a, b) => commandWords(a).localeCompare(commandWords(b)));
17298
+ const members = actions.filter((a) => commandWords(a).split(" ").includes(word)).sort((a, b) => commandWords(a).localeCompare(commandWords(b)));
17138
17299
  if (members.length === 0)
17139
17300
  return;
17140
17301
  return `\`${word}\` commands — run \`arbor <command> --help\` for one command's exact flags.
@@ -17198,11 +17359,11 @@ function helpLine(action) {
17198
17359
  }
17199
17360
  var COMMAND_HELP = CLI_ACTIONS.map(helpLine).join(`
17200
17361
  `);
17201
- function commandHelp(positionals) {
17362
+ function commandHelp(positionals, actions = CLI_ACTIONS) {
17202
17363
  const match = matchCommand(positionals);
17203
17364
  if (!match)
17204
17365
  return;
17205
- const { action } = match;
17366
+ const action = actions.find((action) => action.name === match.action.name) ?? match.action;
17206
17367
  const specs = flagsForSchema(action.inputSchema);
17207
17368
  const explicitPositionals = positionalSpecs(action);
17208
17369
  const primary = explicitPositionals.length === 0 ? primaryPositionalField(action.inputSchema) : undefined;
@@ -17265,8 +17426,8 @@ ${[...lines, ...waitLines].join(`
17265
17426
  `)}${primaryNote}${explicitNote}${aliasNote}${notes}
17266
17427
  `;
17267
17428
  }
17268
- function commandCatalog() {
17269
- return CLI_ACTIONS.map((action) => ({
17429
+ function commandCatalog(actions = CLI_ACTIONS) {
17430
+ return actions.filter((action) => action.surfaces.some((surface) => surface === "cli" || surface === "computer-cli")).map((action) => ({
17270
17431
  command: commandWords(action),
17271
17432
  name: action.name,
17272
17433
  description: action.description,
@@ -17335,7 +17496,8 @@ async function runObjectVerb(positionals, flags, ctx) {
17335
17496
  const typed = positionals.join(" ") || "(none)";
17336
17497
  throw new UsageError(`unknown command: ${typed} — ${suggestCommand(positionals)}`);
17337
17498
  }
17338
- const { action, words } = match;
17499
+ const { words } = match;
17500
+ const action = { ...match.action, inputSchema: canonicalInputShape(match.action) };
17339
17501
  applyPositionals(action, positionals.slice(words), flags);
17340
17502
  const accepted = acceptedFlags(action.inputSchema);
17341
17503
  const unknown = Object.keys(flags).filter((f) => !accepted.has(f) && !RESERVED_FLAGS.has(f));
@@ -17654,8 +17816,22 @@ Tokens: a human PAT or an agent key works in either ARBOR_TOKEN (env, headless)
17654
17816
 
17655
17817
  ${COMMAND_HELP}
17656
17818
  `;
17657
- function renderHelp(ctx) {
17658
- emitDual(commandCatalog(), HELP, "help", ctx);
17819
+ function renderHelp(ctx, actions) {
17820
+ emitDual(commandCatalog(actions), HELP, "help", ctx);
17821
+ }
17822
+ async function renderRequestedHelp(ctx, positionals) {
17823
+ const matched = matchCommand(positionals)?.action;
17824
+ const family = positionals.length === 1 ? positionals[0].replace(/_/g, " ") : null;
17825
+ const needsDiscovery = ctx.json || Boolean(matched?.privilegedVariants?.length) || Boolean(family && ACTIONS3.some((action) => action.privilegedVariants?.length && action.name.replace(/_/g, " ").split(" ").includes(family)));
17826
+ const discovery = needsDiscovery ? await discoverHelpActions() : undefined;
17827
+ if (discovery?.note)
17828
+ writeStderr(`${discovery.note}
17829
+ `);
17830
+ const focused = positionals.length ? commandHelp(positionals, discovery?.actions) ?? familyHelp(positionals, discovery?.actions) : undefined;
17831
+ if (focused)
17832
+ emitDual({ help: focused }, focused, "help", ctx);
17833
+ else
17834
+ renderHelp(ctx, discovery?.actions);
17659
17835
  }
17660
17836
  async function renderHealth(ctx) {
17661
17837
  const cfg = loadConfig();
@@ -17701,7 +17877,7 @@ async function main() {
17701
17877
  if (cmd !== "profile") {
17702
17878
  configureConfigTarget({
17703
17879
  profileFlag,
17704
- allowMissingProfile: cmd === "login" || cmd === "auth" || cmd === "connect"
17880
+ allowMissingProfile: cmd === "login" || cmd === "auth" || cmd === "connect" || cmd === "help" || cmd === undefined || truthyFlag(flags.help)
17705
17881
  });
17706
17882
  } else if (profileFlag !== undefined) {
17707
17883
  throw new UsageError("--profile selects a credential for a command; profile management names its target positionally");
@@ -17718,11 +17894,7 @@ Stream authenticated bytes to a file; verify size and the recorded SHA-256 when
17718
17894
  return;
17719
17895
  }
17720
17896
  if (truthyFlag(flags.help)) {
17721
- const focused = positionals.length > 0 ? commandHelp(positionals) ?? familyHelp(positionals) : undefined;
17722
- if (focused)
17723
- emitDual({ help: focused }, focused, "help", ctx);
17724
- else
17725
- renderHelp(ctx);
17897
+ await renderRequestedHelp(ctx, positionals);
17726
17898
  return;
17727
17899
  }
17728
17900
  if (cmd === "attachment" && positionals[1] === "download") {
@@ -17735,8 +17907,10 @@ Stream authenticated bytes to a file; verify size and the recorded SHA-256 when
17735
17907
  }
17736
17908
  switch (cmd) {
17737
17909
  case undefined:
17910
+ await renderRequestedHelp(ctx, []);
17911
+ return;
17738
17912
  case "help":
17739
- renderHelp(ctx);
17913
+ await renderRequestedHelp(ctx, positionals.slice(1));
17740
17914
  return;
17741
17915
  case "login": {
17742
17916
  await login({ url: stringFlag(flags.url, "url") });