@alfe.ai/gateway 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/health.js CHANGED
@@ -5,13 +5,13 @@ import { homedir } from "node:os";
5
5
  import pino from "pino";
6
6
  import { chmodSync, existsSync, mkdirSync, unlinkSync } from "node:fs";
7
7
  import { getEndpointFromToken, readConfig } from "@alfe.ai/config";
8
- import { AlfeApiClient, AuthService } from "@alfe/api-client";
8
+ import crypto from "crypto";
9
9
  import { parse } from "smol-toml";
10
10
  import WebSocket from "ws";
11
- import crypto from "crypto";
12
11
  import { createConnection, createServer } from "node:net";
13
12
  import { execSync, spawn } from "node:child_process";
14
13
  import { IntegrationManager, IntegrationManagerAdapter, OpenClawApplier } from "@alfe.ai/integrations";
14
+ import { randomUUID } from "node:crypto";
15
15
  import stream, { Readable } from "stream";
16
16
  import util, { format } from "util";
17
17
  import http from "http";
@@ -20,7 +20,6 @@ import url from "url";
20
20
  import http2 from "http2";
21
21
  import zlib from "zlib";
22
22
  import { EventEmitter } from "events";
23
- import { randomUUID } from "node:crypto";
24
23
  //#region \0rolldown/runtime.js
25
24
  var __create = Object.create;
26
25
  var __defProp = Object.defineProperty;
@@ -59,38 +58,3131 @@ var __require = /* @__PURE__ */ createRequire(import.meta.url);
59
58
  * Daemon logger — pino with rolling file output.
60
59
  *
61
60
  * Writes to ~/.alfe/logs/gateway.log with 10MB rotation, keep 5 files.
62
- * Also outputs to stdout in development mode.
61
+ * In managed mode (ECS Fargate): always stdout for CloudWatch capture.
62
+ * In development: stdout.
63
63
  */
64
64
  const LOG_DIR = join(homedir(), ".alfe", "logs");
65
65
  const LOG_FILE = join(LOG_DIR, "gateway.log");
66
- try {
66
+ const isDev = process.env.NODE_ENV !== "production";
67
+ const isManaged = process.env.ALFE_MANAGED === "true";
68
+ if (!isManaged) try {
67
69
  mkdirSync(LOG_DIR, { recursive: true });
68
70
  } catch {}
69
- const isDev = process.env.NODE_ENV !== "production";
70
71
  /**
71
72
  * Create the daemon logger.
72
- * In development: pretty-prints to stdout.
73
- * In production: JSON to rolling file.
73
+ * Managed mode (ECS): JSON to stdout (CloudWatch captures via awslogs driver).
74
+ * Development: JSON to stdout.
75
+ * Production (local): JSON to rolling file.
74
76
  */
75
77
  function createLogger$1() {
76
- if (isDev) return pino({
77
- level: process.env.LOG_LEVEL ?? "debug",
78
+ if (isDev || isManaged) return pino({
79
+ level: process.env.LOG_LEVEL ?? (isDev ? "debug" : "info"),
78
80
  transport: {
79
81
  target: "pino/file",
80
82
  options: { destination: 1 }
81
83
  }
82
84
  });
83
- const transport = pino.transport({
84
- target: "pino-roll",
85
- options: {
86
- file: LOG_FILE,
87
- size: "10m",
88
- limit: { count: 5 }
85
+ const transport = pino.transport({
86
+ target: "pino-roll",
87
+ options: {
88
+ file: LOG_FILE,
89
+ size: "10m",
90
+ limit: { count: 5 }
91
+ }
92
+ });
93
+ return pino({ level: process.env.LOG_LEVEL ?? "info" }, transport);
94
+ }
95
+ const logger$1 = createLogger$1();
96
+ //#endregion
97
+ //#region ../../packages-internal/ids/dist/prefixes.js
98
+ const ID_PREFIXES = {
99
+ agent: "agt",
100
+ organization: "org",
101
+ person: "per",
102
+ auditEvent: "evt",
103
+ token: "tok",
104
+ transaction: "txn",
105
+ subscription: "sub",
106
+ conversation: "conv",
107
+ run: "run",
108
+ request: "req",
109
+ connection: "conn",
110
+ correlation: "cor",
111
+ command: "cmd",
112
+ message: "msg",
113
+ ipcRequest: "ipc",
114
+ pluginConnection: "plg"
115
+ };
116
+ //#endregion
117
+ //#region ../../packages-internal/ids/dist/create.js
118
+ var import_index_umd = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
119
+ (function(global, factory) {
120
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.ULID = {}));
121
+ })(exports, (function(exports$4) {
122
+ "use strict";
123
+ function createError(message) {
124
+ const err = new Error(message);
125
+ err.source = "ulid";
126
+ return err;
127
+ }
128
+ const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
129
+ const ENCODING_LEN = 32;
130
+ const TIME_MAX = Math.pow(2, 48) - 1;
131
+ const TIME_LEN = 10;
132
+ const RANDOM_LEN = 16;
133
+ function replaceCharAt(str, index, char) {
134
+ if (index > str.length - 1) return str;
135
+ return str.substr(0, index) + char + str.substr(index + 1);
136
+ }
137
+ function incrementBase32(str) {
138
+ let done = void 0;
139
+ let index = str.length;
140
+ let char;
141
+ let charIndex;
142
+ const maxCharIndex = ENCODING_LEN - 1;
143
+ while (!done && index-- >= 0) {
144
+ char = str[index];
145
+ charIndex = ENCODING.indexOf(char);
146
+ if (charIndex === -1) throw createError("incorrectly encoded string");
147
+ if (charIndex === maxCharIndex) {
148
+ str = replaceCharAt(str, index, ENCODING[0]);
149
+ continue;
150
+ }
151
+ done = replaceCharAt(str, index, ENCODING[charIndex + 1]);
152
+ }
153
+ if (typeof done === "string") return done;
154
+ throw createError("cannot increment this string");
155
+ }
156
+ function randomChar(prng) {
157
+ let rand = Math.floor(prng() * ENCODING_LEN);
158
+ if (rand === ENCODING_LEN) rand = ENCODING_LEN - 1;
159
+ return ENCODING.charAt(rand);
160
+ }
161
+ function encodeTime(now, len) {
162
+ if (isNaN(now)) throw new Error(now + " must be a number");
163
+ if (now > TIME_MAX) throw createError("cannot encode time greater than " + TIME_MAX);
164
+ if (now < 0) throw createError("time must be positive");
165
+ if (Number.isInteger(Number(now)) === false) throw createError("time must be an integer");
166
+ let mod;
167
+ let str = "";
168
+ for (; len > 0; len--) {
169
+ mod = now % ENCODING_LEN;
170
+ str = ENCODING.charAt(mod) + str;
171
+ now = (now - mod) / ENCODING_LEN;
172
+ }
173
+ return str;
174
+ }
175
+ function encodeRandom(len, prng) {
176
+ let str = "";
177
+ for (; len > 0; len--) str = randomChar(prng) + str;
178
+ return str;
179
+ }
180
+ function decodeTime(id) {
181
+ if (id.length !== TIME_LEN + RANDOM_LEN) throw createError("malformed ulid");
182
+ var time = id.substr(0, TIME_LEN).split("").reverse().reduce((carry, char, index) => {
183
+ const encodingIndex = ENCODING.indexOf(char);
184
+ if (encodingIndex === -1) throw createError("invalid character found: " + char);
185
+ return carry += encodingIndex * Math.pow(ENCODING_LEN, index);
186
+ }, 0);
187
+ if (time > TIME_MAX) throw createError("malformed ulid, timestamp too large");
188
+ return time;
189
+ }
190
+ function detectPrng(allowInsecure = false, root) {
191
+ if (!root) root = typeof window !== "undefined" ? window : null;
192
+ const browserCrypto = root && (root.crypto || root.msCrypto);
193
+ if (browserCrypto) return () => {
194
+ const buffer = new Uint8Array(1);
195
+ browserCrypto.getRandomValues(buffer);
196
+ return buffer[0] / 255;
197
+ };
198
+ else try {
199
+ const nodeCrypto = __require("crypto");
200
+ return () => nodeCrypto.randomBytes(1).readUInt8() / 255;
201
+ } catch (e) {}
202
+ if (allowInsecure) {
203
+ try {
204
+ console.error("secure crypto unusable, falling back to insecure Math.random()!");
205
+ } catch (e) {}
206
+ return () => Math.random();
207
+ }
208
+ throw createError("secure crypto unusable, insecure Math.random not allowed");
209
+ }
210
+ function factory(currPrng) {
211
+ if (!currPrng) currPrng = detectPrng();
212
+ return function ulid(seedTime) {
213
+ if (isNaN(seedTime)) seedTime = Date.now();
214
+ return encodeTime(seedTime, TIME_LEN) + encodeRandom(RANDOM_LEN, currPrng);
215
+ };
216
+ }
217
+ function monotonicFactory(currPrng) {
218
+ if (!currPrng) currPrng = detectPrng();
219
+ let lastTime = 0;
220
+ let lastRandom;
221
+ return function ulid(seedTime) {
222
+ if (isNaN(seedTime)) seedTime = Date.now();
223
+ if (seedTime <= lastTime) {
224
+ const incrementedRandom = lastRandom = incrementBase32(lastRandom);
225
+ return encodeTime(lastTime, TIME_LEN) + incrementedRandom;
226
+ }
227
+ lastTime = seedTime;
228
+ const newRandom = lastRandom = encodeRandom(RANDOM_LEN, currPrng);
229
+ return encodeTime(seedTime, TIME_LEN) + newRandom;
230
+ };
231
+ }
232
+ const ulid = factory();
233
+ exports$4.decodeTime = decodeTime;
234
+ exports$4.detectPrng = detectPrng;
235
+ exports$4.encodeRandom = encodeRandom;
236
+ exports$4.encodeTime = encodeTime;
237
+ exports$4.factory = factory;
238
+ exports$4.incrementBase32 = incrementBase32;
239
+ exports$4.monotonicFactory = monotonicFactory;
240
+ exports$4.randomChar = randomChar;
241
+ exports$4.replaceCharAt = replaceCharAt;
242
+ exports$4.ulid = ulid;
243
+ }));
244
+ })))();
245
+ function createId(prefix) {
246
+ return `${prefix}_${(0, import_index_umd.ulid)()}`;
247
+ }
248
+ function correlationId() {
249
+ return createId(ID_PREFIXES.correlation);
250
+ }
251
+ function pluginConnectionId() {
252
+ return createId(ID_PREFIXES.pluginConnection);
253
+ }
254
+ //#endregion
255
+ //#region ../../packages-internal/api-client/dist/client.js
256
+ /**
257
+ * @alfe/api-client — Typed HTTP client for Alfe services.
258
+ *
259
+ * Platform-agnostic: works in React Native and browser environments.
260
+ * Uses standard fetch() API — no Node.js dependencies.
261
+ */
262
+ var AlfeApiClient = class {
263
+ apiBaseUrl;
264
+ getToken;
265
+ onAuthFailure;
266
+ constructor(options) {
267
+ this.apiBaseUrl = options.apiBaseUrl;
268
+ this.getToken = options.getToken;
269
+ this.onAuthFailure = options.onAuthFailure;
270
+ }
271
+ /** Shared fetch logic — handles auth, 401, and network errors. */
272
+ async _fetch(path, options) {
273
+ try {
274
+ const token = await this.getToken();
275
+ if (!token) {
276
+ this.onAuthFailure?.();
277
+ return {
278
+ ok: false,
279
+ result: {
280
+ ok: false,
281
+ error: "No auth token available",
282
+ status: 401
283
+ }
284
+ };
285
+ }
286
+ const url = `${this.apiBaseUrl}${path}`;
287
+ const headers = new Headers(options?.headers);
288
+ headers.set("Authorization", `Bearer ${token}`);
289
+ headers.set("Content-Type", "application/json");
290
+ headers.set("x-correlation-id", correlationId());
291
+ const res = await fetch(url, {
292
+ ...options,
293
+ headers
294
+ });
295
+ if (res.status === 401) {
296
+ this.onAuthFailure?.();
297
+ return {
298
+ ok: false,
299
+ result: {
300
+ ok: false,
301
+ error: "Session expired",
302
+ status: 401
303
+ }
304
+ };
305
+ }
306
+ const body = await res.json();
307
+ if (!res.ok) return {
308
+ ok: false,
309
+ result: {
310
+ ok: false,
311
+ error: body.message || `API error: ${String(res.status)}`,
312
+ status: res.status
313
+ }
314
+ };
315
+ return {
316
+ ok: true,
317
+ res,
318
+ body
319
+ };
320
+ } catch (err) {
321
+ return {
322
+ ok: false,
323
+ result: {
324
+ ok: false,
325
+ error: err instanceof Error ? err.message : "Network error"
326
+ }
327
+ };
328
+ }
329
+ }
330
+ /**
331
+ * Make an authenticated request to an Alfe API endpoint.
332
+ * Unwraps the @auriclabs/api-core `{ data, timestamp, requestId }` envelope.
333
+ */
334
+ async request(path, options) {
335
+ const result = await this._fetch(path, options);
336
+ if (!result.ok) return result.result;
337
+ return {
338
+ ok: true,
339
+ data: result.body.data
340
+ };
341
+ }
342
+ /**
343
+ * Make an authenticated request that returns the body directly (no envelope unwrap).
344
+ * Use for APIs that don't use the @auriclabs/api-core response format (e.g. gateway).
345
+ */
346
+ async rawRequest(path, options) {
347
+ const result = await this._fetch(path, options);
348
+ if (!result.ok) return result.result;
349
+ return {
350
+ ok: true,
351
+ data: result.body
352
+ };
353
+ }
354
+ getApiBaseUrl() {
355
+ return this.apiBaseUrl;
356
+ }
357
+ };
358
+ //#endregion
359
+ //#region ../../packages-internal/api-client/dist/services/auth.js
360
+ var AuthService = class {
361
+ client;
362
+ constructor(client) {
363
+ this.client = client;
364
+ }
365
+ prefix = "/auth";
366
+ validate(token) {
367
+ return this.client.request(`${this.prefix}/validate`, {
368
+ method: "POST",
369
+ body: JSON.stringify({ token })
370
+ });
371
+ }
372
+ listTokens() {
373
+ return this.client.request(`${this.prefix}/tokens`);
374
+ }
375
+ createToken(data) {
376
+ return this.client.request(`${this.prefix}/tokens`, {
377
+ method: "POST",
378
+ body: JSON.stringify(data)
379
+ });
380
+ }
381
+ deleteToken(tokenId) {
382
+ return this.client.request(`${this.prefix}/tokens/${tokenId}`, { method: "DELETE" });
383
+ }
384
+ };
385
+ //#endregion
386
+ //#region ../../packages-internal/types/dist/lib/enum-values.js
387
+ /**
388
+ * Converts a const enum object into a non-empty readonly tuple.
389
+ *
390
+ * Satisfies both `z.enum()` and ElectroDB `type` field requirements
391
+ * (both need `readonly [string, ...string[]]`).
392
+ */
393
+ function enumValues(obj) {
394
+ return Object.values(obj);
395
+ }
396
+ Object.freeze({ status: "aborted" });
397
+ function $constructor(name, initializer, params) {
398
+ function init(inst, def) {
399
+ if (!inst._zod) Object.defineProperty(inst, "_zod", {
400
+ value: {
401
+ def,
402
+ constr: _,
403
+ traits: /* @__PURE__ */ new Set()
404
+ },
405
+ enumerable: false
406
+ });
407
+ if (inst._zod.traits.has(name)) return;
408
+ inst._zod.traits.add(name);
409
+ initializer(inst, def);
410
+ const proto = _.prototype;
411
+ const keys = Object.keys(proto);
412
+ for (let i = 0; i < keys.length; i++) {
413
+ const k = keys[i];
414
+ if (!(k in inst)) inst[k] = proto[k].bind(inst);
415
+ }
416
+ }
417
+ const Parent = params?.Parent ?? Object;
418
+ class Definition extends Parent {}
419
+ Object.defineProperty(Definition, "name", { value: name });
420
+ function _(def) {
421
+ var _a;
422
+ const inst = params?.Parent ? new Definition() : this;
423
+ init(inst, def);
424
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
425
+ for (const fn of inst._zod.deferred) fn();
426
+ return inst;
427
+ }
428
+ Object.defineProperty(_, "init", { value: init });
429
+ Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => {
430
+ if (params?.Parent && inst instanceof params.Parent) return true;
431
+ return inst?._zod?.traits?.has(name);
432
+ } });
433
+ Object.defineProperty(_, "name", { value: name });
434
+ return _;
435
+ }
436
+ var $ZodAsyncError = class extends Error {
437
+ constructor() {
438
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
439
+ }
440
+ };
441
+ var $ZodEncodeError = class extends Error {
442
+ constructor(name) {
443
+ super(`Encountered unidirectional transform during encode: ${name}`);
444
+ this.name = "ZodEncodeError";
445
+ }
446
+ };
447
+ const globalConfig = {};
448
+ function config$1(newConfig) {
449
+ if (newConfig) Object.assign(globalConfig, newConfig);
450
+ return globalConfig;
451
+ }
452
+ //#endregion
453
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js
454
+ function getEnumValues(entries) {
455
+ const numericValues = Object.values(entries).filter((v) => typeof v === "number");
456
+ return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
457
+ }
458
+ function jsonStringifyReplacer(_, value) {
459
+ if (typeof value === "bigint") return value.toString();
460
+ return value;
461
+ }
462
+ function cached(getter) {
463
+ return { get value() {
464
+ {
465
+ const value = getter();
466
+ Object.defineProperty(this, "value", { value });
467
+ return value;
468
+ }
469
+ throw new Error("cached value already set");
470
+ } };
471
+ }
472
+ function nullish(input) {
473
+ return input === null || input === void 0;
474
+ }
475
+ function cleanRegex(source) {
476
+ const start = source.startsWith("^") ? 1 : 0;
477
+ const end = source.endsWith("$") ? source.length - 1 : source.length;
478
+ return source.slice(start, end);
479
+ }
480
+ function floatSafeRemainder(val, step) {
481
+ const valDecCount = (val.toString().split(".")[1] || "").length;
482
+ const stepString = step.toString();
483
+ let stepDecCount = (stepString.split(".")[1] || "").length;
484
+ if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
485
+ const match = stepString.match(/\d?e-(\d?)/);
486
+ if (match?.[1]) stepDecCount = Number.parseInt(match[1]);
487
+ }
488
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
489
+ return Number.parseInt(val.toFixed(decCount).replace(".", "")) % Number.parseInt(step.toFixed(decCount).replace(".", "")) / 10 ** decCount;
490
+ }
491
+ const EVALUATING = Symbol("evaluating");
492
+ function defineLazy(object, key, getter) {
493
+ let value = void 0;
494
+ Object.defineProperty(object, key, {
495
+ get() {
496
+ if (value === EVALUATING) return;
497
+ if (value === void 0) {
498
+ value = EVALUATING;
499
+ value = getter();
500
+ }
501
+ return value;
502
+ },
503
+ set(v) {
504
+ Object.defineProperty(object, key, { value: v });
505
+ },
506
+ configurable: true
507
+ });
508
+ }
509
+ function assignProp(target, prop, value) {
510
+ Object.defineProperty(target, prop, {
511
+ value,
512
+ writable: true,
513
+ enumerable: true,
514
+ configurable: true
515
+ });
516
+ }
517
+ function mergeDefs(...defs) {
518
+ const mergedDescriptors = {};
519
+ for (const def of defs) Object.assign(mergedDescriptors, Object.getOwnPropertyDescriptors(def));
520
+ return Object.defineProperties({}, mergedDescriptors);
521
+ }
522
+ function esc(str) {
523
+ return JSON.stringify(str);
524
+ }
525
+ const captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
526
+ function isObject$1(data) {
527
+ return typeof data === "object" && data !== null && !Array.isArray(data);
528
+ }
529
+ const allowsEval = cached(() => {
530
+ if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false;
531
+ try {
532
+ new Function("");
533
+ return true;
534
+ } catch (_) {
535
+ return false;
536
+ }
537
+ });
538
+ function isPlainObject$1(o) {
539
+ if (isObject$1(o) === false) return false;
540
+ const ctor = o.constructor;
541
+ if (ctor === void 0) return true;
542
+ if (typeof ctor !== "function") return true;
543
+ const prot = ctor.prototype;
544
+ if (isObject$1(prot) === false) return false;
545
+ if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false;
546
+ return true;
547
+ }
548
+ function shallowClone(o) {
549
+ if (isPlainObject$1(o)) return { ...o };
550
+ if (Array.isArray(o)) return [...o];
551
+ return o;
552
+ }
553
+ const propertyKeyTypes = new Set([
554
+ "string",
555
+ "number",
556
+ "symbol"
557
+ ]);
558
+ function escapeRegex(str) {
559
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
560
+ }
561
+ function clone(inst, def, params) {
562
+ const cl = new inst._zod.constr(def ?? inst._zod.def);
563
+ if (!def || params?.parent) cl._zod.parent = inst;
564
+ return cl;
565
+ }
566
+ function normalizeParams(_params) {
567
+ const params = _params;
568
+ if (!params) return {};
569
+ if (typeof params === "string") return { error: () => params };
570
+ if (params?.message !== void 0) {
571
+ if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params");
572
+ params.error = params.message;
573
+ }
574
+ delete params.message;
575
+ if (typeof params.error === "string") return {
576
+ ...params,
577
+ error: () => params.error
578
+ };
579
+ return params;
580
+ }
581
+ function optionalKeys(shape) {
582
+ return Object.keys(shape).filter((k) => {
583
+ return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
584
+ });
585
+ }
586
+ const NUMBER_FORMAT_RANGES = {
587
+ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
588
+ int32: [-2147483648, 2147483647],
589
+ uint32: [0, 4294967295],
590
+ float32: [-34028234663852886e22, 34028234663852886e22],
591
+ float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
592
+ };
593
+ function pick(schema, mask) {
594
+ const currDef = schema._zod.def;
595
+ const checks = currDef.checks;
596
+ if (checks && checks.length > 0) throw new Error(".pick() cannot be used on object schemas containing refinements");
597
+ return clone(schema, mergeDefs(schema._zod.def, {
598
+ get shape() {
599
+ const newShape = {};
600
+ for (const key in mask) {
601
+ if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
602
+ if (!mask[key]) continue;
603
+ newShape[key] = currDef.shape[key];
604
+ }
605
+ assignProp(this, "shape", newShape);
606
+ return newShape;
607
+ },
608
+ checks: []
609
+ }));
610
+ }
611
+ function omit(schema, mask) {
612
+ const currDef = schema._zod.def;
613
+ const checks = currDef.checks;
614
+ if (checks && checks.length > 0) throw new Error(".omit() cannot be used on object schemas containing refinements");
615
+ return clone(schema, mergeDefs(schema._zod.def, {
616
+ get shape() {
617
+ const newShape = { ...schema._zod.def.shape };
618
+ for (const key in mask) {
619
+ if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
620
+ if (!mask[key]) continue;
621
+ delete newShape[key];
622
+ }
623
+ assignProp(this, "shape", newShape);
624
+ return newShape;
625
+ },
626
+ checks: []
627
+ }));
628
+ }
629
+ function extend$1(schema, shape) {
630
+ if (!isPlainObject$1(shape)) throw new Error("Invalid input to extend: expected a plain object");
631
+ const checks = schema._zod.def.checks;
632
+ if (checks && checks.length > 0) {
633
+ const existingShape = schema._zod.def.shape;
634
+ for (const key in shape) if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
635
+ }
636
+ return clone(schema, mergeDefs(schema._zod.def, { get shape() {
637
+ const _shape = {
638
+ ...schema._zod.def.shape,
639
+ ...shape
640
+ };
641
+ assignProp(this, "shape", _shape);
642
+ return _shape;
643
+ } }));
644
+ }
645
+ function safeExtend(schema, shape) {
646
+ if (!isPlainObject$1(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
647
+ return clone(schema, mergeDefs(schema._zod.def, { get shape() {
648
+ const _shape = {
649
+ ...schema._zod.def.shape,
650
+ ...shape
651
+ };
652
+ assignProp(this, "shape", _shape);
653
+ return _shape;
654
+ } }));
655
+ }
656
+ function merge$1(a, b) {
657
+ return clone(a, mergeDefs(a._zod.def, {
658
+ get shape() {
659
+ const _shape = {
660
+ ...a._zod.def.shape,
661
+ ...b._zod.def.shape
662
+ };
663
+ assignProp(this, "shape", _shape);
664
+ return _shape;
665
+ },
666
+ get catchall() {
667
+ return b._zod.def.catchall;
668
+ },
669
+ checks: []
670
+ }));
671
+ }
672
+ function partial(Class, schema, mask) {
673
+ const checks = schema._zod.def.checks;
674
+ if (checks && checks.length > 0) throw new Error(".partial() cannot be used on object schemas containing refinements");
675
+ return clone(schema, mergeDefs(schema._zod.def, {
676
+ get shape() {
677
+ const oldShape = schema._zod.def.shape;
678
+ const shape = { ...oldShape };
679
+ if (mask) for (const key in mask) {
680
+ if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`);
681
+ if (!mask[key]) continue;
682
+ shape[key] = Class ? new Class({
683
+ type: "optional",
684
+ innerType: oldShape[key]
685
+ }) : oldShape[key];
686
+ }
687
+ else for (const key in oldShape) shape[key] = Class ? new Class({
688
+ type: "optional",
689
+ innerType: oldShape[key]
690
+ }) : oldShape[key];
691
+ assignProp(this, "shape", shape);
692
+ return shape;
693
+ },
694
+ checks: []
695
+ }));
696
+ }
697
+ function required(Class, schema, mask) {
698
+ return clone(schema, mergeDefs(schema._zod.def, { get shape() {
699
+ const oldShape = schema._zod.def.shape;
700
+ const shape = { ...oldShape };
701
+ if (mask) for (const key in mask) {
702
+ if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`);
703
+ if (!mask[key]) continue;
704
+ shape[key] = new Class({
705
+ type: "nonoptional",
706
+ innerType: oldShape[key]
707
+ });
708
+ }
709
+ else for (const key in oldShape) shape[key] = new Class({
710
+ type: "nonoptional",
711
+ innerType: oldShape[key]
712
+ });
713
+ assignProp(this, "shape", shape);
714
+ return shape;
715
+ } }));
716
+ }
717
+ function aborted(x, startIndex = 0) {
718
+ if (x.aborted === true) return true;
719
+ for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true;
720
+ return false;
721
+ }
722
+ function prefixIssues(path, issues) {
723
+ return issues.map((iss) => {
724
+ var _a;
725
+ (_a = iss).path ?? (_a.path = []);
726
+ iss.path.unshift(path);
727
+ return iss;
728
+ });
729
+ }
730
+ function unwrapMessage(message) {
731
+ return typeof message === "string" ? message : message?.message;
732
+ }
733
+ function finalizeIssue(iss, ctx, config) {
734
+ const full = {
735
+ ...iss,
736
+ path: iss.path ?? []
737
+ };
738
+ if (!iss.message) full.message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
739
+ delete full.inst;
740
+ delete full.continue;
741
+ if (!ctx?.reportInput) delete full.input;
742
+ return full;
743
+ }
744
+ function getLengthableOrigin(input) {
745
+ if (Array.isArray(input)) return "array";
746
+ if (typeof input === "string") return "string";
747
+ return "unknown";
748
+ }
749
+ function issue(...args) {
750
+ const [iss, input, inst] = args;
751
+ if (typeof iss === "string") return {
752
+ message: iss,
753
+ code: "custom",
754
+ input,
755
+ inst
756
+ };
757
+ return { ...iss };
758
+ }
759
+ //#endregion
760
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js
761
+ const initializer$1 = (inst, def) => {
762
+ inst.name = "$ZodError";
763
+ Object.defineProperty(inst, "_zod", {
764
+ value: inst._zod,
765
+ enumerable: false
766
+ });
767
+ Object.defineProperty(inst, "issues", {
768
+ value: def,
769
+ enumerable: false
770
+ });
771
+ inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
772
+ Object.defineProperty(inst, "toString", {
773
+ value: () => inst.message,
774
+ enumerable: false
775
+ });
776
+ };
777
+ const $ZodError = $constructor("$ZodError", initializer$1);
778
+ const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
779
+ function flattenError(error, mapper = (issue) => issue.message) {
780
+ const fieldErrors = {};
781
+ const formErrors = [];
782
+ for (const sub of error.issues) if (sub.path.length > 0) {
783
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
784
+ fieldErrors[sub.path[0]].push(mapper(sub));
785
+ } else formErrors.push(mapper(sub));
786
+ return {
787
+ formErrors,
788
+ fieldErrors
789
+ };
790
+ }
791
+ function formatError(error, mapper = (issue) => issue.message) {
792
+ const fieldErrors = { _errors: [] };
793
+ const processError = (error) => {
794
+ for (const issue of error.issues) if (issue.code === "invalid_union" && issue.errors.length) issue.errors.map((issues) => processError({ issues }));
795
+ else if (issue.code === "invalid_key") processError({ issues: issue.issues });
796
+ else if (issue.code === "invalid_element") processError({ issues: issue.issues });
797
+ else if (issue.path.length === 0) fieldErrors._errors.push(mapper(issue));
798
+ else {
799
+ let curr = fieldErrors;
800
+ let i = 0;
801
+ while (i < issue.path.length) {
802
+ const el = issue.path[i];
803
+ if (!(i === issue.path.length - 1)) curr[el] = curr[el] || { _errors: [] };
804
+ else {
805
+ curr[el] = curr[el] || { _errors: [] };
806
+ curr[el]._errors.push(mapper(issue));
807
+ }
808
+ curr = curr[el];
809
+ i++;
810
+ }
811
+ }
812
+ };
813
+ processError(error);
814
+ return fieldErrors;
815
+ }
816
+ //#endregion
817
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js
818
+ const _parse = (_Err) => (schema, value, _ctx, _params) => {
819
+ const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
820
+ const result = schema._zod.run({
821
+ value,
822
+ issues: []
823
+ }, ctx);
824
+ if (result instanceof Promise) throw new $ZodAsyncError();
825
+ if (result.issues.length) {
826
+ const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config$1())));
827
+ captureStackTrace(e, _params?.callee);
828
+ throw e;
829
+ }
830
+ return result.value;
831
+ };
832
+ const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
833
+ const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
834
+ let result = schema._zod.run({
835
+ value,
836
+ issues: []
837
+ }, ctx);
838
+ if (result instanceof Promise) result = await result;
839
+ if (result.issues.length) {
840
+ const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config$1())));
841
+ captureStackTrace(e, params?.callee);
842
+ throw e;
843
+ }
844
+ return result.value;
845
+ };
846
+ const _safeParse = (_Err) => (schema, value, _ctx) => {
847
+ const ctx = _ctx ? {
848
+ ..._ctx,
849
+ async: false
850
+ } : { async: false };
851
+ const result = schema._zod.run({
852
+ value,
853
+ issues: []
854
+ }, ctx);
855
+ if (result instanceof Promise) throw new $ZodAsyncError();
856
+ return result.issues.length ? {
857
+ success: false,
858
+ error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config$1())))
859
+ } : {
860
+ success: true,
861
+ data: result.value
862
+ };
863
+ };
864
+ const safeParse$1 = /* @__PURE__ */ _safeParse($ZodRealError);
865
+ const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
866
+ const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
867
+ let result = schema._zod.run({
868
+ value,
869
+ issues: []
870
+ }, ctx);
871
+ if (result instanceof Promise) result = await result;
872
+ return result.issues.length ? {
873
+ success: false,
874
+ error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config$1())))
875
+ } : {
876
+ success: true,
877
+ data: result.value
878
+ };
879
+ };
880
+ const safeParseAsync$1 = /* @__PURE__ */ _safeParseAsync($ZodRealError);
881
+ const _encode = (_Err) => (schema, value, _ctx) => {
882
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
883
+ return _parse(_Err)(schema, value, ctx);
884
+ };
885
+ const _decode = (_Err) => (schema, value, _ctx) => {
886
+ return _parse(_Err)(schema, value, _ctx);
887
+ };
888
+ const _encodeAsync = (_Err) => async (schema, value, _ctx) => {
889
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
890
+ return _parseAsync(_Err)(schema, value, ctx);
891
+ };
892
+ const _decodeAsync = (_Err) => async (schema, value, _ctx) => {
893
+ return _parseAsync(_Err)(schema, value, _ctx);
894
+ };
895
+ const _safeEncode = (_Err) => (schema, value, _ctx) => {
896
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
897
+ return _safeParse(_Err)(schema, value, ctx);
898
+ };
899
+ const _safeDecode = (_Err) => (schema, value, _ctx) => {
900
+ return _safeParse(_Err)(schema, value, _ctx);
901
+ };
902
+ const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
903
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
904
+ return _safeParseAsync(_Err)(schema, value, ctx);
905
+ };
906
+ const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
907
+ return _safeParseAsync(_Err)(schema, value, _ctx);
908
+ };
909
+ const integer = /^-?\d+$/;
910
+ const number$1 = /^-?\d+(?:\.\d+)?$/;
911
+ //#endregion
912
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js
913
+ const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
914
+ var _a;
915
+ inst._zod ?? (inst._zod = {});
916
+ inst._zod.def = def;
917
+ (_a = inst._zod).onattach ?? (_a.onattach = []);
918
+ });
919
+ const numericOriginMap = {
920
+ number: "number",
921
+ bigint: "bigint",
922
+ object: "date"
923
+ };
924
+ const $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
925
+ $ZodCheck.init(inst, def);
926
+ const origin = numericOriginMap[typeof def.value];
927
+ inst._zod.onattach.push((inst) => {
928
+ const bag = inst._zod.bag;
929
+ const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
930
+ if (def.value < curr) if (def.inclusive) bag.maximum = def.value;
931
+ else bag.exclusiveMaximum = def.value;
932
+ });
933
+ inst._zod.check = (payload) => {
934
+ if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return;
935
+ payload.issues.push({
936
+ origin,
937
+ code: "too_big",
938
+ maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
939
+ input: payload.value,
940
+ inclusive: def.inclusive,
941
+ inst,
942
+ continue: !def.abort
943
+ });
944
+ };
945
+ });
946
+ const $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
947
+ $ZodCheck.init(inst, def);
948
+ const origin = numericOriginMap[typeof def.value];
949
+ inst._zod.onattach.push((inst) => {
950
+ const bag = inst._zod.bag;
951
+ const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
952
+ if (def.value > curr) if (def.inclusive) bag.minimum = def.value;
953
+ else bag.exclusiveMinimum = def.value;
954
+ });
955
+ inst._zod.check = (payload) => {
956
+ if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return;
957
+ payload.issues.push({
958
+ origin,
959
+ code: "too_small",
960
+ minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
961
+ input: payload.value,
962
+ inclusive: def.inclusive,
963
+ inst,
964
+ continue: !def.abort
965
+ });
966
+ };
967
+ });
968
+ const $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
969
+ $ZodCheck.init(inst, def);
970
+ inst._zod.onattach.push((inst) => {
971
+ var _a;
972
+ (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
973
+ });
974
+ inst._zod.check = (payload) => {
975
+ if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check.");
976
+ if (typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0) return;
977
+ payload.issues.push({
978
+ origin: typeof payload.value,
979
+ code: "not_multiple_of",
980
+ divisor: def.value,
981
+ input: payload.value,
982
+ inst,
983
+ continue: !def.abort
984
+ });
985
+ };
986
+ });
987
+ const $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
988
+ $ZodCheck.init(inst, def);
989
+ def.format = def.format || "float64";
990
+ const isInt = def.format?.includes("int");
991
+ const origin = isInt ? "int" : "number";
992
+ const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
993
+ inst._zod.onattach.push((inst) => {
994
+ const bag = inst._zod.bag;
995
+ bag.format = def.format;
996
+ bag.minimum = minimum;
997
+ bag.maximum = maximum;
998
+ if (isInt) bag.pattern = integer;
999
+ });
1000
+ inst._zod.check = (payload) => {
1001
+ const input = payload.value;
1002
+ if (isInt) {
1003
+ if (!Number.isInteger(input)) {
1004
+ payload.issues.push({
1005
+ expected: origin,
1006
+ format: def.format,
1007
+ code: "invalid_type",
1008
+ continue: false,
1009
+ input,
1010
+ inst
1011
+ });
1012
+ return;
1013
+ }
1014
+ if (!Number.isSafeInteger(input)) {
1015
+ if (input > 0) payload.issues.push({
1016
+ input,
1017
+ code: "too_big",
1018
+ maximum: Number.MAX_SAFE_INTEGER,
1019
+ note: "Integers must be within the safe integer range.",
1020
+ inst,
1021
+ origin,
1022
+ inclusive: true,
1023
+ continue: !def.abort
1024
+ });
1025
+ else payload.issues.push({
1026
+ input,
1027
+ code: "too_small",
1028
+ minimum: Number.MIN_SAFE_INTEGER,
1029
+ note: "Integers must be within the safe integer range.",
1030
+ inst,
1031
+ origin,
1032
+ inclusive: true,
1033
+ continue: !def.abort
1034
+ });
1035
+ return;
1036
+ }
1037
+ }
1038
+ if (input < minimum) payload.issues.push({
1039
+ origin: "number",
1040
+ input,
1041
+ code: "too_small",
1042
+ minimum,
1043
+ inclusive: true,
1044
+ inst,
1045
+ continue: !def.abort
1046
+ });
1047
+ if (input > maximum) payload.issues.push({
1048
+ origin: "number",
1049
+ input,
1050
+ code: "too_big",
1051
+ maximum,
1052
+ inclusive: true,
1053
+ inst,
1054
+ continue: !def.abort
1055
+ });
1056
+ };
1057
+ });
1058
+ const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
1059
+ var _a;
1060
+ $ZodCheck.init(inst, def);
1061
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1062
+ const val = payload.value;
1063
+ return !nullish(val) && val.length !== void 0;
1064
+ });
1065
+ inst._zod.onattach.push((inst) => {
1066
+ const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
1067
+ if (def.maximum < curr) inst._zod.bag.maximum = def.maximum;
1068
+ });
1069
+ inst._zod.check = (payload) => {
1070
+ const input = payload.value;
1071
+ if (input.length <= def.maximum) return;
1072
+ const origin = getLengthableOrigin(input);
1073
+ payload.issues.push({
1074
+ origin,
1075
+ code: "too_big",
1076
+ maximum: def.maximum,
1077
+ inclusive: true,
1078
+ input,
1079
+ inst,
1080
+ continue: !def.abort
1081
+ });
1082
+ };
1083
+ });
1084
+ const $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
1085
+ var _a;
1086
+ $ZodCheck.init(inst, def);
1087
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1088
+ const val = payload.value;
1089
+ return !nullish(val) && val.length !== void 0;
1090
+ });
1091
+ inst._zod.onattach.push((inst) => {
1092
+ const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
1093
+ if (def.minimum > curr) inst._zod.bag.minimum = def.minimum;
1094
+ });
1095
+ inst._zod.check = (payload) => {
1096
+ const input = payload.value;
1097
+ if (input.length >= def.minimum) return;
1098
+ const origin = getLengthableOrigin(input);
1099
+ payload.issues.push({
1100
+ origin,
1101
+ code: "too_small",
1102
+ minimum: def.minimum,
1103
+ inclusive: true,
1104
+ input,
1105
+ inst,
1106
+ continue: !def.abort
1107
+ });
1108
+ };
1109
+ });
1110
+ const $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
1111
+ var _a;
1112
+ $ZodCheck.init(inst, def);
1113
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1114
+ const val = payload.value;
1115
+ return !nullish(val) && val.length !== void 0;
1116
+ });
1117
+ inst._zod.onattach.push((inst) => {
1118
+ const bag = inst._zod.bag;
1119
+ bag.minimum = def.length;
1120
+ bag.maximum = def.length;
1121
+ bag.length = def.length;
1122
+ });
1123
+ inst._zod.check = (payload) => {
1124
+ const input = payload.value;
1125
+ const length = input.length;
1126
+ if (length === def.length) return;
1127
+ const origin = getLengthableOrigin(input);
1128
+ const tooBig = length > def.length;
1129
+ payload.issues.push({
1130
+ origin,
1131
+ ...tooBig ? {
1132
+ code: "too_big",
1133
+ maximum: def.length
1134
+ } : {
1135
+ code: "too_small",
1136
+ minimum: def.length
1137
+ },
1138
+ inclusive: true,
1139
+ exact: true,
1140
+ input: payload.value,
1141
+ inst,
1142
+ continue: !def.abort
1143
+ });
1144
+ };
1145
+ });
1146
+ const $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
1147
+ $ZodCheck.init(inst, def);
1148
+ inst._zod.check = (payload) => {
1149
+ payload.value = def.tx(payload.value);
1150
+ };
1151
+ });
1152
+ //#endregion
1153
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js
1154
+ var Doc = class {
1155
+ constructor(args = []) {
1156
+ this.content = [];
1157
+ this.indent = 0;
1158
+ if (this) this.args = args;
1159
+ }
1160
+ indented(fn) {
1161
+ this.indent += 1;
1162
+ fn(this);
1163
+ this.indent -= 1;
1164
+ }
1165
+ write(arg) {
1166
+ if (typeof arg === "function") {
1167
+ arg(this, { execution: "sync" });
1168
+ arg(this, { execution: "async" });
1169
+ return;
1170
+ }
1171
+ const lines = arg.split("\n").filter((x) => x);
1172
+ const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
1173
+ const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
1174
+ for (const line of dedented) this.content.push(line);
1175
+ }
1176
+ compile() {
1177
+ const F = Function;
1178
+ const args = this?.args;
1179
+ const lines = [...(this?.content ?? [``]).map((x) => ` ${x}`)];
1180
+ return new F(...args, lines.join("\n"));
1181
+ }
1182
+ };
1183
+ //#endregion
1184
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js
1185
+ const version = {
1186
+ major: 4,
1187
+ minor: 3,
1188
+ patch: 6
1189
+ };
1190
+ //#endregion
1191
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js
1192
+ const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
1193
+ var _a;
1194
+ inst ?? (inst = {});
1195
+ inst._zod.def = def;
1196
+ inst._zod.bag = inst._zod.bag || {};
1197
+ inst._zod.version = version;
1198
+ const checks = [...inst._zod.def.checks ?? []];
1199
+ if (inst._zod.traits.has("$ZodCheck")) checks.unshift(inst);
1200
+ for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst);
1201
+ if (checks.length === 0) {
1202
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
1203
+ inst._zod.deferred?.push(() => {
1204
+ inst._zod.run = inst._zod.parse;
1205
+ });
1206
+ } else {
1207
+ const runChecks = (payload, checks, ctx) => {
1208
+ let isAborted = aborted(payload);
1209
+ let asyncResult;
1210
+ for (const ch of checks) {
1211
+ if (ch._zod.def.when) {
1212
+ if (!ch._zod.def.when(payload)) continue;
1213
+ } else if (isAborted) continue;
1214
+ const currLen = payload.issues.length;
1215
+ const _ = ch._zod.check(payload);
1216
+ if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError();
1217
+ if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
1218
+ await _;
1219
+ if (payload.issues.length === currLen) return;
1220
+ if (!isAborted) isAborted = aborted(payload, currLen);
1221
+ });
1222
+ else {
1223
+ if (payload.issues.length === currLen) continue;
1224
+ if (!isAborted) isAborted = aborted(payload, currLen);
1225
+ }
1226
+ }
1227
+ if (asyncResult) return asyncResult.then(() => {
1228
+ return payload;
1229
+ });
1230
+ return payload;
1231
+ };
1232
+ const handleCanaryResult = (canary, payload, ctx) => {
1233
+ if (aborted(canary)) {
1234
+ canary.aborted = true;
1235
+ return canary;
1236
+ }
1237
+ const checkResult = runChecks(payload, checks, ctx);
1238
+ if (checkResult instanceof Promise) {
1239
+ if (ctx.async === false) throw new $ZodAsyncError();
1240
+ return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));
1241
+ }
1242
+ return inst._zod.parse(checkResult, ctx);
1243
+ };
1244
+ inst._zod.run = (payload, ctx) => {
1245
+ if (ctx.skipChecks) return inst._zod.parse(payload, ctx);
1246
+ if (ctx.direction === "backward") {
1247
+ const canary = inst._zod.parse({
1248
+ value: payload.value,
1249
+ issues: []
1250
+ }, {
1251
+ ...ctx,
1252
+ skipChecks: true
1253
+ });
1254
+ if (canary instanceof Promise) return canary.then((canary) => {
1255
+ return handleCanaryResult(canary, payload, ctx);
1256
+ });
1257
+ return handleCanaryResult(canary, payload, ctx);
1258
+ }
1259
+ const result = inst._zod.parse(payload, ctx);
1260
+ if (result instanceof Promise) {
1261
+ if (ctx.async === false) throw new $ZodAsyncError();
1262
+ return result.then((result) => runChecks(result, checks, ctx));
1263
+ }
1264
+ return runChecks(result, checks, ctx);
1265
+ };
1266
+ }
1267
+ defineLazy(inst, "~standard", () => ({
1268
+ validate: (value) => {
1269
+ try {
1270
+ const r = safeParse$1(inst, value);
1271
+ return r.success ? { value: r.data } : { issues: r.error?.issues };
1272
+ } catch (_) {
1273
+ return safeParseAsync$1(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
1274
+ }
1275
+ },
1276
+ vendor: "zod",
1277
+ version: 1
1278
+ }));
1279
+ });
1280
+ const $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
1281
+ $ZodType.init(inst, def);
1282
+ inst._zod.pattern = inst._zod.bag.pattern ?? number$1;
1283
+ inst._zod.parse = (payload, _ctx) => {
1284
+ if (def.coerce) try {
1285
+ payload.value = Number(payload.value);
1286
+ } catch (_) {}
1287
+ const input = payload.value;
1288
+ if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) return payload;
1289
+ const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
1290
+ payload.issues.push({
1291
+ expected: "number",
1292
+ code: "invalid_type",
1293
+ input,
1294
+ inst,
1295
+ ...received ? { received } : {}
1296
+ });
1297
+ return payload;
1298
+ };
1299
+ });
1300
+ const $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => {
1301
+ $ZodCheckNumberFormat.init(inst, def);
1302
+ $ZodNumber.init(inst, def);
1303
+ });
1304
+ const $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
1305
+ $ZodType.init(inst, def);
1306
+ inst._zod.parse = (payload) => payload;
1307
+ });
1308
+ const $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
1309
+ $ZodType.init(inst, def);
1310
+ inst._zod.parse = (payload, _ctx) => {
1311
+ payload.issues.push({
1312
+ expected: "never",
1313
+ code: "invalid_type",
1314
+ input: payload.value,
1315
+ inst
1316
+ });
1317
+ return payload;
1318
+ };
1319
+ });
1320
+ function handleArrayResult(result, final, index) {
1321
+ if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues));
1322
+ final.value[index] = result.value;
1323
+ }
1324
+ const $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
1325
+ $ZodType.init(inst, def);
1326
+ inst._zod.parse = (payload, ctx) => {
1327
+ const input = payload.value;
1328
+ if (!Array.isArray(input)) {
1329
+ payload.issues.push({
1330
+ expected: "array",
1331
+ code: "invalid_type",
1332
+ input,
1333
+ inst
1334
+ });
1335
+ return payload;
1336
+ }
1337
+ payload.value = Array(input.length);
1338
+ const proms = [];
1339
+ for (let i = 0; i < input.length; i++) {
1340
+ const item = input[i];
1341
+ const result = def.element._zod.run({
1342
+ value: item,
1343
+ issues: []
1344
+ }, ctx);
1345
+ if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i)));
1346
+ else handleArrayResult(result, payload, i);
1347
+ }
1348
+ if (proms.length) return Promise.all(proms).then(() => payload);
1349
+ return payload;
1350
+ };
1351
+ });
1352
+ function handlePropertyResult(result, final, key, input, isOptionalOut) {
1353
+ if (result.issues.length) {
1354
+ if (isOptionalOut && !(key in input)) return;
1355
+ final.issues.push(...prefixIssues(key, result.issues));
1356
+ }
1357
+ if (result.value === void 0) {
1358
+ if (key in input) final.value[key] = void 0;
1359
+ } else final.value[key] = result.value;
1360
+ }
1361
+ function normalizeDef(def) {
1362
+ const keys = Object.keys(def.shape);
1363
+ for (const k of keys) if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
1364
+ const okeys = optionalKeys(def.shape);
1365
+ return {
1366
+ ...def,
1367
+ keys,
1368
+ keySet: new Set(keys),
1369
+ numKeys: keys.length,
1370
+ optionalKeys: new Set(okeys)
1371
+ };
1372
+ }
1373
+ function handleCatchall(proms, input, payload, ctx, def, inst) {
1374
+ const unrecognized = [];
1375
+ const keySet = def.keySet;
1376
+ const _catchall = def.catchall._zod;
1377
+ const t = _catchall.def.type;
1378
+ const isOptionalOut = _catchall.optout === "optional";
1379
+ for (const key in input) {
1380
+ if (keySet.has(key)) continue;
1381
+ if (t === "never") {
1382
+ unrecognized.push(key);
1383
+ continue;
1384
+ }
1385
+ const r = _catchall.run({
1386
+ value: input[key],
1387
+ issues: []
1388
+ }, ctx);
1389
+ if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));
1390
+ else handlePropertyResult(r, payload, key, input, isOptionalOut);
1391
+ }
1392
+ if (unrecognized.length) payload.issues.push({
1393
+ code: "unrecognized_keys",
1394
+ keys: unrecognized,
1395
+ input,
1396
+ inst
1397
+ });
1398
+ if (!proms.length) return payload;
1399
+ return Promise.all(proms).then(() => {
1400
+ return payload;
1401
+ });
1402
+ }
1403
+ const $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
1404
+ $ZodType.init(inst, def);
1405
+ if (!Object.getOwnPropertyDescriptor(def, "shape")?.get) {
1406
+ const sh = def.shape;
1407
+ Object.defineProperty(def, "shape", { get: () => {
1408
+ const newSh = { ...sh };
1409
+ Object.defineProperty(def, "shape", { value: newSh });
1410
+ return newSh;
1411
+ } });
1412
+ }
1413
+ const _normalized = cached(() => normalizeDef(def));
1414
+ defineLazy(inst._zod, "propValues", () => {
1415
+ const shape = def.shape;
1416
+ const propValues = {};
1417
+ for (const key in shape) {
1418
+ const field = shape[key]._zod;
1419
+ if (field.values) {
1420
+ propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
1421
+ for (const v of field.values) propValues[key].add(v);
1422
+ }
1423
+ }
1424
+ return propValues;
1425
+ });
1426
+ const isObject = isObject$1;
1427
+ const catchall = def.catchall;
1428
+ let value;
1429
+ inst._zod.parse = (payload, ctx) => {
1430
+ value ?? (value = _normalized.value);
1431
+ const input = payload.value;
1432
+ if (!isObject(input)) {
1433
+ payload.issues.push({
1434
+ expected: "object",
1435
+ code: "invalid_type",
1436
+ input,
1437
+ inst
1438
+ });
1439
+ return payload;
1440
+ }
1441
+ payload.value = {};
1442
+ const proms = [];
1443
+ const shape = value.shape;
1444
+ for (const key of value.keys) {
1445
+ const el = shape[key];
1446
+ const isOptionalOut = el._zod.optout === "optional";
1447
+ const r = el._zod.run({
1448
+ value: input[key],
1449
+ issues: []
1450
+ }, ctx);
1451
+ if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));
1452
+ else handlePropertyResult(r, payload, key, input, isOptionalOut);
1453
+ }
1454
+ if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload;
1455
+ return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
1456
+ };
1457
+ });
1458
+ const $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
1459
+ $ZodObject.init(inst, def);
1460
+ const superParse = inst._zod.parse;
1461
+ const _normalized = cached(() => normalizeDef(def));
1462
+ const generateFastpass = (shape) => {
1463
+ const doc = new Doc([
1464
+ "shape",
1465
+ "payload",
1466
+ "ctx"
1467
+ ]);
1468
+ const normalized = _normalized.value;
1469
+ const parseStr = (key) => {
1470
+ const k = esc(key);
1471
+ return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
1472
+ };
1473
+ doc.write(`const input = payload.value;`);
1474
+ const ids = Object.create(null);
1475
+ let counter = 0;
1476
+ for (const key of normalized.keys) ids[key] = `key_${counter++}`;
1477
+ doc.write(`const newResult = {};`);
1478
+ for (const key of normalized.keys) {
1479
+ const id = ids[key];
1480
+ const k = esc(key);
1481
+ const isOptionalOut = shape[key]?._zod?.optout === "optional";
1482
+ doc.write(`const ${id} = ${parseStr(key)};`);
1483
+ if (isOptionalOut) doc.write(`
1484
+ if (${id}.issues.length) {
1485
+ if (${k} in input) {
1486
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
1487
+ ...iss,
1488
+ path: iss.path ? [${k}, ...iss.path] : [${k}]
1489
+ })));
1490
+ }
1491
+ }
1492
+
1493
+ if (${id}.value === undefined) {
1494
+ if (${k} in input) {
1495
+ newResult[${k}] = undefined;
1496
+ }
1497
+ } else {
1498
+ newResult[${k}] = ${id}.value;
1499
+ }
1500
+
1501
+ `);
1502
+ else doc.write(`
1503
+ if (${id}.issues.length) {
1504
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
1505
+ ...iss,
1506
+ path: iss.path ? [${k}, ...iss.path] : [${k}]
1507
+ })));
1508
+ }
1509
+
1510
+ if (${id}.value === undefined) {
1511
+ if (${k} in input) {
1512
+ newResult[${k}] = undefined;
1513
+ }
1514
+ } else {
1515
+ newResult[${k}] = ${id}.value;
1516
+ }
1517
+
1518
+ `);
1519
+ }
1520
+ doc.write(`payload.value = newResult;`);
1521
+ doc.write(`return payload;`);
1522
+ const fn = doc.compile();
1523
+ return (payload, ctx) => fn(shape, payload, ctx);
1524
+ };
1525
+ let fastpass;
1526
+ const isObject = isObject$1;
1527
+ const jit = !globalConfig.jitless;
1528
+ const fastEnabled = jit && allowsEval.value;
1529
+ const catchall = def.catchall;
1530
+ let value;
1531
+ inst._zod.parse = (payload, ctx) => {
1532
+ value ?? (value = _normalized.value);
1533
+ const input = payload.value;
1534
+ if (!isObject(input)) {
1535
+ payload.issues.push({
1536
+ expected: "object",
1537
+ code: "invalid_type",
1538
+ input,
1539
+ inst
1540
+ });
1541
+ return payload;
1542
+ }
1543
+ if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
1544
+ if (!fastpass) fastpass = generateFastpass(def.shape);
1545
+ payload = fastpass(payload, ctx);
1546
+ if (!catchall) return payload;
1547
+ return handleCatchall([], input, payload, ctx, value, inst);
1548
+ }
1549
+ return superParse(payload, ctx);
1550
+ };
1551
+ });
1552
+ function handleUnionResults(results, final, inst, ctx) {
1553
+ for (const result of results) if (result.issues.length === 0) {
1554
+ final.value = result.value;
1555
+ return final;
1556
+ }
1557
+ const nonaborted = results.filter((r) => !aborted(r));
1558
+ if (nonaborted.length === 1) {
1559
+ final.value = nonaborted[0].value;
1560
+ return nonaborted[0];
1561
+ }
1562
+ final.issues.push({
1563
+ code: "invalid_union",
1564
+ input: final.value,
1565
+ inst,
1566
+ errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config$1())))
1567
+ });
1568
+ return final;
1569
+ }
1570
+ const $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
1571
+ $ZodType.init(inst, def);
1572
+ defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);
1573
+ defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
1574
+ defineLazy(inst._zod, "values", () => {
1575
+ if (def.options.every((o) => o._zod.values)) return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
1576
+ });
1577
+ defineLazy(inst._zod, "pattern", () => {
1578
+ if (def.options.every((o) => o._zod.pattern)) {
1579
+ const patterns = def.options.map((o) => o._zod.pattern);
1580
+ return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
1581
+ }
1582
+ });
1583
+ const single = def.options.length === 1;
1584
+ const first = def.options[0]._zod.run;
1585
+ inst._zod.parse = (payload, ctx) => {
1586
+ if (single) return first(payload, ctx);
1587
+ let async = false;
1588
+ const results = [];
1589
+ for (const option of def.options) {
1590
+ const result = option._zod.run({
1591
+ value: payload.value,
1592
+ issues: []
1593
+ }, ctx);
1594
+ if (result instanceof Promise) {
1595
+ results.push(result);
1596
+ async = true;
1597
+ } else {
1598
+ if (result.issues.length === 0) return result;
1599
+ results.push(result);
1600
+ }
1601
+ }
1602
+ if (!async) return handleUnionResults(results, payload, inst, ctx);
1603
+ return Promise.all(results).then((results) => {
1604
+ return handleUnionResults(results, payload, inst, ctx);
1605
+ });
1606
+ };
1607
+ });
1608
+ const $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
1609
+ $ZodType.init(inst, def);
1610
+ inst._zod.parse = (payload, ctx) => {
1611
+ const input = payload.value;
1612
+ const left = def.left._zod.run({
1613
+ value: input,
1614
+ issues: []
1615
+ }, ctx);
1616
+ const right = def.right._zod.run({
1617
+ value: input,
1618
+ issues: []
1619
+ }, ctx);
1620
+ if (left instanceof Promise || right instanceof Promise) return Promise.all([left, right]).then(([left, right]) => {
1621
+ return handleIntersectionResults(payload, left, right);
1622
+ });
1623
+ return handleIntersectionResults(payload, left, right);
1624
+ };
1625
+ });
1626
+ function mergeValues(a, b) {
1627
+ if (a === b) return {
1628
+ valid: true,
1629
+ data: a
1630
+ };
1631
+ if (a instanceof Date && b instanceof Date && +a === +b) return {
1632
+ valid: true,
1633
+ data: a
1634
+ };
1635
+ if (isPlainObject$1(a) && isPlainObject$1(b)) {
1636
+ const bKeys = Object.keys(b);
1637
+ const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
1638
+ const newObj = {
1639
+ ...a,
1640
+ ...b
1641
+ };
1642
+ for (const key of sharedKeys) {
1643
+ const sharedValue = mergeValues(a[key], b[key]);
1644
+ if (!sharedValue.valid) return {
1645
+ valid: false,
1646
+ mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
1647
+ };
1648
+ newObj[key] = sharedValue.data;
1649
+ }
1650
+ return {
1651
+ valid: true,
1652
+ data: newObj
1653
+ };
1654
+ }
1655
+ if (Array.isArray(a) && Array.isArray(b)) {
1656
+ if (a.length !== b.length) return {
1657
+ valid: false,
1658
+ mergeErrorPath: []
1659
+ };
1660
+ const newArray = [];
1661
+ for (let index = 0; index < a.length; index++) {
1662
+ const itemA = a[index];
1663
+ const itemB = b[index];
1664
+ const sharedValue = mergeValues(itemA, itemB);
1665
+ if (!sharedValue.valid) return {
1666
+ valid: false,
1667
+ mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
1668
+ };
1669
+ newArray.push(sharedValue.data);
1670
+ }
1671
+ return {
1672
+ valid: true,
1673
+ data: newArray
1674
+ };
1675
+ }
1676
+ return {
1677
+ valid: false,
1678
+ mergeErrorPath: []
1679
+ };
1680
+ }
1681
+ function handleIntersectionResults(result, left, right) {
1682
+ const unrecKeys = /* @__PURE__ */ new Map();
1683
+ let unrecIssue;
1684
+ for (const iss of left.issues) if (iss.code === "unrecognized_keys") {
1685
+ unrecIssue ?? (unrecIssue = iss);
1686
+ for (const k of iss.keys) {
1687
+ if (!unrecKeys.has(k)) unrecKeys.set(k, {});
1688
+ unrecKeys.get(k).l = true;
1689
+ }
1690
+ } else result.issues.push(iss);
1691
+ for (const iss of right.issues) if (iss.code === "unrecognized_keys") for (const k of iss.keys) {
1692
+ if (!unrecKeys.has(k)) unrecKeys.set(k, {});
1693
+ unrecKeys.get(k).r = true;
1694
+ }
1695
+ else result.issues.push(iss);
1696
+ const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
1697
+ if (bothKeys.length && unrecIssue) result.issues.push({
1698
+ ...unrecIssue,
1699
+ keys: bothKeys
1700
+ });
1701
+ if (aborted(result)) return result;
1702
+ const merged = mergeValues(left.value, right.value);
1703
+ if (!merged.valid) throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
1704
+ result.value = merged.data;
1705
+ return result;
1706
+ }
1707
+ const $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
1708
+ $ZodType.init(inst, def);
1709
+ const values = getEnumValues(def.entries);
1710
+ const valuesSet = new Set(values);
1711
+ inst._zod.values = valuesSet;
1712
+ inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
1713
+ inst._zod.parse = (payload, _ctx) => {
1714
+ const input = payload.value;
1715
+ if (valuesSet.has(input)) return payload;
1716
+ payload.issues.push({
1717
+ code: "invalid_value",
1718
+ values,
1719
+ input,
1720
+ inst
1721
+ });
1722
+ return payload;
1723
+ };
1724
+ });
1725
+ const $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
1726
+ $ZodType.init(inst, def);
1727
+ inst._zod.parse = (payload, ctx) => {
1728
+ if (ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name);
1729
+ const _out = def.transform(payload.value, payload);
1730
+ if (ctx.async) return (_out instanceof Promise ? _out : Promise.resolve(_out)).then((output) => {
1731
+ payload.value = output;
1732
+ return payload;
1733
+ });
1734
+ if (_out instanceof Promise) throw new $ZodAsyncError();
1735
+ payload.value = _out;
1736
+ return payload;
1737
+ };
1738
+ });
1739
+ function handleOptionalResult(result, input) {
1740
+ if (result.issues.length && input === void 0) return {
1741
+ issues: [],
1742
+ value: void 0
1743
+ };
1744
+ return result;
1745
+ }
1746
+ const $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
1747
+ $ZodType.init(inst, def);
1748
+ inst._zod.optin = "optional";
1749
+ inst._zod.optout = "optional";
1750
+ defineLazy(inst._zod, "values", () => {
1751
+ return def.innerType._zod.values ? new Set([...def.innerType._zod.values, void 0]) : void 0;
1752
+ });
1753
+ defineLazy(inst._zod, "pattern", () => {
1754
+ const pattern = def.innerType._zod.pattern;
1755
+ return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
1756
+ });
1757
+ inst._zod.parse = (payload, ctx) => {
1758
+ if (def.innerType._zod.optin === "optional") {
1759
+ const result = def.innerType._zod.run(payload, ctx);
1760
+ if (result instanceof Promise) return result.then((r) => handleOptionalResult(r, payload.value));
1761
+ return handleOptionalResult(result, payload.value);
1762
+ }
1763
+ if (payload.value === void 0) return payload;
1764
+ return def.innerType._zod.run(payload, ctx);
1765
+ };
1766
+ });
1767
+ const $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => {
1768
+ $ZodOptional.init(inst, def);
1769
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1770
+ defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
1771
+ inst._zod.parse = (payload, ctx) => {
1772
+ return def.innerType._zod.run(payload, ctx);
1773
+ };
1774
+ });
1775
+ const $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
1776
+ $ZodType.init(inst, def);
1777
+ defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
1778
+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1779
+ defineLazy(inst._zod, "pattern", () => {
1780
+ const pattern = def.innerType._zod.pattern;
1781
+ return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
1782
+ });
1783
+ defineLazy(inst._zod, "values", () => {
1784
+ return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : void 0;
1785
+ });
1786
+ inst._zod.parse = (payload, ctx) => {
1787
+ if (payload.value === null) return payload;
1788
+ return def.innerType._zod.run(payload, ctx);
1789
+ };
1790
+ });
1791
+ const $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
1792
+ $ZodType.init(inst, def);
1793
+ inst._zod.optin = "optional";
1794
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1795
+ inst._zod.parse = (payload, ctx) => {
1796
+ if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
1797
+ if (payload.value === void 0) {
1798
+ payload.value = def.defaultValue;
1799
+ /**
1800
+ * $ZodDefault returns the default value immediately in forward direction.
1801
+ * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */
1802
+ return payload;
1803
+ }
1804
+ const result = def.innerType._zod.run(payload, ctx);
1805
+ if (result instanceof Promise) return result.then((result) => handleDefaultResult(result, def));
1806
+ return handleDefaultResult(result, def);
1807
+ };
1808
+ });
1809
+ function handleDefaultResult(payload, def) {
1810
+ if (payload.value === void 0) payload.value = def.defaultValue;
1811
+ return payload;
1812
+ }
1813
+ const $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
1814
+ $ZodType.init(inst, def);
1815
+ inst._zod.optin = "optional";
1816
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1817
+ inst._zod.parse = (payload, ctx) => {
1818
+ if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
1819
+ if (payload.value === void 0) payload.value = def.defaultValue;
1820
+ return def.innerType._zod.run(payload, ctx);
1821
+ };
1822
+ });
1823
+ const $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
1824
+ $ZodType.init(inst, def);
1825
+ defineLazy(inst._zod, "values", () => {
1826
+ const v = def.innerType._zod.values;
1827
+ return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;
1828
+ });
1829
+ inst._zod.parse = (payload, ctx) => {
1830
+ const result = def.innerType._zod.run(payload, ctx);
1831
+ if (result instanceof Promise) return result.then((result) => handleNonOptionalResult(result, inst));
1832
+ return handleNonOptionalResult(result, inst);
1833
+ };
1834
+ });
1835
+ function handleNonOptionalResult(payload, inst) {
1836
+ if (!payload.issues.length && payload.value === void 0) payload.issues.push({
1837
+ code: "invalid_type",
1838
+ expected: "nonoptional",
1839
+ input: payload.value,
1840
+ inst
1841
+ });
1842
+ return payload;
1843
+ }
1844
+ const $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
1845
+ $ZodType.init(inst, def);
1846
+ defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
1847
+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1848
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1849
+ inst._zod.parse = (payload, ctx) => {
1850
+ if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
1851
+ const result = def.innerType._zod.run(payload, ctx);
1852
+ if (result instanceof Promise) return result.then((result) => {
1853
+ payload.value = result.value;
1854
+ if (result.issues.length) {
1855
+ payload.value = def.catchValue({
1856
+ ...payload,
1857
+ error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config$1())) },
1858
+ input: payload.value
1859
+ });
1860
+ payload.issues = [];
1861
+ }
1862
+ return payload;
1863
+ });
1864
+ payload.value = result.value;
1865
+ if (result.issues.length) {
1866
+ payload.value = def.catchValue({
1867
+ ...payload,
1868
+ error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config$1())) },
1869
+ input: payload.value
1870
+ });
1871
+ payload.issues = [];
1872
+ }
1873
+ return payload;
1874
+ };
1875
+ });
1876
+ const $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
1877
+ $ZodType.init(inst, def);
1878
+ defineLazy(inst._zod, "values", () => def.in._zod.values);
1879
+ defineLazy(inst._zod, "optin", () => def.in._zod.optin);
1880
+ defineLazy(inst._zod, "optout", () => def.out._zod.optout);
1881
+ defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
1882
+ inst._zod.parse = (payload, ctx) => {
1883
+ if (ctx.direction === "backward") {
1884
+ const right = def.out._zod.run(payload, ctx);
1885
+ if (right instanceof Promise) return right.then((right) => handlePipeResult(right, def.in, ctx));
1886
+ return handlePipeResult(right, def.in, ctx);
1887
+ }
1888
+ const left = def.in._zod.run(payload, ctx);
1889
+ if (left instanceof Promise) return left.then((left) => handlePipeResult(left, def.out, ctx));
1890
+ return handlePipeResult(left, def.out, ctx);
1891
+ };
1892
+ });
1893
+ function handlePipeResult(left, next, ctx) {
1894
+ if (left.issues.length) {
1895
+ left.aborted = true;
1896
+ return left;
1897
+ }
1898
+ return next._zod.run({
1899
+ value: left.value,
1900
+ issues: left.issues
1901
+ }, ctx);
1902
+ }
1903
+ const $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
1904
+ $ZodType.init(inst, def);
1905
+ defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
1906
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1907
+ defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
1908
+ defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
1909
+ inst._zod.parse = (payload, ctx) => {
1910
+ if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
1911
+ const result = def.innerType._zod.run(payload, ctx);
1912
+ if (result instanceof Promise) return result.then(handleReadonlyResult);
1913
+ return handleReadonlyResult(result);
1914
+ };
1915
+ });
1916
+ function handleReadonlyResult(payload) {
1917
+ payload.value = Object.freeze(payload.value);
1918
+ return payload;
1919
+ }
1920
+ const $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
1921
+ $ZodCheck.init(inst, def);
1922
+ $ZodType.init(inst, def);
1923
+ inst._zod.parse = (payload, _) => {
1924
+ return payload;
1925
+ };
1926
+ inst._zod.check = (payload) => {
1927
+ const input = payload.value;
1928
+ const r = def.fn(input);
1929
+ if (r instanceof Promise) return r.then((r) => handleRefineResult(r, payload, input, inst));
1930
+ handleRefineResult(r, payload, input, inst);
1931
+ };
1932
+ });
1933
+ function handleRefineResult(result, payload, input, inst) {
1934
+ if (!result) {
1935
+ const _iss = {
1936
+ code: "custom",
1937
+ input,
1938
+ inst,
1939
+ path: [...inst._zod.def.path ?? []],
1940
+ continue: !inst._zod.def.abort
1941
+ };
1942
+ if (inst._zod.def.params) _iss.params = inst._zod.def.params;
1943
+ payload.issues.push(issue(_iss));
1944
+ }
1945
+ }
1946
+ //#endregion
1947
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js
1948
+ var _a;
1949
+ var $ZodRegistry = class {
1950
+ constructor() {
1951
+ this._map = /* @__PURE__ */ new WeakMap();
1952
+ this._idmap = /* @__PURE__ */ new Map();
1953
+ }
1954
+ add(schema, ..._meta) {
1955
+ const meta = _meta[0];
1956
+ this._map.set(schema, meta);
1957
+ if (meta && typeof meta === "object" && "id" in meta) this._idmap.set(meta.id, schema);
1958
+ return this;
1959
+ }
1960
+ clear() {
1961
+ this._map = /* @__PURE__ */ new WeakMap();
1962
+ this._idmap = /* @__PURE__ */ new Map();
1963
+ return this;
1964
+ }
1965
+ remove(schema) {
1966
+ const meta = this._map.get(schema);
1967
+ if (meta && typeof meta === "object" && "id" in meta) this._idmap.delete(meta.id);
1968
+ this._map.delete(schema);
1969
+ return this;
1970
+ }
1971
+ get(schema) {
1972
+ const p = schema._zod.parent;
1973
+ if (p) {
1974
+ const pm = { ...this.get(p) ?? {} };
1975
+ delete pm.id;
1976
+ const f = {
1977
+ ...pm,
1978
+ ...this._map.get(schema)
1979
+ };
1980
+ return Object.keys(f).length ? f : void 0;
1981
+ }
1982
+ return this._map.get(schema);
1983
+ }
1984
+ has(schema) {
1985
+ return this._map.has(schema);
1986
+ }
1987
+ };
1988
+ function registry() {
1989
+ return new $ZodRegistry();
1990
+ }
1991
+ (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
1992
+ const globalRegistry = globalThis.__zod_globalRegistry;
1993
+ //#endregion
1994
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js
1995
+ /* @__NO_SIDE_EFFECTS__ */
1996
+ function _number(Class, params) {
1997
+ return new Class({
1998
+ type: "number",
1999
+ checks: [],
2000
+ ...normalizeParams(params)
2001
+ });
2002
+ }
2003
+ /* @__NO_SIDE_EFFECTS__ */
2004
+ function _int(Class, params) {
2005
+ return new Class({
2006
+ type: "number",
2007
+ check: "number_format",
2008
+ abort: false,
2009
+ format: "safeint",
2010
+ ...normalizeParams(params)
2011
+ });
2012
+ }
2013
+ /* @__NO_SIDE_EFFECTS__ */
2014
+ function _unknown(Class) {
2015
+ return new Class({ type: "unknown" });
2016
+ }
2017
+ /* @__NO_SIDE_EFFECTS__ */
2018
+ function _never(Class, params) {
2019
+ return new Class({
2020
+ type: "never",
2021
+ ...normalizeParams(params)
2022
+ });
2023
+ }
2024
+ /* @__NO_SIDE_EFFECTS__ */
2025
+ function _lt(value, params) {
2026
+ return new $ZodCheckLessThan({
2027
+ check: "less_than",
2028
+ ...normalizeParams(params),
2029
+ value,
2030
+ inclusive: false
2031
+ });
2032
+ }
2033
+ /* @__NO_SIDE_EFFECTS__ */
2034
+ function _lte(value, params) {
2035
+ return new $ZodCheckLessThan({
2036
+ check: "less_than",
2037
+ ...normalizeParams(params),
2038
+ value,
2039
+ inclusive: true
2040
+ });
2041
+ }
2042
+ /* @__NO_SIDE_EFFECTS__ */
2043
+ function _gt(value, params) {
2044
+ return new $ZodCheckGreaterThan({
2045
+ check: "greater_than",
2046
+ ...normalizeParams(params),
2047
+ value,
2048
+ inclusive: false
2049
+ });
2050
+ }
2051
+ /* @__NO_SIDE_EFFECTS__ */
2052
+ function _gte(value, params) {
2053
+ return new $ZodCheckGreaterThan({
2054
+ check: "greater_than",
2055
+ ...normalizeParams(params),
2056
+ value,
2057
+ inclusive: true
2058
+ });
2059
+ }
2060
+ /* @__NO_SIDE_EFFECTS__ */
2061
+ function _multipleOf(value, params) {
2062
+ return new $ZodCheckMultipleOf({
2063
+ check: "multiple_of",
2064
+ ...normalizeParams(params),
2065
+ value
2066
+ });
2067
+ }
2068
+ /* @__NO_SIDE_EFFECTS__ */
2069
+ function _maxLength(maximum, params) {
2070
+ return new $ZodCheckMaxLength({
2071
+ check: "max_length",
2072
+ ...normalizeParams(params),
2073
+ maximum
2074
+ });
2075
+ }
2076
+ /* @__NO_SIDE_EFFECTS__ */
2077
+ function _minLength(minimum, params) {
2078
+ return new $ZodCheckMinLength({
2079
+ check: "min_length",
2080
+ ...normalizeParams(params),
2081
+ minimum
2082
+ });
2083
+ }
2084
+ /* @__NO_SIDE_EFFECTS__ */
2085
+ function _length(length, params) {
2086
+ return new $ZodCheckLengthEquals({
2087
+ check: "length_equals",
2088
+ ...normalizeParams(params),
2089
+ length
2090
+ });
2091
+ }
2092
+ /* @__NO_SIDE_EFFECTS__ */
2093
+ function _overwrite(tx) {
2094
+ return new $ZodCheckOverwrite({
2095
+ check: "overwrite",
2096
+ tx
2097
+ });
2098
+ }
2099
+ /* @__NO_SIDE_EFFECTS__ */
2100
+ function _array(Class, element, params) {
2101
+ return new Class({
2102
+ type: "array",
2103
+ element,
2104
+ ...normalizeParams(params)
2105
+ });
2106
+ }
2107
+ /* @__NO_SIDE_EFFECTS__ */
2108
+ function _refine(Class, fn, _params) {
2109
+ return new Class({
2110
+ type: "custom",
2111
+ check: "custom",
2112
+ fn,
2113
+ ...normalizeParams(_params)
2114
+ });
2115
+ }
2116
+ /* @__NO_SIDE_EFFECTS__ */
2117
+ function _superRefine(fn) {
2118
+ const ch = /* @__PURE__ */ _check((payload) => {
2119
+ payload.addIssue = (issue$2) => {
2120
+ if (typeof issue$2 === "string") payload.issues.push(issue(issue$2, payload.value, ch._zod.def));
2121
+ else {
2122
+ const _issue = issue$2;
2123
+ if (_issue.fatal) _issue.continue = false;
2124
+ _issue.code ?? (_issue.code = "custom");
2125
+ _issue.input ?? (_issue.input = payload.value);
2126
+ _issue.inst ?? (_issue.inst = ch);
2127
+ _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
2128
+ payload.issues.push(issue(_issue));
2129
+ }
2130
+ };
2131
+ return fn(payload.value, payload);
2132
+ });
2133
+ return ch;
2134
+ }
2135
+ /* @__NO_SIDE_EFFECTS__ */
2136
+ function _check(fn, params) {
2137
+ const ch = new $ZodCheck({
2138
+ check: "custom",
2139
+ ...normalizeParams(params)
2140
+ });
2141
+ ch._zod.check = fn;
2142
+ return ch;
2143
+ }
2144
+ //#endregion
2145
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js
2146
+ function initializeContext(params) {
2147
+ let target = params?.target ?? "draft-2020-12";
2148
+ if (target === "draft-4") target = "draft-04";
2149
+ if (target === "draft-7") target = "draft-07";
2150
+ return {
2151
+ processors: params.processors ?? {},
2152
+ metadataRegistry: params?.metadata ?? globalRegistry,
2153
+ target,
2154
+ unrepresentable: params?.unrepresentable ?? "throw",
2155
+ override: params?.override ?? (() => {}),
2156
+ io: params?.io ?? "output",
2157
+ counter: 0,
2158
+ seen: /* @__PURE__ */ new Map(),
2159
+ cycles: params?.cycles ?? "ref",
2160
+ reused: params?.reused ?? "inline",
2161
+ external: params?.external ?? void 0
2162
+ };
2163
+ }
2164
+ function process$1(schema, ctx, _params = {
2165
+ path: [],
2166
+ schemaPath: []
2167
+ }) {
2168
+ var _a;
2169
+ const def = schema._zod.def;
2170
+ const seen = ctx.seen.get(schema);
2171
+ if (seen) {
2172
+ seen.count++;
2173
+ if (_params.schemaPath.includes(schema)) seen.cycle = _params.path;
2174
+ return seen.schema;
2175
+ }
2176
+ const result = {
2177
+ schema: {},
2178
+ count: 1,
2179
+ cycle: void 0,
2180
+ path: _params.path
2181
+ };
2182
+ ctx.seen.set(schema, result);
2183
+ const overrideSchema = schema._zod.toJSONSchema?.();
2184
+ if (overrideSchema) result.schema = overrideSchema;
2185
+ else {
2186
+ const params = {
2187
+ ..._params,
2188
+ schemaPath: [..._params.schemaPath, schema],
2189
+ path: _params.path
2190
+ };
2191
+ if (schema._zod.processJSONSchema) schema._zod.processJSONSchema(ctx, result.schema, params);
2192
+ else {
2193
+ const _json = result.schema;
2194
+ const processor = ctx.processors[def.type];
2195
+ if (!processor) throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
2196
+ processor(schema, ctx, _json, params);
2197
+ }
2198
+ const parent = schema._zod.parent;
2199
+ if (parent) {
2200
+ if (!result.ref) result.ref = parent;
2201
+ process$1(parent, ctx, params);
2202
+ ctx.seen.get(parent).isParent = true;
2203
+ }
2204
+ }
2205
+ const meta = ctx.metadataRegistry.get(schema);
2206
+ if (meta) Object.assign(result.schema, meta);
2207
+ if (ctx.io === "input" && isTransforming(schema)) {
2208
+ delete result.schema.examples;
2209
+ delete result.schema.default;
2210
+ }
2211
+ if (ctx.io === "input" && result.schema._prefault) (_a = result.schema).default ?? (_a.default = result.schema._prefault);
2212
+ delete result.schema._prefault;
2213
+ return ctx.seen.get(schema).schema;
2214
+ }
2215
+ function extractDefs(ctx, schema) {
2216
+ const root = ctx.seen.get(schema);
2217
+ if (!root) throw new Error("Unprocessed schema. This is a bug in Zod.");
2218
+ const idToSchema = /* @__PURE__ */ new Map();
2219
+ for (const entry of ctx.seen.entries()) {
2220
+ const id = ctx.metadataRegistry.get(entry[0])?.id;
2221
+ if (id) {
2222
+ const existing = idToSchema.get(id);
2223
+ if (existing && existing !== entry[0]) throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
2224
+ idToSchema.set(id, entry[0]);
2225
+ }
2226
+ }
2227
+ const makeURI = (entry) => {
2228
+ const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
2229
+ if (ctx.external) {
2230
+ const externalId = ctx.external.registry.get(entry[0])?.id;
2231
+ const uriGenerator = ctx.external.uri ?? ((id) => id);
2232
+ if (externalId) return { ref: uriGenerator(externalId) };
2233
+ const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
2234
+ entry[1].defId = id;
2235
+ return {
2236
+ defId: id,
2237
+ ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}`
2238
+ };
2239
+ }
2240
+ if (entry[1] === root) return { ref: "#" };
2241
+ const defUriPrefix = `#/${defsSegment}/`;
2242
+ const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
2243
+ return {
2244
+ defId,
2245
+ ref: defUriPrefix + defId
2246
+ };
2247
+ };
2248
+ const extractToDef = (entry) => {
2249
+ if (entry[1].schema.$ref) return;
2250
+ const seen = entry[1];
2251
+ const { ref, defId } = makeURI(entry);
2252
+ seen.def = { ...seen.schema };
2253
+ if (defId) seen.defId = defId;
2254
+ const schema = seen.schema;
2255
+ for (const key in schema) delete schema[key];
2256
+ schema.$ref = ref;
2257
+ };
2258
+ if (ctx.cycles === "throw") for (const entry of ctx.seen.entries()) {
2259
+ const seen = entry[1];
2260
+ if (seen.cycle) throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
2261
+
2262
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
2263
+ }
2264
+ for (const entry of ctx.seen.entries()) {
2265
+ const seen = entry[1];
2266
+ if (schema === entry[0]) {
2267
+ extractToDef(entry);
2268
+ continue;
2269
+ }
2270
+ if (ctx.external) {
2271
+ const ext = ctx.external.registry.get(entry[0])?.id;
2272
+ if (schema !== entry[0] && ext) {
2273
+ extractToDef(entry);
2274
+ continue;
2275
+ }
2276
+ }
2277
+ if (ctx.metadataRegistry.get(entry[0])?.id) {
2278
+ extractToDef(entry);
2279
+ continue;
2280
+ }
2281
+ if (seen.cycle) {
2282
+ extractToDef(entry);
2283
+ continue;
2284
+ }
2285
+ if (seen.count > 1) {
2286
+ if (ctx.reused === "ref") {
2287
+ extractToDef(entry);
2288
+ continue;
2289
+ }
2290
+ }
2291
+ }
2292
+ }
2293
+ function finalize(ctx, schema) {
2294
+ const root = ctx.seen.get(schema);
2295
+ if (!root) throw new Error("Unprocessed schema. This is a bug in Zod.");
2296
+ const flattenRef = (zodSchema) => {
2297
+ const seen = ctx.seen.get(zodSchema);
2298
+ if (seen.ref === null) return;
2299
+ const schema = seen.def ?? seen.schema;
2300
+ const _cached = { ...schema };
2301
+ const ref = seen.ref;
2302
+ seen.ref = null;
2303
+ if (ref) {
2304
+ flattenRef(ref);
2305
+ const refSeen = ctx.seen.get(ref);
2306
+ const refSchema = refSeen.schema;
2307
+ if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
2308
+ schema.allOf = schema.allOf ?? [];
2309
+ schema.allOf.push(refSchema);
2310
+ } else Object.assign(schema, refSchema);
2311
+ Object.assign(schema, _cached);
2312
+ if (zodSchema._zod.parent === ref) for (const key in schema) {
2313
+ if (key === "$ref" || key === "allOf") continue;
2314
+ if (!(key in _cached)) delete schema[key];
2315
+ }
2316
+ if (refSchema.$ref && refSeen.def) for (const key in schema) {
2317
+ if (key === "$ref" || key === "allOf") continue;
2318
+ if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) delete schema[key];
2319
+ }
2320
+ }
2321
+ const parent = zodSchema._zod.parent;
2322
+ if (parent && parent !== ref) {
2323
+ flattenRef(parent);
2324
+ const parentSeen = ctx.seen.get(parent);
2325
+ if (parentSeen?.schema.$ref) {
2326
+ schema.$ref = parentSeen.schema.$ref;
2327
+ if (parentSeen.def) for (const key in schema) {
2328
+ if (key === "$ref" || key === "allOf") continue;
2329
+ if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) delete schema[key];
2330
+ }
2331
+ }
2332
+ }
2333
+ ctx.override({
2334
+ zodSchema,
2335
+ jsonSchema: schema,
2336
+ path: seen.path ?? []
2337
+ });
2338
+ };
2339
+ for (const entry of [...ctx.seen.entries()].reverse()) flattenRef(entry[0]);
2340
+ const result = {};
2341
+ if (ctx.target === "draft-2020-12") result.$schema = "https://json-schema.org/draft/2020-12/schema";
2342
+ else if (ctx.target === "draft-07") result.$schema = "http://json-schema.org/draft-07/schema#";
2343
+ else if (ctx.target === "draft-04") result.$schema = "http://json-schema.org/draft-04/schema#";
2344
+ else if (ctx.target === "openapi-3.0") {}
2345
+ if (ctx.external?.uri) {
2346
+ const id = ctx.external.registry.get(schema)?.id;
2347
+ if (!id) throw new Error("Schema is missing an `id` property");
2348
+ result.$id = ctx.external.uri(id);
2349
+ }
2350
+ Object.assign(result, root.def ?? root.schema);
2351
+ const defs = ctx.external?.defs ?? {};
2352
+ for (const entry of ctx.seen.entries()) {
2353
+ const seen = entry[1];
2354
+ if (seen.def && seen.defId) defs[seen.defId] = seen.def;
2355
+ }
2356
+ if (ctx.external) {} else if (Object.keys(defs).length > 0) if (ctx.target === "draft-2020-12") result.$defs = defs;
2357
+ else result.definitions = defs;
2358
+ try {
2359
+ const finalized = JSON.parse(JSON.stringify(result));
2360
+ Object.defineProperty(finalized, "~standard", {
2361
+ value: {
2362
+ ...schema["~standard"],
2363
+ jsonSchema: {
2364
+ input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
2365
+ output: createStandardJSONSchemaMethod(schema, "output", ctx.processors)
2366
+ }
2367
+ },
2368
+ enumerable: false,
2369
+ writable: false
2370
+ });
2371
+ return finalized;
2372
+ } catch (_err) {
2373
+ throw new Error("Error converting schema to JSON.");
2374
+ }
2375
+ }
2376
+ function isTransforming(_schema, _ctx) {
2377
+ const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() };
2378
+ if (ctx.seen.has(_schema)) return false;
2379
+ ctx.seen.add(_schema);
2380
+ const def = _schema._zod.def;
2381
+ if (def.type === "transform") return true;
2382
+ if (def.type === "array") return isTransforming(def.element, ctx);
2383
+ if (def.type === "set") return isTransforming(def.valueType, ctx);
2384
+ if (def.type === "lazy") return isTransforming(def.getter(), ctx);
2385
+ if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") return isTransforming(def.innerType, ctx);
2386
+ if (def.type === "intersection") return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
2387
+ if (def.type === "record" || def.type === "map") return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
2388
+ if (def.type === "pipe") return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
2389
+ if (def.type === "object") {
2390
+ for (const key in def.shape) if (isTransforming(def.shape[key], ctx)) return true;
2391
+ return false;
2392
+ }
2393
+ if (def.type === "union") {
2394
+ for (const option of def.options) if (isTransforming(option, ctx)) return true;
2395
+ return false;
2396
+ }
2397
+ if (def.type === "tuple") {
2398
+ for (const item of def.items) if (isTransforming(item, ctx)) return true;
2399
+ if (def.rest && isTransforming(def.rest, ctx)) return true;
2400
+ return false;
2401
+ }
2402
+ return false;
2403
+ }
2404
+ /**
2405
+ * Creates a toJSONSchema method for a schema instance.
2406
+ * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.
2407
+ */
2408
+ const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
2409
+ const ctx = initializeContext({
2410
+ ...params,
2411
+ processors
2412
+ });
2413
+ process$1(schema, ctx);
2414
+ extractDefs(ctx, schema);
2415
+ return finalize(ctx, schema);
2416
+ };
2417
+ const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
2418
+ const { libraryOptions, target } = params ?? {};
2419
+ const ctx = initializeContext({
2420
+ ...libraryOptions ?? {},
2421
+ target,
2422
+ io,
2423
+ processors
2424
+ });
2425
+ process$1(schema, ctx);
2426
+ extractDefs(ctx, schema);
2427
+ return finalize(ctx, schema);
2428
+ };
2429
+ //#endregion
2430
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js
2431
+ const numberProcessor = (schema, ctx, _json, _params) => {
2432
+ const json = _json;
2433
+ const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
2434
+ if (typeof format === "string" && format.includes("int")) json.type = "integer";
2435
+ else json.type = "number";
2436
+ if (typeof exclusiveMinimum === "number") if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
2437
+ json.minimum = exclusiveMinimum;
2438
+ json.exclusiveMinimum = true;
2439
+ } else json.exclusiveMinimum = exclusiveMinimum;
2440
+ if (typeof minimum === "number") {
2441
+ json.minimum = minimum;
2442
+ if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") if (exclusiveMinimum >= minimum) delete json.minimum;
2443
+ else delete json.exclusiveMinimum;
2444
+ }
2445
+ if (typeof exclusiveMaximum === "number") if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
2446
+ json.maximum = exclusiveMaximum;
2447
+ json.exclusiveMaximum = true;
2448
+ } else json.exclusiveMaximum = exclusiveMaximum;
2449
+ if (typeof maximum === "number") {
2450
+ json.maximum = maximum;
2451
+ if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") if (exclusiveMaximum <= maximum) delete json.maximum;
2452
+ else delete json.exclusiveMaximum;
2453
+ }
2454
+ if (typeof multipleOf === "number") json.multipleOf = multipleOf;
2455
+ };
2456
+ const neverProcessor = (_schema, _ctx, json, _params) => {
2457
+ json.not = {};
2458
+ };
2459
+ const unknownProcessor = (_schema, _ctx, _json, _params) => {};
2460
+ const enumProcessor = (schema, _ctx, json, _params) => {
2461
+ const def = schema._zod.def;
2462
+ const values = getEnumValues(def.entries);
2463
+ if (values.every((v) => typeof v === "number")) json.type = "number";
2464
+ if (values.every((v) => typeof v === "string")) json.type = "string";
2465
+ json.enum = values;
2466
+ };
2467
+ const customProcessor = (_schema, ctx, _json, _params) => {
2468
+ if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
2469
+ };
2470
+ const transformProcessor = (_schema, ctx, _json, _params) => {
2471
+ if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
2472
+ };
2473
+ const arrayProcessor = (schema, ctx, _json, params) => {
2474
+ const json = _json;
2475
+ const def = schema._zod.def;
2476
+ const { minimum, maximum } = schema._zod.bag;
2477
+ if (typeof minimum === "number") json.minItems = minimum;
2478
+ if (typeof maximum === "number") json.maxItems = maximum;
2479
+ json.type = "array";
2480
+ json.items = process$1(def.element, ctx, {
2481
+ ...params,
2482
+ path: [...params.path, "items"]
2483
+ });
2484
+ };
2485
+ const objectProcessor = (schema, ctx, _json, params) => {
2486
+ const json = _json;
2487
+ const def = schema._zod.def;
2488
+ json.type = "object";
2489
+ json.properties = {};
2490
+ const shape = def.shape;
2491
+ for (const key in shape) json.properties[key] = process$1(shape[key], ctx, {
2492
+ ...params,
2493
+ path: [
2494
+ ...params.path,
2495
+ "properties",
2496
+ key
2497
+ ]
2498
+ });
2499
+ const allKeys = new Set(Object.keys(shape));
2500
+ const requiredKeys = new Set([...allKeys].filter((key) => {
2501
+ const v = def.shape[key]._zod;
2502
+ if (ctx.io === "input") return v.optin === void 0;
2503
+ else return v.optout === void 0;
2504
+ }));
2505
+ if (requiredKeys.size > 0) json.required = Array.from(requiredKeys);
2506
+ if (def.catchall?._zod.def.type === "never") json.additionalProperties = false;
2507
+ else if (!def.catchall) {
2508
+ if (ctx.io === "output") json.additionalProperties = false;
2509
+ } else if (def.catchall) json.additionalProperties = process$1(def.catchall, ctx, {
2510
+ ...params,
2511
+ path: [...params.path, "additionalProperties"]
2512
+ });
2513
+ };
2514
+ const unionProcessor = (schema, ctx, json, params) => {
2515
+ const def = schema._zod.def;
2516
+ const isExclusive = def.inclusive === false;
2517
+ const options = def.options.map((x, i) => process$1(x, ctx, {
2518
+ ...params,
2519
+ path: [
2520
+ ...params.path,
2521
+ isExclusive ? "oneOf" : "anyOf",
2522
+ i
2523
+ ]
2524
+ }));
2525
+ if (isExclusive) json.oneOf = options;
2526
+ else json.anyOf = options;
2527
+ };
2528
+ const intersectionProcessor = (schema, ctx, json, params) => {
2529
+ const def = schema._zod.def;
2530
+ const a = process$1(def.left, ctx, {
2531
+ ...params,
2532
+ path: [
2533
+ ...params.path,
2534
+ "allOf",
2535
+ 0
2536
+ ]
2537
+ });
2538
+ const b = process$1(def.right, ctx, {
2539
+ ...params,
2540
+ path: [
2541
+ ...params.path,
2542
+ "allOf",
2543
+ 1
2544
+ ]
2545
+ });
2546
+ const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
2547
+ json.allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]];
2548
+ };
2549
+ const nullableProcessor = (schema, ctx, json, params) => {
2550
+ const def = schema._zod.def;
2551
+ const inner = process$1(def.innerType, ctx, params);
2552
+ const seen = ctx.seen.get(schema);
2553
+ if (ctx.target === "openapi-3.0") {
2554
+ seen.ref = def.innerType;
2555
+ json.nullable = true;
2556
+ } else json.anyOf = [inner, { type: "null" }];
2557
+ };
2558
+ const nonoptionalProcessor = (schema, ctx, _json, params) => {
2559
+ const def = schema._zod.def;
2560
+ process$1(def.innerType, ctx, params);
2561
+ const seen = ctx.seen.get(schema);
2562
+ seen.ref = def.innerType;
2563
+ };
2564
+ const defaultProcessor = (schema, ctx, json, params) => {
2565
+ const def = schema._zod.def;
2566
+ process$1(def.innerType, ctx, params);
2567
+ const seen = ctx.seen.get(schema);
2568
+ seen.ref = def.innerType;
2569
+ json.default = JSON.parse(JSON.stringify(def.defaultValue));
2570
+ };
2571
+ const prefaultProcessor = (schema, ctx, json, params) => {
2572
+ const def = schema._zod.def;
2573
+ process$1(def.innerType, ctx, params);
2574
+ const seen = ctx.seen.get(schema);
2575
+ seen.ref = def.innerType;
2576
+ if (ctx.io === "input") json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
2577
+ };
2578
+ const catchProcessor = (schema, ctx, json, params) => {
2579
+ const def = schema._zod.def;
2580
+ process$1(def.innerType, ctx, params);
2581
+ const seen = ctx.seen.get(schema);
2582
+ seen.ref = def.innerType;
2583
+ let catchValue;
2584
+ try {
2585
+ catchValue = def.catchValue(void 0);
2586
+ } catch {
2587
+ throw new Error("Dynamic catch values are not supported in JSON Schema");
2588
+ }
2589
+ json.default = catchValue;
2590
+ };
2591
+ const pipeProcessor = (schema, ctx, _json, params) => {
2592
+ const def = schema._zod.def;
2593
+ const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out;
2594
+ process$1(innerType, ctx, params);
2595
+ const seen = ctx.seen.get(schema);
2596
+ seen.ref = innerType;
2597
+ };
2598
+ const readonlyProcessor = (schema, ctx, json, params) => {
2599
+ const def = schema._zod.def;
2600
+ process$1(def.innerType, ctx, params);
2601
+ const seen = ctx.seen.get(schema);
2602
+ seen.ref = def.innerType;
2603
+ json.readOnly = true;
2604
+ };
2605
+ const optionalProcessor = (schema, ctx, _json, params) => {
2606
+ const def = schema._zod.def;
2607
+ process$1(def.innerType, ctx, params);
2608
+ const seen = ctx.seen.get(schema);
2609
+ seen.ref = def.innerType;
2610
+ };
2611
+ //#endregion
2612
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js
2613
+ const initializer = (inst, issues) => {
2614
+ $ZodError.init(inst, issues);
2615
+ inst.name = "ZodError";
2616
+ Object.defineProperties(inst, {
2617
+ format: { value: (mapper) => formatError(inst, mapper) },
2618
+ flatten: { value: (mapper) => flattenError(inst, mapper) },
2619
+ addIssue: { value: (issue) => {
2620
+ inst.issues.push(issue);
2621
+ inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
2622
+ } },
2623
+ addIssues: { value: (issues) => {
2624
+ inst.issues.push(...issues);
2625
+ inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
2626
+ } },
2627
+ isEmpty: { get() {
2628
+ return inst.issues.length === 0;
2629
+ } }
2630
+ });
2631
+ };
2632
+ $constructor("ZodError", initializer);
2633
+ const ZodRealError = $constructor("ZodError", initializer, { Parent: Error });
2634
+ //#endregion
2635
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js
2636
+ const parse$1 = /* @__PURE__ */ _parse(ZodRealError);
2637
+ const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
2638
+ const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
2639
+ const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
2640
+ const encode$2 = /* @__PURE__ */ _encode(ZodRealError);
2641
+ const decode = /* @__PURE__ */ _decode(ZodRealError);
2642
+ const encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
2643
+ const decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError);
2644
+ const safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
2645
+ const safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
2646
+ const safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
2647
+ const safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
2648
+ //#endregion
2649
+ //#region ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js
2650
+ const ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
2651
+ $ZodType.init(inst, def);
2652
+ Object.assign(inst["~standard"], { jsonSchema: {
2653
+ input: createStandardJSONSchemaMethod(inst, "input"),
2654
+ output: createStandardJSONSchemaMethod(inst, "output")
2655
+ } });
2656
+ inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
2657
+ inst.def = def;
2658
+ inst.type = def.type;
2659
+ Object.defineProperty(inst, "_def", { value: def });
2660
+ inst.check = (...checks) => {
2661
+ return inst.clone(mergeDefs(def, { checks: [...def.checks ?? [], ...checks.map((ch) => typeof ch === "function" ? { _zod: {
2662
+ check: ch,
2663
+ def: { check: "custom" },
2664
+ onattach: []
2665
+ } } : ch)] }), { parent: true });
2666
+ };
2667
+ inst.with = inst.check;
2668
+ inst.clone = (def, params) => clone(inst, def, params);
2669
+ inst.brand = () => inst;
2670
+ inst.register = ((reg, meta) => {
2671
+ reg.add(inst, meta);
2672
+ return inst;
2673
+ });
2674
+ inst.parse = (data, params) => parse$1(inst, data, params, { callee: inst.parse });
2675
+ inst.safeParse = (data, params) => safeParse(inst, data, params);
2676
+ inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
2677
+ inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
2678
+ inst.spa = inst.safeParseAsync;
2679
+ inst.encode = (data, params) => encode$2(inst, data, params);
2680
+ inst.decode = (data, params) => decode(inst, data, params);
2681
+ inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
2682
+ inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
2683
+ inst.safeEncode = (data, params) => safeEncode(inst, data, params);
2684
+ inst.safeDecode = (data, params) => safeDecode(inst, data, params);
2685
+ inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params);
2686
+ inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params);
2687
+ inst.refine = (check, params) => inst.check(refine(check, params));
2688
+ inst.superRefine = (refinement) => inst.check(superRefine(refinement));
2689
+ inst.overwrite = (fn) => inst.check(/* @__PURE__ */ _overwrite(fn));
2690
+ inst.optional = () => optional(inst);
2691
+ inst.exactOptional = () => exactOptional(inst);
2692
+ inst.nullable = () => nullable(inst);
2693
+ inst.nullish = () => optional(nullable(inst));
2694
+ inst.nonoptional = (params) => nonoptional(inst, params);
2695
+ inst.array = () => array(inst);
2696
+ inst.or = (arg) => union([inst, arg]);
2697
+ inst.and = (arg) => intersection(inst, arg);
2698
+ inst.transform = (tx) => pipe(inst, transform(tx));
2699
+ inst.default = (def) => _default(inst, def);
2700
+ inst.prefault = (def) => prefault(inst, def);
2701
+ inst.catch = (params) => _catch(inst, params);
2702
+ inst.pipe = (target) => pipe(inst, target);
2703
+ inst.readonly = () => readonly(inst);
2704
+ inst.describe = (description) => {
2705
+ const cl = inst.clone();
2706
+ globalRegistry.add(cl, { description });
2707
+ return cl;
2708
+ };
2709
+ Object.defineProperty(inst, "description", {
2710
+ get() {
2711
+ return globalRegistry.get(inst)?.description;
2712
+ },
2713
+ configurable: true
2714
+ });
2715
+ inst.meta = (...args) => {
2716
+ if (args.length === 0) return globalRegistry.get(inst);
2717
+ const cl = inst.clone();
2718
+ globalRegistry.add(cl, args[0]);
2719
+ return cl;
2720
+ };
2721
+ inst.isOptional = () => inst.safeParse(void 0).success;
2722
+ inst.isNullable = () => inst.safeParse(null).success;
2723
+ inst.apply = (fn) => fn(inst);
2724
+ return inst;
2725
+ });
2726
+ const ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
2727
+ $ZodNumber.init(inst, def);
2728
+ ZodType.init(inst, def);
2729
+ inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params);
2730
+ inst.gt = (value, params) => inst.check(/* @__PURE__ */ _gt(value, params));
2731
+ inst.gte = (value, params) => inst.check(/* @__PURE__ */ _gte(value, params));
2732
+ inst.min = (value, params) => inst.check(/* @__PURE__ */ _gte(value, params));
2733
+ inst.lt = (value, params) => inst.check(/* @__PURE__ */ _lt(value, params));
2734
+ inst.lte = (value, params) => inst.check(/* @__PURE__ */ _lte(value, params));
2735
+ inst.max = (value, params) => inst.check(/* @__PURE__ */ _lte(value, params));
2736
+ inst.int = (params) => inst.check(int(params));
2737
+ inst.safe = (params) => inst.check(int(params));
2738
+ inst.positive = (params) => inst.check(/* @__PURE__ */ _gt(0, params));
2739
+ inst.nonnegative = (params) => inst.check(/* @__PURE__ */ _gte(0, params));
2740
+ inst.negative = (params) => inst.check(/* @__PURE__ */ _lt(0, params));
2741
+ inst.nonpositive = (params) => inst.check(/* @__PURE__ */ _lte(0, params));
2742
+ inst.multipleOf = (value, params) => inst.check(/* @__PURE__ */ _multipleOf(value, params));
2743
+ inst.step = (value, params) => inst.check(/* @__PURE__ */ _multipleOf(value, params));
2744
+ inst.finite = () => inst;
2745
+ const bag = inst._zod.bag;
2746
+ inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
2747
+ inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
2748
+ inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? .5);
2749
+ inst.isFinite = true;
2750
+ inst.format = bag.format ?? null;
2751
+ });
2752
+ function number(params) {
2753
+ return /* @__PURE__ */ _number(ZodNumber, params);
2754
+ }
2755
+ const ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
2756
+ $ZodNumberFormat.init(inst, def);
2757
+ ZodNumber.init(inst, def);
2758
+ });
2759
+ function int(params) {
2760
+ return /* @__PURE__ */ _int(ZodNumberFormat, params);
2761
+ }
2762
+ const ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
2763
+ $ZodUnknown.init(inst, def);
2764
+ ZodType.init(inst, def);
2765
+ inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params);
2766
+ });
2767
+ function unknown() {
2768
+ return /* @__PURE__ */ _unknown(ZodUnknown);
2769
+ }
2770
+ const ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
2771
+ $ZodNever.init(inst, def);
2772
+ ZodType.init(inst, def);
2773
+ inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params);
2774
+ });
2775
+ function never(params) {
2776
+ return /* @__PURE__ */ _never(ZodNever, params);
2777
+ }
2778
+ const ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
2779
+ $ZodArray.init(inst, def);
2780
+ ZodType.init(inst, def);
2781
+ inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params);
2782
+ inst.element = def.element;
2783
+ inst.min = (minLength, params) => inst.check(/* @__PURE__ */ _minLength(minLength, params));
2784
+ inst.nonempty = (params) => inst.check(/* @__PURE__ */ _minLength(1, params));
2785
+ inst.max = (maxLength, params) => inst.check(/* @__PURE__ */ _maxLength(maxLength, params));
2786
+ inst.length = (len, params) => inst.check(/* @__PURE__ */ _length(len, params));
2787
+ inst.unwrap = () => inst.element;
2788
+ });
2789
+ function array(element, params) {
2790
+ return /* @__PURE__ */ _array(ZodArray, element, params);
2791
+ }
2792
+ const ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
2793
+ $ZodObjectJIT.init(inst, def);
2794
+ ZodType.init(inst, def);
2795
+ inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params);
2796
+ defineLazy(inst, "shape", () => {
2797
+ return def.shape;
2798
+ });
2799
+ inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
2800
+ inst.catchall = (catchall) => inst.clone({
2801
+ ...inst._zod.def,
2802
+ catchall
2803
+ });
2804
+ inst.passthrough = () => inst.clone({
2805
+ ...inst._zod.def,
2806
+ catchall: unknown()
2807
+ });
2808
+ inst.loose = () => inst.clone({
2809
+ ...inst._zod.def,
2810
+ catchall: unknown()
2811
+ });
2812
+ inst.strict = () => inst.clone({
2813
+ ...inst._zod.def,
2814
+ catchall: never()
2815
+ });
2816
+ inst.strip = () => inst.clone({
2817
+ ...inst._zod.def,
2818
+ catchall: void 0
2819
+ });
2820
+ inst.extend = (incoming) => {
2821
+ return extend$1(inst, incoming);
2822
+ };
2823
+ inst.safeExtend = (incoming) => {
2824
+ return safeExtend(inst, incoming);
2825
+ };
2826
+ inst.merge = (other) => merge$1(inst, other);
2827
+ inst.pick = (mask) => pick(inst, mask);
2828
+ inst.omit = (mask) => omit(inst, mask);
2829
+ inst.partial = (...args) => partial(ZodOptional, inst, args[0]);
2830
+ inst.required = (...args) => required(ZodNonOptional, inst, args[0]);
2831
+ });
2832
+ function object(shape, params) {
2833
+ return new ZodObject({
2834
+ type: "object",
2835
+ shape: shape ?? {},
2836
+ ...normalizeParams(params)
2837
+ });
2838
+ }
2839
+ const ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
2840
+ $ZodUnion.init(inst, def);
2841
+ ZodType.init(inst, def);
2842
+ inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params);
2843
+ inst.options = def.options;
2844
+ });
2845
+ function union(options, params) {
2846
+ return new ZodUnion({
2847
+ type: "union",
2848
+ options,
2849
+ ...normalizeParams(params)
2850
+ });
2851
+ }
2852
+ const ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
2853
+ $ZodIntersection.init(inst, def);
2854
+ ZodType.init(inst, def);
2855
+ inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params);
2856
+ });
2857
+ function intersection(left, right) {
2858
+ return new ZodIntersection({
2859
+ type: "intersection",
2860
+ left,
2861
+ right
2862
+ });
2863
+ }
2864
+ const ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
2865
+ $ZodEnum.init(inst, def);
2866
+ ZodType.init(inst, def);
2867
+ inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params);
2868
+ inst.enum = def.entries;
2869
+ inst.options = Object.values(def.entries);
2870
+ const keys = new Set(Object.keys(def.entries));
2871
+ inst.extract = (values, params) => {
2872
+ const newEntries = {};
2873
+ for (const value of values) if (keys.has(value)) newEntries[value] = def.entries[value];
2874
+ else throw new Error(`Key ${value} not found in enum`);
2875
+ return new ZodEnum({
2876
+ ...def,
2877
+ checks: [],
2878
+ ...normalizeParams(params),
2879
+ entries: newEntries
2880
+ });
2881
+ };
2882
+ inst.exclude = (values, params) => {
2883
+ const newEntries = { ...def.entries };
2884
+ for (const value of values) if (keys.has(value)) delete newEntries[value];
2885
+ else throw new Error(`Key ${value} not found in enum`);
2886
+ return new ZodEnum({
2887
+ ...def,
2888
+ checks: [],
2889
+ ...normalizeParams(params),
2890
+ entries: newEntries
2891
+ });
2892
+ };
2893
+ });
2894
+ function _enum(values, params) {
2895
+ return new ZodEnum({
2896
+ type: "enum",
2897
+ entries: Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values,
2898
+ ...normalizeParams(params)
2899
+ });
2900
+ }
2901
+ const ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
2902
+ $ZodTransform.init(inst, def);
2903
+ ZodType.init(inst, def);
2904
+ inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params);
2905
+ inst._zod.parse = (payload, _ctx) => {
2906
+ if (_ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name);
2907
+ payload.addIssue = (issue$1) => {
2908
+ if (typeof issue$1 === "string") payload.issues.push(issue(issue$1, payload.value, def));
2909
+ else {
2910
+ const _issue = issue$1;
2911
+ if (_issue.fatal) _issue.continue = false;
2912
+ _issue.code ?? (_issue.code = "custom");
2913
+ _issue.input ?? (_issue.input = payload.value);
2914
+ _issue.inst ?? (_issue.inst = inst);
2915
+ payload.issues.push(issue(_issue));
2916
+ }
2917
+ };
2918
+ const output = def.transform(payload.value, payload);
2919
+ if (output instanceof Promise) return output.then((output) => {
2920
+ payload.value = output;
2921
+ return payload;
2922
+ });
2923
+ payload.value = output;
2924
+ return payload;
2925
+ };
2926
+ });
2927
+ function transform(fn) {
2928
+ return new ZodTransform({
2929
+ type: "transform",
2930
+ transform: fn
2931
+ });
2932
+ }
2933
+ const ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
2934
+ $ZodOptional.init(inst, def);
2935
+ ZodType.init(inst, def);
2936
+ inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
2937
+ inst.unwrap = () => inst._zod.def.innerType;
2938
+ });
2939
+ function optional(innerType) {
2940
+ return new ZodOptional({
2941
+ type: "optional",
2942
+ innerType
2943
+ });
2944
+ }
2945
+ const ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => {
2946
+ $ZodExactOptional.init(inst, def);
2947
+ ZodType.init(inst, def);
2948
+ inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
2949
+ inst.unwrap = () => inst._zod.def.innerType;
2950
+ });
2951
+ function exactOptional(innerType) {
2952
+ return new ZodExactOptional({
2953
+ type: "optional",
2954
+ innerType
2955
+ });
2956
+ }
2957
+ const ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
2958
+ $ZodNullable.init(inst, def);
2959
+ ZodType.init(inst, def);
2960
+ inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params);
2961
+ inst.unwrap = () => inst._zod.def.innerType;
2962
+ });
2963
+ function nullable(innerType) {
2964
+ return new ZodNullable({
2965
+ type: "nullable",
2966
+ innerType
2967
+ });
2968
+ }
2969
+ const ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
2970
+ $ZodDefault.init(inst, def);
2971
+ ZodType.init(inst, def);
2972
+ inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params);
2973
+ inst.unwrap = () => inst._zod.def.innerType;
2974
+ inst.removeDefault = inst.unwrap;
2975
+ });
2976
+ function _default(innerType, defaultValue) {
2977
+ return new ZodDefault({
2978
+ type: "default",
2979
+ innerType,
2980
+ get defaultValue() {
2981
+ return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
2982
+ }
2983
+ });
2984
+ }
2985
+ const ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
2986
+ $ZodPrefault.init(inst, def);
2987
+ ZodType.init(inst, def);
2988
+ inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params);
2989
+ inst.unwrap = () => inst._zod.def.innerType;
2990
+ });
2991
+ function prefault(innerType, defaultValue) {
2992
+ return new ZodPrefault({
2993
+ type: "prefault",
2994
+ innerType,
2995
+ get defaultValue() {
2996
+ return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
89
2997
  }
90
2998
  });
91
- return pino({ level: process.env.LOG_LEVEL ?? "info" }, transport);
92
2999
  }
93
- const logger$1 = createLogger$1();
3000
+ const ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
3001
+ $ZodNonOptional.init(inst, def);
3002
+ ZodType.init(inst, def);
3003
+ inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params);
3004
+ inst.unwrap = () => inst._zod.def.innerType;
3005
+ });
3006
+ function nonoptional(innerType, params) {
3007
+ return new ZodNonOptional({
3008
+ type: "nonoptional",
3009
+ innerType,
3010
+ ...normalizeParams(params)
3011
+ });
3012
+ }
3013
+ const ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
3014
+ $ZodCatch.init(inst, def);
3015
+ ZodType.init(inst, def);
3016
+ inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params);
3017
+ inst.unwrap = () => inst._zod.def.innerType;
3018
+ inst.removeCatch = inst.unwrap;
3019
+ });
3020
+ function _catch(innerType, catchValue) {
3021
+ return new ZodCatch({
3022
+ type: "catch",
3023
+ innerType,
3024
+ catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
3025
+ });
3026
+ }
3027
+ const ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
3028
+ $ZodPipe.init(inst, def);
3029
+ ZodType.init(inst, def);
3030
+ inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params);
3031
+ inst.in = def.in;
3032
+ inst.out = def.out;
3033
+ });
3034
+ function pipe(in_, out) {
3035
+ return new ZodPipe({
3036
+ type: "pipe",
3037
+ in: in_,
3038
+ out
3039
+ });
3040
+ }
3041
+ const ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
3042
+ $ZodReadonly.init(inst, def);
3043
+ ZodType.init(inst, def);
3044
+ inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params);
3045
+ inst.unwrap = () => inst._zod.def.innerType;
3046
+ });
3047
+ function readonly(innerType) {
3048
+ return new ZodReadonly({
3049
+ type: "readonly",
3050
+ innerType
3051
+ });
3052
+ }
3053
+ const ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
3054
+ $ZodCustom.init(inst, def);
3055
+ ZodType.init(inst, def);
3056
+ inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params);
3057
+ });
3058
+ function refine(fn, _params = {}) {
3059
+ return /* @__PURE__ */ _refine(ZodCustom, fn, _params);
3060
+ }
3061
+ function superRefine(fn) {
3062
+ return /* @__PURE__ */ _superRefine(fn);
3063
+ }
3064
+ enumValues({
3065
+ Active: "active",
3066
+ PastDue: "past_due",
3067
+ Canceled: "canceled",
3068
+ Incomplete: "incomplete"
3069
+ });
3070
+ enumValues({
3071
+ Anthropic: "anthropic",
3072
+ OpenAI: "openai"
3073
+ });
3074
+ enumValues({
3075
+ Month: "month",
3076
+ Year: "year"
3077
+ });
3078
+ object({ gracePeriodDays: number().int().positive().optional() });
3079
+ enumValues({
3080
+ Active: "active",
3081
+ Inactive: "inactive",
3082
+ Deleted: "deleted"
3083
+ });
3084
+ enumValues({
3085
+ SelfHosted: "self-hosted",
3086
+ Managed: "managed"
3087
+ });
3088
+ enumValues({
3089
+ OpenClaw: "openclaw",
3090
+ NanoClaw: "nanoclaw"
3091
+ });
3092
+ enumValues({
3093
+ None: "none",
3094
+ Pending: "pending",
3095
+ Provisioning: "provisioning",
3096
+ Running: "running",
3097
+ Stopped: "stopped",
3098
+ Failed: "failed",
3099
+ BillingSuspended: "billing_suspended"
3100
+ });
3101
+ enumValues({
3102
+ Active: "active",
3103
+ Removed: "removed"
3104
+ });
3105
+ enumValues({
3106
+ Installing: "installing",
3107
+ Active: "active",
3108
+ Error: "error",
3109
+ Removing: "removing",
3110
+ Inactive: "inactive",
3111
+ Unknown: "unknown"
3112
+ });
3113
+ enumValues({
3114
+ Active: "active",
3115
+ Depleted: "depleted",
3116
+ Paused: "paused"
3117
+ });
3118
+ enumValues({
3119
+ Usage: "usage",
3120
+ TopUp: "top_up",
3121
+ SubscriptionCredit: "subscription_credit",
3122
+ AutoRecharge: "auto_recharge",
3123
+ AdminGift: "admin_gift",
3124
+ Refund: "refund"
3125
+ });
3126
+ enumValues({
3127
+ Pending: "pending",
3128
+ Completed: "completed",
3129
+ Failed: "failed"
3130
+ });
3131
+ enumValues({
3132
+ Hour: "hour",
3133
+ Day: "day",
3134
+ Week: "week",
3135
+ Month: "month"
3136
+ });
3137
+ enumValues({
3138
+ Synced: "synced",
3139
+ Stale: "stale",
3140
+ Error: "error"
3141
+ });
3142
+ enumValues({
3143
+ Standard: "STANDARD",
3144
+ GlacierIR: "GLACIER_IR"
3145
+ });
3146
+ enumValues({
3147
+ Push: "push",
3148
+ Pull: "pull",
3149
+ Delete: "delete",
3150
+ Restore: "restore"
3151
+ });
3152
+ enumValues({
3153
+ Success: "success",
3154
+ Error: "error"
3155
+ });
3156
+ enumValues({
3157
+ User: "user",
3158
+ Agent: "agent",
3159
+ Support: "support"
3160
+ });
3161
+ enumValues({
3162
+ Dev: "dev",
3163
+ Test: "test",
3164
+ Live: "live"
3165
+ });
3166
+ //#endregion
3167
+ //#region ../../packages-internal/types/dist/models.js
3168
+ const AnthropicModel = {
3169
+ Opus: "claude-opus-4-6",
3170
+ Sonnet: "claude-sonnet-4-6",
3171
+ Haiku: "claude-haiku-4-5"
3172
+ };
3173
+ const ANTHROPIC_MODELS = enumValues(AnthropicModel);
3174
+ const OpenAIModel = {
3175
+ GPT4o: "gpt-4o",
3176
+ GPT4oMini: "gpt-4o-mini",
3177
+ O3: "o3"
3178
+ };
3179
+ const OPENAI_MODELS = enumValues(OpenAIModel);
3180
+ [...ANTHROPIC_MODELS, ...OPENAI_MODELS];
3181
+ _enum(ANTHROPIC_MODELS);
3182
+ _enum(OPENAI_MODELS);
3183
+ _enum([...ANTHROPIC_MODELS, ...OPENAI_MODELS]);
3184
+ AnthropicModel.Opus, AnthropicModel.Sonnet, AnthropicModel.Haiku, OpenAIModel.GPT4o, OpenAIModel.GPT4oMini, OpenAIModel.O3;
3185
+ AnthropicModel.Opus, AnthropicModel.Sonnet, AnthropicModel.Haiku, OpenAIModel.GPT4o, OpenAIModel.GPT4oMini, OpenAIModel.O3;
94
3186
  //#endregion
95
3187
  //#region src/config.ts
96
3188
  /**
@@ -110,6 +3202,10 @@ const PID_PATH = join(ALFE_DIR, "gateway.pid");
110
3202
  * Returns agentId (derived from tokenId) and orgId (tenantId).
111
3203
  */
112
3204
  async function resolveAgentIdentity(apiKey, apiEndpoint) {
3205
+ logger$1.debug({
3206
+ apiEndpoint,
3207
+ keyPrefix: apiKey.slice(0, 8) + "..."
3208
+ }, "Resolving agent identity...");
113
3209
  const auth = new AuthService(new AlfeApiClient({
114
3210
  apiBaseUrl: apiEndpoint,
115
3211
  getToken: () => Promise.resolve(apiKey)
@@ -117,22 +3213,47 @@ async function resolveAgentIdentity(apiKey, apiEndpoint) {
117
3213
  const maxAttempts = 3;
118
3214
  const delayMs = 3e3;
119
3215
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
3216
+ logger$1.debug({
3217
+ attempt,
3218
+ maxAttempts
3219
+ }, "Validating token...");
120
3220
  const result = await auth.validate(apiKey);
121
3221
  if (!result.ok) {
3222
+ logger$1.debug({
3223
+ status: result.status,
3224
+ error: result.error,
3225
+ attempt
3226
+ }, "Token validation failed");
122
3227
  if (result.status === 401 || result.status === 403) throw new Error(`Token validation failed: ${result.error}. Is your API key valid? Run \`alfe login\` to reconfigure.`);
123
3228
  if (attempt < maxAttempts) {
3229
+ logger$1.debug({
3230
+ delayMs,
3231
+ attempt
3232
+ }, "Retrying token validation after transient error...");
124
3233
  await new Promise((r) => setTimeout(r, delayMs));
125
3234
  continue;
126
3235
  }
127
3236
  throw new Error(`Token validation failed after ${String(maxAttempts)} attempts: ${result.error}. Is your API key valid? Run \`alfe login\` to reconfigure.`);
128
3237
  }
3238
+ logger$1.debug({
3239
+ valid: result.data.valid,
3240
+ tenantId: result.data.tenantId,
3241
+ tokenId: result.data.tokenId
3242
+ }, "Token validation response");
129
3243
  if (!result.data.valid) throw new Error("API key invalid: validation failed. Run `alfe login` to reconfigure.");
130
3244
  const orgId = result.data.tenantId;
131
3245
  if (!orgId) throw new Error("Token validation returned no tenantId — cannot determine org.");
3246
+ const agentId = result.data.tokenId ?? deriveAgentId(apiKey);
3247
+ const runtime = result.data.runtime ?? "openclaw";
3248
+ logger$1.debug({
3249
+ agentId,
3250
+ orgId,
3251
+ runtime
3252
+ }, "Agent identity resolved");
132
3253
  return {
133
- agentId: result.data.tokenId ?? deriveAgentId(apiKey),
3254
+ agentId,
134
3255
  orgId,
135
- runtime: result.data.runtime ?? "openclaw"
3256
+ runtime
136
3257
  };
137
3258
  }
138
3259
  throw new Error("Token validation failed: exhausted retries.");
@@ -191,15 +3312,27 @@ function isManagedMode() {
191
3312
  * All config comes from environment variables — no local files needed.
192
3313
  */
193
3314
  async function loadManagedConfig() {
3315
+ logger$1.debug("Loading managed config from environment...");
194
3316
  const apiKey = process.env.ALFE_API_KEY;
195
3317
  const apiEndpoint = process.env.ALFE_API_ENDPOINT;
196
- if (!apiKey || !apiEndpoint) throw new Error("ALFE_API_KEY and ALFE_API_ENDPOINT required in managed mode");
3318
+ if (!apiKey || !apiEndpoint) throw new Error(`ALFE_API_KEY and ALFE_API_ENDPOINT required in managed mode (apiKey=${apiKey ? "set" : "missing"}, apiEndpoint=${apiEndpoint ? "set" : "missing"})`);
3319
+ logger$1.debug({
3320
+ apiEndpoint,
3321
+ gatewayWsUrlEnv: process.env.ALFE_GATEWAY_WS_URL ?? "(not set)"
3322
+ }, "Environment loaded, resolving identity...");
197
3323
  const identity = await resolveAgentIdentity(apiKey, apiEndpoint);
3324
+ const gatewayWsUrl = process.env.ALFE_GATEWAY_WS_URL ?? deriveGatewayWsUrl(apiEndpoint);
3325
+ logger$1.debug({
3326
+ agentId: identity.agentId,
3327
+ orgId: identity.orgId,
3328
+ runtime: identity.runtime,
3329
+ gatewayWsUrl
3330
+ }, "Managed config resolved");
198
3331
  return {
199
3332
  apiKey,
200
3333
  apiEndpoint,
201
- gatewayWsUrl: process.env.ALFE_GATEWAY_WS_URL ?? deriveGatewayWsUrl(apiEndpoint),
202
- socketPath: "",
3334
+ gatewayWsUrl,
3335
+ socketPath: "/tmp/alfe-gateway.sock",
203
3336
  pidPath: "",
204
3337
  agentId: identity.agentId,
205
3338
  orgId: identity.orgId,
@@ -248,185 +3381,48 @@ async function loadDaemonConfig() {
248
3381
  */
249
3382
  async function fetchAgentConfig(apiKey, apiEndpoint) {
250
3383
  try {
3384
+ logger$1.debug({ apiEndpoint }, "Fetching agent workspace config...");
251
3385
  const wsResponse = await fetch(`${apiEndpoint}/agents/me/workspace`, {
252
3386
  method: "GET",
253
3387
  headers: { "Authorization": `Bearer ${apiKey}` }
254
3388
  });
255
- if (!wsResponse.ok) return null;
3389
+ if (!wsResponse.ok) {
3390
+ logger$1.debug({ status: wsResponse.status }, "Workspace config fetch failed");
3391
+ return null;
3392
+ }
256
3393
  const templateKey = (await wsResponse.json()).data?.templateKey;
257
- if (!templateKey) return null;
3394
+ if (!templateKey) {
3395
+ logger$1.debug("No templateKey in workspace response");
3396
+ return null;
3397
+ }
3398
+ logger$1.debug({ templateKey }, "Fetching template files...");
258
3399
  const filesResponse = await fetch(`${apiEndpoint}/templates/${encodeURIComponent(templateKey)}/files`, {
259
3400
  method: "GET",
260
3401
  headers: { "Authorization": `Bearer ${apiKey}` }
261
3402
  });
262
- if (!filesResponse.ok) return {
3403
+ if (!filesResponse.ok) {
3404
+ logger$1.debug({ status: filesResponse.status }, "Template files fetch failed");
3405
+ return {
3406
+ templateKey,
3407
+ files: {}
3408
+ };
3409
+ }
3410
+ const filesResult = await filesResponse.json();
3411
+ const fileCount = Object.keys(filesResult.data?.files ?? {}).length;
3412
+ logger$1.debug({
263
3413
  templateKey,
264
- files: {}
265
- };
3414
+ fileCount
3415
+ }, "Template files fetched");
266
3416
  return {
267
3417
  templateKey,
268
- files: (await filesResponse.json()).data?.files ?? {}
3418
+ files: filesResult.data?.files ?? {}
269
3419
  };
270
- } catch {
3420
+ } catch (err) {
3421
+ logger$1.debug({ err: err instanceof Error ? err.message : String(err) }, "fetchAgentConfig failed");
271
3422
  return null;
272
3423
  }
273
3424
  }
274
3425
  //#endregion
275
- //#region ../../packages-internal/ids/dist/prefixes.js
276
- const ID_PREFIXES = {
277
- agent: "agt",
278
- organization: "org",
279
- person: "per",
280
- auditEvent: "evt",
281
- token: "tok",
282
- transaction: "txn",
283
- subscription: "sub",
284
- conversation: "conv",
285
- run: "run",
286
- request: "req",
287
- connection: "conn",
288
- correlation: "cor",
289
- command: "cmd",
290
- message: "msg",
291
- ipcRequest: "ipc",
292
- pluginConnection: "plg"
293
- };
294
- //#endregion
295
- //#region ../../packages-internal/ids/dist/create.js
296
- var import_index_umd = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
297
- (function(global, factory) {
298
- typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.ULID = {}));
299
- })(exports, (function(exports$4) {
300
- "use strict";
301
- function createError(message) {
302
- const err = new Error(message);
303
- err.source = "ulid";
304
- return err;
305
- }
306
- const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
307
- const ENCODING_LEN = 32;
308
- const TIME_MAX = Math.pow(2, 48) - 1;
309
- const TIME_LEN = 10;
310
- const RANDOM_LEN = 16;
311
- function replaceCharAt(str, index, char) {
312
- if (index > str.length - 1) return str;
313
- return str.substr(0, index) + char + str.substr(index + 1);
314
- }
315
- function incrementBase32(str) {
316
- let done = void 0;
317
- let index = str.length;
318
- let char;
319
- let charIndex;
320
- const maxCharIndex = ENCODING_LEN - 1;
321
- while (!done && index-- >= 0) {
322
- char = str[index];
323
- charIndex = ENCODING.indexOf(char);
324
- if (charIndex === -1) throw createError("incorrectly encoded string");
325
- if (charIndex === maxCharIndex) {
326
- str = replaceCharAt(str, index, ENCODING[0]);
327
- continue;
328
- }
329
- done = replaceCharAt(str, index, ENCODING[charIndex + 1]);
330
- }
331
- if (typeof done === "string") return done;
332
- throw createError("cannot increment this string");
333
- }
334
- function randomChar(prng) {
335
- let rand = Math.floor(prng() * ENCODING_LEN);
336
- if (rand === ENCODING_LEN) rand = ENCODING_LEN - 1;
337
- return ENCODING.charAt(rand);
338
- }
339
- function encodeTime(now, len) {
340
- if (isNaN(now)) throw new Error(now + " must be a number");
341
- if (now > TIME_MAX) throw createError("cannot encode time greater than " + TIME_MAX);
342
- if (now < 0) throw createError("time must be positive");
343
- if (Number.isInteger(Number(now)) === false) throw createError("time must be an integer");
344
- let mod;
345
- let str = "";
346
- for (; len > 0; len--) {
347
- mod = now % ENCODING_LEN;
348
- str = ENCODING.charAt(mod) + str;
349
- now = (now - mod) / ENCODING_LEN;
350
- }
351
- return str;
352
- }
353
- function encodeRandom(len, prng) {
354
- let str = "";
355
- for (; len > 0; len--) str = randomChar(prng) + str;
356
- return str;
357
- }
358
- function decodeTime(id) {
359
- if (id.length !== TIME_LEN + RANDOM_LEN) throw createError("malformed ulid");
360
- var time = id.substr(0, TIME_LEN).split("").reverse().reduce((carry, char, index) => {
361
- const encodingIndex = ENCODING.indexOf(char);
362
- if (encodingIndex === -1) throw createError("invalid character found: " + char);
363
- return carry += encodingIndex * Math.pow(ENCODING_LEN, index);
364
- }, 0);
365
- if (time > TIME_MAX) throw createError("malformed ulid, timestamp too large");
366
- return time;
367
- }
368
- function detectPrng(allowInsecure = false, root) {
369
- if (!root) root = typeof window !== "undefined" ? window : null;
370
- const browserCrypto = root && (root.crypto || root.msCrypto);
371
- if (browserCrypto) return () => {
372
- const buffer = new Uint8Array(1);
373
- browserCrypto.getRandomValues(buffer);
374
- return buffer[0] / 255;
375
- };
376
- else try {
377
- const nodeCrypto = __require("crypto");
378
- return () => nodeCrypto.randomBytes(1).readUInt8() / 255;
379
- } catch (e) {}
380
- if (allowInsecure) {
381
- try {
382
- console.error("secure crypto unusable, falling back to insecure Math.random()!");
383
- } catch (e) {}
384
- return () => Math.random();
385
- }
386
- throw createError("secure crypto unusable, insecure Math.random not allowed");
387
- }
388
- function factory(currPrng) {
389
- if (!currPrng) currPrng = detectPrng();
390
- return function ulid(seedTime) {
391
- if (isNaN(seedTime)) seedTime = Date.now();
392
- return encodeTime(seedTime, TIME_LEN) + encodeRandom(RANDOM_LEN, currPrng);
393
- };
394
- }
395
- function monotonicFactory(currPrng) {
396
- if (!currPrng) currPrng = detectPrng();
397
- let lastTime = 0;
398
- let lastRandom;
399
- return function ulid(seedTime) {
400
- if (isNaN(seedTime)) seedTime = Date.now();
401
- if (seedTime <= lastTime) {
402
- const incrementedRandom = lastRandom = incrementBase32(lastRandom);
403
- return encodeTime(lastTime, TIME_LEN) + incrementedRandom;
404
- }
405
- lastTime = seedTime;
406
- const newRandom = lastRandom = encodeRandom(RANDOM_LEN, currPrng);
407
- return encodeTime(seedTime, TIME_LEN) + newRandom;
408
- };
409
- }
410
- const ulid = factory();
411
- exports$4.decodeTime = decodeTime;
412
- exports$4.detectPrng = detectPrng;
413
- exports$4.encodeRandom = encodeRandom;
414
- exports$4.encodeTime = encodeTime;
415
- exports$4.factory = factory;
416
- exports$4.incrementBase32 = incrementBase32;
417
- exports$4.monotonicFactory = monotonicFactory;
418
- exports$4.randomChar = randomChar;
419
- exports$4.replaceCharAt = replaceCharAt;
420
- exports$4.ulid = ulid;
421
- }));
422
- })))();
423
- function createId(prefix) {
424
- return `${prefix}_${(0, import_index_umd.ulid)()}`;
425
- }
426
- function pluginConnectionId() {
427
- return createId(ID_PREFIXES.pluginConnection);
428
- }
429
- //#endregion
430
3426
  //#region src/protocol.ts
431
3427
  /**
432
3428
  * Map a cloud command name to an IPC method name.
@@ -782,6 +3778,10 @@ var CloudClient = class {
782
3778
  * Start the cloud connection with auto-reconnect.
783
3779
  */
784
3780
  start() {
3781
+ logger$1.debug({
3782
+ wsUrl: this.config.wsUrl,
3783
+ agentId: this.config.agentId
3784
+ }, "Cloud client starting...");
785
3785
  this.closed = false;
786
3786
  this.doConnect();
787
3787
  }
@@ -789,15 +3789,18 @@ var CloudClient = class {
789
3789
  * Stop the cloud connection and all timers.
790
3790
  */
791
3791
  stop() {
3792
+ logger$1.debug("Cloud client stopping...");
792
3793
  this.closed = true;
793
3794
  this.stopPingTimer();
794
3795
  if (this.ws) {
3796
+ logger$1.debug({ readyState: this.ws.readyState }, "Cloud: closing WebSocket");
795
3797
  try {
796
3798
  this.ws.close(1e3, "Daemon shutting down");
797
3799
  } catch {}
798
3800
  this.ws = null;
799
3801
  }
800
3802
  this.registered = false;
3803
+ logger$1.debug("Cloud client stopped");
801
3804
  }
802
3805
  /**
803
3806
  * Get connection latency (time since last pong).
@@ -808,22 +3811,36 @@ var CloudClient = class {
808
3811
  return Date.now() - this.lastPong;
809
3812
  }
810
3813
  doConnect() {
811
- if (this.closed) return;
812
- logger$1.info({ url: this.config.wsUrl }, "Connecting to cloud gateway...");
3814
+ if (this.closed) {
3815
+ logger$1.debug("Cloud: doConnect skipped client is closed");
3816
+ return;
3817
+ }
3818
+ logger$1.info({
3819
+ url: this.config.wsUrl,
3820
+ backoffMs: this.backoffMs
3821
+ }, "Connecting to cloud gateway...");
3822
+ logger$1.debug({
3823
+ agentId: this.config.agentId,
3824
+ keyPrefix: this.config.apiKey.slice(0, 12) + "..."
3825
+ }, "Cloud: connection details");
813
3826
  this.ws = new WebSocket(this.config.wsUrl, {
814
3827
  headers: { authorization: `Bearer ${this.config.apiKey}` },
815
- maxPayload: 10 * 1024 * 1024
3828
+ maxPayload: 10 * 1024 * 1024,
3829
+ handshakeTimeout: 1e4
816
3830
  });
817
3831
  this.ws.on("open", () => {
818
3832
  logger$1.info("Cloud WebSocket connected");
3833
+ logger$1.debug({ readyState: this.ws?.readyState }, "Cloud: WebSocket open, sending registration...");
819
3834
  this.backoffMs = 1e3;
820
3835
  this.sendRegister();
821
3836
  });
822
3837
  this.ws.on("message", (data) => {
823
3838
  const text = Buffer.isBuffer(data) ? data.toString("utf-8") : Buffer.from(data).toString("utf-8");
3839
+ logger$1.debug({ size: text.length }, "Cloud: received message");
824
3840
  this.handleMessage(text);
825
3841
  });
826
3842
  this.ws.on("ping", () => {
3843
+ logger$1.debug("Cloud: received ping, sending pong");
827
3844
  this.ws?.pong();
828
3845
  });
829
3846
  this.ws.on("close", (code, reason) => {
@@ -837,11 +3854,18 @@ var CloudClient = class {
837
3854
  this.scheduleReconnect();
838
3855
  });
839
3856
  this.ws.on("error", (err) => {
840
- logger$1.error({ err: err.message }, "Cloud WebSocket error");
3857
+ logger$1.error({
3858
+ err: err.message,
3859
+ url: this.config.wsUrl
3860
+ }, "Cloud WebSocket error");
841
3861
  });
842
3862
  }
843
3863
  sendRegister() {
844
3864
  const msg = createServiceRegister(this.config.agentId);
3865
+ logger$1.debug({
3866
+ serviceId: msg.serviceId,
3867
+ agentIds: msg.agentIds
3868
+ }, "Cloud: sending SERVICE_REGISTER");
845
3869
  this.send(msg);
846
3870
  logger$1.info({ serviceId: msg.serviceId }, "Sent SERVICE_REGISTER");
847
3871
  }
@@ -954,6 +3978,7 @@ var CloudClient = class {
954
3978
  }
955
3979
  send(msg) {
956
3980
  if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(msg));
3981
+ else logger$1.debug({ readyState: this.ws?.readyState }, "Cloud: send skipped — WebSocket not open");
957
3982
  }
958
3983
  startPingTimer() {
959
3984
  this.stopPingTimer();
@@ -974,10 +3999,16 @@ var CloudClient = class {
974
3999
  }
975
4000
  }
976
4001
  scheduleReconnect() {
977
- if (this.closed) return;
4002
+ if (this.closed) {
4003
+ logger$1.debug("Cloud: reconnect skipped — client is closed");
4004
+ return;
4005
+ }
978
4006
  const delay = this.backoffMs;
979
4007
  this.backoffMs = Math.min(this.backoffMs * 2, 3e4);
980
- logger$1.info({ delayMs: delay }, "Cloud: reconnecting...");
4008
+ logger$1.info({
4009
+ delayMs: delay,
4010
+ nextBackoffMs: this.backoffMs
4011
+ }, "Cloud: scheduling reconnect...");
981
4012
  setTimeout(() => {
982
4013
  this.doConnect();
983
4014
  }, delay);
@@ -16586,7 +19617,11 @@ var RuntimeProcess = class {
16586
19617
  switch (this.options.runtime) {
16587
19618
  case "openclaw": return {
16588
19619
  command: "openclaw",
16589
- args: ["--workspace", this.options.workspace]
19620
+ args: [
19621
+ "gateway",
19622
+ "run",
19623
+ "--allow-unconfigured"
19624
+ ]
16590
19625
  };
16591
19626
  default: throw new Error(`Unsupported runtime: ${this.options.runtime}`);
16592
19627
  }
@@ -16721,6 +19756,7 @@ var LocalAgentRelay = class {
16721
19756
  * Start connecting to the local runtime WS.
16722
19757
  */
16723
19758
  start() {
19759
+ log.debug({ wsUrl: this.options.wsUrl }, "Local relay starting...");
16724
19760
  this.stopped = false;
16725
19761
  this.doConnect();
16726
19762
  }
@@ -16728,12 +19764,14 @@ var LocalAgentRelay = class {
16728
19764
  * Stop the relay and close the local WS connection.
16729
19765
  */
16730
19766
  stop() {
19767
+ log.debug("Local relay stopping...");
16731
19768
  this.stopped = true;
16732
19769
  if (this.retryTimer) {
16733
19770
  clearTimeout(this.retryTimer);
16734
19771
  this.retryTimer = null;
16735
19772
  }
16736
19773
  if (this.ws) {
19774
+ log.debug({ readyState: this.ws.readyState }, "Local relay: closing WebSocket");
16737
19775
  try {
16738
19776
  this.ws.close(1e3);
16739
19777
  } catch (err) {
@@ -16742,25 +19780,33 @@ var LocalAgentRelay = class {
16742
19780
  this.ws = null;
16743
19781
  }
16744
19782
  this.connected = false;
19783
+ log.debug("Local relay stopped");
16745
19784
  }
16746
19785
  /**
16747
19786
  * Forward a message payload from the cloud to the local runtime WS.
16748
19787
  */
16749
19788
  forward(payload) {
16750
19789
  if (this.ws?.readyState !== WebSocket.OPEN) {
16751
- log.warn("Cannot forward to local runtime — not connected");
19790
+ log.warn({ readyState: this.ws?.readyState }, "Cannot forward to local runtime — not connected");
16752
19791
  return;
16753
19792
  }
16754
19793
  const data = typeof payload === "string" ? payload : JSON.stringify(payload);
19794
+ log.debug({ size: data.length }, "Local relay: forwarding message to runtime");
16755
19795
  this.ws.send(data);
16756
19796
  }
16757
19797
  get isConnected() {
16758
19798
  return this.connected;
16759
19799
  }
16760
19800
  doConnect() {
16761
- if (this.stopped) return;
16762
- log.info({ url: this.options.wsUrl }, "Connecting to local runtime WS...");
16763
- this.ws = new WebSocket(this.options.wsUrl);
19801
+ if (this.stopped) {
19802
+ log.debug("Local relay: doConnect skipped relay is stopped");
19803
+ return;
19804
+ }
19805
+ log.info({
19806
+ url: this.options.wsUrl,
19807
+ retryCount: this.retryCount
19808
+ }, "Connecting to local runtime WS...");
19809
+ this.ws = new WebSocket(this.options.wsUrl, { handshakeTimeout: 1e4 });
16764
19810
  this.ws.on("open", () => {
16765
19811
  log.info("Local runtime WS connected — performing handshake");
16766
19812
  this.retryCount = 0;
@@ -16768,6 +19814,7 @@ var LocalAgentRelay = class {
16768
19814
  });
16769
19815
  this.ws.on("message", (data) => {
16770
19816
  const text = Buffer.isBuffer(data) ? data.toString("utf-8") : Buffer.from(data).toString("utf-8");
19817
+ log.debug({ size: text.length }, "Local relay: received message");
16771
19818
  this.handleLocalMessage(text);
16772
19819
  });
16773
19820
  this.ws.on("close", (code, reason) => {
@@ -16779,10 +19826,14 @@ var LocalAgentRelay = class {
16779
19826
  this.scheduleReconnect();
16780
19827
  });
16781
19828
  this.ws.on("error", (err) => {
16782
- log.debug({ err: err.message }, "Local runtime WS error");
19829
+ log.warn({
19830
+ err: err.message,
19831
+ url: this.options.wsUrl
19832
+ }, "Local runtime WS error");
16783
19833
  });
16784
19834
  }
16785
19835
  performHandshake() {
19836
+ log.debug("Local relay: sending connect handshake");
16786
19837
  const connectReq = {
16787
19838
  type: "req",
16788
19839
  id: randomUUID(),
@@ -16791,7 +19842,7 @@ var LocalAgentRelay = class {
16791
19842
  minProtocol: 3,
16792
19843
  maxProtocol: 3,
16793
19844
  client: {
16794
- id: "alfe-daemon-relay",
19845
+ id: "gateway-client",
16795
19846
  displayName: "Alfe Daemon Relay",
16796
19847
  version: "0.1.0",
16797
19848
  platform: process.platform,
@@ -16869,18 +19920,33 @@ let runtimeProcess = null;
16869
19920
  let localRelay = null;
16870
19921
  let cloudConnected = false;
16871
19922
  let shuttingDown = false;
19923
+ /**
19924
+ * Flush pino's async transport and exit.
19925
+ * process.exit() can drop buffered log lines — this ensures they're written first.
19926
+ */
19927
+ async function flushAndExit(code) {
19928
+ await new Promise((resolve) => {
19929
+ logger$1.flush();
19930
+ setTimeout(resolve, 500);
19931
+ });
19932
+ process.exit(code);
19933
+ }
16872
19934
  async function startDaemon() {
16873
19935
  startedAt = Date.now();
16874
19936
  const managed = isManagedMode();
16875
- logger$1.info({ managed }, "Starting Alfe Gateway Daemon...");
19937
+ logger$1.info({
19938
+ managed,
19939
+ pid: process.pid
19940
+ }, "Starting Alfe Gateway Daemon...");
16876
19941
  if (!managed) {
16877
19942
  await mkdir(join(homedir(), ".alfe"), { recursive: true });
16878
19943
  const existingPid = await checkExistingDaemon();
16879
19944
  if (existingPid) {
16880
19945
  logger$1.error({ pid: existingPid }, "Daemon already running. Use `alfe gateway stop` first.");
16881
- process.exit(1);
19946
+ await flushAndExit(1);
16882
19947
  }
16883
19948
  }
19949
+ logger$1.debug("Loading daemon config...");
16884
19950
  try {
16885
19951
  config = await loadDaemonConfig();
16886
19952
  logger$1.info({
@@ -16890,11 +19956,17 @@ async function startDaemon() {
16890
19956
  }, "Config loaded, identity resolved");
16891
19957
  } catch (err) {
16892
19958
  const message = err instanceof Error ? err.message : String(err);
16893
- logger$1.error({ err: message }, "Failed to load config");
16894
- process.exit(1);
16895
- }
19959
+ const stack = err instanceof Error ? err.stack : void 0;
19960
+ logger$1.error({
19961
+ err: message,
19962
+ stack
19963
+ }, "Failed to load config");
19964
+ await flushAndExit(1);
19965
+ }
19966
+ logger$1.debug("Initializing command queue...");
16896
19967
  commandQueue = new CommandQueue();
16897
19968
  commandQueue.startGC();
19969
+ logger$1.debug("Starting AI proxy...");
16898
19970
  try {
16899
19971
  const { createProxyServer } = await import("@alfe.ai/ai-proxy-local");
16900
19972
  const { getAiServiceUrlFromToken } = await import("@alfe.ai/config");
@@ -16918,17 +19990,31 @@ async function startDaemon() {
16918
19990
  });
16919
19991
  } catch (err) {
16920
19992
  const message = err instanceof Error ? err.message : String(err);
16921
- logger$1.error({ err: message }, "Failed to start AI proxy LLM requests will fail");
19993
+ const stack = err instanceof Error ? err.stack : void 0;
19994
+ logger$1.error({
19995
+ err: message,
19996
+ stack
19997
+ }, "Failed to start AI proxy — LLM requests will fail");
16922
19998
  }
19999
+ logger$1.debug({ socketPath: config.socketPath }, "Starting IPC server...");
16923
20000
  ipcServer = new IPCServer(config.socketPath);
16924
20001
  ipcServer.setRequestHandler(handlePluginRequest);
16925
20002
  try {
16926
20003
  await ipcServer.start();
20004
+ logger$1.debug("IPC server started");
16927
20005
  } catch (err) {
16928
20006
  const message = err instanceof Error ? err.message : String(err);
16929
- logger$1.error({ err: message }, "Failed to start IPC server");
16930
- process.exit(1);
16931
- }
20007
+ const stack = err instanceof Error ? err.stack : void 0;
20008
+ logger$1.error({
20009
+ err: message,
20010
+ stack
20011
+ }, "Failed to start IPC server");
20012
+ await flushAndExit(1);
20013
+ }
20014
+ logger$1.debug({
20015
+ wsUrl: config.gatewayWsUrl,
20016
+ agentId: config.agentId
20017
+ }, "Connecting cloud client...");
16932
20018
  cloudClient = new CloudClient({
16933
20019
  wsUrl: config.gatewayWsUrl,
16934
20020
  apiKey: config.apiKey,
@@ -16955,9 +20041,16 @@ async function startDaemon() {
16955
20041
  const integrationAdapter = new IntegrationManagerAdapter(integrationManager);
16956
20042
  cloudClient.setIntegrationManager(integrationAdapter);
16957
20043
  cloudClient.start();
20044
+ logger$1.debug("Cloud client started");
16958
20045
  if (managed && config.runtime) {
20046
+ logger$1.debug({ runtime: config.runtime }, "Starting agent runtime (managed mode)...");
16959
20047
  const runtimeCfg = config.runtimes[config.runtime];
16960
20048
  if (runtimeCfg) {
20049
+ const runtimeToken = randomUUID();
20050
+ logger$1.debug({
20051
+ runtime: config.runtime,
20052
+ workspace: runtimeCfg.workspace
20053
+ }, "Creating runtime process...");
16961
20054
  runtimeProcess = new RuntimeProcess({
16962
20055
  runtime: config.runtime,
16963
20056
  workspace: runtimeCfg.workspace,
@@ -16967,13 +20060,17 @@ async function startDaemon() {
16967
20060
  ALFE_API_URL: config.apiEndpoint,
16968
20061
  ALFE_AGENT_ID: config.agentId,
16969
20062
  ANTHROPIC_BASE_URL: "http://127.0.0.1:18193",
16970
- OPENAI_BASE_URL: "http://127.0.0.1:18193"
20063
+ OPENAI_BASE_URL: "http://127.0.0.1:18193",
20064
+ OPENCLAW_GATEWAY_TOKEN: runtimeToken
16971
20065
  }
16972
20066
  });
16973
20067
  runtimeProcess.start();
20068
+ logger$1.debug("Runtime process started");
20069
+ const RUNTIME_WS_PORT = 18789;
20070
+ logger$1.debug({ runtimeWsPort: RUNTIME_WS_PORT }, "Creating local agent relay...");
16974
20071
  const relay = new LocalAgentRelay({
16975
- wsUrl: `ws://127.0.0.1:${String(18789)}`,
16976
- apiKey: config.apiKey,
20072
+ wsUrl: `ws://127.0.0.1:${String(RUNTIME_WS_PORT)}`,
20073
+ apiKey: runtimeToken,
16977
20074
  onAgentMessage: (payload) => {
16978
20075
  cloudClient.sendAgentEvent(payload);
16979
20076
  }
@@ -16982,6 +20079,7 @@ async function startDaemon() {
16982
20079
  cloudClient.setServiceRelayHandler((msg) => {
16983
20080
  relay.forward(msg.payload);
16984
20081
  });
20082
+ logger$1.debug("Scheduling local relay start in 2s (waiting for runtime WS server)...");
16985
20083
  setTimeout(() => {
16986
20084
  relay.start();
16987
20085
  }, 2e3);
@@ -16992,22 +20090,38 @@ async function startDaemon() {
16992
20090
  if (shuttingDown) return;
16993
20091
  shuttingDown = true;
16994
20092
  logger$1.info({ signal }, "Shutting down...");
16995
- if (localRelay) localRelay.stop();
16996
- if (runtimeProcess) await runtimeProcess.stop();
16997
- if (ipcServer) await ipcServer.stop();
20093
+ if (localRelay) {
20094
+ logger$1.debug("Stopping local relay...");
20095
+ localRelay.stop();
20096
+ logger$1.debug("Local relay stopped");
20097
+ }
20098
+ if (runtimeProcess) {
20099
+ logger$1.debug("Stopping runtime process...");
20100
+ await runtimeProcess.stop();
20101
+ logger$1.debug("Runtime process stopped");
20102
+ }
20103
+ if (ipcServer) {
20104
+ logger$1.debug("Stopping IPC server...");
20105
+ await ipcServer.stop();
20106
+ logger$1.debug("IPC server stopped");
20107
+ }
16998
20108
  if (aiProxyServer) {
20109
+ logger$1.debug("Stopping AI proxy...");
16999
20110
  const proxy = aiProxyServer;
17000
20111
  await new Promise((resolve) => {
17001
20112
  proxy.close(() => {
17002
20113
  resolve();
17003
20114
  });
17004
20115
  });
20116
+ logger$1.debug("AI proxy stopped");
17005
20117
  }
20118
+ logger$1.debug("Stopping cloud client...");
17006
20119
  cloudClient.stop();
20120
+ logger$1.debug("Cloud client stopped");
17007
20121
  commandQueue.stopGC();
17008
20122
  if (!managed) await removePidFile();
17009
20123
  logger$1.info("Daemon stopped");
17010
- process.exit(0);
20124
+ await flushAndExit(0);
17011
20125
  };
17012
20126
  process.on("SIGTERM", () => {
17013
20127
  shutdown("SIGTERM");
@@ -17259,4 +20373,4 @@ function formatDuration(ms) {
17259
20373
  return `${String(Math.round(seconds / 3600))}h`;
17260
20374
  }
17261
20375
  //#endregion
17262
- export { installService as a, PROTOCOL_VERSION as c, SOCKET_PATH as d, fetchAgentConfig as f, LOG_FILE as h, checkExistingDaemon as i, ALFE_DIR as l, resolveAgentIdentity as m, queryDaemonHealth as n, stopExistingDaemon as o, loadDaemonConfig as p, startDaemon as r, uninstallService as s, formatHealthReport as t, PID_PATH as u };
20376
+ export { installService as a, PROTOCOL_VERSION as c, SOCKET_PATH as d, fetchAgentConfig as f, logger$1 as g, LOG_FILE as h, checkExistingDaemon as i, ALFE_DIR as l, resolveAgentIdentity as m, queryDaemonHealth as n, stopExistingDaemon as o, loadDaemonConfig as p, startDaemon as r, uninstallService as s, formatHealthReport as t, PID_PATH as u };