@ephemushroom/opencode-claude-mem 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/v2.js CHANGED
@@ -1,4 +1,19 @@
1
1
  // @bun
2
+ var __defProp = Object.defineProperty;
3
+ var __returnValue = (v) => v;
4
+ function __exportSetter(name, newValue) {
5
+ this[name] = __returnValue.bind(null, newValue);
6
+ }
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, {
10
+ get: all[name],
11
+ enumerable: true,
12
+ configurable: true,
13
+ set: __exportSetter.bind(all, name)
14
+ });
15
+ };
16
+
2
17
  // node_modules/@opencode-ai/plugin-v2/dist/promise/plugin.js
3
18
  function define(plugin) {
4
19
  return plugin;
@@ -6,7 +21,6 @@ function define(plugin) {
6
21
 
7
22
  // src/shared.ts
8
23
  var MAX_OBSERVATION_BYTES = 24 * 1024;
9
- var MAX_TAG_REPLACEMENTS = 100;
10
24
  var META_TOOLS = new Set([
11
25
  "askuserquestion",
12
26
  "getmcpresource",
@@ -19,26 +33,27 @@ var META_TOOLS = new Set([
19
33
  "slashcommand",
20
34
  "todowrite"
21
35
  ]);
22
- var PRIVATE_TAG_REGEX = /<private>[\s\S]*?<\/private>/g;
23
- var CONTEXT_TAG_REGEX = /<claude-mem-context>[\s\S]*?<\/claude-mem-context>/g;
24
36
  function stripTaggedContent(text) {
25
- if (!text) {
26
- return text;
27
- }
28
- let result = text;
29
- let replacements = 0;
30
- while (replacements < MAX_TAG_REPLACEMENTS && PRIVATE_TAG_REGEX.test(result)) {
31
- PRIVATE_TAG_REGEX.lastIndex = 0;
32
- result = result.replace(PRIVATE_TAG_REGEX, "");
33
- replacements++;
37
+ let result = "";
38
+ let offset = 0;
39
+ const stack = [];
40
+ for (const match of text.matchAll(/<(\/?)(private|claude-mem-context)\b[^>]*>/gi)) {
41
+ if (stack.length === 0) {
42
+ result += text.slice(offset, match.index);
43
+ }
44
+ const name = match[2].toLowerCase();
45
+ if (match[1] === "/") {
46
+ if (stack.at(-1) === name) {
47
+ stack.pop();
48
+ }
49
+ } else {
50
+ stack.push(name);
51
+ }
52
+ offset = match.index + match[0].length;
34
53
  }
35
- PRIVATE_TAG_REGEX.lastIndex = 0;
36
- while (replacements < MAX_TAG_REPLACEMENTS && CONTEXT_TAG_REGEX.test(result)) {
37
- CONTEXT_TAG_REGEX.lastIndex = 0;
38
- result = result.replace(CONTEXT_TAG_REGEX, "");
39
- replacements++;
54
+ if (stack.length === 0) {
55
+ result += text.slice(offset);
40
56
  }
41
- CONTEXT_TAG_REGEX.lastIndex = 0;
42
57
  return result.trim();
43
58
  }
44
59
  function sanitizeObservationValue(value) {
@@ -80,7 +95,7 @@ function shouldSkipObservationTool(toolName) {
80
95
  return true;
81
96
  }
82
97
  const normalizedName = toolName.toLowerCase().replaceAll("_", "-");
83
- if (normalizedName.includes("mcp-search") || /(?:^|[-.])mem-(?:search|timeline|get-observations)$/.test(normalizedName)) {
98
+ if (normalizedName.includes("mcp-search") || /(?:^|[-.])mem-(?:save|search|timeline|get-observations)$/.test(normalizedName)) {
84
99
  return true;
85
100
  }
86
101
  return META_TOOLS.has(normalizedName);
@@ -106,6 +121,9 @@ function extractTextFromParts(parts) {
106
121
  `).trim();
107
122
  }
108
123
 
124
+ // src/file-context.ts
125
+ import { relative, resolve } from "path";
126
+
109
127
  // src/worker-client.ts
110
128
  import { existsSync, readFileSync } from "fs";
111
129
  import { homedir } from "os";
@@ -306,7 +324,16 @@ class WorkerClient {
306
324
  if (!response.ok) {
307
325
  return null;
308
326
  }
309
- return await response.json();
327
+ const value = await response.json();
328
+ if (!isRecord(value) || typeof value.sessionDbId !== "number" || typeof value.promptNumber !== "number" || !Number.isFinite(value.sessionDbId) || !Number.isFinite(value.promptNumber)) {
329
+ return null;
330
+ }
331
+ return {
332
+ sessionDbId: value.sessionDbId,
333
+ promptNumber: value.promptNumber,
334
+ skipped: value.skipped === true,
335
+ reason: typeof value.reason === "string" ? value.reason : undefined
336
+ };
310
337
  } catch {
311
338
  return null;
312
339
  }
@@ -340,8 +367,8 @@ class WorkerClient {
340
367
  headers: { "Content-Type": "application/json" },
341
368
  body: JSON.stringify({
342
369
  contentSessionId,
343
- last_user_message: lastUserMessage,
344
- last_assistant_message: lastAssistantMessage,
370
+ last_user_message: stripTaggedContent(lastUserMessage),
371
+ last_assistant_message: stripTaggedContent(lastAssistantMessage),
345
372
  platformSource: PLATFORM_SOURCE,
346
373
  observedModel: metadata.observedModel,
347
374
  observedBilling: metadata.observedBilling
@@ -354,7 +381,7 @@ class WorkerClient {
354
381
  }
355
382
  static async getContext(project) {
356
383
  try {
357
- const response = await fetch(`${this.BASE_URL}/api/context/inject?project=${encodeURIComponent(project)}`);
384
+ const response = await fetch(`${this.BASE_URL}/api/context/inject?project=${encodeURIComponent(project)}`, { signal: AbortSignal.timeout(2000) });
358
385
  if (!response.ok) {
359
386
  return null;
360
387
  }
@@ -505,182 +532,4204 @@ class WorkerClient {
505
532
  }
506
533
  }
507
534
 
508
- // src/tui-registration.ts
509
- import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
510
- import { homedir as homedir2 } from "os";
511
- import { join as join2 } from "path";
512
- var PACKAGE_NAME = "@ephemushroom/opencode-claude-mem";
513
- var SIDEBAR_ENTRIES = [PACKAGE_NAME, `${PACKAGE_NAME}/cli`, `${PACKAGE_NAME}/tui`];
514
- function getConfigDir() {
515
- const custom = process.env["OPENCODE_CONFIG_DIR"]?.trim();
516
- return custom || join2(homedir2(), ".config", "opencode");
517
- }
518
- function readJson(filePath) {
519
- try {
520
- const parsed = JSON.parse(readFileSync2(filePath, "utf8"));
521
- return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
522
- } catch {
523
- return null;
535
+ // node_modules/zod/v4/core/core.js
536
+ var NEVER = Object.freeze({
537
+ status: "aborted"
538
+ });
539
+ function $constructor(name, initializer, params) {
540
+ function init(inst, def) {
541
+ var _a;
542
+ Object.defineProperty(inst, "_zod", {
543
+ value: inst._zod ?? {},
544
+ enumerable: false
545
+ });
546
+ (_a = inst._zod).traits ?? (_a.traits = new Set);
547
+ inst._zod.traits.add(name);
548
+ initializer(inst, def);
549
+ for (const k in _.prototype) {
550
+ if (!(k in inst))
551
+ Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });
552
+ }
553
+ inst._zod.constr = _;
554
+ inst._zod.def = def;
524
555
  }
525
- }
526
- function isCliEntry(entry) {
527
- if (typeof entry === "string") {
528
- return true;
556
+ const Parent = params?.Parent ?? Object;
557
+
558
+ class Definition extends Parent {
529
559
  }
530
- if (typeof entry !== "object" || entry === null || !("package" in entry)) {
531
- return false;
560
+ Object.defineProperty(Definition, "name", { value: name });
561
+ function _(def) {
562
+ var _a;
563
+ const inst = params?.Parent ? new Definition : this;
564
+ init(inst, def);
565
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
566
+ for (const fn of inst._zod.deferred) {
567
+ fn();
568
+ }
569
+ return inst;
532
570
  }
533
- return typeof entry.package === "string" && (!("options" in entry) || typeof entry.options === "object" && entry.options !== null && !Array.isArray(entry.options));
571
+ Object.defineProperty(_, "init", { value: init });
572
+ Object.defineProperty(_, Symbol.hasInstance, {
573
+ value: (inst) => {
574
+ if (params?.Parent && inst instanceof params.Parent)
575
+ return true;
576
+ return inst?._zod?.traits?.has(name);
577
+ }
578
+ });
579
+ Object.defineProperty(_, "name", { value: name });
580
+ return _;
534
581
  }
535
- function v2PluginEntries(config) {
536
- const { plugins } = config;
537
- if (plugins === undefined) {
538
- return [];
582
+ var $brand = Symbol("zod_brand");
583
+
584
+ class $ZodAsyncError extends Error {
585
+ constructor() {
586
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
539
587
  }
540
- return Array.isArray(plugins) && plugins.every(isCliEntry) ? plugins : null;
541
588
  }
542
- function ensureCliPluginEntry() {
543
- try {
544
- const configDir = getConfigDir();
545
- const cliJsonPath = join2(configDir, "cli.json");
546
- let config = {};
547
- if (existsSync2(cliJsonPath)) {
548
- const parsed = readJson(cliJsonPath);
549
- if (!parsed) {
550
- return "malformed";
589
+
590
+ class $ZodEncodeError extends Error {
591
+ constructor(name) {
592
+ super(`Encountered unidirectional transform during encode: ${name}`);
593
+ this.name = "ZodEncodeError";
594
+ }
595
+ }
596
+ var globalConfig = {};
597
+ function config(newConfig) {
598
+ if (newConfig)
599
+ Object.assign(globalConfig, newConfig);
600
+ return globalConfig;
601
+ }
602
+ // node_modules/zod/v4/core/util.js
603
+ function getEnumValues(entries) {
604
+ const numericValues = Object.values(entries).filter((v) => typeof v === "number");
605
+ const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
606
+ return values;
607
+ }
608
+ function joinValues(array, separator = "|") {
609
+ return array.map((val) => stringifyPrimitive(val)).join(separator);
610
+ }
611
+ function jsonStringifyReplacer(_, value) {
612
+ if (typeof value === "bigint")
613
+ return value.toString();
614
+ return value;
615
+ }
616
+ function cached(getter) {
617
+ const set = false;
618
+ return {
619
+ get value() {
620
+ if (!set) {
621
+ const value = getter();
622
+ Object.defineProperty(this, "value", { value });
623
+ return value;
551
624
  }
552
- config = parsed;
553
- }
554
- const plugins = v2PluginEntries(config);
555
- if (!plugins) {
556
- return "malformed";
625
+ throw new Error("cached value already set");
557
626
  }
558
- if (plugins.some((entry) => {
559
- const specifier = typeof entry === "string" ? entry : entry.package;
560
- return SIDEBAR_ENTRIES.some((name) => specifier === name || specifier.startsWith(`${name}@`));
561
- })) {
562
- return "already-present";
627
+ };
628
+ }
629
+ function nullish(input) {
630
+ return input === null || input === undefined;
631
+ }
632
+ function cleanRegex(source) {
633
+ const start = source.startsWith("^") ? 1 : 0;
634
+ const end = source.endsWith("$") ? source.length - 1 : source.length;
635
+ return source.slice(start, end);
636
+ }
637
+ function floatSafeRemainder(val, step) {
638
+ const valDecCount = (val.toString().split(".")[1] || "").length;
639
+ const stepString = step.toString();
640
+ let stepDecCount = (stepString.split(".")[1] || "").length;
641
+ if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
642
+ const match = stepString.match(/\d?e-(\d?)/);
643
+ if (match?.[1]) {
644
+ stepDecCount = Number.parseInt(match[1]);
563
645
  }
564
- mkdirSync(configDir, { recursive: true });
565
- const next = { ...config, plugins: [...plugins, PACKAGE_NAME] };
566
- writeFileSync(cliJsonPath, `${JSON.stringify(next, null, 2)}
567
- `);
568
- return "added";
569
- } catch {
570
- return "failed";
571
646
  }
647
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
648
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
649
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
650
+ return valInt % stepInt / 10 ** decCount;
572
651
  }
573
-
574
- // src/v2.ts
575
- var EVENT_RETRY_DELAY_MS = 1e4;
576
- var v2_default = define({
577
- id: "claude-mem",
578
- setup: async (ctx) => {
579
- ensureCliPluginEntry();
580
- const controller = new AbortController;
581
- const initializedSessions = new Set;
582
- const sessionInits = new Map;
583
- const contextCache = new Map;
584
- const sessionDirs = new Map;
585
- const sessionUserTexts = new Map;
586
- const sessionAssistantTexts = new Map;
587
- const sessionModels = new Map;
588
- const defaultDirectory = ctx.location.directory;
589
- async function checkWorker() {
590
- return !controller.signal.aborted && await WorkerClient.ensureRunning();
591
- }
592
- async function loadSessionLocation(sessionId) {
593
- if (sessionDirs.has(sessionId)) {
594
- return true;
595
- }
596
- try {
597
- const session = await ctx.session.get({ sessionID: sessionId });
598
- if (controller.signal.aborted || session.location.directory !== defaultDirectory) {
599
- return false;
600
- }
601
- sessionDirs.set(sessionId, session.location.directory);
602
- return true;
603
- } catch {
604
- return false;
652
+ var EVALUATING = Symbol("evaluating");
653
+ function defineLazy(object, key, getter) {
654
+ let value = undefined;
655
+ Object.defineProperty(object, key, {
656
+ get() {
657
+ if (value === EVALUATING) {
658
+ return;
605
659
  }
606
- }
607
- function projectNameFromDirectory(directory) {
608
- return directory.split(/[\\/]/).findLast(Boolean) || "unknown-project";
609
- }
610
- function getProjectName(sessionId) {
611
- return projectNameFromDirectory(sessionDirs.get(sessionId) || defaultDirectory);
612
- }
613
- async function ensureSessionInit(sessionId, prompt) {
614
- if (initializedSessions.has(sessionId)) {
615
- return true;
660
+ if (value === undefined) {
661
+ value = EVALUATING;
662
+ value = getter();
616
663
  }
617
- const existing = sessionInits.get(sessionId);
618
- if (existing) {
619
- return existing;
664
+ return value;
665
+ },
666
+ set(v) {
667
+ Object.defineProperty(object, key, {
668
+ value: v
669
+ });
670
+ },
671
+ configurable: true
672
+ });
673
+ }
674
+ function objectClone(obj) {
675
+ return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
676
+ }
677
+ function assignProp(target, prop, value) {
678
+ Object.defineProperty(target, prop, {
679
+ value,
680
+ writable: true,
681
+ enumerable: true,
682
+ configurable: true
683
+ });
684
+ }
685
+ function mergeDefs(...defs) {
686
+ const mergedDescriptors = {};
687
+ for (const def of defs) {
688
+ const descriptors = Object.getOwnPropertyDescriptors(def);
689
+ Object.assign(mergedDescriptors, descriptors);
690
+ }
691
+ return Object.defineProperties({}, mergedDescriptors);
692
+ }
693
+ function esc(str) {
694
+ return JSON.stringify(str);
695
+ }
696
+ var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
697
+ function isObject(data) {
698
+ return typeof data === "object" && data !== null && !Array.isArray(data);
699
+ }
700
+ var allowsEval = cached(() => {
701
+ if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
702
+ return false;
703
+ }
704
+ try {
705
+ const F = Function;
706
+ new F("");
707
+ return true;
708
+ } catch (_) {
709
+ return false;
710
+ }
711
+ });
712
+ function isPlainObject(o) {
713
+ if (isObject(o) === false)
714
+ return false;
715
+ const ctor = o.constructor;
716
+ if (ctor === undefined)
717
+ return true;
718
+ const prot = ctor.prototype;
719
+ if (isObject(prot) === false)
720
+ return false;
721
+ if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
722
+ return false;
723
+ }
724
+ return true;
725
+ }
726
+ function shallowClone(o) {
727
+ if (isPlainObject(o))
728
+ return { ...o };
729
+ if (Array.isArray(o))
730
+ return [...o];
731
+ return o;
732
+ }
733
+ var propertyKeyTypes = new Set(["string", "number", "symbol"]);
734
+ var primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
735
+ function escapeRegex(str) {
736
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
737
+ }
738
+ function clone(inst, def, params) {
739
+ const cl = new inst._zod.constr(def ?? inst._zod.def);
740
+ if (!def || params?.parent)
741
+ cl._zod.parent = inst;
742
+ return cl;
743
+ }
744
+ function normalizeParams(_params) {
745
+ const params = _params;
746
+ if (!params)
747
+ return {};
748
+ if (typeof params === "string")
749
+ return { error: () => params };
750
+ if (params?.message !== undefined) {
751
+ if (params?.error !== undefined)
752
+ throw new Error("Cannot specify both `message` and `error` params");
753
+ params.error = params.message;
754
+ }
755
+ delete params.message;
756
+ if (typeof params.error === "string")
757
+ return { ...params, error: () => params.error };
758
+ return params;
759
+ }
760
+ function stringifyPrimitive(value) {
761
+ if (typeof value === "bigint")
762
+ return value.toString() + "n";
763
+ if (typeof value === "string")
764
+ return `"${value}"`;
765
+ return `${value}`;
766
+ }
767
+ function optionalKeys(shape) {
768
+ return Object.keys(shape).filter((k) => {
769
+ return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
770
+ });
771
+ }
772
+ var NUMBER_FORMAT_RANGES = {
773
+ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
774
+ int32: [-2147483648, 2147483647],
775
+ uint32: [0, 4294967295],
776
+ float32: [-340282346638528860000000000000000000000, 340282346638528860000000000000000000000],
777
+ float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
778
+ };
779
+ function pick(schema, mask) {
780
+ const currDef = schema._zod.def;
781
+ const def = mergeDefs(schema._zod.def, {
782
+ get shape() {
783
+ const newShape = {};
784
+ for (const key in mask) {
785
+ if (!(key in currDef.shape)) {
786
+ throw new Error(`Unrecognized key: "${key}"`);
787
+ }
788
+ if (!mask[key])
789
+ continue;
790
+ newShape[key] = currDef.shape[key];
620
791
  }
621
- const pending = (async () => {
622
- if (!await checkWorker() || !await loadSessionLocation(sessionId)) {
623
- return false;
792
+ assignProp(this, "shape", newShape);
793
+ return newShape;
794
+ },
795
+ checks: []
796
+ });
797
+ return clone(schema, def);
798
+ }
799
+ function omit(schema, mask) {
800
+ const currDef = schema._zod.def;
801
+ const def = mergeDefs(schema._zod.def, {
802
+ get shape() {
803
+ const newShape = { ...schema._zod.def.shape };
804
+ for (const key in mask) {
805
+ if (!(key in currDef.shape)) {
806
+ throw new Error(`Unrecognized key: "${key}"`);
624
807
  }
625
- const result = await WorkerClient.sessionInit(sessionId, getProjectName(sessionId), prompt || "SESSION_START");
626
- if (!result || controller.signal.aborted || !sessionInits.has(sessionId)) {
627
- return false;
808
+ if (!mask[key])
809
+ continue;
810
+ delete newShape[key];
811
+ }
812
+ assignProp(this, "shape", newShape);
813
+ return newShape;
814
+ },
815
+ checks: []
816
+ });
817
+ return clone(schema, def);
818
+ }
819
+ function extend(schema, shape) {
820
+ if (!isPlainObject(shape)) {
821
+ throw new Error("Invalid input to extend: expected a plain object");
822
+ }
823
+ const checks = schema._zod.def.checks;
824
+ const hasChecks = checks && checks.length > 0;
825
+ if (hasChecks) {
826
+ throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");
827
+ }
828
+ const def = mergeDefs(schema._zod.def, {
829
+ get shape() {
830
+ const _shape = { ...schema._zod.def.shape, ...shape };
831
+ assignProp(this, "shape", _shape);
832
+ return _shape;
833
+ },
834
+ checks: []
835
+ });
836
+ return clone(schema, def);
837
+ }
838
+ function safeExtend(schema, shape) {
839
+ if (!isPlainObject(shape)) {
840
+ throw new Error("Invalid input to safeExtend: expected a plain object");
841
+ }
842
+ const def = {
843
+ ...schema._zod.def,
844
+ get shape() {
845
+ const _shape = { ...schema._zod.def.shape, ...shape };
846
+ assignProp(this, "shape", _shape);
847
+ return _shape;
848
+ },
849
+ checks: schema._zod.def.checks
850
+ };
851
+ return clone(schema, def);
852
+ }
853
+ function merge(a, b) {
854
+ const def = mergeDefs(a._zod.def, {
855
+ get shape() {
856
+ const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
857
+ assignProp(this, "shape", _shape);
858
+ return _shape;
859
+ },
860
+ get catchall() {
861
+ return b._zod.def.catchall;
862
+ },
863
+ checks: []
864
+ });
865
+ return clone(a, def);
866
+ }
867
+ function partial(Class, schema, mask) {
868
+ const def = mergeDefs(schema._zod.def, {
869
+ get shape() {
870
+ const oldShape = schema._zod.def.shape;
871
+ const shape = { ...oldShape };
872
+ if (mask) {
873
+ for (const key in mask) {
874
+ if (!(key in oldShape)) {
875
+ throw new Error(`Unrecognized key: "${key}"`);
876
+ }
877
+ if (!mask[key])
878
+ continue;
879
+ shape[key] = Class ? new Class({
880
+ type: "optional",
881
+ innerType: oldShape[key]
882
+ }) : oldShape[key];
628
883
  }
629
- initializedSessions.add(sessionId);
630
- return true;
631
- })();
632
- sessionInits.set(sessionId, pending);
633
- try {
634
- return await pending;
635
- } finally {
636
- if (sessionInits.get(sessionId) === pending) {
637
- sessionInits.delete(sessionId);
884
+ } else {
885
+ for (const key in oldShape) {
886
+ shape[key] = Class ? new Class({
887
+ type: "optional",
888
+ innerType: oldShape[key]
889
+ }) : oldShape[key];
638
890
  }
639
891
  }
640
- }
641
- async function getCachedContext(sessionId) {
642
- if (!contextCache.has(sessionId)) {
643
- const context = await WorkerClient.getContext(getProjectName(sessionId));
644
- if (context !== null && !controller.signal.aborted && sessionDirs.has(sessionId)) {
645
- contextCache.set(sessionId, context);
892
+ assignProp(this, "shape", shape);
893
+ return shape;
894
+ },
895
+ checks: []
896
+ });
897
+ return clone(schema, def);
898
+ }
899
+ function required(Class, schema, mask) {
900
+ const def = mergeDefs(schema._zod.def, {
901
+ get shape() {
902
+ const oldShape = schema._zod.def.shape;
903
+ const shape = { ...oldShape };
904
+ if (mask) {
905
+ for (const key in mask) {
906
+ if (!(key in shape)) {
907
+ throw new Error(`Unrecognized key: "${key}"`);
908
+ }
909
+ if (!mask[key])
910
+ continue;
911
+ shape[key] = new Class({
912
+ type: "nonoptional",
913
+ innerType: oldShape[key]
914
+ });
915
+ }
916
+ } else {
917
+ for (const key in oldShape) {
918
+ shape[key] = new Class({
919
+ type: "nonoptional",
920
+ innerType: oldShape[key]
921
+ });
646
922
  }
647
923
  }
648
- return contextCache.get(sessionId) ?? null;
924
+ assignProp(this, "shape", shape);
925
+ return shape;
926
+ },
927
+ checks: []
928
+ });
929
+ return clone(schema, def);
930
+ }
931
+ function aborted(x, startIndex = 0) {
932
+ if (x.aborted === true)
933
+ return true;
934
+ for (let i = startIndex;i < x.issues.length; i++) {
935
+ if (x.issues[i]?.continue !== true) {
936
+ return true;
649
937
  }
650
- async function sendObservation(sessionId, toolName, toolInput, toolResponse, toolUseId) {
651
- if (!await ensureSessionInit(sessionId)) {
652
- return;
653
- }
654
- try {
655
- await WorkerClient.sendObservation(sessionId, toolName, toolInput, toolResponse, sessionDirs.get(sessionId) || defaultDirectory, toolUseId);
656
- } catch {}
938
+ }
939
+ return false;
940
+ }
941
+ function prefixIssues(path, issues) {
942
+ return issues.map((iss) => {
943
+ var _a;
944
+ (_a = iss).path ?? (_a.path = []);
945
+ iss.path.unshift(path);
946
+ return iss;
947
+ });
948
+ }
949
+ function unwrapMessage(message) {
950
+ return typeof message === "string" ? message : message?.message;
951
+ }
952
+ function finalizeIssue(iss, ctx, config) {
953
+ const full = { ...iss, path: iss.path ?? [] };
954
+ if (!iss.message) {
955
+ const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
956
+ full.message = message;
957
+ }
958
+ delete full.inst;
959
+ delete full.continue;
960
+ if (!ctx?.reportInput) {
961
+ delete full.input;
962
+ }
963
+ return full;
964
+ }
965
+ function getLengthableOrigin(input) {
966
+ if (Array.isArray(input))
967
+ return "array";
968
+ if (typeof input === "string")
969
+ return "string";
970
+ return "unknown";
971
+ }
972
+ function issue(...args) {
973
+ const [iss, input, inst] = args;
974
+ if (typeof iss === "string") {
975
+ return {
976
+ message: iss,
977
+ code: "custom",
978
+ input,
979
+ inst
980
+ };
981
+ }
982
+ return { ...iss };
983
+ }
984
+
985
+ // node_modules/zod/v4/core/errors.js
986
+ var initializer = (inst, def) => {
987
+ inst.name = "$ZodError";
988
+ Object.defineProperty(inst, "_zod", {
989
+ value: inst._zod,
990
+ enumerable: false
991
+ });
992
+ Object.defineProperty(inst, "issues", {
993
+ value: def,
994
+ enumerable: false
995
+ });
996
+ inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
997
+ Object.defineProperty(inst, "toString", {
998
+ value: () => inst.message,
999
+ enumerable: false
1000
+ });
1001
+ };
1002
+ var $ZodError = $constructor("$ZodError", initializer);
1003
+ var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
1004
+ function flattenError(error, mapper = (issue) => issue.message) {
1005
+ const fieldErrors = {};
1006
+ const formErrors = [];
1007
+ for (const sub of error.issues) {
1008
+ if (sub.path.length > 0) {
1009
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
1010
+ fieldErrors[sub.path[0]].push(mapper(sub));
1011
+ } else {
1012
+ formErrors.push(mapper(sub));
657
1013
  }
658
- function extractLastUserText(messages) {
659
- if (!Array.isArray(messages)) {
660
- return "";
661
- }
662
- for (const message of messages.toReversed()) {
663
- if (message && typeof message === "object" && "role" in message && message.role === "user" && "content" in message && Array.isArray(message.content)) {
664
- const text = extractTextFromParts(message.content);
665
- if (text) {
666
- return text;
1014
+ }
1015
+ return { formErrors, fieldErrors };
1016
+ }
1017
+ function formatError(error, _mapper) {
1018
+ const mapper = _mapper || function(issue) {
1019
+ return issue.message;
1020
+ };
1021
+ const fieldErrors = { _errors: [] };
1022
+ const processError = (error) => {
1023
+ for (const issue of error.issues) {
1024
+ if (issue.code === "invalid_union" && issue.errors.length) {
1025
+ issue.errors.map((issues) => processError({ issues }));
1026
+ } else if (issue.code === "invalid_key") {
1027
+ processError({ issues: issue.issues });
1028
+ } else if (issue.code === "invalid_element") {
1029
+ processError({ issues: issue.issues });
1030
+ } else if (issue.path.length === 0) {
1031
+ fieldErrors._errors.push(mapper(issue));
1032
+ } else {
1033
+ let curr = fieldErrors;
1034
+ let i = 0;
1035
+ while (i < issue.path.length) {
1036
+ const el = issue.path[i];
1037
+ const terminal = i === issue.path.length - 1;
1038
+ if (!terminal) {
1039
+ curr[el] = curr[el] || { _errors: [] };
1040
+ } else {
1041
+ curr[el] = curr[el] || { _errors: [] };
1042
+ curr[el]._errors.push(mapper(issue));
667
1043
  }
1044
+ curr = curr[el];
1045
+ i++;
668
1046
  }
669
1047
  }
670
- return "";
671
1048
  }
672
- function normalizeToolResult(result) {
673
- if (typeof result === "string") {
674
- return result;
675
- }
676
- if (!result || typeof result !== "object") {
677
- return normalizeToolOutput(result);
1049
+ };
1050
+ processError(error);
1051
+ return fieldErrors;
1052
+ }
1053
+
1054
+ // node_modules/zod/v4/core/parse.js
1055
+ var _parse = (_Err) => (schema, value, _ctx, _params) => {
1056
+ const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
1057
+ const result = schema._zod.run({ value, issues: [] }, ctx);
1058
+ if (result instanceof Promise) {
1059
+ throw new $ZodAsyncError;
1060
+ }
1061
+ if (result.issues.length) {
1062
+ const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
1063
+ captureStackTrace(e, _params?.callee);
1064
+ throw e;
1065
+ }
1066
+ return result.value;
1067
+ };
1068
+ var _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
1069
+ const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
1070
+ let result = schema._zod.run({ value, issues: [] }, ctx);
1071
+ if (result instanceof Promise)
1072
+ result = await result;
1073
+ if (result.issues.length) {
1074
+ const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
1075
+ captureStackTrace(e, params?.callee);
1076
+ throw e;
1077
+ }
1078
+ return result.value;
1079
+ };
1080
+ var _safeParse = (_Err) => (schema, value, _ctx) => {
1081
+ const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
1082
+ const result = schema._zod.run({ value, issues: [] }, ctx);
1083
+ if (result instanceof Promise) {
1084
+ throw new $ZodAsyncError;
1085
+ }
1086
+ return result.issues.length ? {
1087
+ success: false,
1088
+ error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
1089
+ } : { success: true, data: result.value };
1090
+ };
1091
+ var safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
1092
+ var _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
1093
+ const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
1094
+ let result = schema._zod.run({ value, issues: [] }, ctx);
1095
+ if (result instanceof Promise)
1096
+ result = await result;
1097
+ return result.issues.length ? {
1098
+ success: false,
1099
+ error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
1100
+ } : { success: true, data: result.value };
1101
+ };
1102
+ var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
1103
+ var _encode = (_Err) => (schema, value, _ctx) => {
1104
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
1105
+ return _parse(_Err)(schema, value, ctx);
1106
+ };
1107
+ var _decode = (_Err) => (schema, value, _ctx) => {
1108
+ return _parse(_Err)(schema, value, _ctx);
1109
+ };
1110
+ var _encodeAsync = (_Err) => async (schema, value, _ctx) => {
1111
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
1112
+ return _parseAsync(_Err)(schema, value, ctx);
1113
+ };
1114
+ var _decodeAsync = (_Err) => async (schema, value, _ctx) => {
1115
+ return _parseAsync(_Err)(schema, value, _ctx);
1116
+ };
1117
+ var _safeEncode = (_Err) => (schema, value, _ctx) => {
1118
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
1119
+ return _safeParse(_Err)(schema, value, ctx);
1120
+ };
1121
+ var _safeDecode = (_Err) => (schema, value, _ctx) => {
1122
+ return _safeParse(_Err)(schema, value, _ctx);
1123
+ };
1124
+ var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
1125
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
1126
+ return _safeParseAsync(_Err)(schema, value, ctx);
1127
+ };
1128
+ var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
1129
+ return _safeParseAsync(_Err)(schema, value, _ctx);
1130
+ };
1131
+ // node_modules/zod/v4/core/regexes.js
1132
+ var cuid = /^[cC][^\s-]{8,}$/;
1133
+ var cuid2 = /^[0-9a-z]+$/;
1134
+ var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
1135
+ var xid = /^[0-9a-vA-V]{20}$/;
1136
+ var ksuid = /^[A-Za-z0-9]{27}$/;
1137
+ var nanoid = /^[a-zA-Z0-9_-]{21}$/;
1138
+ var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
1139
+ var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
1140
+ var uuid = (version) => {
1141
+ if (!version)
1142
+ return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
1143
+ return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
1144
+ };
1145
+ var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
1146
+ var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1147
+ function emoji() {
1148
+ return new RegExp(_emoji, "u");
1149
+ }
1150
+ var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
1151
+ var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
1152
+ var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
1153
+ var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
1154
+ var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
1155
+ var base64url = /^[A-Za-z0-9_-]*$/;
1156
+ var hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
1157
+ var e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
1158
+ var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
1159
+ var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
1160
+ function timeSource(args) {
1161
+ const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
1162
+ const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
1163
+ return regex;
1164
+ }
1165
+ function time(args) {
1166
+ return new RegExp(`^${timeSource(args)}$`);
1167
+ }
1168
+ function datetime(args) {
1169
+ const time = timeSource({ precision: args.precision });
1170
+ const opts = ["Z"];
1171
+ if (args.local)
1172
+ opts.push("");
1173
+ if (args.offset)
1174
+ opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
1175
+ const timeRegex = `${time}(?:${opts.join("|")})`;
1176
+ return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
1177
+ }
1178
+ var string = (params) => {
1179
+ const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
1180
+ return new RegExp(`^${regex}$`);
1181
+ };
1182
+ var bigint = /^-?\d+n?$/;
1183
+ var integer = /^-?\d+$/;
1184
+ var number = /^-?\d+(?:\.\d+)?/;
1185
+ var boolean = /^(?:true|false)$/i;
1186
+ var lowercase = /^[^A-Z]*$/;
1187
+ var uppercase = /^[^a-z]*$/;
1188
+
1189
+ // node_modules/zod/v4/core/checks.js
1190
+ var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
1191
+ var _a;
1192
+ inst._zod ?? (inst._zod = {});
1193
+ inst._zod.def = def;
1194
+ (_a = inst._zod).onattach ?? (_a.onattach = []);
1195
+ });
1196
+ var numericOriginMap = {
1197
+ number: "number",
1198
+ bigint: "bigint",
1199
+ object: "date"
1200
+ };
1201
+ var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
1202
+ $ZodCheck.init(inst, def);
1203
+ const origin = numericOriginMap[typeof def.value];
1204
+ inst._zod.onattach.push((inst) => {
1205
+ const bag = inst._zod.bag;
1206
+ const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
1207
+ if (def.value < curr) {
1208
+ if (def.inclusive)
1209
+ bag.maximum = def.value;
1210
+ else
1211
+ bag.exclusiveMaximum = def.value;
1212
+ }
1213
+ });
1214
+ inst._zod.check = (payload) => {
1215
+ if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
1216
+ return;
1217
+ }
1218
+ payload.issues.push({
1219
+ origin,
1220
+ code: "too_big",
1221
+ maximum: def.value,
1222
+ input: payload.value,
1223
+ inclusive: def.inclusive,
1224
+ inst,
1225
+ continue: !def.abort
1226
+ });
1227
+ };
1228
+ });
1229
+ var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
1230
+ $ZodCheck.init(inst, def);
1231
+ const origin = numericOriginMap[typeof def.value];
1232
+ inst._zod.onattach.push((inst) => {
1233
+ const bag = inst._zod.bag;
1234
+ const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
1235
+ if (def.value > curr) {
1236
+ if (def.inclusive)
1237
+ bag.minimum = def.value;
1238
+ else
1239
+ bag.exclusiveMinimum = def.value;
1240
+ }
1241
+ });
1242
+ inst._zod.check = (payload) => {
1243
+ if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
1244
+ return;
1245
+ }
1246
+ payload.issues.push({
1247
+ origin,
1248
+ code: "too_small",
1249
+ minimum: def.value,
1250
+ input: payload.value,
1251
+ inclusive: def.inclusive,
1252
+ inst,
1253
+ continue: !def.abort
1254
+ });
1255
+ };
1256
+ });
1257
+ var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
1258
+ $ZodCheck.init(inst, def);
1259
+ inst._zod.onattach.push((inst) => {
1260
+ var _a;
1261
+ (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
1262
+ });
1263
+ inst._zod.check = (payload) => {
1264
+ if (typeof payload.value !== typeof def.value)
1265
+ throw new Error("Cannot mix number and bigint in multiple_of check.");
1266
+ const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0;
1267
+ if (isMultiple)
1268
+ return;
1269
+ payload.issues.push({
1270
+ origin: typeof payload.value,
1271
+ code: "not_multiple_of",
1272
+ divisor: def.value,
1273
+ input: payload.value,
1274
+ inst,
1275
+ continue: !def.abort
1276
+ });
1277
+ };
1278
+ });
1279
+ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
1280
+ $ZodCheck.init(inst, def);
1281
+ def.format = def.format || "float64";
1282
+ const isInt = def.format?.includes("int");
1283
+ const origin = isInt ? "int" : "number";
1284
+ const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
1285
+ inst._zod.onattach.push((inst) => {
1286
+ const bag = inst._zod.bag;
1287
+ bag.format = def.format;
1288
+ bag.minimum = minimum;
1289
+ bag.maximum = maximum;
1290
+ if (isInt)
1291
+ bag.pattern = integer;
1292
+ });
1293
+ inst._zod.check = (payload) => {
1294
+ const input = payload.value;
1295
+ if (isInt) {
1296
+ if (!Number.isInteger(input)) {
1297
+ payload.issues.push({
1298
+ expected: origin,
1299
+ format: def.format,
1300
+ code: "invalid_type",
1301
+ continue: false,
1302
+ input,
1303
+ inst
1304
+ });
1305
+ return;
678
1306
  }
679
- const content = "content" in result ? result.content : undefined;
680
- if (typeof content === "string") {
681
- return content;
1307
+ if (!Number.isSafeInteger(input)) {
1308
+ if (input > 0) {
1309
+ payload.issues.push({
1310
+ input,
1311
+ code: "too_big",
1312
+ maximum: Number.MAX_SAFE_INTEGER,
1313
+ note: "Integers must be within the safe integer range.",
1314
+ inst,
1315
+ origin,
1316
+ continue: !def.abort
1317
+ });
1318
+ } else {
1319
+ payload.issues.push({
1320
+ input,
1321
+ code: "too_small",
1322
+ minimum: Number.MIN_SAFE_INTEGER,
1323
+ note: "Integers must be within the safe integer range.",
1324
+ inst,
1325
+ origin,
1326
+ continue: !def.abort
1327
+ });
1328
+ }
1329
+ return;
682
1330
  }
683
- if (Array.isArray(content)) {
1331
+ }
1332
+ if (input < minimum) {
1333
+ payload.issues.push({
1334
+ origin: "number",
1335
+ input,
1336
+ code: "too_small",
1337
+ minimum,
1338
+ inclusive: true,
1339
+ inst,
1340
+ continue: !def.abort
1341
+ });
1342
+ }
1343
+ if (input > maximum) {
1344
+ payload.issues.push({
1345
+ origin: "number",
1346
+ input,
1347
+ code: "too_big",
1348
+ maximum,
1349
+ inst
1350
+ });
1351
+ }
1352
+ };
1353
+ });
1354
+ var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
1355
+ var _a;
1356
+ $ZodCheck.init(inst, def);
1357
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1358
+ const val = payload.value;
1359
+ return !nullish(val) && val.length !== undefined;
1360
+ });
1361
+ inst._zod.onattach.push((inst) => {
1362
+ const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
1363
+ if (def.maximum < curr)
1364
+ inst._zod.bag.maximum = def.maximum;
1365
+ });
1366
+ inst._zod.check = (payload) => {
1367
+ const input = payload.value;
1368
+ const length = input.length;
1369
+ if (length <= def.maximum)
1370
+ return;
1371
+ const origin = getLengthableOrigin(input);
1372
+ payload.issues.push({
1373
+ origin,
1374
+ code: "too_big",
1375
+ maximum: def.maximum,
1376
+ inclusive: true,
1377
+ input,
1378
+ inst,
1379
+ continue: !def.abort
1380
+ });
1381
+ };
1382
+ });
1383
+ var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
1384
+ var _a;
1385
+ $ZodCheck.init(inst, def);
1386
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1387
+ const val = payload.value;
1388
+ return !nullish(val) && val.length !== undefined;
1389
+ });
1390
+ inst._zod.onattach.push((inst) => {
1391
+ const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
1392
+ if (def.minimum > curr)
1393
+ inst._zod.bag.minimum = def.minimum;
1394
+ });
1395
+ inst._zod.check = (payload) => {
1396
+ const input = payload.value;
1397
+ const length = input.length;
1398
+ if (length >= def.minimum)
1399
+ return;
1400
+ const origin = getLengthableOrigin(input);
1401
+ payload.issues.push({
1402
+ origin,
1403
+ code: "too_small",
1404
+ minimum: def.minimum,
1405
+ inclusive: true,
1406
+ input,
1407
+ inst,
1408
+ continue: !def.abort
1409
+ });
1410
+ };
1411
+ });
1412
+ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
1413
+ var _a;
1414
+ $ZodCheck.init(inst, def);
1415
+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1416
+ const val = payload.value;
1417
+ return !nullish(val) && val.length !== undefined;
1418
+ });
1419
+ inst._zod.onattach.push((inst) => {
1420
+ const bag = inst._zod.bag;
1421
+ bag.minimum = def.length;
1422
+ bag.maximum = def.length;
1423
+ bag.length = def.length;
1424
+ });
1425
+ inst._zod.check = (payload) => {
1426
+ const input = payload.value;
1427
+ const length = input.length;
1428
+ if (length === def.length)
1429
+ return;
1430
+ const origin = getLengthableOrigin(input);
1431
+ const tooBig = length > def.length;
1432
+ payload.issues.push({
1433
+ origin,
1434
+ ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length },
1435
+ inclusive: true,
1436
+ exact: true,
1437
+ input: payload.value,
1438
+ inst,
1439
+ continue: !def.abort
1440
+ });
1441
+ };
1442
+ });
1443
+ var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
1444
+ var _a, _b;
1445
+ $ZodCheck.init(inst, def);
1446
+ inst._zod.onattach.push((inst) => {
1447
+ const bag = inst._zod.bag;
1448
+ bag.format = def.format;
1449
+ if (def.pattern) {
1450
+ bag.patterns ?? (bag.patterns = new Set);
1451
+ bag.patterns.add(def.pattern);
1452
+ }
1453
+ });
1454
+ if (def.pattern)
1455
+ (_a = inst._zod).check ?? (_a.check = (payload) => {
1456
+ def.pattern.lastIndex = 0;
1457
+ if (def.pattern.test(payload.value))
1458
+ return;
1459
+ payload.issues.push({
1460
+ origin: "string",
1461
+ code: "invalid_format",
1462
+ format: def.format,
1463
+ input: payload.value,
1464
+ ...def.pattern ? { pattern: def.pattern.toString() } : {},
1465
+ inst,
1466
+ continue: !def.abort
1467
+ });
1468
+ });
1469
+ else
1470
+ (_b = inst._zod).check ?? (_b.check = () => {});
1471
+ });
1472
+ var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
1473
+ $ZodCheckStringFormat.init(inst, def);
1474
+ inst._zod.check = (payload) => {
1475
+ def.pattern.lastIndex = 0;
1476
+ if (def.pattern.test(payload.value))
1477
+ return;
1478
+ payload.issues.push({
1479
+ origin: "string",
1480
+ code: "invalid_format",
1481
+ format: "regex",
1482
+ input: payload.value,
1483
+ pattern: def.pattern.toString(),
1484
+ inst,
1485
+ continue: !def.abort
1486
+ });
1487
+ };
1488
+ });
1489
+ var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
1490
+ def.pattern ?? (def.pattern = lowercase);
1491
+ $ZodCheckStringFormat.init(inst, def);
1492
+ });
1493
+ var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
1494
+ def.pattern ?? (def.pattern = uppercase);
1495
+ $ZodCheckStringFormat.init(inst, def);
1496
+ });
1497
+ var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
1498
+ $ZodCheck.init(inst, def);
1499
+ const escapedRegex = escapeRegex(def.includes);
1500
+ const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
1501
+ def.pattern = pattern;
1502
+ inst._zod.onattach.push((inst) => {
1503
+ const bag = inst._zod.bag;
1504
+ bag.patterns ?? (bag.patterns = new Set);
1505
+ bag.patterns.add(pattern);
1506
+ });
1507
+ inst._zod.check = (payload) => {
1508
+ if (payload.value.includes(def.includes, def.position))
1509
+ return;
1510
+ payload.issues.push({
1511
+ origin: "string",
1512
+ code: "invalid_format",
1513
+ format: "includes",
1514
+ includes: def.includes,
1515
+ input: payload.value,
1516
+ inst,
1517
+ continue: !def.abort
1518
+ });
1519
+ };
1520
+ });
1521
+ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
1522
+ $ZodCheck.init(inst, def);
1523
+ const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
1524
+ def.pattern ?? (def.pattern = pattern);
1525
+ inst._zod.onattach.push((inst) => {
1526
+ const bag = inst._zod.bag;
1527
+ bag.patterns ?? (bag.patterns = new Set);
1528
+ bag.patterns.add(pattern);
1529
+ });
1530
+ inst._zod.check = (payload) => {
1531
+ if (payload.value.startsWith(def.prefix))
1532
+ return;
1533
+ payload.issues.push({
1534
+ origin: "string",
1535
+ code: "invalid_format",
1536
+ format: "starts_with",
1537
+ prefix: def.prefix,
1538
+ input: payload.value,
1539
+ inst,
1540
+ continue: !def.abort
1541
+ });
1542
+ };
1543
+ });
1544
+ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
1545
+ $ZodCheck.init(inst, def);
1546
+ const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
1547
+ def.pattern ?? (def.pattern = pattern);
1548
+ inst._zod.onattach.push((inst) => {
1549
+ const bag = inst._zod.bag;
1550
+ bag.patterns ?? (bag.patterns = new Set);
1551
+ bag.patterns.add(pattern);
1552
+ });
1553
+ inst._zod.check = (payload) => {
1554
+ if (payload.value.endsWith(def.suffix))
1555
+ return;
1556
+ payload.issues.push({
1557
+ origin: "string",
1558
+ code: "invalid_format",
1559
+ format: "ends_with",
1560
+ suffix: def.suffix,
1561
+ input: payload.value,
1562
+ inst,
1563
+ continue: !def.abort
1564
+ });
1565
+ };
1566
+ });
1567
+ var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
1568
+ $ZodCheck.init(inst, def);
1569
+ inst._zod.check = (payload) => {
1570
+ payload.value = def.tx(payload.value);
1571
+ };
1572
+ });
1573
+
1574
+ // node_modules/zod/v4/core/doc.js
1575
+ class Doc {
1576
+ constructor(args = []) {
1577
+ this.content = [];
1578
+ this.indent = 0;
1579
+ if (this)
1580
+ this.args = args;
1581
+ }
1582
+ indented(fn) {
1583
+ this.indent += 1;
1584
+ fn(this);
1585
+ this.indent -= 1;
1586
+ }
1587
+ write(arg) {
1588
+ if (typeof arg === "function") {
1589
+ arg(this, { execution: "sync" });
1590
+ arg(this, { execution: "async" });
1591
+ return;
1592
+ }
1593
+ const content = arg;
1594
+ const lines = content.split(`
1595
+ `).filter((x) => x);
1596
+ const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
1597
+ const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
1598
+ for (const line of dedented) {
1599
+ this.content.push(line);
1600
+ }
1601
+ }
1602
+ compile() {
1603
+ const F = Function;
1604
+ const args = this?.args;
1605
+ const content = this?.content ?? [``];
1606
+ const lines = [...content.map((x) => ` ${x}`)];
1607
+ return new F(...args, lines.join(`
1608
+ `));
1609
+ }
1610
+ }
1611
+
1612
+ // node_modules/zod/v4/core/versions.js
1613
+ var version = {
1614
+ major: 4,
1615
+ minor: 1,
1616
+ patch: 8
1617
+ };
1618
+
1619
+ // node_modules/zod/v4/core/schemas.js
1620
+ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
1621
+ var _a;
1622
+ inst ?? (inst = {});
1623
+ inst._zod.def = def;
1624
+ inst._zod.bag = inst._zod.bag || {};
1625
+ inst._zod.version = version;
1626
+ const checks = [...inst._zod.def.checks ?? []];
1627
+ if (inst._zod.traits.has("$ZodCheck")) {
1628
+ checks.unshift(inst);
1629
+ }
1630
+ for (const ch of checks) {
1631
+ for (const fn of ch._zod.onattach) {
1632
+ fn(inst);
1633
+ }
1634
+ }
1635
+ if (checks.length === 0) {
1636
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
1637
+ inst._zod.deferred?.push(() => {
1638
+ inst._zod.run = inst._zod.parse;
1639
+ });
1640
+ } else {
1641
+ const runChecks = (payload, checks, ctx) => {
1642
+ let isAborted = aborted(payload);
1643
+ let asyncResult;
1644
+ for (const ch of checks) {
1645
+ if (ch._zod.def.when) {
1646
+ const shouldRun = ch._zod.def.when(payload);
1647
+ if (!shouldRun)
1648
+ continue;
1649
+ } else if (isAborted) {
1650
+ continue;
1651
+ }
1652
+ const currLen = payload.issues.length;
1653
+ const _ = ch._zod.check(payload);
1654
+ if (_ instanceof Promise && ctx?.async === false) {
1655
+ throw new $ZodAsyncError;
1656
+ }
1657
+ if (asyncResult || _ instanceof Promise) {
1658
+ asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
1659
+ await _;
1660
+ const nextLen = payload.issues.length;
1661
+ if (nextLen === currLen)
1662
+ return;
1663
+ if (!isAborted)
1664
+ isAborted = aborted(payload, currLen);
1665
+ });
1666
+ } else {
1667
+ const nextLen = payload.issues.length;
1668
+ if (nextLen === currLen)
1669
+ continue;
1670
+ if (!isAborted)
1671
+ isAborted = aborted(payload, currLen);
1672
+ }
1673
+ }
1674
+ if (asyncResult) {
1675
+ return asyncResult.then(() => {
1676
+ return payload;
1677
+ });
1678
+ }
1679
+ return payload;
1680
+ };
1681
+ const handleCanaryResult = (canary, payload, ctx) => {
1682
+ if (aborted(canary)) {
1683
+ canary.aborted = true;
1684
+ return canary;
1685
+ }
1686
+ const checkResult = runChecks(payload, checks, ctx);
1687
+ if (checkResult instanceof Promise) {
1688
+ if (ctx.async === false)
1689
+ throw new $ZodAsyncError;
1690
+ return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));
1691
+ }
1692
+ return inst._zod.parse(checkResult, ctx);
1693
+ };
1694
+ inst._zod.run = (payload, ctx) => {
1695
+ if (ctx.skipChecks) {
1696
+ return inst._zod.parse(payload, ctx);
1697
+ }
1698
+ if (ctx.direction === "backward") {
1699
+ const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });
1700
+ if (canary instanceof Promise) {
1701
+ return canary.then((canary) => {
1702
+ return handleCanaryResult(canary, payload, ctx);
1703
+ });
1704
+ }
1705
+ return handleCanaryResult(canary, payload, ctx);
1706
+ }
1707
+ const result = inst._zod.parse(payload, ctx);
1708
+ if (result instanceof Promise) {
1709
+ if (ctx.async === false)
1710
+ throw new $ZodAsyncError;
1711
+ return result.then((result) => runChecks(result, checks, ctx));
1712
+ }
1713
+ return runChecks(result, checks, ctx);
1714
+ };
1715
+ }
1716
+ inst["~standard"] = {
1717
+ validate: (value) => {
1718
+ try {
1719
+ const r = safeParse(inst, value);
1720
+ return r.success ? { value: r.data } : { issues: r.error?.issues };
1721
+ } catch (_) {
1722
+ return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
1723
+ }
1724
+ },
1725
+ vendor: "zod",
1726
+ version: 1
1727
+ };
1728
+ });
1729
+ var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
1730
+ $ZodType.init(inst, def);
1731
+ inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag);
1732
+ inst._zod.parse = (payload, _) => {
1733
+ if (def.coerce)
1734
+ try {
1735
+ payload.value = String(payload.value);
1736
+ } catch (_) {}
1737
+ if (typeof payload.value === "string")
1738
+ return payload;
1739
+ payload.issues.push({
1740
+ expected: "string",
1741
+ code: "invalid_type",
1742
+ input: payload.value,
1743
+ inst
1744
+ });
1745
+ return payload;
1746
+ };
1747
+ });
1748
+ var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
1749
+ $ZodCheckStringFormat.init(inst, def);
1750
+ $ZodString.init(inst, def);
1751
+ });
1752
+ var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
1753
+ def.pattern ?? (def.pattern = guid);
1754
+ $ZodStringFormat.init(inst, def);
1755
+ });
1756
+ var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
1757
+ if (def.version) {
1758
+ const versionMap = {
1759
+ v1: 1,
1760
+ v2: 2,
1761
+ v3: 3,
1762
+ v4: 4,
1763
+ v5: 5,
1764
+ v6: 6,
1765
+ v7: 7,
1766
+ v8: 8
1767
+ };
1768
+ const v = versionMap[def.version];
1769
+ if (v === undefined)
1770
+ throw new Error(`Invalid UUID version: "${def.version}"`);
1771
+ def.pattern ?? (def.pattern = uuid(v));
1772
+ } else
1773
+ def.pattern ?? (def.pattern = uuid());
1774
+ $ZodStringFormat.init(inst, def);
1775
+ });
1776
+ var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
1777
+ def.pattern ?? (def.pattern = email);
1778
+ $ZodStringFormat.init(inst, def);
1779
+ });
1780
+ var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
1781
+ $ZodStringFormat.init(inst, def);
1782
+ inst._zod.check = (payload) => {
1783
+ try {
1784
+ const trimmed = payload.value.trim();
1785
+ const url = new URL(trimmed);
1786
+ if (def.hostname) {
1787
+ def.hostname.lastIndex = 0;
1788
+ if (!def.hostname.test(url.hostname)) {
1789
+ payload.issues.push({
1790
+ code: "invalid_format",
1791
+ format: "url",
1792
+ note: "Invalid hostname",
1793
+ pattern: hostname.source,
1794
+ input: payload.value,
1795
+ inst,
1796
+ continue: !def.abort
1797
+ });
1798
+ }
1799
+ }
1800
+ if (def.protocol) {
1801
+ def.protocol.lastIndex = 0;
1802
+ if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) {
1803
+ payload.issues.push({
1804
+ code: "invalid_format",
1805
+ format: "url",
1806
+ note: "Invalid protocol",
1807
+ pattern: def.protocol.source,
1808
+ input: payload.value,
1809
+ inst,
1810
+ continue: !def.abort
1811
+ });
1812
+ }
1813
+ }
1814
+ if (def.normalize) {
1815
+ payload.value = url.href;
1816
+ } else {
1817
+ payload.value = trimmed;
1818
+ }
1819
+ return;
1820
+ } catch (_) {
1821
+ payload.issues.push({
1822
+ code: "invalid_format",
1823
+ format: "url",
1824
+ input: payload.value,
1825
+ inst,
1826
+ continue: !def.abort
1827
+ });
1828
+ }
1829
+ };
1830
+ });
1831
+ var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
1832
+ def.pattern ?? (def.pattern = emoji());
1833
+ $ZodStringFormat.init(inst, def);
1834
+ });
1835
+ var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
1836
+ def.pattern ?? (def.pattern = nanoid);
1837
+ $ZodStringFormat.init(inst, def);
1838
+ });
1839
+ var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
1840
+ def.pattern ?? (def.pattern = cuid);
1841
+ $ZodStringFormat.init(inst, def);
1842
+ });
1843
+ var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
1844
+ def.pattern ?? (def.pattern = cuid2);
1845
+ $ZodStringFormat.init(inst, def);
1846
+ });
1847
+ var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
1848
+ def.pattern ?? (def.pattern = ulid);
1849
+ $ZodStringFormat.init(inst, def);
1850
+ });
1851
+ var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
1852
+ def.pattern ?? (def.pattern = xid);
1853
+ $ZodStringFormat.init(inst, def);
1854
+ });
1855
+ var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
1856
+ def.pattern ?? (def.pattern = ksuid);
1857
+ $ZodStringFormat.init(inst, def);
1858
+ });
1859
+ var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
1860
+ def.pattern ?? (def.pattern = datetime(def));
1861
+ $ZodStringFormat.init(inst, def);
1862
+ });
1863
+ var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
1864
+ def.pattern ?? (def.pattern = date);
1865
+ $ZodStringFormat.init(inst, def);
1866
+ });
1867
+ var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
1868
+ def.pattern ?? (def.pattern = time(def));
1869
+ $ZodStringFormat.init(inst, def);
1870
+ });
1871
+ var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
1872
+ def.pattern ?? (def.pattern = duration);
1873
+ $ZodStringFormat.init(inst, def);
1874
+ });
1875
+ var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
1876
+ def.pattern ?? (def.pattern = ipv4);
1877
+ $ZodStringFormat.init(inst, def);
1878
+ inst._zod.onattach.push((inst) => {
1879
+ const bag = inst._zod.bag;
1880
+ bag.format = `ipv4`;
1881
+ });
1882
+ });
1883
+ var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
1884
+ def.pattern ?? (def.pattern = ipv6);
1885
+ $ZodStringFormat.init(inst, def);
1886
+ inst._zod.onattach.push((inst) => {
1887
+ const bag = inst._zod.bag;
1888
+ bag.format = `ipv6`;
1889
+ });
1890
+ inst._zod.check = (payload) => {
1891
+ try {
1892
+ new URL(`http://[${payload.value}]`);
1893
+ } catch {
1894
+ payload.issues.push({
1895
+ code: "invalid_format",
1896
+ format: "ipv6",
1897
+ input: payload.value,
1898
+ inst,
1899
+ continue: !def.abort
1900
+ });
1901
+ }
1902
+ };
1903
+ });
1904
+ var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
1905
+ def.pattern ?? (def.pattern = cidrv4);
1906
+ $ZodStringFormat.init(inst, def);
1907
+ });
1908
+ var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
1909
+ def.pattern ?? (def.pattern = cidrv6);
1910
+ $ZodStringFormat.init(inst, def);
1911
+ inst._zod.check = (payload) => {
1912
+ const parts = payload.value.split("/");
1913
+ try {
1914
+ if (parts.length !== 2)
1915
+ throw new Error;
1916
+ const [address, prefix] = parts;
1917
+ if (!prefix)
1918
+ throw new Error;
1919
+ const prefixNum = Number(prefix);
1920
+ if (`${prefixNum}` !== prefix)
1921
+ throw new Error;
1922
+ if (prefixNum < 0 || prefixNum > 128)
1923
+ throw new Error;
1924
+ new URL(`http://[${address}]`);
1925
+ } catch {
1926
+ payload.issues.push({
1927
+ code: "invalid_format",
1928
+ format: "cidrv6",
1929
+ input: payload.value,
1930
+ inst,
1931
+ continue: !def.abort
1932
+ });
1933
+ }
1934
+ };
1935
+ });
1936
+ function isValidBase64(data) {
1937
+ if (data === "")
1938
+ return true;
1939
+ if (data.length % 4 !== 0)
1940
+ return false;
1941
+ try {
1942
+ atob(data);
1943
+ return true;
1944
+ } catch {
1945
+ return false;
1946
+ }
1947
+ }
1948
+ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
1949
+ def.pattern ?? (def.pattern = base64);
1950
+ $ZodStringFormat.init(inst, def);
1951
+ inst._zod.onattach.push((inst) => {
1952
+ inst._zod.bag.contentEncoding = "base64";
1953
+ });
1954
+ inst._zod.check = (payload) => {
1955
+ if (isValidBase64(payload.value))
1956
+ return;
1957
+ payload.issues.push({
1958
+ code: "invalid_format",
1959
+ format: "base64",
1960
+ input: payload.value,
1961
+ inst,
1962
+ continue: !def.abort
1963
+ });
1964
+ };
1965
+ });
1966
+ function isValidBase64URL(data) {
1967
+ if (!base64url.test(data))
1968
+ return false;
1969
+ const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
1970
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
1971
+ return isValidBase64(padded);
1972
+ }
1973
+ var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
1974
+ def.pattern ?? (def.pattern = base64url);
1975
+ $ZodStringFormat.init(inst, def);
1976
+ inst._zod.onattach.push((inst) => {
1977
+ inst._zod.bag.contentEncoding = "base64url";
1978
+ });
1979
+ inst._zod.check = (payload) => {
1980
+ if (isValidBase64URL(payload.value))
1981
+ return;
1982
+ payload.issues.push({
1983
+ code: "invalid_format",
1984
+ format: "base64url",
1985
+ input: payload.value,
1986
+ inst,
1987
+ continue: !def.abort
1988
+ });
1989
+ };
1990
+ });
1991
+ var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
1992
+ def.pattern ?? (def.pattern = e164);
1993
+ $ZodStringFormat.init(inst, def);
1994
+ });
1995
+ function isValidJWT(token, algorithm = null) {
1996
+ try {
1997
+ const tokensParts = token.split(".");
1998
+ if (tokensParts.length !== 3)
1999
+ return false;
2000
+ const [header] = tokensParts;
2001
+ if (!header)
2002
+ return false;
2003
+ const parsedHeader = JSON.parse(atob(header));
2004
+ if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
2005
+ return false;
2006
+ if (!parsedHeader.alg)
2007
+ return false;
2008
+ if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
2009
+ return false;
2010
+ return true;
2011
+ } catch {
2012
+ return false;
2013
+ }
2014
+ }
2015
+ var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
2016
+ $ZodStringFormat.init(inst, def);
2017
+ inst._zod.check = (payload) => {
2018
+ if (isValidJWT(payload.value, def.alg))
2019
+ return;
2020
+ payload.issues.push({
2021
+ code: "invalid_format",
2022
+ format: "jwt",
2023
+ input: payload.value,
2024
+ inst,
2025
+ continue: !def.abort
2026
+ });
2027
+ };
2028
+ });
2029
+ var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
2030
+ $ZodType.init(inst, def);
2031
+ inst._zod.pattern = inst._zod.bag.pattern ?? number;
2032
+ inst._zod.parse = (payload, _ctx) => {
2033
+ if (def.coerce)
2034
+ try {
2035
+ payload.value = Number(payload.value);
2036
+ } catch (_) {}
2037
+ const input = payload.value;
2038
+ if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
2039
+ return payload;
2040
+ }
2041
+ const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : undefined : undefined;
2042
+ payload.issues.push({
2043
+ expected: "number",
2044
+ code: "invalid_type",
2045
+ input,
2046
+ inst,
2047
+ ...received ? { received } : {}
2048
+ });
2049
+ return payload;
2050
+ };
2051
+ });
2052
+ var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
2053
+ $ZodCheckNumberFormat.init(inst, def);
2054
+ $ZodNumber.init(inst, def);
2055
+ });
2056
+ var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
2057
+ $ZodType.init(inst, def);
2058
+ inst._zod.pattern = boolean;
2059
+ inst._zod.parse = (payload, _ctx) => {
2060
+ if (def.coerce)
2061
+ try {
2062
+ payload.value = Boolean(payload.value);
2063
+ } catch (_) {}
2064
+ const input = payload.value;
2065
+ if (typeof input === "boolean")
2066
+ return payload;
2067
+ payload.issues.push({
2068
+ expected: "boolean",
2069
+ code: "invalid_type",
2070
+ input,
2071
+ inst
2072
+ });
2073
+ return payload;
2074
+ };
2075
+ });
2076
+ var $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => {
2077
+ $ZodType.init(inst, def);
2078
+ inst._zod.pattern = bigint;
2079
+ inst._zod.parse = (payload, _ctx) => {
2080
+ if (def.coerce)
2081
+ try {
2082
+ payload.value = BigInt(payload.value);
2083
+ } catch (_) {}
2084
+ if (typeof payload.value === "bigint")
2085
+ return payload;
2086
+ payload.issues.push({
2087
+ expected: "bigint",
2088
+ code: "invalid_type",
2089
+ input: payload.value,
2090
+ inst
2091
+ });
2092
+ return payload;
2093
+ };
2094
+ });
2095
+ var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
2096
+ $ZodType.init(inst, def);
2097
+ inst._zod.parse = (payload) => payload;
2098
+ });
2099
+ var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
2100
+ $ZodType.init(inst, def);
2101
+ inst._zod.parse = (payload, _ctx) => {
2102
+ payload.issues.push({
2103
+ expected: "never",
2104
+ code: "invalid_type",
2105
+ input: payload.value,
2106
+ inst
2107
+ });
2108
+ return payload;
2109
+ };
2110
+ });
2111
+ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
2112
+ $ZodType.init(inst, def);
2113
+ inst._zod.parse = (payload, _ctx) => {
2114
+ if (def.coerce) {
2115
+ try {
2116
+ payload.value = new Date(payload.value);
2117
+ } catch (_err) {}
2118
+ }
2119
+ const input = payload.value;
2120
+ const isDate = input instanceof Date;
2121
+ const isValidDate = isDate && !Number.isNaN(input.getTime());
2122
+ if (isValidDate)
2123
+ return payload;
2124
+ payload.issues.push({
2125
+ expected: "date",
2126
+ code: "invalid_type",
2127
+ input,
2128
+ ...isDate ? { received: "Invalid Date" } : {},
2129
+ inst
2130
+ });
2131
+ return payload;
2132
+ };
2133
+ });
2134
+ function handleArrayResult(result, final, index) {
2135
+ if (result.issues.length) {
2136
+ final.issues.push(...prefixIssues(index, result.issues));
2137
+ }
2138
+ final.value[index] = result.value;
2139
+ }
2140
+ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
2141
+ $ZodType.init(inst, def);
2142
+ inst._zod.parse = (payload, ctx) => {
2143
+ const input = payload.value;
2144
+ if (!Array.isArray(input)) {
2145
+ payload.issues.push({
2146
+ expected: "array",
2147
+ code: "invalid_type",
2148
+ input,
2149
+ inst
2150
+ });
2151
+ return payload;
2152
+ }
2153
+ payload.value = Array(input.length);
2154
+ const proms = [];
2155
+ for (let i = 0;i < input.length; i++) {
2156
+ const item = input[i];
2157
+ const result = def.element._zod.run({
2158
+ value: item,
2159
+ issues: []
2160
+ }, ctx);
2161
+ if (result instanceof Promise) {
2162
+ proms.push(result.then((result) => handleArrayResult(result, payload, i)));
2163
+ } else {
2164
+ handleArrayResult(result, payload, i);
2165
+ }
2166
+ }
2167
+ if (proms.length) {
2168
+ return Promise.all(proms).then(() => payload);
2169
+ }
2170
+ return payload;
2171
+ };
2172
+ });
2173
+ function handlePropertyResult(result, final, key, input) {
2174
+ if (result.issues.length) {
2175
+ final.issues.push(...prefixIssues(key, result.issues));
2176
+ }
2177
+ if (result.value === undefined) {
2178
+ if (key in input) {
2179
+ final.value[key] = undefined;
2180
+ }
2181
+ } else {
2182
+ final.value[key] = result.value;
2183
+ }
2184
+ }
2185
+ function normalizeDef(def) {
2186
+ const keys = Object.keys(def.shape);
2187
+ for (const k of keys) {
2188
+ if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) {
2189
+ throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
2190
+ }
2191
+ }
2192
+ const okeys = optionalKeys(def.shape);
2193
+ return {
2194
+ ...def,
2195
+ keys,
2196
+ keySet: new Set(keys),
2197
+ numKeys: keys.length,
2198
+ optionalKeys: new Set(okeys)
2199
+ };
2200
+ }
2201
+ function handleCatchall(proms, input, payload, ctx, def, inst) {
2202
+ const unrecognized = [];
2203
+ const keySet = def.keySet;
2204
+ const _catchall = def.catchall._zod;
2205
+ const t = _catchall.def.type;
2206
+ for (const key of Object.keys(input)) {
2207
+ if (keySet.has(key))
2208
+ continue;
2209
+ if (t === "never") {
2210
+ unrecognized.push(key);
2211
+ continue;
2212
+ }
2213
+ const r = _catchall.run({ value: input[key], issues: [] }, ctx);
2214
+ if (r instanceof Promise) {
2215
+ proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));
2216
+ } else {
2217
+ handlePropertyResult(r, payload, key, input);
2218
+ }
2219
+ }
2220
+ if (unrecognized.length) {
2221
+ payload.issues.push({
2222
+ code: "unrecognized_keys",
2223
+ keys: unrecognized,
2224
+ input,
2225
+ inst
2226
+ });
2227
+ }
2228
+ if (!proms.length)
2229
+ return payload;
2230
+ return Promise.all(proms).then(() => {
2231
+ return payload;
2232
+ });
2233
+ }
2234
+ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
2235
+ $ZodType.init(inst, def);
2236
+ const _normalized = cached(() => normalizeDef(def));
2237
+ defineLazy(inst._zod, "propValues", () => {
2238
+ const shape = def.shape;
2239
+ const propValues = {};
2240
+ for (const key in shape) {
2241
+ const field = shape[key]._zod;
2242
+ if (field.values) {
2243
+ propValues[key] ?? (propValues[key] = new Set);
2244
+ for (const v of field.values)
2245
+ propValues[key].add(v);
2246
+ }
2247
+ }
2248
+ return propValues;
2249
+ });
2250
+ const isObject2 = isObject;
2251
+ const catchall = def.catchall;
2252
+ let value;
2253
+ inst._zod.parse = (payload, ctx) => {
2254
+ value ?? (value = _normalized.value);
2255
+ const input = payload.value;
2256
+ if (!isObject2(input)) {
2257
+ payload.issues.push({
2258
+ expected: "object",
2259
+ code: "invalid_type",
2260
+ input,
2261
+ inst
2262
+ });
2263
+ return payload;
2264
+ }
2265
+ payload.value = {};
2266
+ const proms = [];
2267
+ const shape = value.shape;
2268
+ for (const key of value.keys) {
2269
+ const el = shape[key];
2270
+ const r = el._zod.run({ value: input[key], issues: [] }, ctx);
2271
+ if (r instanceof Promise) {
2272
+ proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));
2273
+ } else {
2274
+ handlePropertyResult(r, payload, key, input);
2275
+ }
2276
+ }
2277
+ if (!catchall) {
2278
+ return proms.length ? Promise.all(proms).then(() => payload) : payload;
2279
+ }
2280
+ return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
2281
+ };
2282
+ });
2283
+ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
2284
+ $ZodObject.init(inst, def);
2285
+ const superParse = inst._zod.parse;
2286
+ const _normalized = cached(() => normalizeDef(def));
2287
+ const generateFastpass = (shape) => {
2288
+ const doc = new Doc(["shape", "payload", "ctx"]);
2289
+ const normalized = _normalized.value;
2290
+ const parseStr = (key) => {
2291
+ const k = esc(key);
2292
+ return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
2293
+ };
2294
+ doc.write(`const input = payload.value;`);
2295
+ const ids = Object.create(null);
2296
+ let counter = 0;
2297
+ for (const key of normalized.keys) {
2298
+ ids[key] = `key_${counter++}`;
2299
+ }
2300
+ doc.write(`const newResult = {};`);
2301
+ for (const key of normalized.keys) {
2302
+ const id = ids[key];
2303
+ const k = esc(key);
2304
+ doc.write(`const ${id} = ${parseStr(key)};`);
2305
+ doc.write(`
2306
+ if (${id}.issues.length) {
2307
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
2308
+ ...iss,
2309
+ path: iss.path ? [${k}, ...iss.path] : [${k}]
2310
+ })));
2311
+ }
2312
+
2313
+
2314
+ if (${id}.value === undefined) {
2315
+ if (${k} in input) {
2316
+ newResult[${k}] = undefined;
2317
+ }
2318
+ } else {
2319
+ newResult[${k}] = ${id}.value;
2320
+ }
2321
+
2322
+ `);
2323
+ }
2324
+ doc.write(`payload.value = newResult;`);
2325
+ doc.write(`return payload;`);
2326
+ const fn = doc.compile();
2327
+ return (payload, ctx) => fn(shape, payload, ctx);
2328
+ };
2329
+ let fastpass;
2330
+ const isObject2 = isObject;
2331
+ const jit = !globalConfig.jitless;
2332
+ const allowsEval2 = allowsEval;
2333
+ const fastEnabled = jit && allowsEval2.value;
2334
+ const catchall = def.catchall;
2335
+ let value;
2336
+ inst._zod.parse = (payload, ctx) => {
2337
+ value ?? (value = _normalized.value);
2338
+ const input = payload.value;
2339
+ if (!isObject2(input)) {
2340
+ payload.issues.push({
2341
+ expected: "object",
2342
+ code: "invalid_type",
2343
+ input,
2344
+ inst
2345
+ });
2346
+ return payload;
2347
+ }
2348
+ if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
2349
+ if (!fastpass)
2350
+ fastpass = generateFastpass(def.shape);
2351
+ payload = fastpass(payload, ctx);
2352
+ if (!catchall)
2353
+ return payload;
2354
+ return handleCatchall([], input, payload, ctx, value, inst);
2355
+ }
2356
+ return superParse(payload, ctx);
2357
+ };
2358
+ });
2359
+ function handleUnionResults(results, final, inst, ctx) {
2360
+ for (const result of results) {
2361
+ if (result.issues.length === 0) {
2362
+ final.value = result.value;
2363
+ return final;
2364
+ }
2365
+ }
2366
+ const nonaborted = results.filter((r) => !aborted(r));
2367
+ if (nonaborted.length === 1) {
2368
+ final.value = nonaborted[0].value;
2369
+ return nonaborted[0];
2370
+ }
2371
+ final.issues.push({
2372
+ code: "invalid_union",
2373
+ input: final.value,
2374
+ inst,
2375
+ errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
2376
+ });
2377
+ return final;
2378
+ }
2379
+ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
2380
+ $ZodType.init(inst, def);
2381
+ defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined);
2382
+ defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined);
2383
+ defineLazy(inst._zod, "values", () => {
2384
+ if (def.options.every((o) => o._zod.values)) {
2385
+ return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
2386
+ }
2387
+ return;
2388
+ });
2389
+ defineLazy(inst._zod, "pattern", () => {
2390
+ if (def.options.every((o) => o._zod.pattern)) {
2391
+ const patterns = def.options.map((o) => o._zod.pattern);
2392
+ return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
2393
+ }
2394
+ return;
2395
+ });
2396
+ const single = def.options.length === 1;
2397
+ const first = def.options[0]._zod.run;
2398
+ inst._zod.parse = (payload, ctx) => {
2399
+ if (single) {
2400
+ return first(payload, ctx);
2401
+ }
2402
+ let async = false;
2403
+ const results = [];
2404
+ for (const option of def.options) {
2405
+ const result = option._zod.run({
2406
+ value: payload.value,
2407
+ issues: []
2408
+ }, ctx);
2409
+ if (result instanceof Promise) {
2410
+ results.push(result);
2411
+ async = true;
2412
+ } else {
2413
+ if (result.issues.length === 0)
2414
+ return result;
2415
+ results.push(result);
2416
+ }
2417
+ }
2418
+ if (!async)
2419
+ return handleUnionResults(results, payload, inst, ctx);
2420
+ return Promise.all(results).then((results) => {
2421
+ return handleUnionResults(results, payload, inst, ctx);
2422
+ });
2423
+ };
2424
+ });
2425
+ var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
2426
+ $ZodType.init(inst, def);
2427
+ inst._zod.parse = (payload, ctx) => {
2428
+ const input = payload.value;
2429
+ const left = def.left._zod.run({ value: input, issues: [] }, ctx);
2430
+ const right = def.right._zod.run({ value: input, issues: [] }, ctx);
2431
+ const async = left instanceof Promise || right instanceof Promise;
2432
+ if (async) {
2433
+ return Promise.all([left, right]).then(([left, right]) => {
2434
+ return handleIntersectionResults(payload, left, right);
2435
+ });
2436
+ }
2437
+ return handleIntersectionResults(payload, left, right);
2438
+ };
2439
+ });
2440
+ function mergeValues(a, b) {
2441
+ if (a === b) {
2442
+ return { valid: true, data: a };
2443
+ }
2444
+ if (a instanceof Date && b instanceof Date && +a === +b) {
2445
+ return { valid: true, data: a };
2446
+ }
2447
+ if (isPlainObject(a) && isPlainObject(b)) {
2448
+ const bKeys = Object.keys(b);
2449
+ const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
2450
+ const newObj = { ...a, ...b };
2451
+ for (const key of sharedKeys) {
2452
+ const sharedValue = mergeValues(a[key], b[key]);
2453
+ if (!sharedValue.valid) {
2454
+ return {
2455
+ valid: false,
2456
+ mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
2457
+ };
2458
+ }
2459
+ newObj[key] = sharedValue.data;
2460
+ }
2461
+ return { valid: true, data: newObj };
2462
+ }
2463
+ if (Array.isArray(a) && Array.isArray(b)) {
2464
+ if (a.length !== b.length) {
2465
+ return { valid: false, mergeErrorPath: [] };
2466
+ }
2467
+ const newArray = [];
2468
+ for (let index = 0;index < a.length; index++) {
2469
+ const itemA = a[index];
2470
+ const itemB = b[index];
2471
+ const sharedValue = mergeValues(itemA, itemB);
2472
+ if (!sharedValue.valid) {
2473
+ return {
2474
+ valid: false,
2475
+ mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
2476
+ };
2477
+ }
2478
+ newArray.push(sharedValue.data);
2479
+ }
2480
+ return { valid: true, data: newArray };
2481
+ }
2482
+ return { valid: false, mergeErrorPath: [] };
2483
+ }
2484
+ function handleIntersectionResults(result, left, right) {
2485
+ if (left.issues.length) {
2486
+ result.issues.push(...left.issues);
2487
+ }
2488
+ if (right.issues.length) {
2489
+ result.issues.push(...right.issues);
2490
+ }
2491
+ if (aborted(result))
2492
+ return result;
2493
+ const merged = mergeValues(left.value, right.value);
2494
+ if (!merged.valid) {
2495
+ throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);
2496
+ }
2497
+ result.value = merged.data;
2498
+ return result;
2499
+ }
2500
+ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
2501
+ $ZodType.init(inst, def);
2502
+ const values = getEnumValues(def.entries);
2503
+ const valuesSet = new Set(values);
2504
+ inst._zod.values = valuesSet;
2505
+ inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
2506
+ inst._zod.parse = (payload, _ctx) => {
2507
+ const input = payload.value;
2508
+ if (valuesSet.has(input)) {
2509
+ return payload;
2510
+ }
2511
+ payload.issues.push({
2512
+ code: "invalid_value",
2513
+ values,
2514
+ input,
2515
+ inst
2516
+ });
2517
+ return payload;
2518
+ };
2519
+ });
2520
+ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
2521
+ $ZodType.init(inst, def);
2522
+ if (def.values.length === 0) {
2523
+ throw new Error("Cannot create literal schema with no valid values");
2524
+ }
2525
+ inst._zod.values = new Set(def.values);
2526
+ inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
2527
+ inst._zod.parse = (payload, _ctx) => {
2528
+ const input = payload.value;
2529
+ if (inst._zod.values.has(input)) {
2530
+ return payload;
2531
+ }
2532
+ payload.issues.push({
2533
+ code: "invalid_value",
2534
+ values: def.values,
2535
+ input,
2536
+ inst
2537
+ });
2538
+ return payload;
2539
+ };
2540
+ });
2541
+ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
2542
+ $ZodType.init(inst, def);
2543
+ inst._zod.parse = (payload, ctx) => {
2544
+ if (ctx.direction === "backward") {
2545
+ throw new $ZodEncodeError(inst.constructor.name);
2546
+ }
2547
+ const _out = def.transform(payload.value, payload);
2548
+ if (ctx.async) {
2549
+ const output = _out instanceof Promise ? _out : Promise.resolve(_out);
2550
+ return output.then((output) => {
2551
+ payload.value = output;
2552
+ return payload;
2553
+ });
2554
+ }
2555
+ if (_out instanceof Promise) {
2556
+ throw new $ZodAsyncError;
2557
+ }
2558
+ payload.value = _out;
2559
+ return payload;
2560
+ };
2561
+ });
2562
+ function handleOptionalResult(result, input) {
2563
+ if (result.issues.length && input === undefined) {
2564
+ return { issues: [], value: undefined };
2565
+ }
2566
+ return result;
2567
+ }
2568
+ var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
2569
+ $ZodType.init(inst, def);
2570
+ inst._zod.optin = "optional";
2571
+ inst._zod.optout = "optional";
2572
+ defineLazy(inst._zod, "values", () => {
2573
+ return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;
2574
+ });
2575
+ defineLazy(inst._zod, "pattern", () => {
2576
+ const pattern = def.innerType._zod.pattern;
2577
+ return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined;
2578
+ });
2579
+ inst._zod.parse = (payload, ctx) => {
2580
+ if (def.innerType._zod.optin === "optional") {
2581
+ const result = def.innerType._zod.run(payload, ctx);
2582
+ if (result instanceof Promise)
2583
+ return result.then((r) => handleOptionalResult(r, payload.value));
2584
+ return handleOptionalResult(result, payload.value);
2585
+ }
2586
+ if (payload.value === undefined) {
2587
+ return payload;
2588
+ }
2589
+ return def.innerType._zod.run(payload, ctx);
2590
+ };
2591
+ });
2592
+ var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
2593
+ $ZodType.init(inst, def);
2594
+ defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
2595
+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
2596
+ defineLazy(inst._zod, "pattern", () => {
2597
+ const pattern = def.innerType._zod.pattern;
2598
+ return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined;
2599
+ });
2600
+ defineLazy(inst._zod, "values", () => {
2601
+ return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;
2602
+ });
2603
+ inst._zod.parse = (payload, ctx) => {
2604
+ if (payload.value === null)
2605
+ return payload;
2606
+ return def.innerType._zod.run(payload, ctx);
2607
+ };
2608
+ });
2609
+ var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
2610
+ $ZodType.init(inst, def);
2611
+ inst._zod.optin = "optional";
2612
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2613
+ inst._zod.parse = (payload, ctx) => {
2614
+ if (ctx.direction === "backward") {
2615
+ return def.innerType._zod.run(payload, ctx);
2616
+ }
2617
+ if (payload.value === undefined) {
2618
+ payload.value = def.defaultValue;
2619
+ return payload;
2620
+ }
2621
+ const result = def.innerType._zod.run(payload, ctx);
2622
+ if (result instanceof Promise) {
2623
+ return result.then((result) => handleDefaultResult(result, def));
2624
+ }
2625
+ return handleDefaultResult(result, def);
2626
+ };
2627
+ });
2628
+ function handleDefaultResult(payload, def) {
2629
+ if (payload.value === undefined) {
2630
+ payload.value = def.defaultValue;
2631
+ }
2632
+ return payload;
2633
+ }
2634
+ var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
2635
+ $ZodType.init(inst, def);
2636
+ inst._zod.optin = "optional";
2637
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2638
+ inst._zod.parse = (payload, ctx) => {
2639
+ if (ctx.direction === "backward") {
2640
+ return def.innerType._zod.run(payload, ctx);
2641
+ }
2642
+ if (payload.value === undefined) {
2643
+ payload.value = def.defaultValue;
2644
+ }
2645
+ return def.innerType._zod.run(payload, ctx);
2646
+ };
2647
+ });
2648
+ var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
2649
+ $ZodType.init(inst, def);
2650
+ defineLazy(inst._zod, "values", () => {
2651
+ const v = def.innerType._zod.values;
2652
+ return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;
2653
+ });
2654
+ inst._zod.parse = (payload, ctx) => {
2655
+ const result = def.innerType._zod.run(payload, ctx);
2656
+ if (result instanceof Promise) {
2657
+ return result.then((result) => handleNonOptionalResult(result, inst));
2658
+ }
2659
+ return handleNonOptionalResult(result, inst);
2660
+ };
2661
+ });
2662
+ function handleNonOptionalResult(payload, inst) {
2663
+ if (!payload.issues.length && payload.value === undefined) {
2664
+ payload.issues.push({
2665
+ code: "invalid_type",
2666
+ expected: "nonoptional",
2667
+ input: payload.value,
2668
+ inst
2669
+ });
2670
+ }
2671
+ return payload;
2672
+ }
2673
+ var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
2674
+ $ZodType.init(inst, def);
2675
+ defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
2676
+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
2677
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2678
+ inst._zod.parse = (payload, ctx) => {
2679
+ if (ctx.direction === "backward") {
2680
+ return def.innerType._zod.run(payload, ctx);
2681
+ }
2682
+ const result = def.innerType._zod.run(payload, ctx);
2683
+ if (result instanceof Promise) {
2684
+ return result.then((result) => {
2685
+ payload.value = result.value;
2686
+ if (result.issues.length) {
2687
+ payload.value = def.catchValue({
2688
+ ...payload,
2689
+ error: {
2690
+ issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
2691
+ },
2692
+ input: payload.value
2693
+ });
2694
+ payload.issues = [];
2695
+ }
2696
+ return payload;
2697
+ });
2698
+ }
2699
+ payload.value = result.value;
2700
+ if (result.issues.length) {
2701
+ payload.value = def.catchValue({
2702
+ ...payload,
2703
+ error: {
2704
+ issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
2705
+ },
2706
+ input: payload.value
2707
+ });
2708
+ payload.issues = [];
2709
+ }
2710
+ return payload;
2711
+ };
2712
+ });
2713
+ var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
2714
+ $ZodType.init(inst, def);
2715
+ defineLazy(inst._zod, "values", () => def.in._zod.values);
2716
+ defineLazy(inst._zod, "optin", () => def.in._zod.optin);
2717
+ defineLazy(inst._zod, "optout", () => def.out._zod.optout);
2718
+ defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
2719
+ inst._zod.parse = (payload, ctx) => {
2720
+ if (ctx.direction === "backward") {
2721
+ const right = def.out._zod.run(payload, ctx);
2722
+ if (right instanceof Promise) {
2723
+ return right.then((right) => handlePipeResult(right, def.in, ctx));
2724
+ }
2725
+ return handlePipeResult(right, def.in, ctx);
2726
+ }
2727
+ const left = def.in._zod.run(payload, ctx);
2728
+ if (left instanceof Promise) {
2729
+ return left.then((left) => handlePipeResult(left, def.out, ctx));
2730
+ }
2731
+ return handlePipeResult(left, def.out, ctx);
2732
+ };
2733
+ });
2734
+ function handlePipeResult(left, next, ctx) {
2735
+ if (left.issues.length) {
2736
+ left.aborted = true;
2737
+ return left;
2738
+ }
2739
+ return next._zod.run({ value: left.value, issues: left.issues }, ctx);
2740
+ }
2741
+ var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
2742
+ $ZodType.init(inst, def);
2743
+ defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
2744
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2745
+ defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
2746
+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
2747
+ inst._zod.parse = (payload, ctx) => {
2748
+ if (ctx.direction === "backward") {
2749
+ return def.innerType._zod.run(payload, ctx);
2750
+ }
2751
+ const result = def.innerType._zod.run(payload, ctx);
2752
+ if (result instanceof Promise) {
2753
+ return result.then(handleReadonlyResult);
2754
+ }
2755
+ return handleReadonlyResult(result);
2756
+ };
2757
+ });
2758
+ function handleReadonlyResult(payload) {
2759
+ payload.value = Object.freeze(payload.value);
2760
+ return payload;
2761
+ }
2762
+ var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
2763
+ $ZodCheck.init(inst, def);
2764
+ $ZodType.init(inst, def);
2765
+ inst._zod.parse = (payload, _) => {
2766
+ return payload;
2767
+ };
2768
+ inst._zod.check = (payload) => {
2769
+ const input = payload.value;
2770
+ const r = def.fn(input);
2771
+ if (r instanceof Promise) {
2772
+ return r.then((r) => handleRefineResult(r, payload, input, inst));
2773
+ }
2774
+ handleRefineResult(r, payload, input, inst);
2775
+ return;
2776
+ };
2777
+ });
2778
+ function handleRefineResult(result, payload, input, inst) {
2779
+ if (!result) {
2780
+ const _iss = {
2781
+ code: "custom",
2782
+ input,
2783
+ inst,
2784
+ path: [...inst._zod.def.path ?? []],
2785
+ continue: !inst._zod.def.abort
2786
+ };
2787
+ if (inst._zod.def.params)
2788
+ _iss.params = inst._zod.def.params;
2789
+ payload.issues.push(issue(_iss));
2790
+ }
2791
+ }
2792
+ // node_modules/zod/v4/locales/en.js
2793
+ var parsedType = (data) => {
2794
+ const t = typeof data;
2795
+ switch (t) {
2796
+ case "number": {
2797
+ return Number.isNaN(data) ? "NaN" : "number";
2798
+ }
2799
+ case "object": {
2800
+ if (Array.isArray(data)) {
2801
+ return "array";
2802
+ }
2803
+ if (data === null) {
2804
+ return "null";
2805
+ }
2806
+ if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
2807
+ return data.constructor.name;
2808
+ }
2809
+ }
2810
+ }
2811
+ return t;
2812
+ };
2813
+ var error = () => {
2814
+ const Sizable = {
2815
+ string: { unit: "characters", verb: "to have" },
2816
+ file: { unit: "bytes", verb: "to have" },
2817
+ array: { unit: "items", verb: "to have" },
2818
+ set: { unit: "items", verb: "to have" }
2819
+ };
2820
+ function getSizing(origin) {
2821
+ return Sizable[origin] ?? null;
2822
+ }
2823
+ const Nouns = {
2824
+ regex: "input",
2825
+ email: "email address",
2826
+ url: "URL",
2827
+ emoji: "emoji",
2828
+ uuid: "UUID",
2829
+ uuidv4: "UUIDv4",
2830
+ uuidv6: "UUIDv6",
2831
+ nanoid: "nanoid",
2832
+ guid: "GUID",
2833
+ cuid: "cuid",
2834
+ cuid2: "cuid2",
2835
+ ulid: "ULID",
2836
+ xid: "XID",
2837
+ ksuid: "KSUID",
2838
+ datetime: "ISO datetime",
2839
+ date: "ISO date",
2840
+ time: "ISO time",
2841
+ duration: "ISO duration",
2842
+ ipv4: "IPv4 address",
2843
+ ipv6: "IPv6 address",
2844
+ cidrv4: "IPv4 range",
2845
+ cidrv6: "IPv6 range",
2846
+ base64: "base64-encoded string",
2847
+ base64url: "base64url-encoded string",
2848
+ json_string: "JSON string",
2849
+ e164: "E.164 number",
2850
+ jwt: "JWT",
2851
+ template_literal: "input"
2852
+ };
2853
+ return (issue) => {
2854
+ switch (issue.code) {
2855
+ case "invalid_type":
2856
+ return `Invalid input: expected ${issue.expected}, received ${parsedType(issue.input)}`;
2857
+ case "invalid_value":
2858
+ if (issue.values.length === 1)
2859
+ return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`;
2860
+ return `Invalid option: expected one of ${joinValues(issue.values, "|")}`;
2861
+ case "too_big": {
2862
+ const adj = issue.inclusive ? "<=" : "<";
2863
+ const sizing = getSizing(issue.origin);
2864
+ if (sizing)
2865
+ return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`;
2866
+ return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`;
2867
+ }
2868
+ case "too_small": {
2869
+ const adj = issue.inclusive ? ">=" : ">";
2870
+ const sizing = getSizing(issue.origin);
2871
+ if (sizing) {
2872
+ return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;
2873
+ }
2874
+ return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;
2875
+ }
2876
+ case "invalid_format": {
2877
+ const _issue = issue;
2878
+ if (_issue.format === "starts_with") {
2879
+ return `Invalid string: must start with "${_issue.prefix}"`;
2880
+ }
2881
+ if (_issue.format === "ends_with")
2882
+ return `Invalid string: must end with "${_issue.suffix}"`;
2883
+ if (_issue.format === "includes")
2884
+ return `Invalid string: must include "${_issue.includes}"`;
2885
+ if (_issue.format === "regex")
2886
+ return `Invalid string: must match pattern ${_issue.pattern}`;
2887
+ return `Invalid ${Nouns[_issue.format] ?? issue.format}`;
2888
+ }
2889
+ case "not_multiple_of":
2890
+ return `Invalid number: must be a multiple of ${issue.divisor}`;
2891
+ case "unrecognized_keys":
2892
+ return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`;
2893
+ case "invalid_key":
2894
+ return `Invalid key in ${issue.origin}`;
2895
+ case "invalid_union":
2896
+ return "Invalid input";
2897
+ case "invalid_element":
2898
+ return `Invalid value in ${issue.origin}`;
2899
+ default:
2900
+ return `Invalid input`;
2901
+ }
2902
+ };
2903
+ };
2904
+ function en_default() {
2905
+ return {
2906
+ localeError: error()
2907
+ };
2908
+ }
2909
+ // node_modules/zod/v4/core/registries.js
2910
+ var $output = Symbol("ZodOutput");
2911
+ var $input = Symbol("ZodInput");
2912
+
2913
+ class $ZodRegistry {
2914
+ constructor() {
2915
+ this._map = new WeakMap;
2916
+ this._idmap = new Map;
2917
+ }
2918
+ add(schema, ..._meta) {
2919
+ const meta = _meta[0];
2920
+ this._map.set(schema, meta);
2921
+ if (meta && typeof meta === "object" && "id" in meta) {
2922
+ if (this._idmap.has(meta.id)) {
2923
+ throw new Error(`ID ${meta.id} already exists in the registry`);
2924
+ }
2925
+ this._idmap.set(meta.id, schema);
2926
+ }
2927
+ return this;
2928
+ }
2929
+ clear() {
2930
+ this._map = new WeakMap;
2931
+ this._idmap = new Map;
2932
+ return this;
2933
+ }
2934
+ remove(schema) {
2935
+ const meta = this._map.get(schema);
2936
+ if (meta && typeof meta === "object" && "id" in meta) {
2937
+ this._idmap.delete(meta.id);
2938
+ }
2939
+ this._map.delete(schema);
2940
+ return this;
2941
+ }
2942
+ get(schema) {
2943
+ const p = schema._zod.parent;
2944
+ if (p) {
2945
+ const pm = { ...this.get(p) ?? {} };
2946
+ delete pm.id;
2947
+ const f = { ...pm, ...this._map.get(schema) };
2948
+ return Object.keys(f).length ? f : undefined;
2949
+ }
2950
+ return this._map.get(schema);
2951
+ }
2952
+ has(schema) {
2953
+ return this._map.has(schema);
2954
+ }
2955
+ }
2956
+ function registry() {
2957
+ return new $ZodRegistry;
2958
+ }
2959
+ var globalRegistry = /* @__PURE__ */ registry();
2960
+ // node_modules/zod/v4/core/api.js
2961
+ function _string(Class, params) {
2962
+ return new Class({
2963
+ type: "string",
2964
+ ...normalizeParams(params)
2965
+ });
2966
+ }
2967
+ function _coercedString(Class, params) {
2968
+ return new Class({
2969
+ type: "string",
2970
+ coerce: true,
2971
+ ...normalizeParams(params)
2972
+ });
2973
+ }
2974
+ function _email(Class, params) {
2975
+ return new Class({
2976
+ type: "string",
2977
+ format: "email",
2978
+ check: "string_format",
2979
+ abort: false,
2980
+ ...normalizeParams(params)
2981
+ });
2982
+ }
2983
+ function _guid(Class, params) {
2984
+ return new Class({
2985
+ type: "string",
2986
+ format: "guid",
2987
+ check: "string_format",
2988
+ abort: false,
2989
+ ...normalizeParams(params)
2990
+ });
2991
+ }
2992
+ function _uuid(Class, params) {
2993
+ return new Class({
2994
+ type: "string",
2995
+ format: "uuid",
2996
+ check: "string_format",
2997
+ abort: false,
2998
+ ...normalizeParams(params)
2999
+ });
3000
+ }
3001
+ function _uuidv4(Class, params) {
3002
+ return new Class({
3003
+ type: "string",
3004
+ format: "uuid",
3005
+ check: "string_format",
3006
+ abort: false,
3007
+ version: "v4",
3008
+ ...normalizeParams(params)
3009
+ });
3010
+ }
3011
+ function _uuidv6(Class, params) {
3012
+ return new Class({
3013
+ type: "string",
3014
+ format: "uuid",
3015
+ check: "string_format",
3016
+ abort: false,
3017
+ version: "v6",
3018
+ ...normalizeParams(params)
3019
+ });
3020
+ }
3021
+ function _uuidv7(Class, params) {
3022
+ return new Class({
3023
+ type: "string",
3024
+ format: "uuid",
3025
+ check: "string_format",
3026
+ abort: false,
3027
+ version: "v7",
3028
+ ...normalizeParams(params)
3029
+ });
3030
+ }
3031
+ function _url(Class, params) {
3032
+ return new Class({
3033
+ type: "string",
3034
+ format: "url",
3035
+ check: "string_format",
3036
+ abort: false,
3037
+ ...normalizeParams(params)
3038
+ });
3039
+ }
3040
+ function _emoji2(Class, params) {
3041
+ return new Class({
3042
+ type: "string",
3043
+ format: "emoji",
3044
+ check: "string_format",
3045
+ abort: false,
3046
+ ...normalizeParams(params)
3047
+ });
3048
+ }
3049
+ function _nanoid(Class, params) {
3050
+ return new Class({
3051
+ type: "string",
3052
+ format: "nanoid",
3053
+ check: "string_format",
3054
+ abort: false,
3055
+ ...normalizeParams(params)
3056
+ });
3057
+ }
3058
+ function _cuid(Class, params) {
3059
+ return new Class({
3060
+ type: "string",
3061
+ format: "cuid",
3062
+ check: "string_format",
3063
+ abort: false,
3064
+ ...normalizeParams(params)
3065
+ });
3066
+ }
3067
+ function _cuid2(Class, params) {
3068
+ return new Class({
3069
+ type: "string",
3070
+ format: "cuid2",
3071
+ check: "string_format",
3072
+ abort: false,
3073
+ ...normalizeParams(params)
3074
+ });
3075
+ }
3076
+ function _ulid(Class, params) {
3077
+ return new Class({
3078
+ type: "string",
3079
+ format: "ulid",
3080
+ check: "string_format",
3081
+ abort: false,
3082
+ ...normalizeParams(params)
3083
+ });
3084
+ }
3085
+ function _xid(Class, params) {
3086
+ return new Class({
3087
+ type: "string",
3088
+ format: "xid",
3089
+ check: "string_format",
3090
+ abort: false,
3091
+ ...normalizeParams(params)
3092
+ });
3093
+ }
3094
+ function _ksuid(Class, params) {
3095
+ return new Class({
3096
+ type: "string",
3097
+ format: "ksuid",
3098
+ check: "string_format",
3099
+ abort: false,
3100
+ ...normalizeParams(params)
3101
+ });
3102
+ }
3103
+ function _ipv4(Class, params) {
3104
+ return new Class({
3105
+ type: "string",
3106
+ format: "ipv4",
3107
+ check: "string_format",
3108
+ abort: false,
3109
+ ...normalizeParams(params)
3110
+ });
3111
+ }
3112
+ function _ipv6(Class, params) {
3113
+ return new Class({
3114
+ type: "string",
3115
+ format: "ipv6",
3116
+ check: "string_format",
3117
+ abort: false,
3118
+ ...normalizeParams(params)
3119
+ });
3120
+ }
3121
+ function _cidrv4(Class, params) {
3122
+ return new Class({
3123
+ type: "string",
3124
+ format: "cidrv4",
3125
+ check: "string_format",
3126
+ abort: false,
3127
+ ...normalizeParams(params)
3128
+ });
3129
+ }
3130
+ function _cidrv6(Class, params) {
3131
+ return new Class({
3132
+ type: "string",
3133
+ format: "cidrv6",
3134
+ check: "string_format",
3135
+ abort: false,
3136
+ ...normalizeParams(params)
3137
+ });
3138
+ }
3139
+ function _base64(Class, params) {
3140
+ return new Class({
3141
+ type: "string",
3142
+ format: "base64",
3143
+ check: "string_format",
3144
+ abort: false,
3145
+ ...normalizeParams(params)
3146
+ });
3147
+ }
3148
+ function _base64url(Class, params) {
3149
+ return new Class({
3150
+ type: "string",
3151
+ format: "base64url",
3152
+ check: "string_format",
3153
+ abort: false,
3154
+ ...normalizeParams(params)
3155
+ });
3156
+ }
3157
+ function _e164(Class, params) {
3158
+ return new Class({
3159
+ type: "string",
3160
+ format: "e164",
3161
+ check: "string_format",
3162
+ abort: false,
3163
+ ...normalizeParams(params)
3164
+ });
3165
+ }
3166
+ function _jwt(Class, params) {
3167
+ return new Class({
3168
+ type: "string",
3169
+ format: "jwt",
3170
+ check: "string_format",
3171
+ abort: false,
3172
+ ...normalizeParams(params)
3173
+ });
3174
+ }
3175
+ function _isoDateTime(Class, params) {
3176
+ return new Class({
3177
+ type: "string",
3178
+ format: "datetime",
3179
+ check: "string_format",
3180
+ offset: false,
3181
+ local: false,
3182
+ precision: null,
3183
+ ...normalizeParams(params)
3184
+ });
3185
+ }
3186
+ function _isoDate(Class, params) {
3187
+ return new Class({
3188
+ type: "string",
3189
+ format: "date",
3190
+ check: "string_format",
3191
+ ...normalizeParams(params)
3192
+ });
3193
+ }
3194
+ function _isoTime(Class, params) {
3195
+ return new Class({
3196
+ type: "string",
3197
+ format: "time",
3198
+ check: "string_format",
3199
+ precision: null,
3200
+ ...normalizeParams(params)
3201
+ });
3202
+ }
3203
+ function _isoDuration(Class, params) {
3204
+ return new Class({
3205
+ type: "string",
3206
+ format: "duration",
3207
+ check: "string_format",
3208
+ ...normalizeParams(params)
3209
+ });
3210
+ }
3211
+ function _number(Class, params) {
3212
+ return new Class({
3213
+ type: "number",
3214
+ checks: [],
3215
+ ...normalizeParams(params)
3216
+ });
3217
+ }
3218
+ function _coercedNumber(Class, params) {
3219
+ return new Class({
3220
+ type: "number",
3221
+ coerce: true,
3222
+ checks: [],
3223
+ ...normalizeParams(params)
3224
+ });
3225
+ }
3226
+ function _int(Class, params) {
3227
+ return new Class({
3228
+ type: "number",
3229
+ check: "number_format",
3230
+ abort: false,
3231
+ format: "safeint",
3232
+ ...normalizeParams(params)
3233
+ });
3234
+ }
3235
+ function _boolean(Class, params) {
3236
+ return new Class({
3237
+ type: "boolean",
3238
+ ...normalizeParams(params)
3239
+ });
3240
+ }
3241
+ function _coercedBoolean(Class, params) {
3242
+ return new Class({
3243
+ type: "boolean",
3244
+ coerce: true,
3245
+ ...normalizeParams(params)
3246
+ });
3247
+ }
3248
+ function _coercedBigint(Class, params) {
3249
+ return new Class({
3250
+ type: "bigint",
3251
+ coerce: true,
3252
+ ...normalizeParams(params)
3253
+ });
3254
+ }
3255
+ function _unknown(Class) {
3256
+ return new Class({
3257
+ type: "unknown"
3258
+ });
3259
+ }
3260
+ function _never(Class, params) {
3261
+ return new Class({
3262
+ type: "never",
3263
+ ...normalizeParams(params)
3264
+ });
3265
+ }
3266
+ function _coercedDate(Class, params) {
3267
+ return new Class({
3268
+ type: "date",
3269
+ coerce: true,
3270
+ ...normalizeParams(params)
3271
+ });
3272
+ }
3273
+ function _lt(value, params) {
3274
+ return new $ZodCheckLessThan({
3275
+ check: "less_than",
3276
+ ...normalizeParams(params),
3277
+ value,
3278
+ inclusive: false
3279
+ });
3280
+ }
3281
+ function _lte(value, params) {
3282
+ return new $ZodCheckLessThan({
3283
+ check: "less_than",
3284
+ ...normalizeParams(params),
3285
+ value,
3286
+ inclusive: true
3287
+ });
3288
+ }
3289
+ function _gt(value, params) {
3290
+ return new $ZodCheckGreaterThan({
3291
+ check: "greater_than",
3292
+ ...normalizeParams(params),
3293
+ value,
3294
+ inclusive: false
3295
+ });
3296
+ }
3297
+ function _gte(value, params) {
3298
+ return new $ZodCheckGreaterThan({
3299
+ check: "greater_than",
3300
+ ...normalizeParams(params),
3301
+ value,
3302
+ inclusive: true
3303
+ });
3304
+ }
3305
+ function _multipleOf(value, params) {
3306
+ return new $ZodCheckMultipleOf({
3307
+ check: "multiple_of",
3308
+ ...normalizeParams(params),
3309
+ value
3310
+ });
3311
+ }
3312
+ function _maxLength(maximum, params) {
3313
+ const ch = new $ZodCheckMaxLength({
3314
+ check: "max_length",
3315
+ ...normalizeParams(params),
3316
+ maximum
3317
+ });
3318
+ return ch;
3319
+ }
3320
+ function _minLength(minimum, params) {
3321
+ return new $ZodCheckMinLength({
3322
+ check: "min_length",
3323
+ ...normalizeParams(params),
3324
+ minimum
3325
+ });
3326
+ }
3327
+ function _length(length, params) {
3328
+ return new $ZodCheckLengthEquals({
3329
+ check: "length_equals",
3330
+ ...normalizeParams(params),
3331
+ length
3332
+ });
3333
+ }
3334
+ function _regex(pattern, params) {
3335
+ return new $ZodCheckRegex({
3336
+ check: "string_format",
3337
+ format: "regex",
3338
+ ...normalizeParams(params),
3339
+ pattern
3340
+ });
3341
+ }
3342
+ function _lowercase(params) {
3343
+ return new $ZodCheckLowerCase({
3344
+ check: "string_format",
3345
+ format: "lowercase",
3346
+ ...normalizeParams(params)
3347
+ });
3348
+ }
3349
+ function _uppercase(params) {
3350
+ return new $ZodCheckUpperCase({
3351
+ check: "string_format",
3352
+ format: "uppercase",
3353
+ ...normalizeParams(params)
3354
+ });
3355
+ }
3356
+ function _includes(includes, params) {
3357
+ return new $ZodCheckIncludes({
3358
+ check: "string_format",
3359
+ format: "includes",
3360
+ ...normalizeParams(params),
3361
+ includes
3362
+ });
3363
+ }
3364
+ function _startsWith(prefix, params) {
3365
+ return new $ZodCheckStartsWith({
3366
+ check: "string_format",
3367
+ format: "starts_with",
3368
+ ...normalizeParams(params),
3369
+ prefix
3370
+ });
3371
+ }
3372
+ function _endsWith(suffix, params) {
3373
+ return new $ZodCheckEndsWith({
3374
+ check: "string_format",
3375
+ format: "ends_with",
3376
+ ...normalizeParams(params),
3377
+ suffix
3378
+ });
3379
+ }
3380
+ function _overwrite(tx) {
3381
+ return new $ZodCheckOverwrite({
3382
+ check: "overwrite",
3383
+ tx
3384
+ });
3385
+ }
3386
+ function _normalize(form) {
3387
+ return _overwrite((input) => input.normalize(form));
3388
+ }
3389
+ function _trim() {
3390
+ return _overwrite((input) => input.trim());
3391
+ }
3392
+ function _toLowerCase() {
3393
+ return _overwrite((input) => input.toLowerCase());
3394
+ }
3395
+ function _toUpperCase() {
3396
+ return _overwrite((input) => input.toUpperCase());
3397
+ }
3398
+ function _array(Class, element, params) {
3399
+ return new Class({
3400
+ type: "array",
3401
+ element,
3402
+ ...normalizeParams(params)
3403
+ });
3404
+ }
3405
+ function _refine(Class, fn, _params) {
3406
+ const schema = new Class({
3407
+ type: "custom",
3408
+ check: "custom",
3409
+ fn,
3410
+ ...normalizeParams(_params)
3411
+ });
3412
+ return schema;
3413
+ }
3414
+ function _superRefine(fn) {
3415
+ const ch = _check((payload) => {
3416
+ payload.addIssue = (issue2) => {
3417
+ if (typeof issue2 === "string") {
3418
+ payload.issues.push(issue(issue2, payload.value, ch._zod.def));
3419
+ } else {
3420
+ const _issue = issue2;
3421
+ if (_issue.fatal)
3422
+ _issue.continue = false;
3423
+ _issue.code ?? (_issue.code = "custom");
3424
+ _issue.input ?? (_issue.input = payload.value);
3425
+ _issue.inst ?? (_issue.inst = ch);
3426
+ _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
3427
+ payload.issues.push(issue(_issue));
3428
+ }
3429
+ };
3430
+ return fn(payload.value, payload);
3431
+ });
3432
+ return ch;
3433
+ }
3434
+ function _check(fn, params) {
3435
+ const ch = new $ZodCheck({
3436
+ check: "custom",
3437
+ ...normalizeParams(params)
3438
+ });
3439
+ ch._zod.check = fn;
3440
+ return ch;
3441
+ }
3442
+ // node_modules/zod/v4/classic/iso.js
3443
+ var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
3444
+ $ZodISODateTime.init(inst, def);
3445
+ ZodStringFormat.init(inst, def);
3446
+ });
3447
+ function datetime2(params) {
3448
+ return _isoDateTime(ZodISODateTime, params);
3449
+ }
3450
+ var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
3451
+ $ZodISODate.init(inst, def);
3452
+ ZodStringFormat.init(inst, def);
3453
+ });
3454
+ function date2(params) {
3455
+ return _isoDate(ZodISODate, params);
3456
+ }
3457
+ var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
3458
+ $ZodISOTime.init(inst, def);
3459
+ ZodStringFormat.init(inst, def);
3460
+ });
3461
+ function time2(params) {
3462
+ return _isoTime(ZodISOTime, params);
3463
+ }
3464
+ var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
3465
+ $ZodISODuration.init(inst, def);
3466
+ ZodStringFormat.init(inst, def);
3467
+ });
3468
+ function duration2(params) {
3469
+ return _isoDuration(ZodISODuration, params);
3470
+ }
3471
+
3472
+ // node_modules/zod/v4/classic/errors.js
3473
+ var initializer2 = (inst, issues) => {
3474
+ $ZodError.init(inst, issues);
3475
+ inst.name = "ZodError";
3476
+ Object.defineProperties(inst, {
3477
+ format: {
3478
+ value: (mapper) => formatError(inst, mapper)
3479
+ },
3480
+ flatten: {
3481
+ value: (mapper) => flattenError(inst, mapper)
3482
+ },
3483
+ addIssue: {
3484
+ value: (issue) => {
3485
+ inst.issues.push(issue);
3486
+ inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
3487
+ }
3488
+ },
3489
+ addIssues: {
3490
+ value: (issues) => {
3491
+ inst.issues.push(...issues);
3492
+ inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
3493
+ }
3494
+ },
3495
+ isEmpty: {
3496
+ get() {
3497
+ return inst.issues.length === 0;
3498
+ }
3499
+ }
3500
+ });
3501
+ };
3502
+ var ZodError = $constructor("ZodError", initializer2);
3503
+ var ZodRealError = $constructor("ZodError", initializer2, {
3504
+ Parent: Error
3505
+ });
3506
+
3507
+ // node_modules/zod/v4/classic/parse.js
3508
+ var parse3 = /* @__PURE__ */ _parse(ZodRealError);
3509
+ var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
3510
+ var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError);
3511
+ var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
3512
+ var encode = /* @__PURE__ */ _encode(ZodRealError);
3513
+ var decode = /* @__PURE__ */ _decode(ZodRealError);
3514
+ var encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
3515
+ var decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError);
3516
+ var safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
3517
+ var safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
3518
+ var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
3519
+ var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
3520
+
3521
+ // node_modules/zod/v4/classic/schemas.js
3522
+ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
3523
+ $ZodType.init(inst, def);
3524
+ inst.def = def;
3525
+ inst.type = def.type;
3526
+ Object.defineProperty(inst, "_def", { value: def });
3527
+ inst.check = (...checks) => {
3528
+ return inst.clone({
3529
+ ...def,
3530
+ checks: [
3531
+ ...def.checks ?? [],
3532
+ ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
3533
+ ]
3534
+ });
3535
+ };
3536
+ inst.clone = (def, params) => clone(inst, def, params);
3537
+ inst.brand = () => inst;
3538
+ inst.register = (reg, meta) => {
3539
+ reg.add(inst, meta);
3540
+ return inst;
3541
+ };
3542
+ inst.parse = (data, params) => parse3(inst, data, params, { callee: inst.parse });
3543
+ inst.safeParse = (data, params) => safeParse2(inst, data, params);
3544
+ inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync });
3545
+ inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params);
3546
+ inst.spa = inst.safeParseAsync;
3547
+ inst.encode = (data, params) => encode(inst, data, params);
3548
+ inst.decode = (data, params) => decode(inst, data, params);
3549
+ inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
3550
+ inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
3551
+ inst.safeEncode = (data, params) => safeEncode(inst, data, params);
3552
+ inst.safeDecode = (data, params) => safeDecode(inst, data, params);
3553
+ inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params);
3554
+ inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params);
3555
+ inst.refine = (check, params) => inst.check(refine(check, params));
3556
+ inst.superRefine = (refinement) => inst.check(superRefine(refinement));
3557
+ inst.overwrite = (fn) => inst.check(_overwrite(fn));
3558
+ inst.optional = () => optional(inst);
3559
+ inst.nullable = () => nullable(inst);
3560
+ inst.nullish = () => optional(nullable(inst));
3561
+ inst.nonoptional = (params) => nonoptional(inst, params);
3562
+ inst.array = () => array(inst);
3563
+ inst.or = (arg) => union([inst, arg]);
3564
+ inst.and = (arg) => intersection(inst, arg);
3565
+ inst.transform = (tx) => pipe(inst, transform(tx));
3566
+ inst.default = (def) => _default(inst, def);
3567
+ inst.prefault = (def) => prefault(inst, def);
3568
+ inst.catch = (params) => _catch(inst, params);
3569
+ inst.pipe = (target) => pipe(inst, target);
3570
+ inst.readonly = () => readonly(inst);
3571
+ inst.describe = (description) => {
3572
+ const cl = inst.clone();
3573
+ globalRegistry.add(cl, { description });
3574
+ return cl;
3575
+ };
3576
+ Object.defineProperty(inst, "description", {
3577
+ get() {
3578
+ return globalRegistry.get(inst)?.description;
3579
+ },
3580
+ configurable: true
3581
+ });
3582
+ inst.meta = (...args) => {
3583
+ if (args.length === 0) {
3584
+ return globalRegistry.get(inst);
3585
+ }
3586
+ const cl = inst.clone();
3587
+ globalRegistry.add(cl, args[0]);
3588
+ return cl;
3589
+ };
3590
+ inst.isOptional = () => inst.safeParse(undefined).success;
3591
+ inst.isNullable = () => inst.safeParse(null).success;
3592
+ return inst;
3593
+ });
3594
+ var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
3595
+ $ZodString.init(inst, def);
3596
+ ZodType.init(inst, def);
3597
+ const bag = inst._zod.bag;
3598
+ inst.format = bag.format ?? null;
3599
+ inst.minLength = bag.minimum ?? null;
3600
+ inst.maxLength = bag.maximum ?? null;
3601
+ inst.regex = (...args) => inst.check(_regex(...args));
3602
+ inst.includes = (...args) => inst.check(_includes(...args));
3603
+ inst.startsWith = (...args) => inst.check(_startsWith(...args));
3604
+ inst.endsWith = (...args) => inst.check(_endsWith(...args));
3605
+ inst.min = (...args) => inst.check(_minLength(...args));
3606
+ inst.max = (...args) => inst.check(_maxLength(...args));
3607
+ inst.length = (...args) => inst.check(_length(...args));
3608
+ inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
3609
+ inst.lowercase = (params) => inst.check(_lowercase(params));
3610
+ inst.uppercase = (params) => inst.check(_uppercase(params));
3611
+ inst.trim = () => inst.check(_trim());
3612
+ inst.normalize = (...args) => inst.check(_normalize(...args));
3613
+ inst.toLowerCase = () => inst.check(_toLowerCase());
3614
+ inst.toUpperCase = () => inst.check(_toUpperCase());
3615
+ });
3616
+ var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
3617
+ $ZodString.init(inst, def);
3618
+ _ZodString.init(inst, def);
3619
+ inst.email = (params) => inst.check(_email(ZodEmail, params));
3620
+ inst.url = (params) => inst.check(_url(ZodURL, params));
3621
+ inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
3622
+ inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params));
3623
+ inst.guid = (params) => inst.check(_guid(ZodGUID, params));
3624
+ inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
3625
+ inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
3626
+ inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
3627
+ inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
3628
+ inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
3629
+ inst.guid = (params) => inst.check(_guid(ZodGUID, params));
3630
+ inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
3631
+ inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
3632
+ inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
3633
+ inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
3634
+ inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
3635
+ inst.xid = (params) => inst.check(_xid(ZodXID, params));
3636
+ inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
3637
+ inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
3638
+ inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
3639
+ inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
3640
+ inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
3641
+ inst.e164 = (params) => inst.check(_e164(ZodE164, params));
3642
+ inst.datetime = (params) => inst.check(datetime2(params));
3643
+ inst.date = (params) => inst.check(date2(params));
3644
+ inst.time = (params) => inst.check(time2(params));
3645
+ inst.duration = (params) => inst.check(duration2(params));
3646
+ });
3647
+ function string2(params) {
3648
+ return _string(ZodString, params);
3649
+ }
3650
+ var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
3651
+ $ZodStringFormat.init(inst, def);
3652
+ _ZodString.init(inst, def);
3653
+ });
3654
+ var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
3655
+ $ZodEmail.init(inst, def);
3656
+ ZodStringFormat.init(inst, def);
3657
+ });
3658
+ var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
3659
+ $ZodGUID.init(inst, def);
3660
+ ZodStringFormat.init(inst, def);
3661
+ });
3662
+ var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
3663
+ $ZodUUID.init(inst, def);
3664
+ ZodStringFormat.init(inst, def);
3665
+ });
3666
+ var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
3667
+ $ZodURL.init(inst, def);
3668
+ ZodStringFormat.init(inst, def);
3669
+ });
3670
+ var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
3671
+ $ZodEmoji.init(inst, def);
3672
+ ZodStringFormat.init(inst, def);
3673
+ });
3674
+ var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
3675
+ $ZodNanoID.init(inst, def);
3676
+ ZodStringFormat.init(inst, def);
3677
+ });
3678
+ var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
3679
+ $ZodCUID.init(inst, def);
3680
+ ZodStringFormat.init(inst, def);
3681
+ });
3682
+ var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
3683
+ $ZodCUID2.init(inst, def);
3684
+ ZodStringFormat.init(inst, def);
3685
+ });
3686
+ var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
3687
+ $ZodULID.init(inst, def);
3688
+ ZodStringFormat.init(inst, def);
3689
+ });
3690
+ var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
3691
+ $ZodXID.init(inst, def);
3692
+ ZodStringFormat.init(inst, def);
3693
+ });
3694
+ var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
3695
+ $ZodKSUID.init(inst, def);
3696
+ ZodStringFormat.init(inst, def);
3697
+ });
3698
+ var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
3699
+ $ZodIPv4.init(inst, def);
3700
+ ZodStringFormat.init(inst, def);
3701
+ });
3702
+ var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
3703
+ $ZodIPv6.init(inst, def);
3704
+ ZodStringFormat.init(inst, def);
3705
+ });
3706
+ var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
3707
+ $ZodCIDRv4.init(inst, def);
3708
+ ZodStringFormat.init(inst, def);
3709
+ });
3710
+ var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
3711
+ $ZodCIDRv6.init(inst, def);
3712
+ ZodStringFormat.init(inst, def);
3713
+ });
3714
+ var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
3715
+ $ZodBase64.init(inst, def);
3716
+ ZodStringFormat.init(inst, def);
3717
+ });
3718
+ var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
3719
+ $ZodBase64URL.init(inst, def);
3720
+ ZodStringFormat.init(inst, def);
3721
+ });
3722
+ var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
3723
+ $ZodE164.init(inst, def);
3724
+ ZodStringFormat.init(inst, def);
3725
+ });
3726
+ var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
3727
+ $ZodJWT.init(inst, def);
3728
+ ZodStringFormat.init(inst, def);
3729
+ });
3730
+ var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
3731
+ $ZodNumber.init(inst, def);
3732
+ ZodType.init(inst, def);
3733
+ inst.gt = (value, params) => inst.check(_gt(value, params));
3734
+ inst.gte = (value, params) => inst.check(_gte(value, params));
3735
+ inst.min = (value, params) => inst.check(_gte(value, params));
3736
+ inst.lt = (value, params) => inst.check(_lt(value, params));
3737
+ inst.lte = (value, params) => inst.check(_lte(value, params));
3738
+ inst.max = (value, params) => inst.check(_lte(value, params));
3739
+ inst.int = (params) => inst.check(int(params));
3740
+ inst.safe = (params) => inst.check(int(params));
3741
+ inst.positive = (params) => inst.check(_gt(0, params));
3742
+ inst.nonnegative = (params) => inst.check(_gte(0, params));
3743
+ inst.negative = (params) => inst.check(_lt(0, params));
3744
+ inst.nonpositive = (params) => inst.check(_lte(0, params));
3745
+ inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
3746
+ inst.step = (value, params) => inst.check(_multipleOf(value, params));
3747
+ inst.finite = () => inst;
3748
+ const bag = inst._zod.bag;
3749
+ inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
3750
+ inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
3751
+ inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);
3752
+ inst.isFinite = true;
3753
+ inst.format = bag.format ?? null;
3754
+ });
3755
+ function number2(params) {
3756
+ return _number(ZodNumber, params);
3757
+ }
3758
+ var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
3759
+ $ZodNumberFormat.init(inst, def);
3760
+ ZodNumber.init(inst, def);
3761
+ });
3762
+ function int(params) {
3763
+ return _int(ZodNumberFormat, params);
3764
+ }
3765
+ var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
3766
+ $ZodBoolean.init(inst, def);
3767
+ ZodType.init(inst, def);
3768
+ });
3769
+ function boolean2(params) {
3770
+ return _boolean(ZodBoolean, params);
3771
+ }
3772
+ var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => {
3773
+ $ZodBigInt.init(inst, def);
3774
+ ZodType.init(inst, def);
3775
+ inst.gte = (value, params) => inst.check(_gte(value, params));
3776
+ inst.min = (value, params) => inst.check(_gte(value, params));
3777
+ inst.gt = (value, params) => inst.check(_gt(value, params));
3778
+ inst.gte = (value, params) => inst.check(_gte(value, params));
3779
+ inst.min = (value, params) => inst.check(_gte(value, params));
3780
+ inst.lt = (value, params) => inst.check(_lt(value, params));
3781
+ inst.lte = (value, params) => inst.check(_lte(value, params));
3782
+ inst.max = (value, params) => inst.check(_lte(value, params));
3783
+ inst.positive = (params) => inst.check(_gt(BigInt(0), params));
3784
+ inst.negative = (params) => inst.check(_lt(BigInt(0), params));
3785
+ inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params));
3786
+ inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params));
3787
+ inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
3788
+ const bag = inst._zod.bag;
3789
+ inst.minValue = bag.minimum ?? null;
3790
+ inst.maxValue = bag.maximum ?? null;
3791
+ inst.format = bag.format ?? null;
3792
+ });
3793
+ var ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
3794
+ $ZodUnknown.init(inst, def);
3795
+ ZodType.init(inst, def);
3796
+ });
3797
+ function unknown() {
3798
+ return _unknown(ZodUnknown);
3799
+ }
3800
+ var ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
3801
+ $ZodNever.init(inst, def);
3802
+ ZodType.init(inst, def);
3803
+ });
3804
+ function never(params) {
3805
+ return _never(ZodNever, params);
3806
+ }
3807
+ var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => {
3808
+ $ZodDate.init(inst, def);
3809
+ ZodType.init(inst, def);
3810
+ inst.min = (value, params) => inst.check(_gte(value, params));
3811
+ inst.max = (value, params) => inst.check(_lte(value, params));
3812
+ const c = inst._zod.bag;
3813
+ inst.minDate = c.minimum ? new Date(c.minimum) : null;
3814
+ inst.maxDate = c.maximum ? new Date(c.maximum) : null;
3815
+ });
3816
+ var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
3817
+ $ZodArray.init(inst, def);
3818
+ ZodType.init(inst, def);
3819
+ inst.element = def.element;
3820
+ inst.min = (minLength, params) => inst.check(_minLength(minLength, params));
3821
+ inst.nonempty = (params) => inst.check(_minLength(1, params));
3822
+ inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));
3823
+ inst.length = (len, params) => inst.check(_length(len, params));
3824
+ inst.unwrap = () => inst.element;
3825
+ });
3826
+ function array(element, params) {
3827
+ return _array(ZodArray, element, params);
3828
+ }
3829
+ var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
3830
+ $ZodObjectJIT.init(inst, def);
3831
+ ZodType.init(inst, def);
3832
+ defineLazy(inst, "shape", () => def.shape);
3833
+ inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
3834
+ inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall });
3835
+ inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
3836
+ inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
3837
+ inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });
3838
+ inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });
3839
+ inst.extend = (incoming) => {
3840
+ return extend(inst, incoming);
3841
+ };
3842
+ inst.safeExtend = (incoming) => {
3843
+ return safeExtend(inst, incoming);
3844
+ };
3845
+ inst.merge = (other) => merge(inst, other);
3846
+ inst.pick = (mask) => pick(inst, mask);
3847
+ inst.omit = (mask) => omit(inst, mask);
3848
+ inst.partial = (...args) => partial(ZodOptional, inst, args[0]);
3849
+ inst.required = (...args) => required(ZodNonOptional, inst, args[0]);
3850
+ });
3851
+ function object(shape, params) {
3852
+ const def = {
3853
+ type: "object",
3854
+ get shape() {
3855
+ assignProp(this, "shape", shape ? objectClone(shape) : {});
3856
+ return this.shape;
3857
+ },
3858
+ ...normalizeParams(params)
3859
+ };
3860
+ return new ZodObject(def);
3861
+ }
3862
+ var ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
3863
+ $ZodUnion.init(inst, def);
3864
+ ZodType.init(inst, def);
3865
+ inst.options = def.options;
3866
+ });
3867
+ function union(options, params) {
3868
+ return new ZodUnion({
3869
+ type: "union",
3870
+ options,
3871
+ ...normalizeParams(params)
3872
+ });
3873
+ }
3874
+ var ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
3875
+ $ZodIntersection.init(inst, def);
3876
+ ZodType.init(inst, def);
3877
+ });
3878
+ function intersection(left, right) {
3879
+ return new ZodIntersection({
3880
+ type: "intersection",
3881
+ left,
3882
+ right
3883
+ });
3884
+ }
3885
+ var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
3886
+ $ZodEnum.init(inst, def);
3887
+ ZodType.init(inst, def);
3888
+ inst.enum = def.entries;
3889
+ inst.options = Object.values(def.entries);
3890
+ const keys = new Set(Object.keys(def.entries));
3891
+ inst.extract = (values, params) => {
3892
+ const newEntries = {};
3893
+ for (const value of values) {
3894
+ if (keys.has(value)) {
3895
+ newEntries[value] = def.entries[value];
3896
+ } else
3897
+ throw new Error(`Key ${value} not found in enum`);
3898
+ }
3899
+ return new ZodEnum({
3900
+ ...def,
3901
+ checks: [],
3902
+ ...normalizeParams(params),
3903
+ entries: newEntries
3904
+ });
3905
+ };
3906
+ inst.exclude = (values, params) => {
3907
+ const newEntries = { ...def.entries };
3908
+ for (const value of values) {
3909
+ if (keys.has(value)) {
3910
+ delete newEntries[value];
3911
+ } else
3912
+ throw new Error(`Key ${value} not found in enum`);
3913
+ }
3914
+ return new ZodEnum({
3915
+ ...def,
3916
+ checks: [],
3917
+ ...normalizeParams(params),
3918
+ entries: newEntries
3919
+ });
3920
+ };
3921
+ });
3922
+ function _enum(values, params) {
3923
+ const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
3924
+ return new ZodEnum({
3925
+ type: "enum",
3926
+ entries,
3927
+ ...normalizeParams(params)
3928
+ });
3929
+ }
3930
+ var ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
3931
+ $ZodLiteral.init(inst, def);
3932
+ ZodType.init(inst, def);
3933
+ inst.values = new Set(def.values);
3934
+ Object.defineProperty(inst, "value", {
3935
+ get() {
3936
+ if (def.values.length > 1) {
3937
+ throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
3938
+ }
3939
+ return def.values[0];
3940
+ }
3941
+ });
3942
+ });
3943
+ function literal(value, params) {
3944
+ return new ZodLiteral({
3945
+ type: "literal",
3946
+ values: Array.isArray(value) ? value : [value],
3947
+ ...normalizeParams(params)
3948
+ });
3949
+ }
3950
+ var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
3951
+ $ZodTransform.init(inst, def);
3952
+ ZodType.init(inst, def);
3953
+ inst._zod.parse = (payload, _ctx) => {
3954
+ if (_ctx.direction === "backward") {
3955
+ throw new $ZodEncodeError(inst.constructor.name);
3956
+ }
3957
+ payload.addIssue = (issue2) => {
3958
+ if (typeof issue2 === "string") {
3959
+ payload.issues.push(issue(issue2, payload.value, def));
3960
+ } else {
3961
+ const _issue = issue2;
3962
+ if (_issue.fatal)
3963
+ _issue.continue = false;
3964
+ _issue.code ?? (_issue.code = "custom");
3965
+ _issue.input ?? (_issue.input = payload.value);
3966
+ _issue.inst ?? (_issue.inst = inst);
3967
+ payload.issues.push(issue(_issue));
3968
+ }
3969
+ };
3970
+ const output = def.transform(payload.value, payload);
3971
+ if (output instanceof Promise) {
3972
+ return output.then((output) => {
3973
+ payload.value = output;
3974
+ return payload;
3975
+ });
3976
+ }
3977
+ payload.value = output;
3978
+ return payload;
3979
+ };
3980
+ });
3981
+ function transform(fn) {
3982
+ return new ZodTransform({
3983
+ type: "transform",
3984
+ transform: fn
3985
+ });
3986
+ }
3987
+ var ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
3988
+ $ZodOptional.init(inst, def);
3989
+ ZodType.init(inst, def);
3990
+ inst.unwrap = () => inst._zod.def.innerType;
3991
+ });
3992
+ function optional(innerType) {
3993
+ return new ZodOptional({
3994
+ type: "optional",
3995
+ innerType
3996
+ });
3997
+ }
3998
+ var ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
3999
+ $ZodNullable.init(inst, def);
4000
+ ZodType.init(inst, def);
4001
+ inst.unwrap = () => inst._zod.def.innerType;
4002
+ });
4003
+ function nullable(innerType) {
4004
+ return new ZodNullable({
4005
+ type: "nullable",
4006
+ innerType
4007
+ });
4008
+ }
4009
+ var ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
4010
+ $ZodDefault.init(inst, def);
4011
+ ZodType.init(inst, def);
4012
+ inst.unwrap = () => inst._zod.def.innerType;
4013
+ inst.removeDefault = inst.unwrap;
4014
+ });
4015
+ function _default(innerType, defaultValue) {
4016
+ return new ZodDefault({
4017
+ type: "default",
4018
+ innerType,
4019
+ get defaultValue() {
4020
+ return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
4021
+ }
4022
+ });
4023
+ }
4024
+ var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
4025
+ $ZodPrefault.init(inst, def);
4026
+ ZodType.init(inst, def);
4027
+ inst.unwrap = () => inst._zod.def.innerType;
4028
+ });
4029
+ function prefault(innerType, defaultValue) {
4030
+ return new ZodPrefault({
4031
+ type: "prefault",
4032
+ innerType,
4033
+ get defaultValue() {
4034
+ return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
4035
+ }
4036
+ });
4037
+ }
4038
+ var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
4039
+ $ZodNonOptional.init(inst, def);
4040
+ ZodType.init(inst, def);
4041
+ inst.unwrap = () => inst._zod.def.innerType;
4042
+ });
4043
+ function nonoptional(innerType, params) {
4044
+ return new ZodNonOptional({
4045
+ type: "nonoptional",
4046
+ innerType,
4047
+ ...normalizeParams(params)
4048
+ });
4049
+ }
4050
+ var ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
4051
+ $ZodCatch.init(inst, def);
4052
+ ZodType.init(inst, def);
4053
+ inst.unwrap = () => inst._zod.def.innerType;
4054
+ inst.removeCatch = inst.unwrap;
4055
+ });
4056
+ function _catch(innerType, catchValue) {
4057
+ return new ZodCatch({
4058
+ type: "catch",
4059
+ innerType,
4060
+ catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
4061
+ });
4062
+ }
4063
+ var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
4064
+ $ZodPipe.init(inst, def);
4065
+ ZodType.init(inst, def);
4066
+ inst.in = def.in;
4067
+ inst.out = def.out;
4068
+ });
4069
+ function pipe(in_, out) {
4070
+ return new ZodPipe({
4071
+ type: "pipe",
4072
+ in: in_,
4073
+ out
4074
+ });
4075
+ }
4076
+ var ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
4077
+ $ZodReadonly.init(inst, def);
4078
+ ZodType.init(inst, def);
4079
+ inst.unwrap = () => inst._zod.def.innerType;
4080
+ });
4081
+ function readonly(innerType) {
4082
+ return new ZodReadonly({
4083
+ type: "readonly",
4084
+ innerType
4085
+ });
4086
+ }
4087
+ var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
4088
+ $ZodCustom.init(inst, def);
4089
+ ZodType.init(inst, def);
4090
+ });
4091
+ function refine(fn, _params = {}) {
4092
+ return _refine(ZodCustom, fn, _params);
4093
+ }
4094
+ function superRefine(fn) {
4095
+ return _superRefine(fn);
4096
+ }
4097
+ // node_modules/zod/v4/classic/coerce.js
4098
+ var exports_coerce = {};
4099
+ __export(exports_coerce, {
4100
+ bigint: () => bigint2,
4101
+ boolean: () => boolean3,
4102
+ date: () => date3,
4103
+ number: () => number3,
4104
+ string: () => string3
4105
+ });
4106
+ function string3(params) {
4107
+ return _coercedString(ZodString, params);
4108
+ }
4109
+ function number3(params) {
4110
+ return _coercedNumber(ZodNumber, params);
4111
+ }
4112
+ function boolean3(params) {
4113
+ return _coercedBoolean(ZodBoolean, params);
4114
+ }
4115
+ function bigint2(params) {
4116
+ return _coercedBigint(ZodBigInt, params);
4117
+ }
4118
+ function date3(params) {
4119
+ return _coercedDate(ZodDate, params);
4120
+ }
4121
+
4122
+ // node_modules/zod/v4/classic/external.js
4123
+ config(en_default());
4124
+ // src/memory-worker.ts
4125
+ var saveInput = object({
4126
+ text: string2().min(1).max(MAX_OBSERVATION_BYTES),
4127
+ title: string2().max(MAX_OBSERVATION_BYTES).optional(),
4128
+ project: string2().trim().min(1).max(1000).optional()
4129
+ });
4130
+ var saveResponse = object({
4131
+ success: literal(true),
4132
+ id: number2().int().positive(),
4133
+ title: string2(),
4134
+ project: string2(),
4135
+ message: string2()
4136
+ });
4137
+ var semanticResponse = object({ context: string2(), count: number2().int().nonnegative() });
4138
+ var fileResponse = object({
4139
+ observations: array(object({
4140
+ id: number2().int().positive(),
4141
+ title: string2().nullable(),
4142
+ type: string2(),
4143
+ created_at_epoch: number2().finite(),
4144
+ memory_session_id: string2().nullable().optional()
4145
+ })),
4146
+ count: number2().int().nonnegative()
4147
+ });
4148
+
4149
+ class MemoryWorker {
4150
+ static baseUrl = getWorkerBaseUrl();
4151
+ static async json(path, init) {
4152
+ try {
4153
+ const response = await fetch(`${this.baseUrl}${path}`, init);
4154
+ if (!response.ok) {
4155
+ return null;
4156
+ }
4157
+ const reader = response.body?.getReader();
4158
+ if (!reader) {
4159
+ return null;
4160
+ }
4161
+ const chunks = [];
4162
+ let size = 0;
4163
+ try {
4164
+ while (true) {
4165
+ const { done, value } = await reader.read();
4166
+ if (done) {
4167
+ break;
4168
+ }
4169
+ size += value.byteLength;
4170
+ if (size > 512 * 1024) {
4171
+ return null;
4172
+ }
4173
+ chunks.push(value);
4174
+ }
4175
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
4176
+ } finally {
4177
+ await reader.cancel();
4178
+ }
4179
+ } catch {
4180
+ return null;
4181
+ }
4182
+ }
4183
+ static async save(input, project) {
4184
+ const parsed = saveInput.safeParse(input);
4185
+ if (!parsed.success) {
4186
+ return "Memory not saved: invalid or oversized input.";
4187
+ }
4188
+ const text = stripTaggedContent(parsed.data.text);
4189
+ const title = parsed.data.title === undefined ? undefined : stripTaggedContent(parsed.data.title);
4190
+ if (!text || title !== undefined && !title || Buffer.byteLength(text) > MAX_OBSERVATION_BYTES || title !== undefined && Buffer.byteLength(title) > MAX_OBSERVATION_BYTES) {
4191
+ return "Memory not saved: content is empty, private, or exceeds 24 KiB.";
4192
+ }
4193
+ const result = saveResponse.safeParse(await this.json("/api/memory/save", {
4194
+ method: "POST",
4195
+ signal: AbortSignal.timeout(1e4),
4196
+ headers: { "Content-Type": "application/json" },
4197
+ body: JSON.stringify({
4198
+ text,
4199
+ title,
4200
+ project: parsed.data.project ?? project,
4201
+ metadata: { platformSource: "opencode" }
4202
+ })
4203
+ }));
4204
+ return result.success ? JSON.stringify(result.data) : "Memory save not confirmed. The Worker may be unavailable or unsupported; check before retrying to avoid duplicates.";
4205
+ }
4206
+ static async semantic(prompt, project, options) {
4207
+ const q = stripTaggedContent(prompt);
4208
+ if (!options.enabled || q.length < 20) {
4209
+ return "";
4210
+ }
4211
+ const result = semanticResponse.safeParse(await this.json("/api/context/semantic", {
4212
+ method: "POST",
4213
+ signal: AbortSignal.timeout(options.timeoutMs),
4214
+ headers: { "Content-Type": "application/json" },
4215
+ body: JSON.stringify({ q, project, limit: options.limit })
4216
+ }));
4217
+ return result.success ? stripTaggedContent(result.data.context).slice(0, options.maxChars) : "";
4218
+ }
4219
+ static async byFile(paths, project, options) {
4220
+ const lookahead = Math.max(40, options.limit);
4221
+ const params = new URLSearchParams({ projects: project, limit: String(lookahead) });
4222
+ for (const path of new Set(paths.map((item) => item.replaceAll("\\", "/")))) {
4223
+ params.append("path", path);
4224
+ }
4225
+ const result = fileResponse.safeParse(await this.json(`/api/observations/by-file?${params}`, {
4226
+ signal: AbortSignal.timeout(options.timeoutMs)
4227
+ }));
4228
+ return result.success ? result.data.observations.slice(0, lookahead) : [];
4229
+ }
4230
+ }
4231
+
4232
+ // src/file-context.ts
4233
+ import { stat } from "fs/promises";
4234
+ var readInput = object({
4235
+ filePath: string2().optional(),
4236
+ file_path: string2().optional(),
4237
+ filePaths: array(string2()).optional(),
4238
+ file_paths: array(string2()).optional(),
4239
+ path: string2().optional()
4240
+ }).passthrough();
4241
+
4242
+ class FileContext {
4243
+ sessions = new Map;
4244
+ options;
4245
+ worker;
4246
+ constructor(options, worker = MemoryWorker) {
4247
+ this.options = options;
4248
+ this.worker = worker;
4249
+ }
4250
+ async read(session, input, location) {
4251
+ if (!this.options.enabled || !/(?:^|[._-])read(?:_file|_files)?$/i.test(input.tool)) {
4252
+ return "";
4253
+ }
4254
+ const parsed = readInput.safeParse(input.args);
4255
+ if (!parsed.success) {
4256
+ return "";
4257
+ }
4258
+ const args = parsed.data;
4259
+ const paths = [
4260
+ ...new Set([
4261
+ args.filePath,
4262
+ args.file_path,
4263
+ args.path,
4264
+ ...args.filePaths ?? [],
4265
+ ...args.file_paths ?? []
4266
+ ].filter((path) => path !== undefined))
4267
+ ].slice(0, 10);
4268
+ let seen = this.sessions.get(session);
4269
+ if (!seen) {
4270
+ seen = new Map;
4271
+ this.sessions.set(session, seen);
4272
+ }
4273
+ const revisions = seen;
4274
+ const attempted = new Map;
4275
+ const deadline = Date.now() + this.options.timeoutMs;
4276
+ let active = true;
4277
+ const timeout = Promise.withResolvers();
4278
+ const timer = setTimeout(() => timeout.resolve(""), this.options.timeoutMs);
4279
+ const pending = (async () => {
4280
+ const results = await Promise.all(paths.map(async (path) => {
4281
+ const absolute = resolve(location.directory, path);
4282
+ const file = await stat(absolute).catch(() => null);
4283
+ if (!active || this.sessions.get(session) !== revisions || !file?.isFile() || file.size < 1500) {
4284
+ return [];
4285
+ }
4286
+ const revision = `${file.mtimeMs}:${file.size}`;
4287
+ const inFlight = `pending:${revision}`;
4288
+ if (revisions.get(absolute) === revision || revisions.get(absolute) === inFlight) {
4289
+ return [];
4290
+ }
4291
+ attempted.set(absolute, inFlight);
4292
+ revisions.set(absolute, inFlight);
4293
+ const rows = await this.worker.byFile([absolute, relative(location.directory, absolute)], location.project, { ...this.options, timeoutMs: Math.max(1, deadline - Date.now()) });
4294
+ if (!active || this.sessions.get(session) !== revisions || !rows.length || file.mtimeMs >= Math.max(...rows.map((row) => row.created_at_epoch))) {
4295
+ return [];
4296
+ }
4297
+ return rows.map((row) => ({ row, path: absolute, revision }));
4298
+ }));
4299
+ const sessions = new Set;
4300
+ const selected = results.flat().toSorted((a, b) => b.row.created_at_epoch - a.row.created_at_epoch).filter(({ row }) => {
4301
+ const key = row.memory_session_id ?? `observation:${row.id}`;
4302
+ if (sessions.has(key)) {
4303
+ return false;
4304
+ }
4305
+ sessions.add(key);
4306
+ return true;
4307
+ }).slice(0, this.options.limit);
4308
+ const delivered = new Map;
4309
+ let text = "";
4310
+ for (const { row, path, revision } of selected) {
4311
+ const separator = text ? `
4312
+ ` : "";
4313
+ const available = this.options.maxChars - text.length - separator.length;
4314
+ if (available <= 0) {
4315
+ break;
4316
+ }
4317
+ const line = `#${row.id} ${stripTaggedContent(row.type)}: ${stripTaggedContent(row.title ?? "")}`;
4318
+ text += separator + line.slice(0, available);
4319
+ delivered.set(path, revision);
4320
+ }
4321
+ if (text && active && this.sessions.get(session) === revisions) {
4322
+ for (const [path, revision] of delivered) {
4323
+ revisions.set(path, revision);
4324
+ }
4325
+ }
4326
+ return text ? `
4327
+
4328
+ <claude-mem-context>
4329
+ Supplementary file history (past observations, not file contents):
4330
+ ${text}
4331
+ </claude-mem-context>` : "";
4332
+ })();
4333
+ try {
4334
+ return await Promise.race([pending, timeout.promise]);
4335
+ } catch {
4336
+ return "";
4337
+ } finally {
4338
+ active = false;
4339
+ clearTimeout(timer);
4340
+ for (const [path, revision] of attempted) {
4341
+ if (revisions.get(path) === revision) {
4342
+ revisions.delete(path);
4343
+ }
4344
+ }
4345
+ }
4346
+ }
4347
+ delete(session) {
4348
+ this.sessions.delete(session);
4349
+ }
4350
+ clear() {
4351
+ this.sessions.clear();
4352
+ }
4353
+ }
4354
+
4355
+ // src/memory-session.ts
4356
+ class MemorySessions {
4357
+ sessions = new Map;
4358
+ deleted = new Set;
4359
+ options;
4360
+ worker;
4361
+ constructor(options, worker = MemoryWorker) {
4362
+ this.options = options;
4363
+ this.worker = worker;
4364
+ }
4365
+ state(id) {
4366
+ let state = this.sessions.get(id);
4367
+ if (!state) {
4368
+ state = {
4369
+ turns: new Map,
4370
+ registered: new Set,
4371
+ blocked: new Set,
4372
+ pending: [],
4373
+ semantic: new Map
4374
+ };
4375
+ this.sessions.set(id, state);
4376
+ }
4377
+ return state;
4378
+ }
4379
+ select(session, turn) {
4380
+ if (this.isDeleted(session)) {
4381
+ return false;
4382
+ }
4383
+ const state = this.state(session);
4384
+ const known = state.turns.get(turn.id);
4385
+ if (known && state.current !== known) {
4386
+ return false;
4387
+ }
4388
+ state.current = known ?? turn;
4389
+ if (!known) {
4390
+ state.turns.set(turn.id, turn);
4391
+ if (turn.capture) {
4392
+ state.pending.push(turn);
4393
+ }
4394
+ }
4395
+ return !known;
4396
+ }
4397
+ hasTurn(session) {
4398
+ return Boolean(this.sessions.get(session)?.current);
4399
+ }
4400
+ hasMessage(session, id) {
4401
+ return this.sessions.get(session)?.turns.has(id) ?? false;
4402
+ }
4403
+ isDeleted(session) {
4404
+ return this.deleted.has(session);
4405
+ }
4406
+ canCapture(session) {
4407
+ const state = this.sessions.get(session);
4408
+ const turn = state?.current;
4409
+ return Boolean(turn?.capture && state?.registered.has(turn.id) && !state.blocked.has(turn.id));
4410
+ }
4411
+ async register(session, project) {
4412
+ const state = this.sessions.get(session);
4413
+ if (!state?.current?.capture) {
4414
+ return false;
4415
+ }
4416
+ if (state.registration) {
4417
+ return state.registration;
4418
+ }
4419
+ const pending = (async () => {
4420
+ while (state.pending.length) {
4421
+ const [turn] = state.pending;
4422
+ if (!turn || this.sessions.get(session) !== state) {
4423
+ return false;
4424
+ }
4425
+ const result = await WorkerClient.sessionInit(session, project, turn.text);
4426
+ if (!result || this.sessions.get(session) !== state) {
4427
+ return false;
4428
+ }
4429
+ if (result.skipped && result.reason !== "duplicate") {
4430
+ state.blocked.add(turn.id);
4431
+ }
4432
+ state.registered.add(turn.id);
4433
+ state.pending.shift();
4434
+ }
4435
+ return this.canCapture(session);
4436
+ })();
4437
+ state.registration = pending;
4438
+ try {
4439
+ return await pending;
4440
+ } finally {
4441
+ state.registration = undefined;
4442
+ }
4443
+ }
4444
+ async semantic(session, project) {
4445
+ const state = this.sessions.get(session);
4446
+ const turn = state?.current;
4447
+ if (!state || !turn?.semantic || !this.canCapture(session)) {
4448
+ return "";
4449
+ }
4450
+ let pending = state.semantic.get(turn.id);
4451
+ if (!pending) {
4452
+ pending = this.worker.semantic(turn.text, project, this.options.semanticInjection);
4453
+ state.semantic.set(turn.id, pending);
4454
+ }
4455
+ const result = await pending;
4456
+ return this.sessions.get(session) === state && state.current === turn ? result : "";
4457
+ }
4458
+ async context(session, project) {
4459
+ if (this.isDeleted(session)) {
4460
+ return null;
4461
+ }
4462
+ const state = this.state(session);
4463
+ if (!state.context) {
4464
+ state.context = WorkerClient.getContext(project);
4465
+ }
4466
+ const pending = state.context;
4467
+ const value = await pending;
4468
+ if (this.sessions.get(session) !== state || state.context !== pending) {
4469
+ return null;
4470
+ }
4471
+ if (value === null) {
4472
+ state.context = undefined;
4473
+ }
4474
+ return value === null ? null : stripTaggedContent(value).slice(0, 24000);
4475
+ }
4476
+ invalidate(session) {
4477
+ const state = this.sessions.get(session);
4478
+ if (state) {
4479
+ state.context = undefined;
4480
+ }
4481
+ }
4482
+ delete(session) {
4483
+ this.deleted.add(session);
4484
+ this.sessions.delete(session);
4485
+ }
4486
+ clear() {
4487
+ for (const session of this.sessions.keys()) {
4488
+ this.deleted.add(session);
4489
+ }
4490
+ this.sessions.clear();
4491
+ }
4492
+ }
4493
+
4494
+ // src/memory-turn.ts
4495
+ function memoryTurn(id, text, media = false) {
4496
+ const cleaned = stripTaggedContent(text.replace(/<(system-reminder|system_instruction|system-instruction|persisted-output)\b[^>]*>[\s\S]*?<\/\1>/gi, ""));
4497
+ const internal = /^\s*<task-notification\b[^>]*>[\s\S]*?<\/task-notification>\s*$/i.test(text);
4498
+ return {
4499
+ id,
4500
+ text: truncateUtf8Bytes(cleaned || (media ? "[media prompt]" : ""), 256 * 1024),
4501
+ capture: !internal && (Boolean(cleaned) || media && !text.trim()),
4502
+ semantic: !internal && cleaned.length >= 20
4503
+ };
4504
+ }
4505
+ var deliveredRecord = object({
4506
+ id: string2(),
4507
+ type: string2(),
4508
+ text: string2().optional(),
4509
+ files: array(unknown()).optional(),
4510
+ metadata: object({ synthetic: boolean2().optional(), agentId: string2().optional() }).optional()
4511
+ });
4512
+ function deliveredTurn(messages) {
4513
+ for (const raw of messages.toReversed()) {
4514
+ const parsed = deliveredRecord.safeParse(raw);
4515
+ if (parsed.success) {
4516
+ const message = parsed.data;
4517
+ if (message.type === "synthetic") {
4518
+ return { id: message.id, text: "", capture: false, semantic: false };
4519
+ }
4520
+ if (message.type === "user") {
4521
+ if (message.metadata?.synthetic || message.metadata?.agentId) {
4522
+ return { id: message.id, text: "", capture: false, semantic: false };
4523
+ }
4524
+ return memoryTurn(message.id, message.text ?? "", Boolean(message.files?.length));
4525
+ }
4526
+ }
4527
+ }
4528
+ return;
4529
+ }
4530
+ var v1Record = object({
4531
+ info: object({ id: string2(), role: string2() }),
4532
+ parts: array(unknown())
4533
+ });
4534
+
4535
+ // src/tui-registration.ts
4536
+ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
4537
+ import { homedir as homedir2 } from "os";
4538
+ import { join as join2 } from "path";
4539
+ var PACKAGE_NAME = "@ephemushroom/opencode-claude-mem";
4540
+ var SIDEBAR_ENTRIES = [PACKAGE_NAME, `${PACKAGE_NAME}/cli`, `${PACKAGE_NAME}/tui`];
4541
+ function getConfigDir() {
4542
+ const custom = process.env["OPENCODE_CONFIG_DIR"]?.trim();
4543
+ return custom || join2(homedir2(), ".config", "opencode");
4544
+ }
4545
+ function readJson(filePath) {
4546
+ try {
4547
+ const parsed = JSON.parse(readFileSync2(filePath, "utf8"));
4548
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
4549
+ } catch {
4550
+ return null;
4551
+ }
4552
+ }
4553
+ function isCliEntry(entry) {
4554
+ if (typeof entry === "string") {
4555
+ return true;
4556
+ }
4557
+ if (typeof entry !== "object" || entry === null || !("package" in entry)) {
4558
+ return false;
4559
+ }
4560
+ return typeof entry.package === "string" && (!("options" in entry) || typeof entry.options === "object" && entry.options !== null && !Array.isArray(entry.options));
4561
+ }
4562
+ function v2PluginEntries(config) {
4563
+ const { plugins } = config;
4564
+ if (plugins === undefined) {
4565
+ return [];
4566
+ }
4567
+ return Array.isArray(plugins) && plugins.every(isCliEntry) ? plugins : null;
4568
+ }
4569
+ function ensureCliPluginEntry() {
4570
+ try {
4571
+ const configDir = getConfigDir();
4572
+ const cliJsonPath = join2(configDir, "cli.json");
4573
+ let config = {};
4574
+ if (existsSync2(cliJsonPath)) {
4575
+ const parsed = readJson(cliJsonPath);
4576
+ if (!parsed) {
4577
+ return "malformed";
4578
+ }
4579
+ config = parsed;
4580
+ }
4581
+ const plugins = v2PluginEntries(config);
4582
+ if (!plugins) {
4583
+ return "malformed";
4584
+ }
4585
+ if (plugins.some((entry) => {
4586
+ const specifier = typeof entry === "string" ? entry : entry.package;
4587
+ return SIDEBAR_ENTRIES.some((name) => specifier === name || specifier.startsWith(`${name}@`));
4588
+ })) {
4589
+ return "already-present";
4590
+ }
4591
+ mkdirSync(configDir, { recursive: true });
4592
+ const next = { ...config, plugins: [...plugins, PACKAGE_NAME] };
4593
+ writeFileSync(cliJsonPath, `${JSON.stringify(next, null, 2)}
4594
+ `);
4595
+ return "added";
4596
+ } catch {
4597
+ return "failed";
4598
+ }
4599
+ }
4600
+
4601
+ // src/memory-options.ts
4602
+ import { homedir as homedir3 } from "os";
4603
+ import { join as join3 } from "path";
4604
+ import { readFileSync as readFileSync3 } from "fs";
4605
+ var group = object({
4606
+ enabled: boolean2().optional().catch(undefined),
4607
+ limit: number2().int().min(1).max(50).optional().catch(undefined),
4608
+ maxChars: number2().int().min(256).max(24000).optional().catch(undefined),
4609
+ timeoutMs: number2().int().min(100).max(1e4).optional().catch(undefined)
4610
+ }).catch({});
4611
+ var optionsSchema = object({
4612
+ semanticInjection: group.optional(),
4613
+ fileContext: group.optional()
4614
+ }).catch({});
4615
+ var settingsSchema = object({
4616
+ CLAUDE_MEM_SEMANTIC_INJECT: unknown().optional(),
4617
+ CLAUDE_MEM_SEMANTIC_INJECT_LIMIT: unknown().optional()
4618
+ }).catch({});
4619
+ function booleanSetting(value) {
4620
+ const normalized = typeof value === "string" ? value.trim().toLowerCase() : value;
4621
+ if (normalized === true || normalized === "true" || normalized === "1") {
4622
+ return true;
4623
+ }
4624
+ if (normalized === false || normalized === "false" || normalized === "0") {
4625
+ return false;
4626
+ }
4627
+ return;
4628
+ }
4629
+ function limitSetting(value) {
4630
+ const parsed = exports_coerce.number().int().min(1).max(50).safeParse(value);
4631
+ return parsed.success ? parsed.data : undefined;
4632
+ }
4633
+ function parseMemoryOptions(options, env, settings) {
4634
+ const explicit = optionsSchema.parse(options);
4635
+ const stored = settingsSchema.parse(settings);
4636
+ return {
4637
+ semanticInjection: {
4638
+ enabled: explicit.semanticInjection?.enabled ?? booleanSetting(env.CLAUDE_MEM_SEMANTIC_INJECT) ?? booleanSetting(stored.CLAUDE_MEM_SEMANTIC_INJECT) ?? false,
4639
+ limit: explicit.semanticInjection?.limit ?? limitSetting(env.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT) ?? limitSetting(stored.CLAUDE_MEM_SEMANTIC_INJECT_LIMIT) ?? 5,
4640
+ maxChars: explicit.semanticInjection?.maxChars ?? 6000,
4641
+ timeoutMs: explicit.semanticInjection?.timeoutMs ?? 2000
4642
+ },
4643
+ fileContext: {
4644
+ enabled: explicit.fileContext?.enabled ?? true,
4645
+ limit: explicit.fileContext?.limit ?? 15,
4646
+ maxChars: explicit.fileContext?.maxChars ?? 6000,
4647
+ timeoutMs: explicit.fileContext?.timeoutMs ?? 1500
4648
+ }
4649
+ };
4650
+ }
4651
+ function resolveMemoryOptions(options) {
4652
+ let settings = {};
4653
+ try {
4654
+ settings = JSON.parse(readFileSync3(join3(homedir3(), ".claude-mem", "settings.json"), "utf8"));
4655
+ } catch {}
4656
+ return parseMemoryOptions(options, process.env, settings);
4657
+ }
4658
+
4659
+ // src/v2.ts
4660
+ var EVENT_RETRY_DELAY_MS = 1e4;
4661
+ var v2_default = define({
4662
+ id: "claude-mem",
4663
+ setup: async (ctx) => {
4664
+ ensureCliPluginEntry();
4665
+ const controller = new AbortController;
4666
+ const config = resolveMemoryOptions(ctx.options);
4667
+ const memory = new MemorySessions(config);
4668
+ const files = new FileContext(config.fileContext);
4669
+ const admitted = new Map;
4670
+ const compactions = new Map;
4671
+ const subagentSessions = new Set;
4672
+ const sessionDirs = new Map;
4673
+ const sessionUserTexts = new Map;
4674
+ const sessionAssistantTexts = new Map;
4675
+ const sessionModels = new Map;
4676
+ const defaultDirectory = ctx.location.directory;
4677
+ async function checkWorker() {
4678
+ return !controller.signal.aborted && await WorkerClient.ensureRunning();
4679
+ }
4680
+ async function loadSessionLocation(sessionId) {
4681
+ if (memory.isDeleted(sessionId)) {
4682
+ return false;
4683
+ }
4684
+ if (sessionDirs.has(sessionId)) {
4685
+ return true;
4686
+ }
4687
+ try {
4688
+ const session = await ctx.session.get({ sessionID: sessionId });
4689
+ if (controller.signal.aborted || memory.isDeleted(sessionId) || session.location.directory !== defaultDirectory) {
4690
+ return false;
4691
+ }
4692
+ sessionDirs.set(sessionId, session.location.directory);
4693
+ if ("parentID" in session && session.parentID) {
4694
+ subagentSessions.add(sessionId);
4695
+ }
4696
+ return true;
4697
+ } catch {
4698
+ return false;
4699
+ }
4700
+ }
4701
+ function projectNameFromDirectory(directory) {
4702
+ return directory.split(/[\\/]/).findLast(Boolean) || "unknown-project";
4703
+ }
4704
+ function getProjectName(sessionId) {
4705
+ return projectNameFromDirectory(sessionDirs.get(sessionId) || defaultDirectory);
4706
+ }
4707
+ async function ensureSessionInit(sessionId) {
4708
+ if (!memory.hasTurn(sessionId) || !await checkWorker() || !await loadSessionLocation(sessionId)) {
4709
+ return false;
4710
+ }
4711
+ return memory.register(sessionId, getProjectName(sessionId));
4712
+ }
4713
+ async function sendObservation(sessionId, toolName, toolInput, toolResponse, toolUseId) {
4714
+ if (!await ensureSessionInit(sessionId)) {
4715
+ return;
4716
+ }
4717
+ try {
4718
+ await WorkerClient.sendObservation(sessionId, toolName, toolInput, toolResponse, sessionDirs.get(sessionId) || defaultDirectory, toolUseId);
4719
+ } catch {}
4720
+ }
4721
+ function normalizeToolResult(result) {
4722
+ if (typeof result === "string") {
4723
+ return result;
4724
+ }
4725
+ if (!result || typeof result !== "object") {
4726
+ return normalizeToolOutput(result);
4727
+ }
4728
+ const content = "content" in result ? result.content : undefined;
4729
+ if (typeof content === "string") {
4730
+ return content;
4731
+ }
4732
+ if (Array.isArray(content)) {
684
4733
  const text = extractTextFromParts(content);
685
4734
  if (text) {
686
4735
  return text;
@@ -691,6 +4740,22 @@ var v2_default = define({
691
4740
  }
692
4741
  return normalizeToolOutput(result);
693
4742
  }
4743
+ await ctx.session.hook("prompt", (event) => {
4744
+ if (controller.signal.aborted || memory.isDeleted(event.sessionID)) {
4745
+ return;
4746
+ }
4747
+ let ids = admitted.get(event.sessionID);
4748
+ if (!ids) {
4749
+ ids = new Set;
4750
+ admitted.set(event.sessionID, ids);
4751
+ }
4752
+ ids.add(event.messageID);
4753
+ });
4754
+ await ctx.session.hook("model.request", (event) => {
4755
+ if (event.kind === "compaction") {
4756
+ memory.invalidate(event.sessionID);
4757
+ }
4758
+ });
694
4759
  await ctx.session.hook("context", async (event) => {
695
4760
  const sessionId = event.sessionID;
696
4761
  if (!sessionId) {
@@ -700,13 +4765,42 @@ var v2_default = define({
700
4765
  return;
701
4766
  }
702
4767
  sessionModels.set(sessionId, event.model.id);
703
- sessionUserTexts.set(sessionId, extractLastUserText(event.messages));
704
- await ensureSessionInit(sessionId, sessionUserTexts.get(sessionId));
705
- if (!await checkWorker()) {
706
- return;
707
- }
708
4768
  try {
709
- const context = await getCachedContext(sessionId);
4769
+ const messages = await ctx.session.context({ sessionID: sessionId });
4770
+ if (controller.signal.aborted || !sessionDirs.has(sessionId)) {
4771
+ return;
4772
+ }
4773
+ const compaction = messages.findLast((message) => message.type === "compaction");
4774
+ if (compaction && compactions.get(sessionId) !== compaction.id) {
4775
+ compactions.set(sessionId, compaction.id);
4776
+ memory.invalidate(sessionId);
4777
+ }
4778
+ for (const message of messages) {
4779
+ if (admitted.get(sessionId)?.has(message.id)) {
4780
+ const consumed = deliveredTurn([message]);
4781
+ if (consumed && memory.select(sessionId, consumed)) {
4782
+ sessionAssistantTexts.delete(sessionId);
4783
+ }
4784
+ admitted.get(sessionId)?.delete(message.id);
4785
+ }
4786
+ }
4787
+ const turn = deliveredTurn(messages);
4788
+ if (turn) {
4789
+ if (memory.select(sessionId, turn)) {
4790
+ sessionAssistantTexts.delete(sessionId);
4791
+ }
4792
+ sessionUserTexts.set(sessionId, turn.text);
4793
+ }
4794
+ await ensureSessionInit(sessionId);
4795
+ if (!await checkWorker()) {
4796
+ return;
4797
+ }
4798
+ const base = await memory.context(sessionId, getProjectName(sessionId));
4799
+ const semantic = await memory.semantic(sessionId, getProjectName(sessionId));
4800
+ const context = [base, semantic].filter(Boolean).join(`
4801
+
4802
+ `);
4803
+ event.system = event.system.filter((part) => part.type !== "text" || !part.text.startsWith("<claude-mem-context>"));
710
4804
  if (context) {
711
4805
  event.system.push({
712
4806
  type: "text",
@@ -729,8 +4823,42 @@ ${context}
729
4823
  const sanitizedInput = sanitizeObservationValue(event.input ?? {});
730
4824
  const sanitizedOutput = truncateUtf8Bytes(stripTaggedContent(event.status === "error" ? event.error?.message ?? String(event.error ?? "") : normalizeToolResult(event.result)), MAX_OBSERVATION_BYTES);
731
4825
  await sendObservation(sessionId, event.tool, sanitizedInput, sanitizedOutput, event.id);
4826
+ if (event.status === "completed" && memory.canCapture(sessionId) && !subagentSessions.has(sessionId)) {
4827
+ const history = await files.read(sessionId, { tool: event.tool, args: event.input }, {
4828
+ directory: sessionDirs.get(sessionId) || defaultDirectory,
4829
+ project: getProjectName(sessionId)
4830
+ });
4831
+ if (history) {
4832
+ if (typeof event.result.content === "string") {
4833
+ event.result = { ...event.result, content: event.result.content + history };
4834
+ } else if (Array.isArray(event.result.content)) {
4835
+ event.result = {
4836
+ ...event.result,
4837
+ content: [...event.result.content, { type: "text", text: history }]
4838
+ };
4839
+ }
4840
+ }
4841
+ }
732
4842
  });
733
4843
  await ctx.tool.transform((tools) => {
4844
+ tools.add({
4845
+ name: "mem-save",
4846
+ description: "Save explicit memory to Claude-Mem. Private and injected context are removed. Check uncertain results before retrying.",
4847
+ input: {
4848
+ type: "object",
4849
+ properties: {
4850
+ text: { type: "string", minLength: 1, maxLength: MAX_OBSERVATION_BYTES },
4851
+ title: { type: "string", maxLength: MAX_OBSERVATION_BYTES },
4852
+ project: { type: "string", minLength: 1 }
4853
+ },
4854
+ required: ["text"],
4855
+ additionalProperties: false
4856
+ },
4857
+ options: { codemode: false },
4858
+ execute: async (input, toolContext) => ({
4859
+ content: await MemoryWorker.save(input, getProjectName(toolContext.sessionID))
4860
+ })
4861
+ });
734
4862
  tools.add({
735
4863
  name: "mem-search",
736
4864
  description: "Search Claude-Mem persistent memory. Supports query, project, platformSource, type, obs_type, dateStart, dateEnd, offset, and orderBy filters.",
@@ -906,13 +5034,16 @@ ${context}
906
5034
  return;
907
5035
  }
908
5036
  const directory = data.location?.directory;
5037
+ if ("parentID" in data && typeof data.parentID === "string") {
5038
+ subagentSessions.add(data.sessionID);
5039
+ }
909
5040
  if (typeof directory === "string" && directory) {
910
5041
  if (directory !== defaultDirectory) {
911
5042
  return;
912
5043
  }
913
5044
  sessionDirs.set(data.sessionID, directory);
914
5045
  }
915
- contextCache.delete(data.sessionID);
5046
+ memory.invalidate(data.sessionID);
916
5047
  await checkWorker();
917
5048
  return;
918
5049
  }
@@ -926,7 +5057,10 @@ ${context}
926
5057
  if (!await loadSessionLocation(sessionId)) {
927
5058
  return;
928
5059
  }
929
- sessionAssistantTexts.set(sessionId, text);
5060
+ if (!memory.canCapture(sessionId)) {
5061
+ return;
5062
+ }
5063
+ sessionAssistantTexts.set(sessionId, stripTaggedContent(text));
930
5064
  if (!await checkWorker()) {
931
5065
  return;
932
5066
  }
@@ -942,10 +5076,13 @@ ${context}
942
5076
  if (typeof sessionId !== "string") {
943
5077
  return;
944
5078
  }
5079
+ if (event.type === "session.compaction.ended") {
5080
+ memory.invalidate(sessionId);
5081
+ }
945
5082
  if (!await checkWorker()) {
946
5083
  return;
947
5084
  }
948
- if (!initializedSessions.has(sessionId)) {
5085
+ if (!memory.canCapture(sessionId)) {
949
5086
  return;
950
5087
  }
951
5088
  try {
@@ -958,9 +5095,11 @@ ${context}
958
5095
  if (typeof sessionId !== "string") {
959
5096
  return;
960
5097
  }
961
- initializedSessions.delete(sessionId);
962
- sessionInits.delete(sessionId);
963
- contextCache.delete(sessionId);
5098
+ memory.delete(sessionId);
5099
+ files.delete(sessionId);
5100
+ admitted.delete(sessionId);
5101
+ compactions.delete(sessionId);
5102
+ subagentSessions.delete(sessionId);
964
5103
  sessionDirs.delete(sessionId);
965
5104
  sessionUserTexts.delete(sessionId);
966
5105
  sessionAssistantTexts.delete(sessionId);
@@ -977,9 +5116,11 @@ ${context}
977
5116
  aborted = true;
978
5117
  controller.abort();
979
5118
  clearTimeout(retryTimer);
980
- initializedSessions.clear();
981
- sessionInits.clear();
982
- contextCache.clear();
5119
+ memory.clear();
5120
+ files.clear();
5121
+ admitted.clear();
5122
+ compactions.clear();
5123
+ subagentSessions.clear();
983
5124
  sessionDirs.clear();
984
5125
  sessionUserTexts.clear();
985
5126
  sessionAssistantTexts.clear();